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

lib-jitsi-meet.js 997KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599
  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. }
  62. /**
  63. * Joins the conference.
  64. * @param password {string} the password
  65. */
  66. JitsiConference.prototype.join = function (password) {
  67. if(this.room)
  68. this.room.join(password);
  69. };
  70. /**
  71. * Check if joined to the conference.
  72. */
  73. JitsiConference.prototype.isJoined = function () {
  74. return this.room && this.room.joined;
  75. };
  76. /**
  77. * Leaves the conference.
  78. */
  79. JitsiConference.prototype.leave = function () {
  80. if(this.xmpp && this.room)
  81. this.xmpp.leaveRoom(this.room.roomjid);
  82. this.room = null;
  83. };
  84. /**
  85. * Returns name of this conference.
  86. */
  87. JitsiConference.prototype.getName = function () {
  88. return this.options.name;
  89. };
  90. /**
  91. * Check if authentication is enabled for this conference.
  92. */
  93. JitsiConference.prototype.isAuthEnabled = function () {
  94. return this.authEnabled;
  95. };
  96. /**
  97. * Check if user is logged in.
  98. */
  99. JitsiConference.prototype.isLoggedIn = function () {
  100. return !!this.authIdentity;
  101. };
  102. /**
  103. * Get authorized login.
  104. */
  105. JitsiConference.prototype.getAuthLogin = function () {
  106. return this.authIdentity;
  107. };
  108. /**
  109. * Check if external authentication is enabled for this conference.
  110. */
  111. JitsiConference.prototype.isExternalAuthEnabled = function () {
  112. return this.room && this.room.moderator.isExternalAuthEnabled();
  113. };
  114. /**
  115. * Get url for external authentication.
  116. * @param {boolean} [urlForPopup] if true then return url for login popup,
  117. * else url of login page.
  118. * @returns {Promise}
  119. */
  120. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  121. return new Promise(function (resolve, reject) {
  122. if (!this.isExternalAuthEnabled()) {
  123. reject();
  124. return;
  125. }
  126. if (urlForPopup) {
  127. this.room.moderator.getPopupLoginUrl(resolve, reject);
  128. } else {
  129. this.room.moderator.getLoginUrl(resolve, reject);
  130. }
  131. }.bind(this));
  132. };
  133. /**
  134. * Returns the local tracks.
  135. */
  136. JitsiConference.prototype.getLocalTracks = function () {
  137. if (this.rtc) {
  138. return this.rtc.localStreams;
  139. } else {
  140. return [];
  141. }
  142. };
  143. /**
  144. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  145. * in JitsiConferenceEvents.
  146. * @param eventId the event ID.
  147. * @param handler handler for the event.
  148. *
  149. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  150. */
  151. JitsiConference.prototype.on = function (eventId, handler) {
  152. if(this.eventEmitter)
  153. this.eventEmitter.on(eventId, handler);
  154. };
  155. /**
  156. * Removes event listener
  157. * @param eventId the event ID.
  158. * @param [handler] optional, the specific handler to unbind
  159. *
  160. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  161. */
  162. JitsiConference.prototype.off = function (eventId, handler) {
  163. if(this.eventEmitter)
  164. this.eventEmitter.removeListener(eventId, handler);
  165. };
  166. // Common aliases for event emitter
  167. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  168. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  169. /**
  170. * Receives notifications from another participants for commands / custom events
  171. * (send by sendPresenceCommand method).
  172. * @param command {String} the name of the command
  173. * @param handler {Function} handler for the command
  174. */
  175. JitsiConference.prototype.addCommandListener = function (command, handler) {
  176. if(this.room)
  177. this.room.addPresenceListener(command, handler);
  178. };
  179. /**
  180. * Removes command listener
  181. * @param command {String} the name of the command
  182. */
  183. JitsiConference.prototype.removeCommandListener = function (command) {
  184. if(this.room)
  185. this.room.removePresenceListener(command);
  186. };
  187. /**
  188. * Sends text message to the other participants in the conference
  189. * @param message the text message.
  190. */
  191. JitsiConference.prototype.sendTextMessage = function (message) {
  192. if(this.room)
  193. this.room.sendMessage(message);
  194. };
  195. /**
  196. * Send presence command.
  197. * @param name the name of the command.
  198. * @param values Object with keys and values that will be send.
  199. **/
  200. JitsiConference.prototype.sendCommand = function (name, values) {
  201. if(this.room) {
  202. this.room.addToPresence(name, values);
  203. this.room.sendPresence();
  204. }
  205. };
  206. /**
  207. * Send presence command one time.
  208. * @param name the name of the command.
  209. * @param values Object with keys and values that will be send.
  210. **/
  211. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  212. this.sendCommand(name, values);
  213. this.removeCommand(name);
  214. };
  215. /**
  216. * Send presence command.
  217. * @param name the name of the command.
  218. * @param values Object with keys and values that will be send.
  219. * @param persistent if false the command will be sent only one time
  220. **/
  221. JitsiConference.prototype.removeCommand = function (name) {
  222. if(this.room)
  223. this.room.removeFromPresence(name);
  224. };
  225. /**
  226. * Sets the display name for this conference.
  227. * @param name the display name to set
  228. */
  229. JitsiConference.prototype.setDisplayName = function(name) {
  230. if(this.room){
  231. // remove previously set nickname
  232. this.room.removeFromPresence("nick");
  233. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  234. this.room.sendPresence();
  235. }
  236. };
  237. /**
  238. * Set new subject for this conference. (available only for moderator)
  239. * @param {string} subject new subject
  240. */
  241. JitsiConference.prototype.setSubject = function (subject) {
  242. if (this.room && this.isModerator()) {
  243. this.room.setSubject(subject);
  244. }
  245. };
  246. /**
  247. * Adds JitsiLocalTrack object to the conference.
  248. * @param track the JitsiLocalTrack object.
  249. */
  250. JitsiConference.prototype.addTrack = function (track) {
  251. this.room.addStream(track.getOriginalStream(), function () {
  252. this.rtc.addLocalStream(track);
  253. if (track.startMuted) {
  254. track.mute();
  255. }
  256. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  257. track.stopHandler = this.removeTrack.bind(this, track);
  258. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  259. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  260. track.muteHandler);
  261. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
  262. track.stopHandler);
  263. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  264. track.audioLevelHandler);
  265. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  266. }.bind(this));
  267. };
  268. /**
  269. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  270. * @param audioLevel the audio level
  271. */
  272. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  273. this.eventEmitter.emit(
  274. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  275. this.myUserId(), audioLevel);
  276. };
  277. /**
  278. * Fires TRACK_MUTE_CHANGED change conference event.
  279. * @param track the JitsiTrack object related to the event.
  280. */
  281. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  282. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  283. };
  284. /**
  285. * Removes JitsiLocalTrack object to the conference.
  286. * @param track the JitsiLocalTrack object.
  287. */
  288. JitsiConference.prototype.removeTrack = function (track) {
  289. if(!this.room){
  290. if(this.rtc)
  291. this.rtc.removeLocalStream(track);
  292. return;
  293. }
  294. this.room.removeStream(track.getOriginalStream(), function(){
  295. this.rtc.removeLocalStream(track);
  296. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  297. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  298. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  299. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  300. }.bind(this));
  301. };
  302. /**
  303. * Get role of the local user.
  304. * @returns {string} user role: 'moderator' or 'none'
  305. */
  306. JitsiConference.prototype.getRole = function () {
  307. return this.room.role;
  308. };
  309. /**
  310. * Check if local user is moderator.
  311. * @returns {boolean} true if local user is moderator, false otherwise.
  312. */
  313. JitsiConference.prototype.isModerator = function () {
  314. return this.room.isModerator();
  315. };
  316. /**
  317. * Set password for the room.
  318. * @param {string} password new password for the room.
  319. * @returns {Promise}
  320. */
  321. JitsiConference.prototype.lock = function (password) {
  322. if (!this.isModerator()) {
  323. return Promise.reject();
  324. }
  325. var conference = this;
  326. return new Promise(function (resolve, reject) {
  327. conference.room.lockRoom(password || "", function () {
  328. resolve();
  329. }, function (err) {
  330. reject(err);
  331. }, function () {
  332. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  333. });
  334. });
  335. };
  336. /**
  337. * Remove password from the room.
  338. * @returns {Promise}
  339. */
  340. JitsiConference.prototype.unlock = function () {
  341. return this.lock();
  342. };
  343. /**
  344. * Elects the participant with the given id to be the selected participant or the speaker.
  345. * @param id the identifier of the participant
  346. */
  347. JitsiConference.prototype.selectParticipant = function(participantId) {
  348. if (this.rtc) {
  349. this.rtc.selectedEndpoint(participantId);
  350. }
  351. };
  352. /**
  353. *
  354. * @param id the identifier of the participant
  355. */
  356. JitsiConference.prototype.pinParticipant = function(participantId) {
  357. if (this.rtc) {
  358. this.rtc.pinEndpoint(participantId);
  359. }
  360. };
  361. /**
  362. * Returns the list of participants for this conference.
  363. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  364. */
  365. JitsiConference.prototype.getParticipants = function() {
  366. return Object.keys(this.participants).map(function (key) {
  367. return this.participants[key];
  368. }, this);
  369. };
  370. /**
  371. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  372. * undefined if there isn't one).
  373. * @param id the id of the participant.
  374. */
  375. JitsiConference.prototype.getParticipantById = function(id) {
  376. return this.participants[id];
  377. };
  378. /**
  379. * Kick participant from this conference.
  380. * @param {string} id id of the participant to kick
  381. */
  382. JitsiConference.prototype.kickParticipant = function (id) {
  383. var participant = this.getParticipantById(id);
  384. if (!participant) {
  385. return;
  386. }
  387. this.room.kick(participant.getJid());
  388. };
  389. /**
  390. * Kick participant from this conference.
  391. * @param {string} id id of the participant to kick
  392. */
  393. JitsiConference.prototype.muteParticipant = function (id) {
  394. var participant = this.getParticipantById(id);
  395. if (!participant) {
  396. return;
  397. }
  398. this.room.muteParticipant(participant.getJid(), true);
  399. };
  400. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  401. var id = Strophe.getResourceFromJid(jid);
  402. if (id === 'focus' || this.myUserId() === id) {
  403. return;
  404. }
  405. var participant = new JitsiParticipant(jid, this, nick);
  406. participant._role = role;
  407. this.participants[id] = participant;
  408. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  409. this.xmpp.connection.disco.info(
  410. jid, "node", function(iq) {
  411. participant._supportsDTMF = $(iq).find(
  412. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  413. this.updateDTMFSupport();
  414. }.bind(this)
  415. );
  416. };
  417. JitsiConference.prototype.onMemberLeft = function (jid) {
  418. var id = Strophe.getResourceFromJid(jid);
  419. if (id === 'focus' || this.myUserId() === id) {
  420. return;
  421. }
  422. var participant = this.participants[id];
  423. delete this.participants[id];
  424. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  425. };
  426. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  427. var id = Strophe.getResourceFromJid(jid);
  428. var participant = this.getParticipantById(id);
  429. if (!participant) {
  430. return;
  431. }
  432. participant._role = role;
  433. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  434. };
  435. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  436. var id = Strophe.getResourceFromJid(jid);
  437. var participant = this.getParticipantById(id);
  438. if (!participant) {
  439. return;
  440. }
  441. participant._displayName = displayName;
  442. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  443. };
  444. JitsiConference.prototype.onTrackAdded = function (track) {
  445. var id = track.getParticipantId();
  446. var participant = this.getParticipantById(id);
  447. if (!participant) {
  448. return;
  449. }
  450. // add track to JitsiParticipant
  451. participant._tracks.push(track);
  452. var emitter = this.eventEmitter;
  453. track.addEventListener(
  454. JitsiTrackEvents.TRACK_STOPPED,
  455. function () {
  456. // remove track from JitsiParticipant
  457. var pos = participant._tracks.indexOf(track);
  458. if (pos > -1) {
  459. participant._tracks.splice(pos, 1);
  460. }
  461. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  462. }
  463. );
  464. track.addEventListener(
  465. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  466. function () {
  467. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  468. }
  469. );
  470. track.addEventListener(
  471. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  472. function (audioLevel) {
  473. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  474. }
  475. );
  476. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  477. };
  478. JitsiConference.prototype.updateDTMFSupport = function () {
  479. var somebodySupportsDTMF = false;
  480. var participants = this.getParticipants();
  481. // check if at least 1 participant supports DTMF
  482. for (var i = 0; i < participants.length; i += 1) {
  483. if (participants[i].supportsDTMF()) {
  484. somebodySupportsDTMF = true;
  485. break;
  486. }
  487. }
  488. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  489. this.somebodySupportsDTMF = somebodySupportsDTMF;
  490. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  491. }
  492. };
  493. /**
  494. * Allows to check if there is at least one user in the conference
  495. * that supports DTMF.
  496. * @returns {boolean} true if somebody supports DTMF, false otherwise
  497. */
  498. JitsiConference.prototype.isDTMFSupported = function () {
  499. return this.somebodySupportsDTMF;
  500. };
  501. /**
  502. * Returns the local user's ID
  503. * @return {string} local user's ID
  504. */
  505. JitsiConference.prototype.myUserId = function () {
  506. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  507. };
  508. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  509. if (!this.dtmfManager) {
  510. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  511. if (!connection) {
  512. logger.warn("cannot sendTones: no conneciton");
  513. return;
  514. }
  515. var tracks = this.getLocalTracks().filter(function (track) {
  516. return track.isAudioTrack();
  517. });
  518. if (!tracks.length) {
  519. logger.warn("cannot sendTones: no local audio stream");
  520. return;
  521. }
  522. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  523. }
  524. this.dtmfManager.sendTones(tones, duration, pause);
  525. };
  526. /**
  527. * Returns true if the recording is supproted and false if not.
  528. */
  529. JitsiConference.prototype.isRecordingSupported = function () {
  530. if(this.room)
  531. return this.room.isRecordingSupported();
  532. return false;
  533. };
  534. /**
  535. * Returns null if the recording is not supported, "on" if the recording started
  536. * and "off" if the recording is not started.
  537. */
  538. JitsiConference.prototype.getRecordingState = function () {
  539. if(this.room)
  540. return this.room.getRecordingState();
  541. return "off";
  542. }
  543. /**
  544. * Returns the url of the recorded video.
  545. */
  546. JitsiConference.prototype.getRecordingURL = function () {
  547. if(this.room)
  548. return this.room.getRecordingURL();
  549. return null;
  550. }
  551. /**
  552. * Starts/stops the recording
  553. */
  554. JitsiConference.prototype.toggleRecording = function (options) {
  555. if(this.room)
  556. return this.room.toggleRecording(options, function (status, error) {
  557. this.eventEmitter.emit(
  558. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  559. }.bind(this));
  560. this.eventEmitter.emit(
  561. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  562. new Error("The conference is not created yet!"));
  563. }
  564. /**
  565. * Returns true if the SIP calls are supported and false otherwise
  566. */
  567. JitsiConference.prototype.isSIPCallingSupported = function () {
  568. if(this.room)
  569. return this.room.isSIPCallingSupported();
  570. return false;
  571. }
  572. /**
  573. * Dials a number.
  574. * @param number the number
  575. */
  576. JitsiConference.prototype.dial = function (number) {
  577. if(this.room)
  578. return this.room.dial(number);
  579. return new Promise(function(resolve, reject){
  580. reject(new Error("The conference is not created yet!"))});
  581. }
  582. /**
  583. * Hangup an existing call
  584. */
  585. JitsiConference.prototype.hangup = function () {
  586. if(this.room)
  587. return this.room.hangup();
  588. return new Promise(function(resolve, reject){
  589. reject(new Error("The conference is not created yet!"))});
  590. }
  591. /**
  592. * Returns the phone number for joining the conference.
  593. */
  594. JitsiConference.prototype.getPhoneNumber = function () {
  595. if(this.room)
  596. return this.room.getPhoneNumber();
  597. return null;
  598. }
  599. /**
  600. * Returns the pin for joining the conference with phone.
  601. */
  602. JitsiConference.prototype.getPhonePin = function () {
  603. if(this.room)
  604. return this.room.getPhonePin();
  605. return null;
  606. }
  607. /**
  608. * Returns the connection state for the current room. Its ice connection state
  609. * for its session.
  610. */
  611. JitsiConference.prototype.getConnectionState = function () {
  612. if(this.room)
  613. return this.room.getConnectionState();
  614. return null;
  615. }
  616. /**
  617. * Make all new participants mute their audio/video on join.
  618. * @param policy {Object} object with 2 boolean properties for video and audio:
  619. * @param {boolean} audio if audio should be muted.
  620. * @param {boolean} video if video should be muted.
  621. */
  622. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  623. if (!this.isModerator()) {
  624. return;
  625. }
  626. this.startMutedPolicy = policy;
  627. this.room.removeFromPresence("startmuted");
  628. this.room.addToPresence("startmuted", {
  629. attributes: {
  630. audio: policy.audio,
  631. video: policy.video,
  632. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  633. }
  634. });
  635. this.room.sendPresence();
  636. };
  637. /**
  638. * Returns current start muted policy
  639. * @returns {Object} with 2 proprties - audio and video.
  640. */
  641. JitsiConference.prototype.getStartMutedPolicy = function () {
  642. return this.startMutedPolicy;
  643. };
  644. /**
  645. * Check if audio is muted on join.
  646. */
  647. JitsiConference.prototype.isStartAudioMuted = function () {
  648. return this.startAudioMuted;
  649. };
  650. /**
  651. * Check if video is muted on join.
  652. */
  653. JitsiConference.prototype.isStartVideoMuted = function () {
  654. return this.startVideoMuted;
  655. };
  656. /**
  657. * Get object with internal logs.
  658. */
  659. JitsiConference.prototype.getLogs = function () {
  660. var data = this.xmpp.getJingleLog();
  661. var metadata = {};
  662. metadata.time = new Date();
  663. metadata.url = window.location.href;
  664. metadata.ua = navigator.userAgent;
  665. var log = this.xmpp.getXmppLog();
  666. if (log) {
  667. metadata.xmpp = log;
  668. }
  669. data.metadata = metadata;
  670. return data;
  671. };
  672. /**
  673. * Sends the given feedback through CallStats if enabled.
  674. *
  675. * @param overallFeedback an integer between 1 and 5 indicating the
  676. * user feedback
  677. * @param detailedFeedback detailed feedback from the user. Not yet used
  678. */
  679. JitsiConference.prototype.sendFeedback =
  680. function(overallFeedback, detailedFeedback){
  681. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  682. }
  683. /**
  684. * Returns true if the callstats integration is enabled, otherwise returns
  685. * false.
  686. *
  687. * @returns true if the callstats integration is enabled, otherwise returns
  688. * false.
  689. */
  690. JitsiConference.prototype.isCallstatsEnabled = function () {
  691. return this.statistics.isCallstatsEnabled();
  692. }
  693. /**
  694. * Setups the listeners needed for the conference.
  695. * @param conference the conference
  696. */
  697. function setupListeners(conference) {
  698. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  699. conference.rtc.onIncommingCall(event);
  700. conference.statistics.startRemoteStats(event.peerconnection);
  701. });
  702. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  703. function (data, sid, thessrc) {
  704. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  705. if (track) {
  706. conference.onTrackAdded(track);
  707. }
  708. }
  709. );
  710. conference.rtc.addListener(RTCEvents.FAKE_VIDEO_TRACK_CREATED,
  711. function (track) {
  712. conference.onTrackAdded(track);
  713. }
  714. );
  715. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  716. function (value) {
  717. conference.rtc.setAudioMute(value);
  718. }
  719. );
  720. conference.room.addListener(XMPPEvents.SUBJECT_CHANGED, function (subject) {
  721. conference.eventEmitter.emit(JitsiConferenceEvents.SUBJECT_CHANGED, subject);
  722. });
  723. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  724. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  725. });
  726. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  727. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  728. });
  729. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  730. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  731. });
  732. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  733. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  734. });
  735. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  736. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  737. });
  738. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  739. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  740. });
  741. // FIXME
  742. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  743. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  744. // });
  745. conference.room.addListener(XMPPEvents.KICKED, function () {
  746. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  747. });
  748. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  749. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  750. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  751. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  752. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  753. });
  754. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  755. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  756. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  757. });
  758. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  759. function () {
  760. conference.eventEmitter.emit(
  761. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  762. });
  763. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  764. conference.eventEmitter.emit(
  765. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  766. });
  767. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  768. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  769. });
  770. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  771. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  772. });
  773. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  774. conference.authEnabled = authEnabled;
  775. conference.authIdentity = authIdentity;
  776. });
  777. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  778. var id = Strophe.getResourceFromJid(jid);
  779. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  780. });
  781. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  782. if(conference.lastDominantSpeaker !== id && conference.room) {
  783. conference.lastDominantSpeaker = id;
  784. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  785. }
  786. });
  787. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  788. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  789. });
  790. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  791. function (lastNEndpoints, endpointsEnteringLastN) {
  792. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  793. lastNEndpoints, endpointsEnteringLastN);
  794. });
  795. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  796. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  797. });
  798. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  799. function (audioMuted, videoMuted) {
  800. conference.startAudioMuted = audioMuted;
  801. conference.startVideoMuted = videoMuted;
  802. // mute existing local tracks because this is initial mute from
  803. // Jicofo
  804. conference.getLocalTracks().forEach(function (track) {
  805. if (conference.startAudioMuted && track.isAudioTrack()) {
  806. track.mute();
  807. }
  808. if (conference.startVideoMuted && track.isVideoTrack()) {
  809. track.mute();
  810. }
  811. });
  812. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  813. });
  814. conference.room.addPresenceListener("startmuted", function (data, from) {
  815. var isModerator = false;
  816. if (conference.myUserId() === from && conference.isModerator()) {
  817. isModerator = true;
  818. } else {
  819. var participant = conference.getParticipantById(from);
  820. if (participant && participant.isModerator()) {
  821. isModerator = true;
  822. }
  823. }
  824. if (!isModerator) {
  825. return;
  826. }
  827. var startAudioMuted = data.attributes.audio === 'true';
  828. var startVideoMuted = data.attributes.video === 'true';
  829. var updated = false;
  830. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  831. conference.startMutedPolicy.audio = startAudioMuted;
  832. updated = true;
  833. }
  834. if (startVideoMuted !== conference.startMutedPolicy.video) {
  835. conference.startMutedPolicy.video = startVideoMuted;
  836. updated = true;
  837. }
  838. if (updated) {
  839. conference.eventEmitter.emit(
  840. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  841. conference.startMutedPolicy
  842. );
  843. }
  844. });
  845. if(conference.statistics) {
  846. //FIXME: Maybe remove event should not be associated with the conference.
  847. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  848. var userId = null;
  849. var jid = conference.room.getJidBySSRC(ssrc);
  850. if (!jid)
  851. return;
  852. conference.rtc.setAudioLevel(jid, level);
  853. });
  854. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  855. function () {
  856. conference.statistics.dispose();
  857. });
  858. // FIXME: Maybe we should move this.
  859. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  860. // conference.room.updateDeviceAvailability(devices);
  861. // });
  862. conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
  863. function (session) {
  864. conference.statistics.startCallStats(
  865. session, conference.settings);
  866. });
  867. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
  868. function () {
  869. conference.statistics.sendSetupFailedEvent();
  870. });
  871. conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  872. function (track) {
  873. if(!track.isLocal())
  874. return;
  875. var type = (track.getType() === "audio")? "audio" : "video";
  876. conference.statistics.sendMuteEvent(track.isMuted(), type);
  877. });
  878. conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
  879. conference.statistics.sendCreateOfferFailed(e, pc);
  880. });
  881. conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
  882. conference.statistics.sendCreateAnswerFailed(e, pc);
  883. });
  884. conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  885. function (e, pc) {
  886. conference.statistics.sendSetLocalDescFailed(e, pc);
  887. }
  888. );
  889. conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  890. function (e, pc) {
  891. conference.statistics.sendSetRemoteDescFailed(e, pc);
  892. }
  893. );
  894. conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  895. function (e, pc) {
  896. conference.statistics.sendAddIceCandidateFailed(e, pc);
  897. }
  898. );
  899. }
  900. }
  901. module.exports = JitsiConference;
  902. }).call(this,"/JitsiConference.js")
  903. },{"./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":136,"./service/authentication/AuthenticationEvents":138,"./service/xmpp/XMPPEvents":142,"events":45,"jitsi-meet-logger":49}],2:[function(require,module,exports){
  904. /**
  905. * Enumeration with the errors for the conference.
  906. * @type {{string: string}}
  907. */
  908. var JitsiConferenceErrors = {
  909. /**
  910. * Indicates that a password is required in order to join the conference.
  911. */
  912. PASSWORD_REQUIRED: "conference.passwordRequired",
  913. /**
  914. * Indicates that client must be authenticated to create the conference.
  915. */
  916. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  917. /**
  918. * Indicates that password cannot be set for this conference.
  919. */
  920. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  921. /**
  922. * Indicates that a connection error occurred when trying to join a
  923. * conference.
  924. */
  925. CONNECTION_ERROR: "conference.connectionError",
  926. /**
  927. * Indicates that the conference setup failed.
  928. */
  929. SETUP_FAILED: "conference.setup_failed",
  930. /**
  931. * Indicates that there is no available videobridge.
  932. */
  933. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  934. /**
  935. * Many more errors TBD here.
  936. */
  937. };
  938. module.exports = JitsiConferenceErrors;
  939. },{}],3:[function(require,module,exports){
  940. /**
  941. * Enumeration with the events for the conference.
  942. * @type {{string: string}}
  943. */
  944. var JitsiConferenceEvents = {
  945. /**
  946. * A new media track was added to the conference.
  947. */
  948. TRACK_ADDED: "conference.trackAdded",
  949. /**
  950. * The media track was removed from the conference.
  951. */
  952. TRACK_REMOVED: "conference.trackRemoved",
  953. /**
  954. * The dominant speaker was changed.
  955. */
  956. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  957. /**
  958. * A new user joinned the conference.
  959. */
  960. USER_JOINED: "conference.userJoined",
  961. /**
  962. * A user has left the conference.
  963. */
  964. USER_LEFT: "conference.userLeft",
  965. /**
  966. * User role changed.
  967. */
  968. USER_ROLE_CHANGED: "conference.roleChanged",
  969. /**
  970. * New text message was received.
  971. */
  972. MESSAGE_RECEIVED: "conference.messageReceived",
  973. /**
  974. * A user has changed it display name
  975. */
  976. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  977. /**
  978. * Indicates that subject of the conference has changed.
  979. */
  980. SUBJECT_CHANGED: "conference.subjectChanged",
  981. /**
  982. * A participant avatar has changed.
  983. */
  984. AVATAR_CHANGED: "conference.avatarChanged",
  985. /**
  986. * New connection statistics are received.
  987. */
  988. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  989. /**
  990. * The Last N set is changed.
  991. */
  992. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  993. /**
  994. * You are included / excluded in somebody's last N set
  995. */
  996. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  997. /**
  998. * A media track ( attached to the conference) mute status was changed.
  999. */
  1000. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  1001. /**
  1002. * Audio levels of a media track ( attached to the conference) was changed.
  1003. */
  1004. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  1005. /**
  1006. * Indicates that the connection to the conference has been interrupted
  1007. * for some reason.
  1008. */
  1009. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  1010. /**
  1011. * Indicates that the connection to the conference has been restored.
  1012. */
  1013. CONNECTION_RESTORED: "conference.connectionRestored",
  1014. /**
  1015. * Indicates that conference failed.
  1016. */
  1017. CONFERENCE_FAILED: "conference.failed",
  1018. /**
  1019. * Indicates that conference has been joined.
  1020. */
  1021. CONFERENCE_JOINED: "conference.joined",
  1022. /**
  1023. * Indicates that conference has been left.
  1024. */
  1025. CONFERENCE_LEFT: "conference.left",
  1026. /**
  1027. * You are kicked from the conference.
  1028. */
  1029. KICKED: "conferenece.kicked",
  1030. /**
  1031. * Indicates that start muted settings changed.
  1032. */
  1033. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  1034. /**
  1035. * Indicates that the local user has started muted.
  1036. */
  1037. STARTED_MUTED: "conference.started_muted",
  1038. /**
  1039. * Indicates that DTMF support changed.
  1040. */
  1041. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  1042. /**
  1043. * Indicates that recording state changed.
  1044. */
  1045. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  1046. /**
  1047. * Indicates that phone number changed.
  1048. */
  1049. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  1050. };
  1051. module.exports = JitsiConferenceEvents;
  1052. },{}],4:[function(require,module,exports){
  1053. var JitsiConference = require("./JitsiConference");
  1054. var XMPP = require("./modules/xmpp/xmpp");
  1055. /**
  1056. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  1057. * JitsiConference interface.
  1058. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  1059. * @param token the JWT token used to authenticate with the server(optional)
  1060. * @param options Object with properties / settings related to connection with the server.
  1061. * @constructor
  1062. */
  1063. function JitsiConnection(appID, token, options) {
  1064. this.appID = appID;
  1065. this.token = token;
  1066. this.options = options;
  1067. this.xmpp = new XMPP(options);
  1068. this.conferences = {};
  1069. }
  1070. /**
  1071. * Connect the client with the server.
  1072. * @param options {object} connecting options (for example authentications parameters).
  1073. */
  1074. JitsiConnection.prototype.connect = function (options) {
  1075. if(!options)
  1076. options = {};
  1077. this.xmpp.connect(options.id, options.password);
  1078. }
  1079. /**
  1080. * Disconnect the client from the server.
  1081. */
  1082. JitsiConnection.prototype.disconnect = function () {
  1083. this.xmpp.disconnect();
  1084. }
  1085. /**
  1086. * This method allows renewal of the tokens if they are expiring.
  1087. * @param token the new token.
  1088. */
  1089. JitsiConnection.prototype.setToken = function (token) {
  1090. this.token = token;
  1091. }
  1092. /**
  1093. * Creates and joins new conference.
  1094. * @param name the name of the conference; if null - a generated name will be
  1095. * provided from the api
  1096. * @param options Object with properties / settings related to the conference
  1097. * that will be created.
  1098. * @returns {JitsiConference} returns the new conference object.
  1099. */
  1100. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1101. this.conferences[name] = new JitsiConference({name: name, config: options,
  1102. connection: this});
  1103. return this.conferences[name];
  1104. }
  1105. /**
  1106. * Subscribes the passed listener to the event.
  1107. * @param event {JitsiConnectionEvents} the connection event.
  1108. * @param listener {Function} the function that will receive the event
  1109. */
  1110. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1111. this.xmpp.addListener(event, listener);
  1112. }
  1113. /**
  1114. * Unsubscribes the passed handler.
  1115. * @param event {JitsiConnectionEvents} the connection event.
  1116. * @param listener {Function} the function that will receive the event
  1117. */
  1118. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1119. this.xmpp.removeListener(event, listener);
  1120. }
  1121. module.exports = JitsiConnection;
  1122. },{"./JitsiConference":1,"./modules/xmpp/xmpp":43}],5:[function(require,module,exports){
  1123. /**
  1124. * Enumeration with the errors for the connection.
  1125. * @type {{string: string}}
  1126. */
  1127. var JitsiConnectionErrors = {
  1128. /**
  1129. * Indicates that a password is required in order to join the conference.
  1130. */
  1131. PASSWORD_REQUIRED: "connection.passwordRequired",
  1132. /**
  1133. * Indicates that a connection error occurred when trying to join a
  1134. * conference.
  1135. */
  1136. CONNECTION_ERROR: "connection.connectionError",
  1137. /**
  1138. * Not specified errors.
  1139. */
  1140. OTHER_ERROR: "connection.otherError"
  1141. };
  1142. module.exports = JitsiConnectionErrors;
  1143. },{}],6:[function(require,module,exports){
  1144. /**
  1145. * Enumeration with the events for the connection.
  1146. * @type {{string: string}}
  1147. */
  1148. var JitsiConnnectionEvents = {
  1149. /**
  1150. * Indicates that the connection has been failed for some reason.
  1151. */
  1152. CONNECTION_FAILED: "connection.connectionFailed",
  1153. /**
  1154. * Indicates that the connection has been established.
  1155. */
  1156. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1157. /**
  1158. * Indicates that the connection has been disconnected.
  1159. */
  1160. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1161. /**
  1162. * Indicates that the perfomed action cannot be executed because the
  1163. * connection is not in the correct state(connected, disconnected, etc.)
  1164. */
  1165. WRONG_STATE: "connection.wrongState"
  1166. };
  1167. module.exports = JitsiConnnectionEvents;
  1168. },{}],7:[function(require,module,exports){
  1169. var JitsiConnection = require("./JitsiConnection");
  1170. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1171. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1172. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1173. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1174. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1175. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1176. var Logger = require("jitsi-meet-logger");
  1177. var RTC = require("./modules/RTC/RTC");
  1178. var Statistics = require("./modules/statistics/statistics");
  1179. var Resolutions = require("./service/RTC/Resolutions");
  1180. function getLowerResolution(resolution) {
  1181. if(!Resolutions[resolution])
  1182. return null;
  1183. var order = Resolutions[resolution].order;
  1184. var res = null;
  1185. var resName = null;
  1186. for(var i in Resolutions) {
  1187. var tmp = Resolutions[i];
  1188. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1189. resName = i;
  1190. res = tmp;
  1191. }
  1192. }
  1193. return resName;
  1194. }
  1195. /**
  1196. * Namespace for the interface of Jitsi Meet Library.
  1197. */
  1198. var LibJitsiMeet = {
  1199. JitsiConnection: JitsiConnection,
  1200. events: {
  1201. conference: JitsiConferenceEvents,
  1202. connection: JitsiConnectionEvents,
  1203. track: JitsiTrackEvents
  1204. },
  1205. errors: {
  1206. conference: JitsiConferenceErrors,
  1207. connection: JitsiConnectionErrors,
  1208. track: JitsiTrackErrors
  1209. },
  1210. logLevels: Logger.levels,
  1211. /**
  1212. * Array of functions that will receive the GUM error.
  1213. */
  1214. _gumFailedHandler: [],
  1215. init: function (options) {
  1216. Statistics.audioLevelsEnabled = !options.disableAudioLevels || true;
  1217. return RTC.init(options || {});
  1218. },
  1219. /**
  1220. * Returns whether the desktop sharing is enabled or not.
  1221. * @returns {boolean}
  1222. */
  1223. isDesktopSharingEnabled: function () {
  1224. return RTC.isDesktopSharingEnabled();
  1225. },
  1226. setLogLevel: function (level) {
  1227. Logger.setLogLevel(level);
  1228. },
  1229. /**
  1230. * Creates the media tracks and returns them trough the callback.
  1231. * @param options Object with properties / settings specifying the tracks which should be created.
  1232. * should be created or some additional configurations about resolution for example.
  1233. * @param {Array} options.devices the devices that will be requested
  1234. * @param {string} options.resolution resolution constraints
  1235. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1236. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1237. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1238. * @param {string} options.cameraDeviceId
  1239. * @param {string} options.micDeviceId
  1240. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1241. * A promise that returns an array of created JitsiTracks if resolved,
  1242. * or a JitsiConferenceError if rejected.
  1243. */
  1244. createLocalTracks: function (options) {
  1245. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1246. function(tracks) {
  1247. if(!RTC.options.disableAudioLevels)
  1248. for(var i = 0; i < tracks.length; i++) {
  1249. var track = tracks[i];
  1250. var mStream = track.getOriginalStream();
  1251. if(track.getType() === "audio"){
  1252. Statistics.startLocalStats(mStream,
  1253. track.setAudioLevel.bind(track));
  1254. track.addEventListener(
  1255. JitsiTrackEvents.TRACK_STOPPED,
  1256. function(){
  1257. Statistics.stopLocalStats(mStream);
  1258. });
  1259. }
  1260. }
  1261. return tracks;
  1262. }).catch(function (error) {
  1263. this._gumFailedHandler.forEach(function (handler) {
  1264. handler(error);
  1265. });
  1266. if(!this._gumFailedHandler.length)
  1267. Statistics.sendGetUserMediaFailed(error);
  1268. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1269. var oldResolution = options.resolution || '360';
  1270. var newResolution = getLowerResolution(oldResolution);
  1271. if(newResolution === null)
  1272. return Promise.reject(error);
  1273. options.resolution = newResolution;
  1274. return LibJitsiMeet.createLocalTracks(options);
  1275. }
  1276. return Promise.reject(error);
  1277. }.bind(this));
  1278. },
  1279. /**
  1280. * Checks if its possible to enumerate available cameras/micropones.
  1281. * @returns {boolean} true if available, false otherwise.
  1282. */
  1283. isDeviceListAvailable: function () {
  1284. return RTC.isDeviceListAvailable();
  1285. },
  1286. /**
  1287. * Returns true if changing the camera / microphone device is supported and
  1288. * false if not.
  1289. * @returns {boolean} true if available, false otherwise.
  1290. */
  1291. isDeviceChangeAvailable: function () {
  1292. return RTC.isDeviceChangeAvailable();
  1293. },
  1294. enumerateDevices: function (callback) {
  1295. RTC.enumerateDevices(callback);
  1296. }
  1297. };
  1298. //Setups the promise object.
  1299. window.Promise = window.Promise || require("es6-promise").Promise;
  1300. module.exports = LibJitsiMeet;
  1301. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./service/RTC/Resolutions":137,"es6-promise":47,"jitsi-meet-logger":49}],8:[function(require,module,exports){
  1302. /* global Strophe */
  1303. /**
  1304. * Represents a participant in (a member of) a conference.
  1305. */
  1306. function JitsiParticipant(jid, conference, displayName){
  1307. this._jid = jid;
  1308. this._id = Strophe.getResourceFromJid(jid);
  1309. this._conference = conference;
  1310. this._displayName = displayName;
  1311. this._supportsDTMF = false;
  1312. this._tracks = [];
  1313. this._role = 'none';
  1314. }
  1315. /**
  1316. * @returns {JitsiConference} The conference that this participant belongs to.
  1317. */
  1318. JitsiParticipant.prototype.getConference = function() {
  1319. return this._conference;
  1320. };
  1321. /**
  1322. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1323. */
  1324. JitsiParticipant.prototype.getTracks = function() {
  1325. return this._tracks;
  1326. };
  1327. /**
  1328. * @returns {String} The ID of this participant.
  1329. */
  1330. JitsiParticipant.prototype.getId = function() {
  1331. return this._id;
  1332. };
  1333. /**
  1334. * @returns {String} The JID of this participant.
  1335. */
  1336. JitsiParticipant.prototype.getJid = function() {
  1337. return this._jid;
  1338. };
  1339. /**
  1340. * @returns {String} The human-readable display name of this participant.
  1341. */
  1342. JitsiParticipant.prototype.getDisplayName = function() {
  1343. return this._displayName;
  1344. };
  1345. /**
  1346. * @returns {Boolean} Whether this participant is a moderator or not.
  1347. */
  1348. JitsiParticipant.prototype.isModerator = function() {
  1349. return this._role === 'moderator';
  1350. };
  1351. // Gets a link to an etherpad instance advertised by the participant?
  1352. //JitsiParticipant.prototype.getEtherpad = function() {
  1353. //
  1354. //}
  1355. /*
  1356. * @returns {Boolean} Whether this participant has muted their audio.
  1357. */
  1358. JitsiParticipant.prototype.isAudioMuted = function() {
  1359. return this.getTracks().reduce(function (track, isAudioMuted) {
  1360. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1361. }, true);
  1362. };
  1363. /*
  1364. * @returns {Boolean} Whether this participant has muted their video.
  1365. */
  1366. JitsiParticipant.prototype.isVideoMuted = function() {
  1367. return this.getTracks().reduce(function (track, isVideoMuted) {
  1368. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1369. }, true);
  1370. };
  1371. /*
  1372. * @returns {???} The latest statistics reported by this participant
  1373. * (i.e. info used to populate the GSM bars)
  1374. * TODO: do we expose this or handle it internally?
  1375. */
  1376. JitsiParticipant.prototype.getLatestStats = function() {
  1377. };
  1378. /**
  1379. * @returns {String} The role of this participant.
  1380. */
  1381. JitsiParticipant.prototype.getRole = function() {
  1382. return this._role;
  1383. };
  1384. /*
  1385. * @returns {Boolean} Whether this participant is
  1386. * the conference focus (i.e. jicofo).
  1387. */
  1388. JitsiParticipant.prototype.isFocus = function() {
  1389. };
  1390. /*
  1391. * @returns {Boolean} Whether this participant is
  1392. * a conference recorder (i.e. jirecon).
  1393. */
  1394. JitsiParticipant.prototype.isRecorder = function() {
  1395. };
  1396. /*
  1397. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1398. */
  1399. JitsiParticipant.prototype.isSipGateway = function() {
  1400. };
  1401. /**
  1402. * @returns {Boolean} Whether this participant
  1403. * is currently sharing their screen.
  1404. */
  1405. JitsiParticipant.prototype.isScreenSharing = function() {
  1406. };
  1407. /**
  1408. * @returns {String} The user agent of this participant
  1409. * (i.e. browser userAgent string).
  1410. */
  1411. JitsiParticipant.prototype.getUserAgent = function() {
  1412. };
  1413. /**
  1414. * Kicks the participant from the conference (requires certain privileges).
  1415. */
  1416. JitsiParticipant.prototype.kick = function() {
  1417. };
  1418. /**
  1419. * Asks this participant to mute themselves.
  1420. */
  1421. JitsiParticipant.prototype.askToMute = function() {
  1422. };
  1423. JitsiParticipant.prototype.supportsDTMF = function () {
  1424. return this._supportsDTMF;
  1425. };
  1426. module.exports = JitsiParticipant;
  1427. },{}],9:[function(require,module,exports){
  1428. module.exports = {
  1429. /**
  1430. * Returns JitsiTrackErrors based on the error object passed by GUM
  1431. * @param error the error
  1432. * @param {Array} devices Array with the requested devices
  1433. */
  1434. parseError: function (error, devices) {
  1435. devices = devices || [];
  1436. if (typeof error == "object" && error.constraintName && error.name
  1437. && (error.name == "ConstraintNotSatisfiedError" ||
  1438. error.name == "OverconstrainedError") &&
  1439. (error.constraintName == "minWidth" ||
  1440. error.constraintName == "maxWidth" ||
  1441. error.constraintName == "minHeight" ||
  1442. error.constraintName == "maxHeight") &&
  1443. devices.indexOf("video") !== -1) {
  1444. return this.UNSUPPORTED_RESOLUTION;
  1445. } else if(typeof error === "object" && error.type === "jitsiError") {
  1446. return error.errorObject;
  1447. } else {
  1448. return this.GENERAL;
  1449. }
  1450. },
  1451. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1452. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1453. GENERAL: "gum.general"
  1454. };
  1455. },{}],10:[function(require,module,exports){
  1456. var JitsiTrackEvents = {
  1457. /**
  1458. * A media track mute status was changed.
  1459. */
  1460. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1461. /**
  1462. * Audio levels of a this track was changed.
  1463. */
  1464. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1465. /**
  1466. * The media track was removed to the conference.
  1467. */
  1468. TRACK_STOPPED: "track.stopped"
  1469. };
  1470. module.exports = JitsiTrackEvents;
  1471. },{}],11:[function(require,module,exports){
  1472. (function (__filename){
  1473. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1474. function JitsiDTMFManager (localAudio, peerConnection) {
  1475. var tracks = localAudio._getTracks();
  1476. if (!tracks.length) {
  1477. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1478. }
  1479. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1480. logger.debug("Initialized DTMFSender");
  1481. }
  1482. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1483. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1484. };
  1485. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1486. },{"jitsi-meet-logger":49}],12:[function(require,module,exports){
  1487. (function (__filename){
  1488. /* global config, APP, Strophe */
  1489. // cache datachannels to avoid garbage collection
  1490. // https://code.google.com/p/chromium/issues/detail?id=405545
  1491. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1492. var RTCEvents = require("../../service/RTC/RTCEvents");
  1493. /**
  1494. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1495. * @param peerConnection WebRTC peer connection instance.
  1496. */
  1497. function DataChannels(peerConnection, emitter) {
  1498. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1499. this.eventEmitter = emitter;
  1500. this._dataChannels = [];
  1501. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1502. // Although it's not a requirement to open separate channels from both bridge
  1503. // and peer as single channel can be used for sending and receiving data.
  1504. // So either channel opened by the bridge or the one opened here is enough
  1505. // for communication with the bridge.
  1506. /*var dataChannelOptions =
  1507. {
  1508. reliable: true
  1509. };
  1510. var dataChannel
  1511. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1512. // Can be used only when is in open state
  1513. dataChannel.onopen = function ()
  1514. {
  1515. dataChannel.send("My channel !!!");
  1516. };
  1517. dataChannel.onmessage = function (event)
  1518. {
  1519. var msgData = event.data;
  1520. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1521. };*/
  1522. };
  1523. /**
  1524. * Callback triggered by PeerConnection when new data channel is opened
  1525. * on the bridge.
  1526. * @param event the event info object.
  1527. */
  1528. DataChannels.prototype.onDataChannel = function (event) {
  1529. var dataChannel = event.channel;
  1530. var self = this;
  1531. var lastSelectedEndpoint = null;
  1532. dataChannel.onopen = function () {
  1533. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1534. // Code sample for sending string and/or binary data
  1535. // Sends String message to the bridge
  1536. //dataChannel.send("Hello bridge!");
  1537. // Sends 12 bytes binary message to the bridge
  1538. //dataChannel.send(new ArrayBuffer(12));
  1539. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1540. // when the data channel becomes available, tell the bridge about video
  1541. // selections so that it can do adaptive simulcast,
  1542. // we want the notification to trigger even if userJid is undefined,
  1543. // or null.
  1544. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1545. };
  1546. dataChannel.onerror = function (error) {
  1547. logger.error("Data Channel Error:", error, dataChannel);
  1548. };
  1549. dataChannel.onmessage = function (event) {
  1550. var data = event.data;
  1551. // JSON
  1552. var obj;
  1553. try {
  1554. obj = JSON.parse(data);
  1555. }
  1556. catch (e) {
  1557. logger.error(
  1558. "Failed to parse data channel message as JSON: ",
  1559. data,
  1560. dataChannel);
  1561. }
  1562. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1563. var colibriClass = obj.colibriClass;
  1564. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1565. // Endpoint ID from the Videobridge.
  1566. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1567. logger.info(
  1568. "Data channel new dominant speaker event: ",
  1569. dominantSpeakerEndpoint);
  1570. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1571. }
  1572. else if ("InLastNChangeEvent" === colibriClass) {
  1573. var oldValue = obj.oldValue;
  1574. var newValue = obj.newValue;
  1575. // Make sure that oldValue and newValue are of type boolean.
  1576. var type;
  1577. if ((type = typeof oldValue) !== 'boolean') {
  1578. if (type === 'string') {
  1579. oldValue = (oldValue == "true");
  1580. } else {
  1581. oldValue = new Boolean(oldValue).valueOf();
  1582. }
  1583. }
  1584. if ((type = typeof newValue) !== 'boolean') {
  1585. if (type === 'string') {
  1586. newValue = (newValue == "true");
  1587. } else {
  1588. newValue = new Boolean(newValue).valueOf();
  1589. }
  1590. }
  1591. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1592. }
  1593. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1594. // The new/latest list of last-n endpoint IDs.
  1595. var lastNEndpoints = obj.lastNEndpoints;
  1596. // The list of endpoint IDs which are entering the list of
  1597. // last-n at this time i.e. were not in the old list of last-n
  1598. // endpoint IDs.
  1599. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1600. logger.info(
  1601. "Data channel new last-n event: ",
  1602. lastNEndpoints, endpointsEnteringLastN, obj);
  1603. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1604. lastNEndpoints, endpointsEnteringLastN, obj);
  1605. }
  1606. else {
  1607. logger.debug("Data channel JSON-formatted message: ", obj);
  1608. // The received message appears to be appropriately formatted
  1609. // (i.e. is a JSON object which assigns a value to the mandatory
  1610. // property colibriClass) so don't just swallow it, expose it to
  1611. // public consumption.
  1612. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1613. }
  1614. }
  1615. };
  1616. dataChannel.onclose = function () {
  1617. logger.info("The Data Channel closed", dataChannel);
  1618. var idx = self._dataChannels.indexOf(dataChannel);
  1619. if (idx > -1)
  1620. self._dataChannels = self._dataChannels.splice(idx, 1);
  1621. };
  1622. this._dataChannels.push(dataChannel);
  1623. };
  1624. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1625. this.lastSelectedEndpoint = userResource;
  1626. this._onXXXEndpointChanged("selected", userResource);
  1627. }
  1628. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1629. this._onXXXEndpointChanged("pinnned", userResource);
  1630. }
  1631. /**
  1632. * Notifies Videobridge about a change in the value of a specific
  1633. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1634. *
  1635. * @param xxx the name of the endpoint-related property whose value changed
  1636. * @param userResource the new value of the endpoint-related property after the
  1637. * change
  1638. */
  1639. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1640. // Derive the correct words from xxx such as selected and Selected, pinned
  1641. // and Pinned.
  1642. var head = xxx.charAt(0);
  1643. var tail = xxx.substring(1);
  1644. var lower = head.toLowerCase() + tail;
  1645. var upper = head.toUpperCase() + tail;
  1646. // Notify Videobridge about the specified endpoint change.
  1647. console.log(lower + ' endpoint changed: ', userResource);
  1648. this._some(function (dataChannel) {
  1649. if (dataChannel.readyState == 'open') {
  1650. console.log(
  1651. 'sending ' + lower
  1652. + ' endpoint changed notification to the bridge: ',
  1653. userResource);
  1654. var jsonObject = {};
  1655. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1656. jsonObject[lower + "Endpoint"]
  1657. = (userResource ? userResource : null);
  1658. dataChannel.send(JSON.stringify(jsonObject));
  1659. return true;
  1660. }
  1661. });
  1662. }
  1663. DataChannels.prototype._some = function (callback, thisArg) {
  1664. var dataChannels = this._dataChannels;
  1665. if (dataChannels && dataChannels.length !== 0) {
  1666. if (thisArg)
  1667. return dataChannels.some(callback, thisArg);
  1668. else
  1669. return dataChannels.some(callback);
  1670. } else {
  1671. return false;
  1672. }
  1673. }
  1674. module.exports = DataChannels;
  1675. }).call(this,"/modules/RTC/DataChannels.js")
  1676. },{"../../service/RTC/RTCEvents":136,"jitsi-meet-logger":49}],13:[function(require,module,exports){
  1677. var JitsiTrack = require("./JitsiTrack");
  1678. var RTCBrowserType = require("./RTCBrowserType");
  1679. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1680. var RTCUtils = require("./RTCUtils");
  1681. /**
  1682. * Represents a single media track (either audio or video).
  1683. * @constructor
  1684. */
  1685. function JitsiLocalTrack(stream, videoType,
  1686. resolution)
  1687. {
  1688. this.videoType = videoType;
  1689. this.dontFireRemoveEvent = false;
  1690. this.resolution = resolution;
  1691. this.startMuted = false;
  1692. var self = this;
  1693. JitsiTrack.call(this, null, stream,
  1694. function () {
  1695. if(!this.dontFireRemoveEvent)
  1696. this.eventEmitter.emit(
  1697. JitsiTrackEvents.TRACK_STOPPED);
  1698. this.dontFireRemoveEvent = false;
  1699. }.bind(this));
  1700. }
  1701. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1702. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1703. /**
  1704. * Mutes / unmutes the track.
  1705. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1706. */
  1707. JitsiLocalTrack.prototype._setMute = function (mute) {
  1708. if (this.isMuted() === mute) {
  1709. return;
  1710. }
  1711. if(!this.rtc) {
  1712. this.startMuted = mute;
  1713. return;
  1714. }
  1715. var isAudio = this.type === JitsiTrack.AUDIO;
  1716. this.dontFireRemoveEvent = false;
  1717. if ((window.location.protocol != "https:") ||
  1718. (isAudio) || this.videoType === "desktop" ||
  1719. // FIXME FF does not support 'removeStream' method used to mute
  1720. RTCBrowserType.isFirefox()) {
  1721. var tracks = this._getTracks();
  1722. for (var idx = 0; idx < tracks.length; idx++) {
  1723. tracks[idx].enabled = !mute;
  1724. }
  1725. if(isAudio)
  1726. this.rtc.room.setAudioMute(mute);
  1727. else
  1728. this.rtc.room.setVideoMute(mute);
  1729. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1730. } else {
  1731. if (mute) {
  1732. this.dontFireRemoveEvent = true;
  1733. this.rtc.room.removeStream(this.stream, function () {});
  1734. RTCUtils.stopMediaStream(this.stream);
  1735. if(isAudio)
  1736. this.rtc.room.setAudioMute(mute);
  1737. else
  1738. this.rtc.room.setVideoMute(mute);
  1739. this.stream = null;
  1740. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1741. //FIXME: Maybe here we should set the SRC for the containers to something
  1742. } else {
  1743. var self = this;
  1744. RTCUtils.obtainAudioAndVideoPermissions({
  1745. devices: (isAudio ? ["audio"] : ["video"]),
  1746. resolution: self.resolution})
  1747. .then(function (streams) {
  1748. var stream = null;
  1749. for(var i = 0; i < streams.length; i++) {
  1750. stream = streams[i];
  1751. if(stream.type === self.type) {
  1752. self.stream = stream.stream;
  1753. self.videoType = stream.videoType;
  1754. break;
  1755. }
  1756. }
  1757. if(!stream)
  1758. return;
  1759. for(var i = 0; i < self.containers.length; i++)
  1760. {
  1761. RTCUtils.attachMediaStream(
  1762. self.containers[i], self.stream);
  1763. }
  1764. self.rtc.room.addStream(stream.stream,
  1765. function () {
  1766. if(isAudio)
  1767. self.rtc.room.setAudioMute(mute);
  1768. else
  1769. self.rtc.room.setVideoMute(mute);
  1770. self.eventEmitter.emit(
  1771. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1772. });
  1773. });
  1774. }
  1775. }
  1776. }
  1777. /**
  1778. * Stops sending the media track. And removes it from the HTML.
  1779. * NOTE: Works for local tracks only.
  1780. */
  1781. JitsiLocalTrack.prototype.stop = function () {
  1782. if(!this.stream)
  1783. return;
  1784. if(this.rtc)
  1785. this.rtc.room.removeStream(this.stream, function () {});
  1786. RTCUtils.stopMediaStream(this.stream);
  1787. this.detach();
  1788. }
  1789. /**
  1790. * Returns <tt>true</tt> - if the stream is muted
  1791. * and <tt>false</tt> otherwise.
  1792. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1793. * and <tt>false</tt> otherwise.
  1794. */
  1795. JitsiLocalTrack.prototype.isMuted = function () {
  1796. if (!this.stream)
  1797. return true;
  1798. var tracks = [];
  1799. var isAudio = this.type === JitsiTrack.AUDIO;
  1800. if (isAudio) {
  1801. tracks = this.stream.getAudioTracks();
  1802. } else {
  1803. if (!this.isActive())
  1804. return true;
  1805. tracks = this.stream.getVideoTracks();
  1806. }
  1807. for (var idx = 0; idx < tracks.length; idx++) {
  1808. if(tracks[idx].enabled)
  1809. return false;
  1810. }
  1811. return true;
  1812. };
  1813. /**
  1814. * Private method. Updates rtc property of the track.
  1815. * @param rtc the rtc instance.
  1816. */
  1817. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1818. this.rtc = rtc;
  1819. };
  1820. /**
  1821. * Return true;
  1822. */
  1823. JitsiLocalTrack.prototype.isLocal = function () {
  1824. return true;
  1825. }
  1826. module.exports = JitsiLocalTrack;
  1827. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1828. var JitsiTrack = require("./JitsiTrack");
  1829. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1830. /**
  1831. * Represents a single media track (either audio or video).
  1832. * @param RTC the rtc instance.
  1833. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1834. * @param sid sid for the Media Stream
  1835. * @param ssrc ssrc for the Media Stream
  1836. * @param eventEmitter the event emitter
  1837. * @constructor
  1838. */
  1839. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1840. JitsiTrack.call(this, RTC, data.stream,
  1841. function () {
  1842. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1843. }.bind(this), data.jitsiTrackType);
  1844. this.rtc = RTC;
  1845. this.sid = sid;
  1846. this.stream = data.stream;
  1847. this.peerjid = data.peerjid;
  1848. this.videoType = data.videoType;
  1849. this.ssrc = ssrc;
  1850. this.muted = false;
  1851. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1852. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1853. this.muted = true;
  1854. }
  1855. }
  1856. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1857. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1858. /**
  1859. * Sets current muted status and fires an events for the change.
  1860. * @param value the muted status.
  1861. */
  1862. JitsiRemoteTrack.prototype.setMute = function (value) {
  1863. if(this.muted === value)
  1864. return;
  1865. // we can have a fake video stream
  1866. if(this.stream)
  1867. this.stream.muted = value;
  1868. this.muted = value;
  1869. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1870. };
  1871. /**
  1872. * Returns the current muted status of the track.
  1873. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1874. */
  1875. JitsiRemoteTrack.prototype.isMuted = function () {
  1876. return this.muted;
  1877. };
  1878. /**
  1879. * Returns the participant id which owns the track.
  1880. * @returns {string} the id of the participants.
  1881. */
  1882. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1883. return Strophe.getResourceFromJid(this.peerjid);
  1884. };
  1885. /**
  1886. * Return false;
  1887. */
  1888. JitsiRemoteTrack.prototype.isLocal = function () {
  1889. return false;
  1890. };
  1891. delete JitsiRemoteTrack.prototype.stop;
  1892. module.exports = JitsiRemoteTrack;
  1893. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1894. var RTCBrowserType = require("./RTCBrowserType");
  1895. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1896. var EventEmitter = require("events");
  1897. var RTC = require("./RTCUtils");
  1898. /**
  1899. * This implements 'onended' callback normally fired by WebRTC after the stream
  1900. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1901. * @param jitsiTrack our track object holding the original WebRTC stream object
  1902. * to which 'onended' handling will be added.
  1903. */
  1904. function implementOnEndedHandling(jitsiTrack) {
  1905. var stream = jitsiTrack.getOriginalStream();
  1906. if(!stream)
  1907. return;
  1908. var originalStop = stream.stop;
  1909. stream.stop = function () {
  1910. originalStop.apply(stream);
  1911. if (jitsiTrack.isActive()) {
  1912. stream.onended();
  1913. }
  1914. };
  1915. }
  1916. /**
  1917. * Adds onended/oninactive handler to a MediaStream.
  1918. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1919. * @param handler the handler
  1920. */
  1921. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1922. if(RTCBrowserType.isTemasysPluginUsed()) {
  1923. // themasys
  1924. //FIXME: Seems that not working properly.
  1925. if(mediaStream.onended) {
  1926. mediaStream.onended = handler;
  1927. } else if(mediaStream.addEventListener) {
  1928. mediaStream.addEventListener('ended', function () {
  1929. handler(mediaStream);
  1930. });
  1931. } else if(mediaStream.attachEvent) {
  1932. mediaStream.attachEvent('ended', function () {
  1933. handler(mediaStream);
  1934. });
  1935. }
  1936. }
  1937. else {
  1938. if(typeof mediaStream.active !== "undefined")
  1939. mediaStream.oninactive = handler;
  1940. else
  1941. mediaStream.onended = handler;
  1942. }
  1943. }
  1944. /**
  1945. * Represents a single media track (either audio or video).
  1946. * @constructor
  1947. * @param rtc the rtc instance
  1948. * @param stream the stream
  1949. * @param streamInactiveHandler the function that will handle
  1950. * onended/oninactive events of the stream.
  1951. * @param jitsiTrackType optionally a type can be specified.
  1952. * This is the case where we are creating a dummy track with no stream
  1953. * Currently this happens when a remote side is starting with video muted
  1954. */
  1955. function JitsiTrack(rtc, stream, streamInactiveHandler, jitsiTrackType)
  1956. {
  1957. /**
  1958. * Array with the HTML elements that are displaying the streams.
  1959. * @type {Array}
  1960. */
  1961. this.containers = [];
  1962. this.rtc = rtc;
  1963. this.stream = stream;
  1964. this.eventEmitter = new EventEmitter();
  1965. this.audioLevel = -1;
  1966. this.type = jitsiTrackType || (this.stream.getVideoTracks().length > 0)?
  1967. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1968. if(this.type == JitsiTrack.AUDIO) {
  1969. this._getTracks = function () {
  1970. return this.stream.getAudioTracks();
  1971. }.bind(this);
  1972. } else {
  1973. this._getTracks = function () {
  1974. return this.stream.getVideoTracks();
  1975. }.bind(this);
  1976. }
  1977. if (RTCBrowserType.isFirefox() && this.stream) {
  1978. implementOnEndedHandling(this);
  1979. }
  1980. if(stream)
  1981. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1982. }
  1983. /**
  1984. * JitsiTrack video type.
  1985. * @type {string}
  1986. */
  1987. JitsiTrack.VIDEO = "video";
  1988. /**
  1989. * JitsiTrack audio type.
  1990. * @type {string}
  1991. */
  1992. JitsiTrack.AUDIO = "audio";
  1993. /**
  1994. * Returns the type (audio or video) of this track.
  1995. */
  1996. JitsiTrack.prototype.getType = function() {
  1997. return this.type;
  1998. };
  1999. /**
  2000. * Check if this is audiotrack.
  2001. */
  2002. JitsiTrack.prototype.isAudioTrack = function () {
  2003. return this.getType() === JitsiTrack.AUDIO;
  2004. };
  2005. /**
  2006. * Check if this is videotrack.
  2007. */
  2008. JitsiTrack.prototype.isVideoTrack = function () {
  2009. return this.getType() === JitsiTrack.VIDEO;
  2010. };
  2011. /**
  2012. * Returns the RTCMediaStream from the browser (?).
  2013. */
  2014. JitsiTrack.prototype.getOriginalStream = function() {
  2015. return this.stream;
  2016. }
  2017. /**
  2018. * Mutes the track.
  2019. */
  2020. JitsiTrack.prototype.mute = function () {
  2021. this._setMute(true);
  2022. }
  2023. /**
  2024. * Unmutes the stream.
  2025. */
  2026. JitsiTrack.prototype.unmute = function () {
  2027. this._setMute(false);
  2028. }
  2029. /**
  2030. * Attaches the MediaStream of this track to an HTML container (?).
  2031. * Adds the container to the list of containers that are displaying the track.
  2032. * @param container the HTML container
  2033. */
  2034. JitsiTrack.prototype.attach = function (container) {
  2035. if(this.stream)
  2036. require("./RTCUtils").attachMediaStream(container, this.stream);
  2037. this.containers.push(container);
  2038. }
  2039. /**
  2040. * Removes the track from the passed HTML container.
  2041. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  2042. */
  2043. JitsiTrack.prototype.detach = function (container) {
  2044. for(var i = 0; i < this.containers.length; i++)
  2045. {
  2046. if(this.containers[i].is(container))
  2047. {
  2048. this.containers.splice(i,1);
  2049. }
  2050. if(!container)
  2051. {
  2052. this.containers[i].find(">video").remove();
  2053. }
  2054. }
  2055. if(container)
  2056. $(container).find(">video").remove();
  2057. }
  2058. /**
  2059. * Stops sending the media track. And removes it from the HTML.
  2060. * NOTE: Works for local tracks only.
  2061. */
  2062. JitsiTrack.prototype.stop = function () {
  2063. }
  2064. /**
  2065. * Returns true if this is a video track and the source of the video is a
  2066. * screen capture as opposed to a camera.
  2067. */
  2068. JitsiTrack.prototype.isScreenSharing = function(){
  2069. }
  2070. /**
  2071. * Returns id of the track.
  2072. * @returns {string} id of the track or null if this is fake track.
  2073. */
  2074. JitsiTrack.prototype._getId = function () {
  2075. var tracks = this.stream.getTracks();
  2076. if(!tracks || tracks.length === 0)
  2077. return null;
  2078. return tracks[0].id;
  2079. };
  2080. /**
  2081. * Returns id of the track.
  2082. * @returns {string} id of the track or null if this is fake track.
  2083. */
  2084. JitsiTrack.prototype.getId = function () {
  2085. if(this.stream)
  2086. return RTC.getStreamID(this.stream);
  2087. else
  2088. return null;
  2089. };
  2090. /**
  2091. * Checks whether the MediaStream is avtive/not ended.
  2092. * When there is no check for active we don't have information and so
  2093. * will return that stream is active (in case of FF).
  2094. * @returns {boolean} whether MediaStream is active.
  2095. */
  2096. JitsiTrack.prototype.isActive = function () {
  2097. if((typeof this.stream.active !== "undefined"))
  2098. return this.stream.active;
  2099. else
  2100. return true;
  2101. };
  2102. /**
  2103. * Attaches a handler for events(For example - "audio level changed".).
  2104. * All possible event are defined in JitsiTrackEvents.
  2105. * @param eventId the event ID.
  2106. * @param handler handler for the event.
  2107. */
  2108. JitsiTrack.prototype.on = function (eventId, handler) {
  2109. if(this.eventEmitter)
  2110. this.eventEmitter.on(eventId, handler);
  2111. }
  2112. /**
  2113. * Removes event listener
  2114. * @param eventId the event ID.
  2115. * @param [handler] optional, the specific handler to unbind
  2116. */
  2117. JitsiTrack.prototype.off = function (eventId, handler) {
  2118. if(this.eventEmitter)
  2119. this.eventEmitter.removeListener(eventId, handler);
  2120. }
  2121. // Common aliases for event emitter
  2122. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2123. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2124. /**
  2125. * Sets the audio level for the stream
  2126. * @param audioLevel the new audio level
  2127. */
  2128. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2129. if(this.audioLevel !== audioLevel) {
  2130. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2131. audioLevel);
  2132. this.audioLevel = audioLevel;
  2133. }
  2134. }
  2135. module.exports = JitsiTrack;
  2136. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":45}],16:[function(require,module,exports){
  2137. /* global APP */
  2138. var EventEmitter = require("events");
  2139. var RTCBrowserType = require("./RTCBrowserType");
  2140. var RTCUtils = require("./RTCUtils.js");
  2141. var JitsiTrack = require("./JitsiTrack");
  2142. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2143. var DataChannels = require("./DataChannels");
  2144. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2145. var DesktopSharingEventTypes
  2146. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2147. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2148. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2149. function createLocalTracks(streams) {
  2150. var newStreams = []
  2151. for (var i = 0; i < streams.length; i++) {
  2152. var localStream = new JitsiLocalTrack(streams[i].stream,
  2153. streams[i].videoType, streams[i].resolution);
  2154. newStreams.push(localStream);
  2155. if (streams[i].isMuted === true)
  2156. localStream.setMute(true);
  2157. }
  2158. return newStreams;
  2159. }
  2160. function RTC(room, options) {
  2161. this.room = room;
  2162. this.localStreams = [];
  2163. //FIXME: we should start removing those streams.
  2164. //FIXME: We should support multiple streams per jid.
  2165. this.remoteStreams = {};
  2166. this.localAudio = null;
  2167. this.localVideo = null;
  2168. this.eventEmitter = new EventEmitter();
  2169. var self = this;
  2170. this.options = options || {};
  2171. room.addPresenceListener("videomuted", function (values, from) {
  2172. if(self.remoteStreams[from]) {
  2173. // If there is no video track, but we receive it is muted,
  2174. // we need to create a dummy track which we will mute, so we can
  2175. // notify interested about the muting
  2176. if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
  2177. var track = self.createRemoteStream(
  2178. {peerjid:room.roomjid + "/" + from,
  2179. videoType:"camera",
  2180. jitsiTrackType:JitsiTrack.VIDEO},
  2181. null, null);
  2182. self.eventEmitter
  2183. .emit(RTCEvents.FAKE_VIDEO_TRACK_CREATED, track);
  2184. }
  2185. self.remoteStreams[from][JitsiTrack.VIDEO]
  2186. .setMute(values.value == "true");
  2187. }
  2188. });
  2189. room.addPresenceListener("audiomuted", function (values, from) {
  2190. if(self.remoteStreams[from]) {
  2191. self.remoteStreams[from][JitsiTrack.AUDIO]
  2192. .setMute(values.value == "true");
  2193. }
  2194. });
  2195. }
  2196. /**
  2197. * Creates the local MediaStreams.
  2198. * @param {Object} [options] optional parameters
  2199. * @param {Array} options.devices the devices that will be requested
  2200. * @param {string} options.resolution resolution constraints
  2201. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2202. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2203. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2204. * @param {string} options.cameraDeviceId
  2205. * @param {string} options.micDeviceId
  2206. * @returns {*} Promise object that will receive the new JitsiTracks
  2207. */
  2208. RTC.obtainAudioAndVideoPermissions = function (options) {
  2209. return RTCUtils.obtainAudioAndVideoPermissions(options).then(createLocalTracks);
  2210. }
  2211. RTC.prototype.onIncommingCall = function(event) {
  2212. if(this.options.config.openSctp)
  2213. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2214. for(var i = 0; i < this.localStreams.length; i++)
  2215. if(this.localStreams[i])
  2216. {
  2217. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2218. }
  2219. }
  2220. RTC.prototype.selectedEndpoint = function (id) {
  2221. if(this.dataChannels)
  2222. this.dataChannels.handleSelectedEndpointEvent(id);
  2223. }
  2224. RTC.prototype.pinEndpoint = function (id) {
  2225. if(this.dataChannels)
  2226. this.dataChannels.handlePinnedEndpointEvent(id);
  2227. }
  2228. RTC.prototype.addListener = function (type, listener) {
  2229. this.eventEmitter.on(type, listener);
  2230. };
  2231. RTC.prototype.removeListener = function (eventType, listener) {
  2232. this.eventEmitter.removeListener(eventType, listener);
  2233. };
  2234. RTC.addListener = function (eventType, listener) {
  2235. RTCUtils.addListener(eventType, listener);
  2236. }
  2237. RTC.removeListener = function (eventType, listener) {
  2238. RTCUtils.removeListener(eventType, listener)
  2239. }
  2240. RTC.isRTCReady = function () {
  2241. return RTCUtils.isRTCReady();
  2242. }
  2243. RTC.init = function (options) {
  2244. this.options = options || {};
  2245. return RTCUtils.init(this.options);
  2246. }
  2247. RTC.getDeviceAvailability = function () {
  2248. return RTCUtils.getDeviceAvailability();
  2249. }
  2250. RTC.prototype.addLocalStream = function (stream) {
  2251. this.localStreams.push(stream);
  2252. stream._setRTC(this);
  2253. if (stream.type == "audio") {
  2254. this.localAudio = stream;
  2255. } else {
  2256. this.localVideo = stream;
  2257. }
  2258. };
  2259. /**
  2260. * Set mute for all local audio streams attached to the conference.
  2261. * @param value the mute value
  2262. */
  2263. RTC.prototype.setAudioMute = function (value) {
  2264. for(var i = 0; i < this.localStreams.length; i++) {
  2265. var stream = this.localStreams[i];
  2266. if(stream.getType() !== "audio") {
  2267. continue;
  2268. }
  2269. stream._setMute(value);
  2270. }
  2271. }
  2272. RTC.prototype.removeLocalStream = function (track) {
  2273. var pos = this.localStreams.indexOf(track);
  2274. if (pos > -1) {
  2275. this.localStreams.splice(pos, 1);
  2276. }
  2277. };
  2278. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2279. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2280. if(!data.peerjid)
  2281. return;
  2282. var jid = Strophe.getResourceFromJid(data.peerjid);
  2283. if(!this.remoteStreams[jid]) {
  2284. this.remoteStreams[jid] = {};
  2285. }
  2286. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2287. return remoteStream;
  2288. };
  2289. RTC.getPCConstraints = function () {
  2290. return RTCUtils.pc_constraints;
  2291. };
  2292. RTC.attachMediaStream = function (elSelector, stream) {
  2293. RTCUtils.attachMediaStream(elSelector, stream);
  2294. };
  2295. RTC.getStreamID = function (stream) {
  2296. return RTCUtils.getStreamID(stream);
  2297. };
  2298. RTC.getVideoSrc = function (element) {
  2299. return RTCUtils.getVideoSrc(element);
  2300. };
  2301. /**
  2302. * Returns true if retrieving the the list of input devices is supported and
  2303. * false if not.
  2304. */
  2305. RTC.isDeviceListAvailable = function () {
  2306. return RTCUtils.isDeviceListAvailable();
  2307. };
  2308. /**
  2309. * Returns true if changing the camera / microphone device is supported and
  2310. * false if not.
  2311. */
  2312. RTC.isDeviceChangeAvailable = function () {
  2313. return RTCUtils.isDeviceChangeAvailable();
  2314. }
  2315. /**
  2316. * Allows to receive list of available cameras/microphones.
  2317. * @param {function} callback would receive array of devices as an argument
  2318. */
  2319. RTC.enumerateDevices = function (callback) {
  2320. RTCUtils.enumerateDevices(callback);
  2321. };
  2322. RTC.setVideoSrc = function (element, src) {
  2323. RTCUtils.setVideoSrc(element, src);
  2324. };
  2325. /**
  2326. * A method to handle stopping of the stream.
  2327. * One point to handle the differences in various implementations.
  2328. * @param mediaStream MediaStream object to stop.
  2329. */
  2330. RTC.stopMediaStream = function (mediaStream) {
  2331. RTCUtils.stopMediaStream(mediaStream);
  2332. };
  2333. /**
  2334. * Returns whether the desktop sharing is enabled or not.
  2335. * @returns {boolean}
  2336. */
  2337. RTC.isDesktopSharingEnabled = function () {
  2338. return RTCUtils.isDesktopSharingEnabled();
  2339. }
  2340. RTC.prototype.getVideoElementName = function () {
  2341. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2342. };
  2343. RTC.prototype.dispose = function() {
  2344. };
  2345. RTC.prototype.switchVideoStreams = function (newStream) {
  2346. this.localVideo.stream = newStream;
  2347. this.localStreams = [];
  2348. //in firefox we have only one stream object
  2349. if (this.localAudio.getOriginalStream() != newStream)
  2350. this.localStreams.push(this.localAudio);
  2351. this.localStreams.push(this.localVideo);
  2352. };
  2353. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2354. if(!jid)
  2355. return;
  2356. var resource = Strophe.getResourceFromJid(jid);
  2357. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2358. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2359. }
  2360. module.exports = RTC;
  2361. },{"../../service/RTC/MediaStreamTypes":135,"../../service/RTC/RTCEvents.js":136,"../../service/desktopsharing/DesktopSharingEventTypes":139,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":45}],17:[function(require,module,exports){
  2362. var currentBrowser;
  2363. var browserVersion;
  2364. var isAndroid;
  2365. var RTCBrowserType = {
  2366. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2367. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2368. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2369. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2370. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2371. getBrowserType: function () {
  2372. return currentBrowser;
  2373. },
  2374. isChrome: function () {
  2375. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2376. },
  2377. isOpera: function () {
  2378. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2379. },
  2380. isFirefox: function () {
  2381. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2382. },
  2383. isIExplorer: function () {
  2384. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2385. },
  2386. isSafari: function () {
  2387. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2388. },
  2389. isTemasysPluginUsed: function () {
  2390. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2391. },
  2392. getFirefoxVersion: function () {
  2393. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2394. },
  2395. getChromeVersion: function () {
  2396. return RTCBrowserType.isChrome() ? browserVersion : null;
  2397. },
  2398. usesPlanB: function() {
  2399. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2400. RTCBrowserType.isTemasysPluginUsed();
  2401. },
  2402. usesUnifiedPlan: function() {
  2403. return RTCBrowserType.isFirefox();
  2404. },
  2405. /**
  2406. * Whether the browser is running on an android device.
  2407. */
  2408. isAndroid: function() {
  2409. return isAndroid;
  2410. }
  2411. // Add version getters for other browsers when needed
  2412. };
  2413. // detectOpera() must be called before detectChrome() !!!
  2414. // otherwise Opera wil be detected as Chrome
  2415. function detectChrome() {
  2416. if (navigator.webkitGetUserMedia) {
  2417. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2418. var userAgent = navigator.userAgent.toLowerCase();
  2419. // We can assume that user agent is chrome, because it's
  2420. // enforced when 'ext' streaming method is set
  2421. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2422. console.log("This appears to be Chrome, ver: " + ver);
  2423. return ver;
  2424. }
  2425. return null;
  2426. }
  2427. function detectOpera() {
  2428. var userAgent = navigator.userAgent;
  2429. if (userAgent.match(/Opera|OPR/)) {
  2430. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2431. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2432. console.info("This appears to be Opera, ver: " + version);
  2433. return version;
  2434. }
  2435. return null;
  2436. }
  2437. function detectFirefox() {
  2438. if (navigator.mozGetUserMedia) {
  2439. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2440. var version = parseInt(
  2441. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2442. console.log('This appears to be Firefox, ver: ' + version);
  2443. return version;
  2444. }
  2445. return null;
  2446. }
  2447. function detectSafari() {
  2448. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2449. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2450. console.info("This appears to be Safari");
  2451. // FIXME detect Safari version when needed
  2452. return 1;
  2453. }
  2454. return null;
  2455. }
  2456. function detectIE() {
  2457. var version;
  2458. var ua = window.navigator.userAgent;
  2459. var msie = ua.indexOf('MSIE ');
  2460. if (msie > 0) {
  2461. // IE 10 or older => return version number
  2462. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2463. }
  2464. var trident = ua.indexOf('Trident/');
  2465. if (!version && trident > 0) {
  2466. // IE 11 => return version number
  2467. var rv = ua.indexOf('rv:');
  2468. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2469. }
  2470. var edge = ua.indexOf('Edge/');
  2471. if (!version && edge > 0) {
  2472. // IE 12 => return version number
  2473. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2474. }
  2475. if (version) {
  2476. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2477. console.info("This appears to be IExplorer, ver: " + version);
  2478. }
  2479. return version;
  2480. }
  2481. function detectBrowser() {
  2482. var version;
  2483. var detectors = [
  2484. detectOpera,
  2485. detectChrome,
  2486. detectFirefox,
  2487. detectIE,
  2488. detectSafari
  2489. ];
  2490. // Try all browser detectors
  2491. for (var i = 0; i < detectors.length; i++) {
  2492. version = detectors[i]();
  2493. if (version)
  2494. return version;
  2495. }
  2496. console.warn("Browser type defaults to Safari ver 1");
  2497. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2498. return 1;
  2499. }
  2500. browserVersion = detectBrowser();
  2501. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2502. module.exports = RTCBrowserType;
  2503. },{}],18:[function(require,module,exports){
  2504. (function (__filename){
  2505. /* global config, require, attachMediaStream, getUserMedia,
  2506. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2507. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2508. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2509. */
  2510. /* jshint -W101 */
  2511. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2512. var RTCBrowserType = require("./RTCBrowserType");
  2513. var Resolutions = require("../../service/RTC/Resolutions");
  2514. var RTCEvents = require("../../service/RTC/RTCEvents");
  2515. var AdapterJS = require("./adapter.screenshare");
  2516. var SDPUtil = require("../xmpp/SDPUtil");
  2517. var EventEmitter = require("events");
  2518. var screenObtainer = require("./ScreenObtainer");
  2519. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2520. var eventEmitter = new EventEmitter();
  2521. var devices = {
  2522. audio: true,
  2523. video: true
  2524. };
  2525. var rtcReady = false;
  2526. function setResolutionConstraints(constraints, resolution) {
  2527. var isAndroid = RTCBrowserType.isAndroid();
  2528. if (Resolutions[resolution]) {
  2529. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2530. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2531. }
  2532. else if (isAndroid) {
  2533. // FIXME can't remember if the purpose of this was to always request
  2534. // low resolution on Android ? if yes it should be moved up front
  2535. constraints.video.mandatory.minWidth = 320;
  2536. constraints.video.mandatory.minHeight = 240;
  2537. constraints.video.mandatory.maxFrameRate = 15;
  2538. }
  2539. if (constraints.video.mandatory.minWidth)
  2540. constraints.video.mandatory.maxWidth =
  2541. constraints.video.mandatory.minWidth;
  2542. if (constraints.video.mandatory.minHeight)
  2543. constraints.video.mandatory.maxHeight =
  2544. constraints.video.mandatory.minHeight;
  2545. }
  2546. /**
  2547. * @param {string[]} um required user media types
  2548. *
  2549. * @param {Object} [options={}] optional parameters
  2550. * @param {string} options.resolution
  2551. * @param {number} options.bandwidth
  2552. * @param {number} options.fps
  2553. * @param {string} options.desktopStream
  2554. * @param {string} options.cameraDeviceId
  2555. * @param {string} options.micDeviceId
  2556. * @param {bool} firefox_fake_device
  2557. */
  2558. function getConstraints(um, options) {
  2559. var constraints = {audio: false, video: false};
  2560. if (um.indexOf('video') >= 0) {
  2561. // same behaviour as true
  2562. constraints.video = { mandatory: {}, optional: [] };
  2563. if (options.cameraDeviceId) {
  2564. constraints.video.optional.push({
  2565. sourceId: options.cameraDeviceId
  2566. });
  2567. }
  2568. constraints.video.optional.push({ googLeakyBucket: true });
  2569. setResolutionConstraints(constraints, options.resolution);
  2570. }
  2571. if (um.indexOf('audio') >= 0) {
  2572. if (!RTCBrowserType.isFirefox()) {
  2573. // same behaviour as true
  2574. constraints.audio = { mandatory: {}, optional: []};
  2575. if (options.micDeviceId) {
  2576. constraints.audio.optional.push({
  2577. sourceId: options.micDeviceId
  2578. });
  2579. }
  2580. // if it is good enough for hangouts...
  2581. constraints.audio.optional.push(
  2582. {googEchoCancellation: true},
  2583. {googAutoGainControl: true},
  2584. {googNoiseSupression: true},
  2585. {googHighpassFilter: true},
  2586. {googNoisesuppression2: true},
  2587. {googEchoCancellation2: true},
  2588. {googAutoGainControl2: true}
  2589. );
  2590. } else {
  2591. if (options.micDeviceId) {
  2592. constraints.audio = {
  2593. mandatory: {},
  2594. optional: [{
  2595. sourceId: options.micDeviceId
  2596. }]};
  2597. } else {
  2598. constraints.audio = true;
  2599. }
  2600. }
  2601. }
  2602. if (um.indexOf('screen') >= 0) {
  2603. if (RTCBrowserType.isChrome()) {
  2604. constraints.video = {
  2605. mandatory: {
  2606. chromeMediaSource: "screen",
  2607. googLeakyBucket: true,
  2608. maxWidth: window.screen.width,
  2609. maxHeight: window.screen.height,
  2610. maxFrameRate: 3
  2611. },
  2612. optional: []
  2613. };
  2614. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2615. constraints.video = {
  2616. optional: [
  2617. {
  2618. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2619. }
  2620. ]
  2621. };
  2622. } else if (RTCBrowserType.isFirefox()) {
  2623. constraints.video = {
  2624. mozMediaSource: "window",
  2625. mediaSource: "window"
  2626. };
  2627. } else {
  2628. logger.error(
  2629. "'screen' WebRTC media source is supported only in Chrome" +
  2630. " and with Temasys plugin");
  2631. }
  2632. }
  2633. if (um.indexOf('desktop') >= 0) {
  2634. constraints.video = {
  2635. mandatory: {
  2636. chromeMediaSource: "desktop",
  2637. chromeMediaSourceId: options.desktopStream,
  2638. googLeakyBucket: true,
  2639. maxWidth: window.screen.width,
  2640. maxHeight: window.screen.height,
  2641. maxFrameRate: 3
  2642. },
  2643. optional: []
  2644. };
  2645. }
  2646. if (options.bandwidth) {
  2647. if (!constraints.video) {
  2648. //same behaviour as true
  2649. constraints.video = {mandatory: {}, optional: []};
  2650. }
  2651. constraints.video.optional.push({bandwidth: options.bandwidth});
  2652. }
  2653. if (options.fps) {
  2654. // for some cameras it might be necessary to request 30fps
  2655. // so they choose 30fps mjpg over 10fps yuy2
  2656. if (!constraints.video) {
  2657. // same behaviour as true;
  2658. constraints.video = {mandatory: {}, optional: []};
  2659. }
  2660. constraints.video.mandatory.minFrameRate = options.fps;
  2661. }
  2662. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2663. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2664. // this later can be a problem with some of the tests
  2665. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2666. {
  2667. // seems to be fixed now, removing this experimental fix, as having
  2668. // multiple audio tracks brake the tests
  2669. //constraints.audio = true;
  2670. constraints.fake = true;
  2671. }
  2672. return constraints;
  2673. }
  2674. function setAvailableDevices(um, available) {
  2675. if (um.indexOf("video") != -1) {
  2676. devices.video = available;
  2677. }
  2678. if (um.indexOf("audio") != -1) {
  2679. devices.audio = available;
  2680. }
  2681. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2682. }
  2683. // In case of IE we continue from 'onReady' callback
  2684. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2685. // once it is initialized.
  2686. function onReady (options, GUM) {
  2687. rtcReady = true;
  2688. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2689. screenObtainer.init(options, GUM);
  2690. }
  2691. /**
  2692. * Apply function with arguments if function exists.
  2693. * Do nothing if function not provided.
  2694. * @param {function} [fn] function to apply
  2695. * @param {Array} [args=[]] arguments for function
  2696. */
  2697. function maybeApply(fn, args) {
  2698. if (fn) {
  2699. fn.apply(null, args || []);
  2700. }
  2701. }
  2702. var getUserMediaStatus = {
  2703. initialized: false,
  2704. callbacks: []
  2705. };
  2706. /**
  2707. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2708. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2709. * @param {Function} getUserMedia native function
  2710. * @returns {Function} wrapped function
  2711. */
  2712. function wrapGetUserMedia(getUserMedia) {
  2713. return function (constraints, successCallback, errorCallback) {
  2714. getUserMedia(constraints, function (stream) {
  2715. maybeApply(successCallback, [stream]);
  2716. if (!getUserMediaStatus.initialized) {
  2717. getUserMediaStatus.initialized = true;
  2718. getUserMediaStatus.callbacks.forEach(function (callback) {
  2719. callback();
  2720. });
  2721. getUserMediaStatus.callbacks.length = 0;
  2722. }
  2723. }, function (error) {
  2724. maybeApply(errorCallback, [error]);
  2725. });
  2726. };
  2727. }
  2728. /**
  2729. * Create stub device which equals to auto selected device.
  2730. * @param {string} kind if that should be `audio` or `video` device
  2731. * @returns {Object} stub device description in `enumerateDevices` format
  2732. */
  2733. function createAutoDeviceInfo(kind) {
  2734. return {
  2735. facing: null,
  2736. label: 'Auto',
  2737. kind: kind,
  2738. deviceId: '',
  2739. groupId: null
  2740. };
  2741. }
  2742. /**
  2743. * Execute function after getUserMedia was executed at least once.
  2744. * @param {Function} callback function to execute after getUserMedia
  2745. */
  2746. function afterUserMediaInitialized(callback) {
  2747. if (getUserMediaStatus.initialized) {
  2748. callback();
  2749. } else {
  2750. getUserMediaStatus.callbacks.push(callback);
  2751. }
  2752. }
  2753. /**
  2754. * Wrapper function which makes enumerateDevices to wait
  2755. * until someone executes getUserMedia first time.
  2756. * @param {Function} enumerateDevices native function
  2757. * @returns {Funtion} wrapped function
  2758. */
  2759. function wrapEnumerateDevices(enumerateDevices) {
  2760. return function (callback) {
  2761. // enumerate devices only after initial getUserMedia
  2762. afterUserMediaInitialized(function () {
  2763. enumerateDevices().then(function (devices) {
  2764. //add auto devices
  2765. devices.unshift(
  2766. createAutoDeviceInfo('audioinput'),
  2767. createAutoDeviceInfo('videoinput')
  2768. );
  2769. callback(devices);
  2770. }, function (err) {
  2771. console.error('cannot enumerate devices: ', err);
  2772. // return only auto devices
  2773. callback([createAutoDeviceInfo('audioInput'),
  2774. createAutoDeviceInfo('videoinput')]);
  2775. });
  2776. });
  2777. };
  2778. }
  2779. /**
  2780. * Use old MediaStreamTrack to get devices list and
  2781. * convert it to enumerateDevices format.
  2782. * @param {Function} callback function to call when received devices list.
  2783. */
  2784. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2785. MediaStreamTrack.getSources(function (sources) {
  2786. var devices = sources.map(function (source) {
  2787. var kind = (source.kind || '').toLowerCase();
  2788. return {
  2789. facing: source.facing || null,
  2790. label: source.label,
  2791. kind: kind ? kind + 'input': null,
  2792. deviceId: source.id,
  2793. groupId: source.groupId || null
  2794. };
  2795. });
  2796. //add auto devices
  2797. devices.unshift(
  2798. createAutoDeviceInfo('audioinput'),
  2799. createAutoDeviceInfo('videoinput')
  2800. );
  2801. callback(devices);
  2802. });
  2803. }
  2804. function obtainDevices(options) {
  2805. if(!options.devices || options.devices.length === 0) {
  2806. return options.successCallback(options.streams || {});
  2807. }
  2808. var device = options.devices.splice(0, 1);
  2809. var devices = [];
  2810. devices.push(device);
  2811. options.deviceGUM[device](function (stream) {
  2812. options.streams = options.streams || {};
  2813. options.streams[device] = stream;
  2814. obtainDevices(options);
  2815. },
  2816. function (error) {
  2817. Object.keys(options.streams).forEach(function(device) {
  2818. RTCUtils.stopMediaStream(options.streams[device]);
  2819. });
  2820. logger.error(
  2821. "failed to obtain " + device + " stream - stop", error);
  2822. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2823. });
  2824. }
  2825. /**
  2826. * Handles the newly created Media Streams.
  2827. * @param streams the new Media Streams
  2828. * @param resolution the resolution of the video streams
  2829. * @returns {*[]} object that describes the new streams
  2830. */
  2831. function handleLocalStream(streams, resolution) {
  2832. var audioStream, videoStream, desktopStream, res = [];
  2833. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2834. // an object with two properties: audioStream, videoStream.
  2835. if (window.webkitMediaStream) {
  2836. var audioVideo = streams.audioVideo;
  2837. if (audioVideo) {
  2838. var audioTracks = audioVideo.getAudioTracks();
  2839. if(audioTracks.length) {
  2840. audioStream = new webkitMediaStream();
  2841. for (var i = 0; i < audioTracks.length; i++) {
  2842. audioStream.addTrack(audioTracks[i]);
  2843. }
  2844. }
  2845. var videoTracks = audioVideo.getVideoTracks();
  2846. if(videoTracks.length) {
  2847. videoStream = new webkitMediaStream();
  2848. for (var j = 0; j < videoTracks.length; j++) {
  2849. videoStream.addTrack(videoTracks[j]);
  2850. }
  2851. }
  2852. }
  2853. if (streams && streams.desktopStream)
  2854. desktopStream = streams.desktopStream;
  2855. }
  2856. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2857. if (streams && streams.audio)
  2858. audioStream = streams.audio;
  2859. if (streams && streams.video)
  2860. videoStream = streams.video;
  2861. if(streams && streams.desktop)
  2862. desktopStream = streams.desktop;
  2863. }
  2864. if (desktopStream)
  2865. res.push({stream: desktopStream,
  2866. type: "video", videoType: "desktop"});
  2867. if(audioStream)
  2868. res.push({stream: audioStream, type: "audio", videoType: null});
  2869. if(videoStream)
  2870. res.push({stream: videoStream, type: "video", videoType: "camera",
  2871. resolution: resolution});
  2872. return res;
  2873. }
  2874. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2875. var RTCUtils = {
  2876. init: function (options) {
  2877. return new Promise(function(resolve, reject) {
  2878. if (RTCBrowserType.isFirefox()) {
  2879. var FFversion = RTCBrowserType.getFirefoxVersion();
  2880. if (FFversion < 40) {
  2881. logger.error(
  2882. "Firefox version too old: " + FFversion +
  2883. ". Required >= 40.");
  2884. reject(new Error("Firefox version too old: " + FFversion +
  2885. ". Required >= 40."));
  2886. return;
  2887. }
  2888. this.peerconnection = mozRTCPeerConnection;
  2889. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2890. this.enumerateDevices = wrapEnumerateDevices(
  2891. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2892. );
  2893. this.pc_constraints = {};
  2894. this.attachMediaStream = function (element, stream) {
  2895. // srcObject is being standardized and FF will eventually
  2896. // support that unprefixed. FF also supports the
  2897. // "element.src = URL.createObjectURL(...)" combo, but that
  2898. // will be deprecated in favour of srcObject.
  2899. //
  2900. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2901. // https://github.com/webrtc/samples/issues/302
  2902. if (!element[0])
  2903. return;
  2904. element[0].mozSrcObject = stream;
  2905. element[0].play();
  2906. };
  2907. this.getStreamID = function (stream) {
  2908. var id = stream.id;
  2909. if (!id) {
  2910. var tracks = stream.getVideoTracks();
  2911. if (!tracks || tracks.length === 0) {
  2912. tracks = stream.getAudioTracks();
  2913. }
  2914. id = tracks[0].id;
  2915. }
  2916. return SDPUtil.filter_special_chars(id);
  2917. };
  2918. this.getVideoSrc = function (element) {
  2919. if (!element)
  2920. return null;
  2921. return element.mozSrcObject;
  2922. };
  2923. this.setVideoSrc = function (element, src) {
  2924. if (element)
  2925. element.mozSrcObject = src;
  2926. };
  2927. RTCSessionDescription = mozRTCSessionDescription;
  2928. RTCIceCandidate = mozRTCIceCandidate;
  2929. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2930. this.peerconnection = webkitRTCPeerConnection;
  2931. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2932. if (navigator.mediaDevices) {
  2933. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2934. this.enumerateDevices = wrapEnumerateDevices(
  2935. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2936. );
  2937. } else {
  2938. this.getUserMedia = getUserMedia;
  2939. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2940. }
  2941. this.attachMediaStream = function (element, stream) {
  2942. // saves the created url for the stream, so we can reuse it
  2943. // and not keep creating urls
  2944. if (!stream.jitsiObjectURL) {
  2945. stream.jitsiObjectURL
  2946. = webkitURL.createObjectURL(stream);
  2947. }
  2948. element.attr('src', stream.jitsiObjectURL);
  2949. };
  2950. this.getStreamID = function (stream) {
  2951. // streams from FF endpoints have the characters '{' and '}'
  2952. // that make jQuery choke.
  2953. return SDPUtil.filter_special_chars(stream.id);
  2954. };
  2955. this.getVideoSrc = function (element) {
  2956. if (!element)
  2957. return null;
  2958. return element.getAttribute("src");
  2959. };
  2960. this.setVideoSrc = function (element, src) {
  2961. if (element)
  2962. element.setAttribute("src", src);
  2963. };
  2964. // DTLS should now be enabled by default but..
  2965. this.pc_constraints = {'optional': [
  2966. {'DtlsSrtpKeyAgreement': 'true'}
  2967. ]};
  2968. if (options.useIPv6) {
  2969. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2970. this.pc_constraints.optional.push({googIPv6: true});
  2971. }
  2972. if (RTCBrowserType.isAndroid()) {
  2973. this.pc_constraints = {}; // disable DTLS on Android
  2974. }
  2975. if (!webkitMediaStream.prototype.getVideoTracks) {
  2976. webkitMediaStream.prototype.getVideoTracks = function () {
  2977. return this.videoTracks;
  2978. };
  2979. }
  2980. if (!webkitMediaStream.prototype.getAudioTracks) {
  2981. webkitMediaStream.prototype.getAudioTracks = function () {
  2982. return this.audioTracks;
  2983. };
  2984. }
  2985. }
  2986. // Detect IE/Safari
  2987. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2988. //AdapterJS.WebRTCPlugin.setLogLevel(
  2989. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2990. var self = this;
  2991. AdapterJS.webRTCReady(function (isPlugin) {
  2992. self.peerconnection = RTCPeerConnection;
  2993. self.getUserMedia = window.getUserMedia;
  2994. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2995. self.attachMediaStream = function (elSel, stream) {
  2996. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  2997. return;
  2998. }
  2999. attachMediaStream(elSel[0], stream);
  3000. };
  3001. self.getStreamID = function (stream) {
  3002. var id = SDPUtil.filter_special_chars(stream.label);
  3003. return id;
  3004. };
  3005. self.getVideoSrc = function (element) {
  3006. if (!element) {
  3007. logger.warn("Attempt to get video SRC of null element");
  3008. return null;
  3009. }
  3010. var children = element.children;
  3011. for (var i = 0; i !== children.length; ++i) {
  3012. if (children[i].name === 'streamId') {
  3013. return children[i].value;
  3014. }
  3015. }
  3016. //logger.info(element.id + " SRC: " + src);
  3017. return null;
  3018. };
  3019. self.setVideoSrc = function (element, src) {
  3020. //logger.info("Set video src: ", element, src);
  3021. if (!src) {
  3022. logger.warn("Not attaching video stream, 'src' is null");
  3023. return;
  3024. }
  3025. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3026. var stream = AdapterJS.WebRTCPlugin.plugin
  3027. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  3028. attachMediaStream(element, stream);
  3029. };
  3030. onReady(options, self.getUserMediaWithConstraints);
  3031. resolve();
  3032. });
  3033. } else {
  3034. try {
  3035. logger.error('Browser does not appear to be WebRTC-capable');
  3036. } catch (e) {
  3037. }
  3038. reject('Browser does not appear to be WebRTC-capable');
  3039. return;
  3040. }
  3041. // Call onReady() if Temasys plugin is not used
  3042. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3043. onReady(options, this.getUserMediaWithConstraints);
  3044. resolve();
  3045. }
  3046. }.bind(this));
  3047. },
  3048. /**
  3049. * @param {string[]} um required user media types
  3050. * @param {function} success_callback
  3051. * @param {Function} failure_callback
  3052. * @param {Object} [options] optional parameters
  3053. * @param {string} options.resolution
  3054. * @param {number} options.bandwidth
  3055. * @param {number} options.fps
  3056. * @param {string} options.desktopStream
  3057. * @param {string} options.cameraDeviceId
  3058. * @param {string} options.micDeviceId
  3059. **/
  3060. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3061. options = options || {};
  3062. var resolution = options.resolution;
  3063. var constraints = getConstraints(um, options);
  3064. logger.info("Get media constraints", constraints);
  3065. try {
  3066. this.getUserMedia(constraints,
  3067. function (stream) {
  3068. logger.log('onUserMediaSuccess');
  3069. setAvailableDevices(um, true);
  3070. success_callback(stream);
  3071. },
  3072. function (error) {
  3073. setAvailableDevices(um, false);
  3074. logger.warn('Failed to get access to local media. Error ',
  3075. error, constraints);
  3076. if (failure_callback) {
  3077. failure_callback(error, resolution);
  3078. }
  3079. });
  3080. } catch (e) {
  3081. logger.error('GUM failed: ', e);
  3082. if (failure_callback) {
  3083. failure_callback(e);
  3084. }
  3085. }
  3086. },
  3087. /**
  3088. * Creates the local MediaStreams.
  3089. * @param {Object} [options] optional parameters
  3090. * @param {Array} options.devices the devices that will be requested
  3091. * @param {string} options.resolution resolution constraints
  3092. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3093. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3094. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3095. * @param {string} options.cameraDeviceId
  3096. * @param {string} options.micDeviceId
  3097. * @returns {*} Promise object that will receive the new JitsiTracks
  3098. */
  3099. obtainAudioAndVideoPermissions: function (options) {
  3100. var self = this;
  3101. options = options || {};
  3102. return new Promise(function (resolve, reject) {
  3103. var successCallback = function (stream) {
  3104. resolve(handleLocalStream(stream, options.resolution));
  3105. };
  3106. options.devices = options.devices || ['audio', 'video'];
  3107. if(!screenObtainer.isSupported()
  3108. && options.devices.indexOf("desktop") !== -1){
  3109. reject(new Error("Desktop sharing is not supported!"));
  3110. }
  3111. if (RTCBrowserType.isFirefox() ||
  3112. RTCBrowserType.isTemasysPluginUsed()) {
  3113. var GUM = function (device, s, e) {
  3114. this.getUserMediaWithConstraints(device, s, e, options);
  3115. };
  3116. var deviceGUM = {
  3117. "audio": GUM.bind(self, ["audio"]),
  3118. "video": GUM.bind(self, ["video"])
  3119. };
  3120. if(screenObtainer.isSupported()){
  3121. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3122. screenObtainer);
  3123. }
  3124. // With FF/IE we can't split the stream into audio and video because FF
  3125. // doesn't support media stream constructors. So, we need to get the
  3126. // audio stream separately from the video stream using two distinct GUM
  3127. // calls. Not very user friendly :-( but we don't have many other
  3128. // options neither.
  3129. //
  3130. // Note that we pack those 2 streams in a single object and pass it to
  3131. // the successCallback method.
  3132. obtainDevices({
  3133. devices: options.devices,
  3134. streams: [],
  3135. successCallback: successCallback,
  3136. errorCallback: reject,
  3137. deviceGUM: deviceGUM
  3138. });
  3139. } else {
  3140. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3141. if (hasDesktop) {
  3142. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3143. }
  3144. options.resolution = options.resolution || '360';
  3145. if(options.devices.length) {
  3146. this.getUserMediaWithConstraints(
  3147. options.devices,
  3148. function (stream) {
  3149. if((options.devices.indexOf("audio") !== -1 &&
  3150. !stream.getAudioTracks().length) ||
  3151. (options.devices.indexOf("video") !== -1 &&
  3152. !stream.getVideoTracks().length))
  3153. {
  3154. self.stopMediaStream(stream);
  3155. reject(JitsiTrackErrors.parseError(
  3156. new Error("Unable to get the audio and " +
  3157. "video tracks."),
  3158. options.devices));
  3159. return;
  3160. }
  3161. if(hasDesktop) {
  3162. screenObtainer.obtainStream(
  3163. function (desktopStream) {
  3164. successCallback({audioVideo: stream,
  3165. desktopStream: desktopStream});
  3166. }, function (error) {
  3167. self.stopMediaStream(stream);
  3168. reject(
  3169. JitsiTrackErrors.parseError(error,
  3170. options.devices));
  3171. });
  3172. } else {
  3173. successCallback({audioVideo: stream});
  3174. }
  3175. },
  3176. function (error) {
  3177. reject(JitsiTrackErrors.parseError(error,
  3178. options.devices));
  3179. },
  3180. options);
  3181. } else if (hasDesktop) {
  3182. screenObtainer.obtainStream(
  3183. function (stream) {
  3184. successCallback({desktopStream: stream});
  3185. }, function (error) {
  3186. reject(
  3187. JitsiTrackErrors.parseError(error,
  3188. ["desktop"]));
  3189. });
  3190. }
  3191. }
  3192. }.bind(this));
  3193. },
  3194. addListener: function (eventType, listener) {
  3195. eventEmitter.on(eventType, listener);
  3196. },
  3197. removeListener: function (eventType, listener) {
  3198. eventEmitter.removeListener(eventType, listener);
  3199. },
  3200. getDeviceAvailability: function () {
  3201. return devices;
  3202. },
  3203. isRTCReady: function () {
  3204. return rtcReady;
  3205. },
  3206. /**
  3207. * Checks if its possible to enumerate available cameras/micropones.
  3208. * @returns {boolean} true if available, false otherwise.
  3209. */
  3210. isDeviceListAvailable: function () {
  3211. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3212. if (isEnumerateDevicesAvailable) {
  3213. return true;
  3214. }
  3215. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3216. },
  3217. /**
  3218. * Returns true if changing the camera / microphone device is supported and
  3219. * false if not.
  3220. */
  3221. isDeviceChangeAvailable: function () {
  3222. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3223. RTCBrowserType.isTemasysPluginUsed())
  3224. return true;
  3225. return false;
  3226. },
  3227. /**
  3228. * A method to handle stopping of the stream.
  3229. * One point to handle the differences in various implementations.
  3230. * @param mediaStream MediaStream object to stop.
  3231. */
  3232. stopMediaStream: function (mediaStream) {
  3233. mediaStream.getTracks().forEach(function (track) {
  3234. // stop() not supported with IE
  3235. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3236. track.stop();
  3237. }
  3238. });
  3239. // leave stop for implementation still using it
  3240. if (mediaStream.stop) {
  3241. mediaStream.stop();
  3242. }
  3243. // if we have done createObjectURL, lets clean it
  3244. if (mediaStream.jitsiObjectURL) {
  3245. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3246. }
  3247. },
  3248. /**
  3249. * Returns whether the desktop sharing is enabled or not.
  3250. * @returns {boolean}
  3251. */
  3252. isDesktopSharingEnabled: function () {
  3253. return screenObtainer.isSupported();
  3254. }
  3255. };
  3256. module.exports = RTCUtils;
  3257. }).call(this,"/modules/RTC/RTCUtils.js")
  3258. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":136,"../../service/RTC/Resolutions":137,"../xmpp/SDPUtil":33,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":45,"jitsi-meet-logger":49}],19:[function(require,module,exports){
  3259. (function (__filename){
  3260. /* global chrome, $, alert */
  3261. /* jshint -W003 */
  3262. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3263. var RTCBrowserType = require("./RTCBrowserType");
  3264. var AdapterJS = require("./adapter.screenshare");
  3265. var DesktopSharingEventTypes
  3266. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3267. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3268. /**
  3269. * Indicates whether the Chrome desktop sharing extension is installed.
  3270. * @type {boolean}
  3271. */
  3272. var chromeExtInstalled = false;
  3273. /**
  3274. * Indicates whether an update of the Chrome desktop sharing extension is
  3275. * required.
  3276. * @type {boolean}
  3277. */
  3278. var chromeExtUpdateRequired = false;
  3279. /**
  3280. * Whether the jidesha extension for firefox is installed for the domain on
  3281. * which we are running. Null designates an unknown value.
  3282. * @type {null}
  3283. */
  3284. var firefoxExtInstalled = null;
  3285. /**
  3286. * If set to true, detection of an installed firefox extension will be started
  3287. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3288. * user tries to enable screen sharing).
  3289. */
  3290. var reDetectFirefoxExtension = false;
  3291. var GUM = null;
  3292. /**
  3293. * Handles obtaining a stream from a screen capture on different browsers.
  3294. */
  3295. var ScreenObtainer = {
  3296. obtainStream: null,
  3297. /**
  3298. * Initializes the function used to obtain a screen capture
  3299. * (this.obtainStream).
  3300. *
  3301. * If the browser is Chrome, it uses the value of
  3302. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3303. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3304. * use the "screen" media source (if the value is 'webrtc'),
  3305. * or disable screen capture (if the value is other).
  3306. * Note that for the "screen" media source to work the
  3307. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3308. */
  3309. init: function(options, gum) {
  3310. var obtainDesktopStream = null;
  3311. this.options = options = options || {};
  3312. GUM = gum;
  3313. if (RTCBrowserType.isFirefox())
  3314. initFirefoxExtensionDetection(options);
  3315. // TODO remove this, options.desktopSharing is deprecated.
  3316. var chromeMethod =
  3317. (options.desktopSharingChromeMethod || options.desktopSharing);
  3318. if (RTCBrowserType.isTemasysPluginUsed()) {
  3319. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3320. logger.info("Screensharing not supported by this plugin " +
  3321. "version");
  3322. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3323. logger.info(
  3324. "Screensharing not available with Temasys plugin on" +
  3325. " this site");
  3326. } else {
  3327. obtainDesktopStream = obtainWebRTCScreen;
  3328. logger.info("Using Temasys plugin for desktop sharing");
  3329. }
  3330. } else if (RTCBrowserType.isChrome()) {
  3331. if (chromeMethod == "ext") {
  3332. if (RTCBrowserType.getChromeVersion() >= 34) {
  3333. obtainDesktopStream =
  3334. this.obtainScreenFromExtension;
  3335. logger.info("Using Chrome extension for desktop sharing");
  3336. initChromeExtension(options);
  3337. } else {
  3338. logger.info("Chrome extension not supported until ver 34");
  3339. }
  3340. } else if (chromeMethod == "webrtc") {
  3341. obtainDesktopStream = obtainWebRTCScreen;
  3342. logger.info("Using Chrome WebRTC for desktop sharing");
  3343. }
  3344. } else if (RTCBrowserType.isFirefox()) {
  3345. if (options.desktopSharingFirefoxDisabled) {
  3346. obtainDesktopStream = null;
  3347. } else if (window.location.protocol === "http:"){
  3348. logger.log("Screen sharing is not supported over HTTP. " +
  3349. "Use of HTTPS is required.");
  3350. obtainDesktopStream = null;
  3351. } else {
  3352. obtainDesktopStream = this.obtainScreenOnFirefox;
  3353. }
  3354. }
  3355. if (!obtainDesktopStream) {
  3356. logger.info("Desktop sharing disabled");
  3357. }
  3358. this.obtainStream = obtainDesktopStream;
  3359. },
  3360. /**
  3361. * Checks whether obtaining a screen capture is supported in the current
  3362. * environment.
  3363. * @returns {boolean}
  3364. */
  3365. isSupported: function() {
  3366. return !!this.obtainStream;
  3367. },
  3368. /**
  3369. * Obtains a screen capture stream on Firefox.
  3370. * @param callback
  3371. * @param errorCallback
  3372. */
  3373. obtainScreenOnFirefox:
  3374. function (callback, errorCallback) {
  3375. var self = this;
  3376. var extensionRequired = false;
  3377. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3378. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3379. RTCBrowserType.getFirefoxVersion() <=
  3380. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3381. extensionRequired = true;
  3382. logger.log("Jidesha extension required on firefox version " +
  3383. RTCBrowserType.getFirefoxVersion());
  3384. }
  3385. if (!extensionRequired || firefoxExtInstalled === true) {
  3386. obtainWebRTCScreen(callback, errorCallback);
  3387. return;
  3388. }
  3389. if (reDetectFirefoxExtension) {
  3390. reDetectFirefoxExtension = false;
  3391. initFirefoxExtensionDetection(this.options);
  3392. }
  3393. // Give it some (more) time to initialize, and assume lack of
  3394. // extension if it hasn't.
  3395. if (firefoxExtInstalled === null) {
  3396. window.setTimeout(
  3397. function() {
  3398. if (firefoxExtInstalled === null)
  3399. firefoxExtInstalled = false;
  3400. self.obtainScreenOnFirefox(callback, errorCallback);
  3401. },
  3402. 300
  3403. );
  3404. logger.log("Waiting for detection of jidesha on firefox to " +
  3405. "finish.");
  3406. return;
  3407. }
  3408. // We need an extension and it isn't installed.
  3409. // Make sure we check for the extension when the user clicks again.
  3410. firefoxExtInstalled = null;
  3411. reDetectFirefoxExtension = true;
  3412. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3413. // stuck in 'switching' mode.
  3414. errorCallback({
  3415. type: "jitsiError",
  3416. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3417. });
  3418. },
  3419. /**
  3420. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3421. * 'desktop' stream for returned stream token.
  3422. */
  3423. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3424. var self = this;
  3425. if (chromeExtInstalled) {
  3426. doGetStreamFromExtension(this.options, streamCallback,
  3427. failCallback);
  3428. } else {
  3429. if (chromeExtUpdateRequired) {
  3430. alert(
  3431. 'Jitsi Desktop Streamer requires update. ' +
  3432. 'Changes will take effect after next Chrome restart.');
  3433. }
  3434. chrome.webstore.install(
  3435. getWebStoreInstallUrl(this.options),
  3436. function (arg) {
  3437. logger.log("Extension installed successfully", arg);
  3438. chromeExtInstalled = true;
  3439. // We need to give a moment for the endpoint to become
  3440. // available
  3441. window.setTimeout(function () {
  3442. doGetStreamFromExtension(self.options, streamCallback,
  3443. failCallback);
  3444. }, 500);
  3445. },
  3446. function (arg) {
  3447. logger.log("Failed to install the extension", arg);
  3448. failCallback(arg);
  3449. }
  3450. );
  3451. }
  3452. }
  3453. };
  3454. /**
  3455. * Obtains a desktop stream using getUserMedia.
  3456. * For this to work on Chrome, the
  3457. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3458. *
  3459. * On firefox, the document's domain must be white-listed in the
  3460. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3461. * 'about:config'.
  3462. */
  3463. function obtainWebRTCScreen(streamCallback, failCallback) {
  3464. GUM(
  3465. ['screen'],
  3466. streamCallback,
  3467. failCallback
  3468. );
  3469. }
  3470. /**
  3471. * Constructs inline install URL for Chrome desktop streaming extension.
  3472. * The 'chromeExtensionId' must be defined in options parameter.
  3473. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3474. * @returns {string}
  3475. */
  3476. function getWebStoreInstallUrl(options)
  3477. {
  3478. //TODO remove chromeExtensionId (deprecated)
  3479. return "https://chrome.google.com/webstore/detail/" +
  3480. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3481. }
  3482. /**
  3483. * Checks whether an update of the Chrome extension is required.
  3484. * @param minVersion minimal required version
  3485. * @param extVersion current extension version
  3486. * @returns {boolean}
  3487. */
  3488. function isUpdateRequired(minVersion, extVersion) {
  3489. try {
  3490. var s1 = minVersion.split('.');
  3491. var s2 = extVersion.split('.');
  3492. var len = Math.max(s1.length, s2.length);
  3493. for (var i = 0; i < len; i++) {
  3494. var n1 = 0,
  3495. n2 = 0;
  3496. if (i < s1.length)
  3497. n1 = parseInt(s1[i]);
  3498. if (i < s2.length)
  3499. n2 = parseInt(s2[i]);
  3500. if (isNaN(n1) || isNaN(n2)) {
  3501. return true;
  3502. } else if (n1 !== n2) {
  3503. return n1 > n2;
  3504. }
  3505. }
  3506. // will happen if both versions have identical numbers in
  3507. // their components (even if one of them is longer, has more components)
  3508. return false;
  3509. }
  3510. catch (e) {
  3511. logger.error("Failed to parse extension version", e);
  3512. return true;
  3513. }
  3514. }
  3515. function checkChromeExtInstalled(callback, options) {
  3516. if (!chrome || !chrome.runtime) {
  3517. // No API, so no extension for sure
  3518. callback(false, false);
  3519. return;
  3520. }
  3521. chrome.runtime.sendMessage(
  3522. //TODO: remove chromeExtensionId (deprecated)
  3523. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3524. { getVersion: true },
  3525. function (response) {
  3526. if (!response || !response.version) {
  3527. // Communication failure - assume that no endpoint exists
  3528. logger.warn(
  3529. "Extension not installed?: ", chrome.runtime.lastError);
  3530. callback(false, false);
  3531. return;
  3532. }
  3533. // Check installed extension version
  3534. var extVersion = response.version;
  3535. logger.log('Extension version is: ' + extVersion);
  3536. //TODO: remove minChromeExtVersion (deprecated)
  3537. var updateRequired
  3538. = isUpdateRequired(
  3539. (options.desktopSharingChromeMinExtVersion ||
  3540. options.minChromeExtVersion),
  3541. extVersion);
  3542. callback(!updateRequired, updateRequired);
  3543. }
  3544. );
  3545. }
  3546. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3547. // Sends 'getStream' msg to the extension.
  3548. // Extension id must be defined in the config.
  3549. chrome.runtime.sendMessage(
  3550. //TODO: remove chromeExtensionId (deprecated)
  3551. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3552. {
  3553. getStream: true,
  3554. //TODO: remove desktopSharingSources (deprecated).
  3555. sources: (options.desktopSharingChromeSources ||
  3556. options.desktopSharingSources)
  3557. },
  3558. function (response) {
  3559. if (!response) {
  3560. failCallback(chrome.runtime.lastError);
  3561. return;
  3562. }
  3563. logger.log("Response from extension: " + response);
  3564. if (response.streamId) {
  3565. GUM(
  3566. ['desktop'],
  3567. function (stream) {
  3568. streamCallback(stream);
  3569. },
  3570. failCallback,
  3571. {desktopStream: response.streamId});
  3572. } else {
  3573. failCallback("Extension failed to get the stream");
  3574. }
  3575. }
  3576. );
  3577. }
  3578. /**
  3579. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3580. * config.js to support inline installs. Host site must be selected as main
  3581. * website of published extension.
  3582. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3583. */
  3584. function initInlineInstalls(options)
  3585. {
  3586. $("link[rel=chrome-webstore-item]").attr("href",
  3587. getWebStoreInstallUrl(options));
  3588. }
  3589. function initChromeExtension(options) {
  3590. // Initialize Chrome extension inline installs
  3591. initInlineInstalls(options);
  3592. // Check if extension is installed
  3593. checkChromeExtInstalled(function (installed, updateRequired) {
  3594. chromeExtInstalled = installed;
  3595. chromeExtUpdateRequired = updateRequired;
  3596. logger.info(
  3597. "Chrome extension installed: " + chromeExtInstalled +
  3598. " updateRequired: " + chromeExtUpdateRequired);
  3599. }, options);
  3600. }
  3601. /**
  3602. * Starts the detection of an installed jidesha extension for firefox.
  3603. * @param options supports "desktopSharingFirefoxDisabled",
  3604. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3605. */
  3606. function initFirefoxExtensionDetection(options) {
  3607. if (options.desktopSharingFirefoxDisabled) {
  3608. return;
  3609. }
  3610. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3611. return;
  3612. if (!options.desktopSharingFirefoxExtId) {
  3613. firefoxExtInstalled = false;
  3614. return;
  3615. }
  3616. var img = document.createElement('img');
  3617. img.onload = function(){
  3618. logger.log("Detected firefox screen sharing extension.");
  3619. firefoxExtInstalled = true;
  3620. };
  3621. img.onerror = function(){
  3622. logger.log("Detected lack of firefox screen sharing extension.");
  3623. firefoxExtInstalled = false;
  3624. };
  3625. // The jidesha extension exposes an empty image file under the url:
  3626. // "chrome://EXT_ID/content/DOMAIN.png"
  3627. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3628. // DOMAIN is a domain whitelisted by the extension.
  3629. var src = "chrome://" +
  3630. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3631. "/content/" + document.location.hostname + ".png";
  3632. img.setAttribute('src', src);
  3633. }
  3634. module.exports = ScreenObtainer;
  3635. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3636. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":139,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":49}],20:[function(require,module,exports){
  3637. (function (__filename){
  3638. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3639. var console = require("jitsi-meet-logger").getLogger(__filename);
  3640. // Adapter's interface.
  3641. var AdapterJS = AdapterJS || {};
  3642. // Browserify compatibility
  3643. if(typeof exports !== 'undefined') {
  3644. module.exports = AdapterJS;
  3645. }
  3646. AdapterJS.options = AdapterJS.options || {};
  3647. // uncomment to get virtual webcams
  3648. // AdapterJS.options.getAllCams = true;
  3649. // uncomment to prevent the install prompt when the plugin in not yet installed
  3650. // AdapterJS.options.hidePluginInstallPrompt = true;
  3651. // AdapterJS version
  3652. AdapterJS.VERSION = '0.12.3';
  3653. // This function will be called when the WebRTC API is ready to be used
  3654. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3655. // the plugin
  3656. // You may Override this function to synchronise the start of your application
  3657. // with the WebRTC API being ready.
  3658. // If you decide not to override use this synchronisation, it may result in
  3659. // an extensive CPU usage on the plugin start (once per tab loaded)
  3660. // Params:
  3661. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3662. //
  3663. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3664. // The WebRTC API is ready.
  3665. // Override me and do whatever you want here
  3666. };
  3667. // Sets a callback function to be called when the WebRTC interface is ready.
  3668. // The first argument is the function to callback.\
  3669. // Throws an error if the first argument is not a function
  3670. AdapterJS.webRTCReady = function (callback) {
  3671. if (typeof callback !== 'function') {
  3672. throw new Error('Callback provided is not a function');
  3673. }
  3674. if (true === AdapterJS.onwebrtcreadyDone) {
  3675. // All WebRTC interfaces are ready, just call the callback
  3676. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3677. } else {
  3678. // will be triggered automatically when your browser/plugin is ready.
  3679. AdapterJS.onwebrtcready = callback;
  3680. }
  3681. };
  3682. // Plugin namespace
  3683. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3684. // The object to store plugin information
  3685. AdapterJS.WebRTCPlugin.pluginInfo = {
  3686. prefix : 'Tem',
  3687. plugName : 'TemWebRTCPlugin',
  3688. pluginId : 'plugin0',
  3689. type : 'application/x-temwebrtcplugin',
  3690. onload : '__TemWebRTCReady0',
  3691. portalLink : 'http://skylink.io/plugin/',
  3692. downloadLink : null, //set below
  3693. companyName: 'Temasys'
  3694. };
  3695. if(!!navigator.platform.match(/^Mac/i)) {
  3696. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3697. }
  3698. else if(!!navigator.platform.match(/^Win/i)) {
  3699. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3700. }
  3701. AdapterJS.WebRTCPlugin.TAGS = {
  3702. NONE : 'none',
  3703. AUDIO : 'audio',
  3704. VIDEO : 'video'
  3705. };
  3706. // Unique identifier of each opened page
  3707. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3708. // Use this whenever you want to call the plugin.
  3709. AdapterJS.WebRTCPlugin.plugin = null;
  3710. // Set log level for the plugin once it is ready.
  3711. // The different values are
  3712. // This is an asynchronous function that will run when the plugin is ready
  3713. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3714. // Defines webrtc's JS interface according to the plugin's implementation.
  3715. // Define plugin Browsers as WebRTC Interface.
  3716. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3717. // This function detects whether or not a plugin is installed.
  3718. // Checks if Not IE (firefox, for example), else if it's IE,
  3719. // we're running IE and do something. If not it is not supported.
  3720. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3721. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3722. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3723. // Inject the HTML DOM object element into the page.
  3724. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3725. // States of readiness that the plugin goes through when
  3726. // being injected and stated
  3727. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3728. NONE : 0, // no plugin use
  3729. INITIALIZING : 1, // Detected need for plugin
  3730. INJECTING : 2, // Injecting plugin
  3731. INJECTED: 3, // Plugin element injected but not usable yet
  3732. READY: 4 // Plugin ready to be used
  3733. };
  3734. // Current state of the plugin. You cannot use the plugin before this is
  3735. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3736. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3737. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3738. // Used to make sure AdapterJS.onwebrtcready is only called once
  3739. AdapterJS.onwebrtcreadyDone = false;
  3740. // Log levels for the plugin.
  3741. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3742. /*
  3743. Log outputs are prefixed in some cases.
  3744. INFO: Information reported by the plugin.
  3745. ERROR: Errors originating from within the plugin.
  3746. WEBRTC: Error originating from within the libWebRTC library
  3747. */
  3748. // From the least verbose to the most verbose
  3749. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3750. NONE : 'NONE',
  3751. ERROR : 'ERROR',
  3752. WARNING : 'WARNING',
  3753. INFO: 'INFO',
  3754. VERBOSE: 'VERBOSE',
  3755. SENSITIVE: 'SENSITIVE'
  3756. };
  3757. // Does a waiting check before proceeding to load the plugin.
  3758. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3759. // This methid will use an interval to wait for the plugin to be ready.
  3760. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3761. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3762. // This function will be called when plugin is ready. It sends necessary
  3763. // details to the plugin.
  3764. // The function will wait for the document to be ready and the set the
  3765. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3766. // indicating that it can start being requested.
  3767. // This function is not in the IE/Safari condition brackets so that
  3768. // TemPluginLoaded function might be called on Chrome/Firefox.
  3769. // This function is the only private function that is not encapsulated to
  3770. // allow the plugin method to be called.
  3771. __TemWebRTCReady0 = function () {
  3772. if (document.readyState === 'complete') {
  3773. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3774. AdapterJS.maybeThroughWebRTCReady();
  3775. } else {
  3776. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3777. if (document.readyState === 'complete') {
  3778. // TODO: update comments, we wait for the document to be ready
  3779. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3780. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3781. AdapterJS.maybeThroughWebRTCReady();
  3782. }
  3783. }, 100);
  3784. }
  3785. };
  3786. AdapterJS.maybeThroughWebRTCReady = function() {
  3787. if (!AdapterJS.onwebrtcreadyDone) {
  3788. AdapterJS.onwebrtcreadyDone = true;
  3789. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3790. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3791. }
  3792. }
  3793. };
  3794. // Text namespace
  3795. AdapterJS.TEXT = {
  3796. PLUGIN: {
  3797. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3798. 'to work on this browser.',
  3799. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3800. BUTTON: 'Install Now'
  3801. },
  3802. REFRESH: {
  3803. REQUIRE_REFRESH: 'Please refresh page',
  3804. BUTTON: 'Refresh Page'
  3805. }
  3806. };
  3807. // The result of ice connection states.
  3808. // - starting: Ice connection is starting.
  3809. // - checking: Ice connection is checking.
  3810. // - connected Ice connection is connected.
  3811. // - completed Ice connection is connected.
  3812. // - done Ice connection has been completed.
  3813. // - disconnected Ice connection has been disconnected.
  3814. // - failed Ice connection has failed.
  3815. // - closed Ice connection is closed.
  3816. AdapterJS._iceConnectionStates = {
  3817. starting : 'starting',
  3818. checking : 'checking',
  3819. connected : 'connected',
  3820. completed : 'connected',
  3821. done : 'completed',
  3822. disconnected : 'disconnected',
  3823. failed : 'failed',
  3824. closed : 'closed'
  3825. };
  3826. //The IceConnection states that has been fired for each peer.
  3827. AdapterJS._iceConnectionFiredStates = [];
  3828. // Check if WebRTC Interface is defined.
  3829. AdapterJS.isDefined = null;
  3830. // This function helps to retrieve the webrtc detected browser information.
  3831. // This sets:
  3832. // - webrtcDetectedBrowser: The browser agent name.
  3833. // - webrtcDetectedVersion: The browser version.
  3834. // - webrtcDetectedType: The types of webRTC support.
  3835. // - 'moz': Mozilla implementation of webRTC.
  3836. // - 'webkit': WebKit implementation of webRTC.
  3837. // - 'plugin': Using the plugin implementation.
  3838. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3839. var hasMatch, checkMatch = navigator.userAgent.match(
  3840. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3841. if (/trident/i.test(checkMatch[1])) {
  3842. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3843. webrtcDetectedBrowser = 'IE';
  3844. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3845. } else if (checkMatch[1] === 'Chrome') {
  3846. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3847. if (hasMatch !== null) {
  3848. webrtcDetectedBrowser = 'opera';
  3849. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3850. }
  3851. }
  3852. if (navigator.userAgent.indexOf('Safari')) {
  3853. if (typeof InstallTrigger !== 'undefined') {
  3854. webrtcDetectedBrowser = 'firefox';
  3855. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3856. webrtcDetectedBrowser = 'IE';
  3857. } else if (
  3858. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3859. webrtcDetectedBrowser = 'safari';
  3860. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3861. webrtcDetectedBrowser = 'opera';
  3862. } else if (!!window.chrome) {
  3863. webrtcDetectedBrowser = 'chrome';
  3864. }
  3865. }
  3866. if (!webrtcDetectedBrowser) {
  3867. webrtcDetectedVersion = checkMatch[1];
  3868. }
  3869. if (!webrtcDetectedVersion) {
  3870. try {
  3871. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3872. [navigator.appName, navigator.appVersion, '-?'];
  3873. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3874. checkMatch.splice(1, 1, hasMatch[1]);
  3875. }
  3876. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3877. } catch (error) { }
  3878. }
  3879. };
  3880. // To fix configuration as some browsers does not support
  3881. // the 'urls' attribute.
  3882. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3883. if (pcConfig === null) {
  3884. return;
  3885. }
  3886. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3887. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3888. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3889. delete pcConfig.iceServers[i].urls;
  3890. }
  3891. }
  3892. };
  3893. AdapterJS.addEvent = function(elem, evnt, func) {
  3894. if (elem.addEventListener) { // W3C DOM
  3895. elem.addEventListener(evnt, func, false);
  3896. } else if (elem.attachEvent) {// OLD IE DOM
  3897. elem.attachEvent('on'+evnt, func);
  3898. } else { // No much to do
  3899. elem[evnt] = func;
  3900. }
  3901. };
  3902. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3903. // only inject once the page is ready
  3904. if (document.readyState !== 'complete') {
  3905. return;
  3906. }
  3907. var w = window;
  3908. var i = document.createElement('iframe');
  3909. i.style.position = 'fixed';
  3910. i.style.top = '-41px';
  3911. i.style.left = 0;
  3912. i.style.right = 0;
  3913. i.style.width = '100%';
  3914. i.style.height = '40px';
  3915. i.style.backgroundColor = '#ffffe1';
  3916. i.style.border = 'none';
  3917. i.style.borderBottom = '1px solid #888888';
  3918. i.style.zIndex = '9999999';
  3919. if(typeof i.style.webkitTransition === 'string') {
  3920. i.style.webkitTransition = 'all .5s ease-out';
  3921. } else if(typeof i.style.transition === 'string') {
  3922. i.style.transition = 'all .5s ease-out';
  3923. }
  3924. document.body.appendChild(i);
  3925. c = (i.contentWindow) ? i.contentWindow :
  3926. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3927. c.document.open();
  3928. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3929. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3930. 'middle; cursor: default;">' + text + '</span>');
  3931. if(buttonText && buttonLink) {
  3932. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3933. c.document.close();
  3934. // On click on okay
  3935. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3936. if (!!displayRefreshBar) {
  3937. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3938. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3939. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3940. }
  3941. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3942. e.preventDefault();
  3943. try {
  3944. event.cancelBubble = true;
  3945. } catch(error) { }
  3946. var pluginInstallInterval = setInterval(function(){
  3947. if(! isIE) {
  3948. navigator.plugins.refresh(false);
  3949. }
  3950. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3951. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3952. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3953. function() { // plugin now installed
  3954. clearInterval(pluginInstallInterval);
  3955. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3956. },
  3957. function() {
  3958. // still no plugin detected, nothing to do
  3959. });
  3960. } , 500);
  3961. });
  3962. // On click on Cancel
  3963. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3964. w.document.body.removeChild(i);
  3965. });
  3966. } else {
  3967. c.document.close();
  3968. }
  3969. setTimeout(function() {
  3970. if(typeof i.style.webkitTransform === 'string') {
  3971. i.style.webkitTransform = 'translateY(40px)';
  3972. } else if(typeof i.style.transform === 'string') {
  3973. i.style.transform = 'translateY(40px)';
  3974. } else {
  3975. i.style.top = '0px';
  3976. }
  3977. }, 300);
  3978. };
  3979. // -----------------------------------------------------------
  3980. // Detected webrtc implementation. Types are:
  3981. // - 'moz': Mozilla implementation of webRTC.
  3982. // - 'webkit': WebKit implementation of webRTC.
  3983. // - 'plugin': Using the plugin implementation.
  3984. webrtcDetectedType = null;
  3985. // Detected webrtc datachannel support. Types are:
  3986. // - 'SCTP': SCTP datachannel support.
  3987. // - 'RTP': RTP datachannel support.
  3988. webrtcDetectedDCSupport = null;
  3989. // Set the settings for creating DataChannels, MediaStream for
  3990. // Cross-browser compability.
  3991. // - This is only for SCTP based support browsers.
  3992. // the 'urls' attribute.
  3993. checkMediaDataChannelSettings =
  3994. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  3995. if (typeof callback !== 'function') {
  3996. return;
  3997. }
  3998. var beOfferer = true;
  3999. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  4000. // Nightly version does not require MozDontOfferDataChannel for interop
  4001. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  4002. var isPeerFirefox = peerBrowserAgent === 'firefox';
  4003. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  4004. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  4005. // Resends an updated version of constraints for MozDataChannel to work
  4006. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  4007. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  4008. try {
  4009. delete constraints.mandatory.MozDontOfferDataChannel;
  4010. } catch (error) {
  4011. console.error('Failed deleting MozDontOfferDataChannel');
  4012. console.error(error);
  4013. }
  4014. } else if ((isLocalFirefox && !isPeerFirefox)) {
  4015. constraints.mandatory.MozDontOfferDataChannel = true;
  4016. }
  4017. if (!isLocalFirefox) {
  4018. // temporary measure to remove Moz* constraints in non Firefox browsers
  4019. for (var prop in constraints.mandatory) {
  4020. if (constraints.mandatory.hasOwnProperty(prop)) {
  4021. if (prop.indexOf('Moz') !== -1) {
  4022. delete constraints.mandatory[prop];
  4023. }
  4024. }
  4025. }
  4026. }
  4027. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  4028. // interopability of the media stream
  4029. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4030. beOfferer = false;
  4031. }
  4032. callback(beOfferer, constraints);
  4033. };
  4034. // Handles the differences for all browsers ice connection state output.
  4035. // - Tested outcomes are:
  4036. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4037. // - Chrome (answerer) : 'checking' > 'connected'
  4038. // - Firefox (offerer) : 'checking' > 'connected'
  4039. // - Firefox (answerer): 'checking' > 'connected'
  4040. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4041. if (typeof callback !== 'function') {
  4042. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4043. return;
  4044. }
  4045. peerId = (peerId) ? peerId : 'peer';
  4046. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4047. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4048. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4049. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4050. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4051. }
  4052. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4053. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4054. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4055. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4056. setTimeout(function () {
  4057. AdapterJS._iceConnectionFiredStates[peerId]
  4058. .push(AdapterJS._iceConnectionStates.done);
  4059. callback(AdapterJS._iceConnectionStates.done);
  4060. }, 1000);
  4061. }
  4062. callback(iceConnectionState);
  4063. }
  4064. return;
  4065. };
  4066. // Firefox:
  4067. // - Creates iceServer from the url for Firefox.
  4068. // - Create iceServer with stun url.
  4069. // - Create iceServer with turn url.
  4070. // - Ignore the transport parameter from TURN url for FF version <=27.
  4071. // - Return null for createIceServer if transport=tcp.
  4072. // - FF 27 and above supports transport parameters in TURN url,
  4073. // - So passing in the full url to create iceServer.
  4074. // Chrome:
  4075. // - Creates iceServer from the url for Chrome M33 and earlier.
  4076. // - Create iceServer with stun url.
  4077. // - Chrome M28 & above uses below TURN format.
  4078. // Plugin:
  4079. // - Creates Ice Server for Plugin Browsers
  4080. // - If Stun - Create iceServer with stun url.
  4081. // - Else - Create iceServer with turn url
  4082. // - This is a WebRTC Function
  4083. createIceServer = null;
  4084. // Firefox:
  4085. // - Creates IceServers for Firefox
  4086. // - Use .url for FireFox.
  4087. // - Multiple Urls support
  4088. // Chrome:
  4089. // - Creates iceServers from the urls for Chrome M34 and above.
  4090. // - .urls is supported since Chrome M34.
  4091. // - Multiple Urls support
  4092. // Plugin:
  4093. // - Creates Ice Servers for Plugin Browsers
  4094. // - Multiple Urls support
  4095. // - This is a WebRTC Function
  4096. createIceServers = null;
  4097. //------------------------------------------------------------
  4098. //The RTCPeerConnection object.
  4099. RTCPeerConnection = null;
  4100. // Creates RTCSessionDescription object for Plugin Browsers
  4101. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4102. RTCSessionDescription : null;
  4103. // Creates RTCIceCandidate object for Plugin Browsers
  4104. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4105. RTCIceCandidate : null;
  4106. // Get UserMedia (only difference is the prefix).
  4107. // Code from Adam Barth.
  4108. getUserMedia = null;
  4109. // Attach a media stream to an element.
  4110. attachMediaStream = null;
  4111. // Re-attach a media stream to an element.
  4112. reattachMediaStream = null;
  4113. // Detected browser agent name. Types are:
  4114. // - 'firefox': Firefox browser.
  4115. // - 'chrome': Chrome browser.
  4116. // - 'opera': Opera browser.
  4117. // - 'safari': Safari browser.
  4118. // - 'IE' - Internet Explorer browser.
  4119. webrtcDetectedBrowser = null;
  4120. // Detected browser version.
  4121. webrtcDetectedVersion = null;
  4122. // Check for browser types and react accordingly
  4123. if (navigator.mozGetUserMedia) {
  4124. webrtcDetectedBrowser = 'firefox';
  4125. webrtcDetectedVersion = parseInt(navigator
  4126. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4127. webrtcDetectedType = 'moz';
  4128. webrtcDetectedDCSupport = 'SCTP';
  4129. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4130. AdapterJS.maybeFixConfiguration(pcConfig);
  4131. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4132. };
  4133. // The RTCSessionDescription object.
  4134. RTCSessionDescription = mozRTCSessionDescription;
  4135. window.RTCSessionDescription = RTCSessionDescription;
  4136. // The RTCIceCandidate object.
  4137. RTCIceCandidate = mozRTCIceCandidate;
  4138. window.RTCIceCandidate = RTCIceCandidate;
  4139. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4140. navigator.getUserMedia = window.getUserMedia;
  4141. // Shim for MediaStreamTrack.getSources.
  4142. MediaStreamTrack.getSources = function(successCb) {
  4143. setTimeout(function() {
  4144. var infos = [
  4145. { kind: 'audio', id: 'default', label:'', facing:'' },
  4146. { kind: 'video', id: 'default', label:'', facing:'' }
  4147. ];
  4148. successCb(infos);
  4149. }, 0);
  4150. };
  4151. createIceServer = function (url, username, password) {
  4152. var iceServer = null;
  4153. var url_parts = url.split(':');
  4154. if (url_parts[0].indexOf('stun') === 0) {
  4155. iceServer = { url : url };
  4156. } else if (url_parts[0].indexOf('turn') === 0) {
  4157. if (webrtcDetectedVersion < 27) {
  4158. var turn_url_parts = url.split('?');
  4159. if (turn_url_parts.length === 1 ||
  4160. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4161. iceServer = {
  4162. url : turn_url_parts[0],
  4163. credential : password,
  4164. username : username
  4165. };
  4166. }
  4167. } else {
  4168. iceServer = {
  4169. url : url,
  4170. credential : password,
  4171. username : username
  4172. };
  4173. }
  4174. }
  4175. return iceServer;
  4176. };
  4177. createIceServers = function (urls, username, password) {
  4178. var iceServers = [];
  4179. for (var i = 0; i < urls.length; i++) {
  4180. var iceServer = createIceServer(urls[i], username, password);
  4181. if (iceServer !== null) {
  4182. iceServers.push(iceServer);
  4183. }
  4184. }
  4185. return iceServers;
  4186. };
  4187. attachMediaStream = function (element, stream) {
  4188. element.mozSrcObject = stream;
  4189. if (stream !== null)
  4190. element.play();
  4191. return element;
  4192. };
  4193. reattachMediaStream = function (to, from) {
  4194. to.mozSrcObject = from.mozSrcObject;
  4195. to.play();
  4196. return to;
  4197. };
  4198. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4199. if (!callback) {
  4200. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4201. ': 1 argument required, but only 0 present.');
  4202. }
  4203. return callback([]);
  4204. };
  4205. // Fake get{Video,Audio}Tracks
  4206. if (!MediaStream.prototype.getVideoTracks) {
  4207. MediaStream.prototype.getVideoTracks = function () {
  4208. return [];
  4209. };
  4210. }
  4211. if (!MediaStream.prototype.getAudioTracks) {
  4212. MediaStream.prototype.getAudioTracks = function () {
  4213. return [];
  4214. };
  4215. }
  4216. AdapterJS.maybeThroughWebRTCReady();
  4217. } else if (navigator.webkitGetUserMedia) {
  4218. webrtcDetectedBrowser = 'chrome';
  4219. webrtcDetectedType = 'webkit';
  4220. webrtcDetectedVersion = parseInt(navigator
  4221. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4222. // check if browser is opera 20+
  4223. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4224. if (checkIfOpera !== null) {
  4225. webrtcDetectedBrowser = 'opera';
  4226. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4227. }
  4228. // check browser datachannel support
  4229. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4230. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4231. webrtcDetectedDCSupport = 'SCTP';
  4232. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4233. webrtcDetectedVersion > 24) {
  4234. webrtcDetectedDCSupport = 'RTP';
  4235. } else {
  4236. webrtcDetectedDCSupport = '';
  4237. }
  4238. createIceServer = function (url, username, password) {
  4239. var iceServer = null;
  4240. var url_parts = url.split(':');
  4241. if (url_parts[0].indexOf('stun') === 0) {
  4242. iceServer = { 'url' : url };
  4243. } else if (url_parts[0].indexOf('turn') === 0) {
  4244. iceServer = {
  4245. 'url' : url,
  4246. 'credential' : password,
  4247. 'username' : username
  4248. };
  4249. }
  4250. return iceServer;
  4251. };
  4252. createIceServers = function (urls, username, password) {
  4253. var iceServers = [];
  4254. if (webrtcDetectedVersion >= 34) {
  4255. iceServers = {
  4256. 'urls' : urls,
  4257. 'credential' : password,
  4258. 'username' : username
  4259. };
  4260. } else {
  4261. for (var i = 0; i < urls.length; i++) {
  4262. var iceServer = createIceServer(urls[i], username, password);
  4263. if (iceServer !== null) {
  4264. iceServers.push(iceServer);
  4265. }
  4266. }
  4267. }
  4268. return iceServers;
  4269. };
  4270. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4271. if (webrtcDetectedVersion < 34) {
  4272. AdapterJS.maybeFixConfiguration(pcConfig);
  4273. }
  4274. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4275. };
  4276. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4277. navigator.getUserMedia = window.getUserMedia;
  4278. attachMediaStream = function (element, stream) {
  4279. if (typeof element.srcObject !== 'undefined') {
  4280. element.srcObject = stream;
  4281. } else if (typeof element.mozSrcObject !== 'undefined') {
  4282. element.mozSrcObject = stream;
  4283. } else if (typeof element.src !== 'undefined') {
  4284. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4285. } else {
  4286. console.log('Error attaching stream to element.');
  4287. }
  4288. return element;
  4289. };
  4290. reattachMediaStream = function (to, from) {
  4291. to.src = from.src;
  4292. return to;
  4293. };
  4294. AdapterJS.maybeThroughWebRTCReady();
  4295. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4296. /Edge\/(\d+).(\d+)$/)) {
  4297. webrtcDetectedBrowser = 'edge';
  4298. webrtcDetectedVersion =
  4299. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4300. // the minimum version still supported by adapter.
  4301. webrtcMinimumVersion = 12;
  4302. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4303. attachMediaStream = function(element, stream) {
  4304. element.srcObject = stream;
  4305. return element;
  4306. };
  4307. reattachMediaStream = function(to, from) {
  4308. to.srcObject = from.srcObject;
  4309. return to;
  4310. };
  4311. AdapterJS.maybeThroughWebRTCReady();
  4312. } else { // TRY TO USE PLUGIN
  4313. // IE 9 is not offering an implementation of console.log until you open a console
  4314. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4315. /* jshint -W020 */
  4316. console = {} || console;
  4317. // Implemented based on console specs from MDN
  4318. // You may override these functions
  4319. console.log = function (arg) {};
  4320. console.info = function (arg) {};
  4321. console.error = function (arg) {};
  4322. console.dir = function (arg) {};
  4323. console.exception = function (arg) {};
  4324. console.trace = function (arg) {};
  4325. console.warn = function (arg) {};
  4326. console.count = function (arg) {};
  4327. console.debug = function (arg) {};
  4328. console.count = function (arg) {};
  4329. console.time = function (arg) {};
  4330. console.timeEnd = function (arg) {};
  4331. console.group = function (arg) {};
  4332. console.groupCollapsed = function (arg) {};
  4333. console.groupEnd = function (arg) {};
  4334. /* jshint +W020 */
  4335. }
  4336. webrtcDetectedType = 'plugin';
  4337. webrtcDetectedDCSupport = 'plugin';
  4338. AdapterJS.parseWebrtcDetectedBrowser();
  4339. isIE = webrtcDetectedBrowser === 'IE';
  4340. /* jshint -W035 */
  4341. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4342. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4343. /* empty because it needs to prevent the function from running. */
  4344. }
  4345. };
  4346. /* jshint +W035 */
  4347. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4348. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4349. // Call immediately if possible
  4350. // Once the plugin is set, the code will always take this path
  4351. callback();
  4352. } else {
  4353. // otherwise start a 100ms interval
  4354. var checkPluginReadyState = setInterval(function () {
  4355. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4356. clearInterval(checkPluginReadyState);
  4357. callback();
  4358. }
  4359. }, 100);
  4360. }
  4361. };
  4362. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4363. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4364. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4365. });
  4366. };
  4367. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4368. // only inject once the page is ready
  4369. if (document.readyState !== 'complete') {
  4370. return;
  4371. }
  4372. // Prevent multiple injections
  4373. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4374. return;
  4375. }
  4376. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4377. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4378. var frag = document.createDocumentFragment();
  4379. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4380. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4381. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4382. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4383. '<param name="pluginId" value="' +
  4384. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4385. '<param name="windowless" value="false" /> ' +
  4386. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4387. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4388. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4389. // uncomment to be able to use virtual cams
  4390. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4391. '</object>';
  4392. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4393. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4394. }
  4395. document.body.appendChild(frag);
  4396. // Need to re-fetch the plugin
  4397. AdapterJS.WebRTCPlugin.plugin =
  4398. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4399. } else {
  4400. // Load Plugin
  4401. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4402. AdapterJS.WebRTCPlugin.plugin.id =
  4403. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4404. // IE will only start the plugin if it's ACTUALLY visible
  4405. if (isIE) {
  4406. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4407. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4408. } else { // The size of the plugin on Safari should be 0x0px
  4409. // so that the autorisation prompt is at the top
  4410. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4411. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4412. }
  4413. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4414. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4415. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4416. '<param name="pluginId" value="' +
  4417. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4418. '<param name="windowless" value="false" /> ' +
  4419. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4420. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4421. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4422. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4423. }
  4424. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4425. };
  4426. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4427. function (comName, plugName, installedCb, notInstalledCb) {
  4428. if (!isIE) {
  4429. var pluginArray = navigator.plugins;
  4430. for (var i = 0; i < pluginArray.length; i++) {
  4431. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4432. installedCb();
  4433. return;
  4434. }
  4435. }
  4436. notInstalledCb();
  4437. } else {
  4438. try {
  4439. var axo = new ActiveXObject(comName + '.' + plugName);
  4440. } catch (e) {
  4441. notInstalledCb();
  4442. return;
  4443. }
  4444. installedCb();
  4445. }
  4446. };
  4447. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4448. if (AdapterJS.WebRTCPlugin.pluginState ===
  4449. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4450. console.error("AdapterJS - WebRTC interface has already been defined");
  4451. return;
  4452. }
  4453. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4454. AdapterJS.isDefined = function (variable) {
  4455. return variable !== null && variable !== undefined;
  4456. };
  4457. createIceServer = function (url, username, password) {
  4458. var iceServer = null;
  4459. var url_parts = url.split(':');
  4460. if (url_parts[0].indexOf('stun') === 0) {
  4461. iceServer = {
  4462. 'url' : url,
  4463. 'hasCredentials' : false
  4464. };
  4465. } else if (url_parts[0].indexOf('turn') === 0) {
  4466. iceServer = {
  4467. 'url' : url,
  4468. 'hasCredentials' : true,
  4469. 'credential' : password,
  4470. 'username' : username
  4471. };
  4472. }
  4473. return iceServer;
  4474. };
  4475. createIceServers = function (urls, username, password) {
  4476. var iceServers = [];
  4477. for (var i = 0; i < urls.length; ++i) {
  4478. iceServers.push(createIceServer(urls[i], username, password));
  4479. }
  4480. return iceServers;
  4481. };
  4482. RTCSessionDescription = function (info) {
  4483. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4484. return AdapterJS.WebRTCPlugin.plugin.
  4485. ConstructSessionDescription(info.type, info.sdp);
  4486. };
  4487. RTCPeerConnection = function (servers, constraints) {
  4488. var iceServers = null;
  4489. if (servers) {
  4490. iceServers = servers.iceServers;
  4491. for (var i = 0; i < iceServers.length; i++) {
  4492. if (iceServers[i].urls && !iceServers[i].url) {
  4493. iceServers[i].url = iceServers[i].urls;
  4494. }
  4495. iceServers[i].hasCredentials = AdapterJS.
  4496. isDefined(iceServers[i].username) &&
  4497. AdapterJS.isDefined(iceServers[i].credential);
  4498. }
  4499. }
  4500. var mandatory = (constraints && constraints.mandatory) ?
  4501. constraints.mandatory : null;
  4502. var optional = (constraints && constraints.optional) ?
  4503. constraints.optional : null;
  4504. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4505. return AdapterJS.WebRTCPlugin.plugin.
  4506. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4507. iceServers, mandatory, optional);
  4508. };
  4509. MediaStreamTrack = {};
  4510. MediaStreamTrack.getSources = function (callback) {
  4511. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4512. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4513. });
  4514. };
  4515. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4516. constraints.audio = constraints.audio || false;
  4517. constraints.video = constraints.video || false;
  4518. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4519. AdapterJS.WebRTCPlugin.plugin.
  4520. getUserMedia(constraints, successCallback, failureCallback);
  4521. });
  4522. };
  4523. window.navigator.getUserMedia = window.getUserMedia;
  4524. attachMediaStream = function (element, stream) {
  4525. if (!element || !element.parentNode) {
  4526. return;
  4527. }
  4528. var streamId;
  4529. if (stream === null) {
  4530. streamId = '';
  4531. } else {
  4532. if (typeof stream.enableSoundTracks !== 'undefined') {
  4533. stream.enableSoundTracks(true);
  4534. }
  4535. streamId = stream.id;
  4536. }
  4537. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4538. var nodeName = element.nodeName.toLowerCase();
  4539. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4540. var tag;
  4541. switch(nodeName) {
  4542. case 'audio':
  4543. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4544. break;
  4545. case 'video':
  4546. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4547. break;
  4548. default:
  4549. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4550. }
  4551. var frag = document.createDocumentFragment();
  4552. var temp = document.createElement('div');
  4553. var classHTML = '';
  4554. if (element.className) {
  4555. classHTML = 'class="' + element.className + '" ';
  4556. } else if (element.attributes && element.attributes['class']) {
  4557. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4558. }
  4559. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4560. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4561. '<param name="pluginId" value="' + elementId + '" /> ' +
  4562. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4563. '<param name="windowless" value="true" /> ' +
  4564. '<param name="streamId" value="' + streamId + '" /> ' +
  4565. '<param name="tag" value="' + tag + '" /> ' +
  4566. '</object>';
  4567. while (temp.firstChild) {
  4568. frag.appendChild(temp.firstChild);
  4569. }
  4570. var height = '';
  4571. var width = '';
  4572. if (element.clientWidth || element.clientHeight) {
  4573. width = element.clientWidth;
  4574. height = element.clientHeight;
  4575. }
  4576. else if (element.width || element.height) {
  4577. width = element.width;
  4578. height = element.height;
  4579. }
  4580. element.parentNode.insertBefore(frag, element);
  4581. frag = document.getElementById(elementId);
  4582. frag.width = width;
  4583. frag.height = height;
  4584. element.parentNode.removeChild(element);
  4585. } else { // already an <object> tag, just change the stream id
  4586. var children = element.children;
  4587. for (var i = 0; i !== children.length; ++i) {
  4588. if (children[i].name === 'streamId') {
  4589. children[i].value = streamId;
  4590. break;
  4591. }
  4592. }
  4593. element.setStreamId(streamId);
  4594. }
  4595. var newElement = document.getElementById(elementId);
  4596. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4597. return newElement;
  4598. };
  4599. reattachMediaStream = function (to, from) {
  4600. var stream = null;
  4601. var children = from.children;
  4602. for (var i = 0; i !== children.length; ++i) {
  4603. if (children[i].name === 'streamId') {
  4604. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4605. stream = AdapterJS.WebRTCPlugin.plugin
  4606. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4607. break;
  4608. }
  4609. }
  4610. if (stream !== null) {
  4611. return attachMediaStream(to, stream);
  4612. } else {
  4613. console.log('Could not find the stream associated with this element');
  4614. }
  4615. };
  4616. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4617. properties = Object.getOwnPropertyNames( prototype );
  4618. for(prop in properties) {
  4619. propName = properties[prop];
  4620. if (typeof(propName.slice) === 'function') {
  4621. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4622. if (isIE) {
  4623. destElem.attachEvent(propName,srcElem[propName]);
  4624. } else {
  4625. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4626. }
  4627. } else {
  4628. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4629. }
  4630. }
  4631. }
  4632. var subPrototype = Object.getPrototypeOf(prototype)
  4633. if(subPrototype != null) {
  4634. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4635. }
  4636. }
  4637. RTCIceCandidate = function (candidate) {
  4638. if (!candidate.sdpMid) {
  4639. candidate.sdpMid = '';
  4640. }
  4641. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4642. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4643. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4644. );
  4645. };
  4646. // inject plugin
  4647. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4648. AdapterJS.WebRTCPlugin.injectPlugin();
  4649. };
  4650. // This function will be called if the plugin is needed (browser different
  4651. // from Chrome or Firefox), but the plugin is not installed.
  4652. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4653. function() {
  4654. AdapterJS.addEvent(document,
  4655. 'readystatechange',
  4656. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4657. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4658. };
  4659. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4660. if (AdapterJS.options.hidePluginInstallPrompt) {
  4661. return;
  4662. }
  4663. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4664. if(downloadLink) { // if download link
  4665. var popupString;
  4666. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4667. popupString = 'This website requires you to install the ' +
  4668. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4669. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4670. ' WebRTC Plugin</a>' +
  4671. ' to work on this browser.';
  4672. } else { // no portal link, just print a generic explanation
  4673. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4674. }
  4675. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4676. } else { // no download link, just print a generic explanation
  4677. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4678. }
  4679. };
  4680. // Try to detect the plugin and act accordingly
  4681. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4682. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4683. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4684. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4685. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4686. }
  4687. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4688. },{"jitsi-meet-logger":49}],21:[function(require,module,exports){
  4689. (function (__filename){
  4690. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4691. var UsernameGenerator = require('../util/UsernameGenerator');
  4692. function supportsLocalStorage() {
  4693. try {
  4694. return 'localStorage' in window && window.localStorage !== null;
  4695. } catch (e) {
  4696. logger.log("localstorage is not supported");
  4697. return false;
  4698. }
  4699. }
  4700. function generateUniqueId() {
  4701. function _p8() {
  4702. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4703. }
  4704. return _p8() + _p8() + _p8() + _p8();
  4705. }
  4706. function Settings(conferenceID) {
  4707. this.displayName = '';
  4708. this.userId;
  4709. this.confSettings = null;
  4710. this.conferenceID = conferenceID;
  4711. this.callStatsUserName;
  4712. if (supportsLocalStorage()) {
  4713. if(!window.localStorage.getItem(conferenceID))
  4714. this.confSettings = {};
  4715. else
  4716. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4717. if(!this.confSettings.jitsiMeetId) {
  4718. this.confSettings.jitsiMeetId = generateUniqueId();
  4719. logger.log("generated id",
  4720. this.confSettings.jitsiMeetId);
  4721. this.save();
  4722. }
  4723. if (!this.confSettings.callStatsUserName) {
  4724. this.confSettings.callStatsUserName
  4725. = UsernameGenerator.generateUsername();
  4726. logger.log('generated callstats uid',
  4727. this.confSettings.callStatsUserName);
  4728. this.save();
  4729. }
  4730. this.userId = this.confSettings.jitsiMeetId || '';
  4731. this.displayName = this.confSettings.displayname || '';
  4732. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4733. } else {
  4734. logger.log("local storage is not supported");
  4735. this.userId = generateUniqueId();
  4736. this.callStatsUserName = UsernameGenerator.generateUsername();
  4737. }
  4738. }
  4739. Settings.prototype.save = function () {
  4740. if(!supportsLocalStorage())
  4741. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4742. }
  4743. Settings.prototype.setDisplayName = function (newDisplayName) {
  4744. this.displayName = newDisplayName;
  4745. if(this.confSettings != null)
  4746. this.confSettings.displayname = displayName;
  4747. this.save();
  4748. return this.displayName;
  4749. }
  4750. Settings.prototype.getSettings = function () {
  4751. return {
  4752. displayName: this.displayName,
  4753. uid: this.userId
  4754. };
  4755. }
  4756. /**
  4757. * Returns fake username for callstats
  4758. * @returns {string} fake username for callstats
  4759. */
  4760. Settings.prototype.getCallStatsUserName = function () {
  4761. return this.callStatsUserName;
  4762. }
  4763. module.exports = Settings;
  4764. }).call(this,"/modules/settings/Settings.js")
  4765. },{"../util/UsernameGenerator":27,"jitsi-meet-logger":49}],22:[function(require,module,exports){
  4766. (function (__filename){
  4767. /* global $, Strophe, callstats */
  4768. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4769. var jsSHA = require('jssha');
  4770. var io = require('socket.io-client');
  4771. /**
  4772. * @const
  4773. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4774. */
  4775. var wrtcFuncNames = {
  4776. createOffer: "createOffer",
  4777. createAnswer: "createAnswer",
  4778. setLocalDescription: "setLocalDescription",
  4779. setRemoteDescription: "setRemoteDescription",
  4780. addIceCandidate: "addIceCandidate",
  4781. getUserMedia: "getUserMedia"
  4782. };
  4783. var callStats = null;
  4784. function initCallback (err, msg) {
  4785. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4786. }
  4787. /**
  4788. * Returns a function which invokes f in a try/catch block, logs any exception
  4789. * to the console, and then swallows it.
  4790. *
  4791. * @param f the function to invoke in a try/catch block
  4792. * @return a function which invokes f in a try/catch block, logs any exception
  4793. * to the console, and then swallows it
  4794. */
  4795. function _try_catch (f) {
  4796. return function () {
  4797. try {
  4798. f.apply(this, arguments);
  4799. } catch (e) {
  4800. logger.error(e);
  4801. }
  4802. };
  4803. }
  4804. /**
  4805. * Creates new CallStats instance that handles all callstats API calls.
  4806. * @param peerConnection {JingleSessionPC} the session object
  4807. * @param Settings {Settings} the settings instance. Declared in
  4808. * /modules/settings/Settings.js
  4809. * @param options {object} credentials for callstats.
  4810. */
  4811. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4812. try{
  4813. //check weather that should work with more than 1 peerconnection
  4814. if(!callStats) {
  4815. callStats = new callstats($, io, jsSHA);
  4816. } else {
  4817. return;
  4818. }
  4819. this.session = jingleSession;
  4820. this.peerconnection = jingleSession.peerconnection.peerconnection;
  4821. this.userID = Settings.getCallStatsUserName();
  4822. //FIXME: change it to something else (maybe roomName)
  4823. var location = window.location;
  4824. this.confID = location.hostname + location.pathname;
  4825. //userID is generated or given by the origin server
  4826. callStats.initialize(options.callStatsID,
  4827. options.callStatsSecret,
  4828. this.userID,
  4829. initCallback);
  4830. callStats.addNewFabric(this.peerconnection,
  4831. Strophe.getResourceFromJid(jingleSession.peerjid),
  4832. callStats.fabricUsage.multiplex,
  4833. this.confID,
  4834. this.pcCallback.bind(this));
  4835. } catch (e) {
  4836. // The callstats.io API failed to initialize (e.g. because its
  4837. // download failed to succeed in general or on time). Further
  4838. // attempts to utilize it cannot possibly succeed.
  4839. callStats = null;
  4840. logger.error(e);
  4841. }
  4842. // notify callstats about failures if there were any
  4843. if (CallStats.pendingErrors.length) {
  4844. CallStats.pendingErrors.forEach(function (error) {
  4845. CallStats._reportError.call(this, error.type, error.error,
  4846. error.pc);
  4847. }, this);
  4848. CallStats.pendingErrors.length = 0;
  4849. }
  4850. });
  4851. // some errors may happen before CallStats init
  4852. // in this case we accumulate them in this array
  4853. // and send them to callstats on init
  4854. CallStats.pendingErrors = [];
  4855. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  4856. if (!callStats) {
  4857. return;
  4858. }
  4859. logger.log("Monitoring status: "+ err + " msg: " + msg);
  4860. callStats.sendFabricEvent(this.peerconnection,
  4861. callStats.fabricEvent.fabricSetup, this.confID);
  4862. });
  4863. /**
  4864. * Notifies CallStats for mute events
  4865. * @param mute {boolean} true for muted and false for not muted
  4866. * @param type {String} "audio"/"video"
  4867. */
  4868. CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
  4869. if (!callStats) {
  4870. return;
  4871. }
  4872. var event = null;
  4873. if (type === "video") {
  4874. event = (mute? callStats.fabricEvent.videoPause :
  4875. callStats.fabricEvent.videoResume);
  4876. }
  4877. else {
  4878. event = (mute? callStats.fabricEvent.audioMute :
  4879. callStats.fabricEvent.audioUnmute);
  4880. }
  4881. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  4882. });
  4883. /**
  4884. * Notifies CallStats for connection setup errors
  4885. */
  4886. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  4887. if(!callStats) {
  4888. return;
  4889. }
  4890. callStats.sendFabricEvent(this.peerconnection,
  4891. callStats.fabricEvent.fabricTerminated, this.confID);
  4892. });
  4893. /**
  4894. * Notifies CallStats for connection setup errors
  4895. */
  4896. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  4897. if(!callStats) {
  4898. return;
  4899. }
  4900. callStats.sendFabricEvent(this.peerconnection,
  4901. callStats.fabricEvent.fabricSetupFailed, this.confID);
  4902. });
  4903. /**
  4904. * Sends the given feedback through CallStats.
  4905. *
  4906. * @param overallFeedback an integer between 1 and 5 indicating the
  4907. * user feedback
  4908. * @param detailedFeedback detailed feedback from the user. Not yet used
  4909. */
  4910. CallStats.prototype.sendFeedback = _try_catch(
  4911. function(overallFeedback, detailedFeedback) {
  4912. if(!callStats) {
  4913. return;
  4914. }
  4915. var feedbackString = '{"userID":"' + this.userID + '"' +
  4916. ', "overall":' + overallFeedback +
  4917. ', "comment": "' + detailedFeedback + '"}';
  4918. var feedbackJSON = JSON.parse(feedbackString);
  4919. callStats.sendUserFeedback(this.confID, feedbackJSON);
  4920. });
  4921. /**
  4922. * Reports an error to callstats.
  4923. *
  4924. * @param type the type of the error, which will be one of the wrtcFuncNames
  4925. * @param e the error
  4926. * @param pc the peerconnection
  4927. * @private
  4928. */
  4929. CallStats._reportError = function (type, e, pc) {
  4930. if (callStats) {
  4931. callStats.reportError(pc, this.confID, type, e);
  4932. } else {
  4933. CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
  4934. }
  4935. // else just ignore it
  4936. };
  4937. /**
  4938. * Notifies CallStats that getUserMedia failed.
  4939. *
  4940. * @param {Error} e error to send
  4941. * @param {CallStats} cs callstats instance related to the error (optional)
  4942. */
  4943. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  4944. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  4945. });
  4946. /**
  4947. * Notifies CallStats that peer connection failed to create offer.
  4948. *
  4949. * @param {Error} e error to send
  4950. * @param {RTCPeerConnection} pc connection on which failure occured.
  4951. * @param {CallStats} cs callstats instance related to the error (optional)
  4952. */
  4953. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  4954. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  4955. });
  4956. /**
  4957. * Notifies CallStats that peer connection failed to create answer.
  4958. *
  4959. * @param {Error} e error to send
  4960. * @param {RTCPeerConnection} pc connection on which failure occured.
  4961. * @param {CallStats} cs callstats instance related to the error (optional)
  4962. */
  4963. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  4964. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  4965. });
  4966. /**
  4967. * Notifies CallStats that peer connection failed to set local description.
  4968. *
  4969. * @param {Error} e error to send
  4970. * @param {RTCPeerConnection} pc connection on which failure occured.
  4971. * @param {CallStats} cs callstats instance related to the error (optional)
  4972. */
  4973. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  4974. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  4975. });
  4976. /**
  4977. * Notifies CallStats that peer connection failed to set remote description.
  4978. *
  4979. * @param {Error} e error to send
  4980. * @param {RTCPeerConnection} pc connection on which failure occured.
  4981. * @param {CallStats} cs callstats instance related to the error (optional)
  4982. */
  4983. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  4984. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  4985. });
  4986. /**
  4987. * Notifies CallStats that peer connection failed to add ICE candidate.
  4988. *
  4989. * @param {Error} e error to send
  4990. * @param {RTCPeerConnection} pc connection on which failure occured.
  4991. * @param {CallStats} cs callstats instance related to the error (optional)
  4992. */
  4993. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  4994. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  4995. });
  4996. module.exports = CallStats;
  4997. }).call(this,"/modules/statistics/CallStats.js")
  4998. },{"jitsi-meet-logger":49,"jssha":50,"socket.io-client":85}],23:[function(require,module,exports){
  4999. /* global config */
  5000. /**
  5001. * Provides statistics for the local stream.
  5002. */
  5003. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5004. /**
  5005. * Size of the webaudio analyzer buffer.
  5006. * @type {number}
  5007. */
  5008. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  5009. /**
  5010. * Value of the webaudio analyzer smoothing time parameter.
  5011. * @type {number}
  5012. */
  5013. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  5014. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  5015. var context = null;
  5016. if(window.AudioContext) {
  5017. context = new AudioContext();
  5018. }
  5019. /**
  5020. * Converts time domain data array to audio level.
  5021. * @param samples the time domain data array.
  5022. * @returns {number} the audio level
  5023. */
  5024. function timeDomainDataToAudioLevel(samples) {
  5025. var maxVolume = 0;
  5026. var length = samples.length;
  5027. for (var i = 0; i < length; i++) {
  5028. if (maxVolume < samples[i])
  5029. maxVolume = samples[i];
  5030. }
  5031. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5032. }
  5033. /**
  5034. * Animates audio level change
  5035. * @param newLevel the new audio level
  5036. * @param lastLevel the last audio level
  5037. * @returns {Number} the audio level to be set
  5038. */
  5039. function animateLevel(newLevel, lastLevel) {
  5040. var value = 0;
  5041. var diff = lastLevel - newLevel;
  5042. if(diff > 0.2) {
  5043. value = lastLevel - 0.2;
  5044. }
  5045. else if(diff < -0.4) {
  5046. value = lastLevel + 0.4;
  5047. }
  5048. else {
  5049. value = newLevel;
  5050. }
  5051. return parseFloat(value.toFixed(3));
  5052. }
  5053. /**
  5054. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5055. *
  5056. * @param stream the local stream
  5057. * @param interval stats refresh interval given in ms.
  5058. * @param callback function that receives the audio levels.
  5059. * @constructor
  5060. */
  5061. function LocalStatsCollector(stream, interval, callback) {
  5062. this.stream = stream;
  5063. this.intervalId = null;
  5064. this.intervalMilis = interval;
  5065. this.audioLevel = 0;
  5066. this.callback = callback;
  5067. }
  5068. /**
  5069. * Starts the collecting the statistics.
  5070. */
  5071. LocalStatsCollector.prototype.start = function () {
  5072. if (!context ||
  5073. RTCBrowserType.isTemasysPluginUsed())
  5074. return;
  5075. var analyser = context.createAnalyser();
  5076. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5077. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5078. var source = context.createMediaStreamSource(this.stream);
  5079. source.connect(analyser);
  5080. var self = this;
  5081. this.intervalId = setInterval(
  5082. function () {
  5083. var array = new Uint8Array(analyser.frequencyBinCount);
  5084. analyser.getByteTimeDomainData(array);
  5085. var audioLevel = timeDomainDataToAudioLevel(array);
  5086. if (audioLevel != self.audioLevel) {
  5087. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5088. self.callback(self.audioLevel);
  5089. }
  5090. },
  5091. this.intervalMilis
  5092. );
  5093. };
  5094. /**
  5095. * Stops collecting the statistics.
  5096. */
  5097. LocalStatsCollector.prototype.stop = function () {
  5098. if (this.intervalId) {
  5099. clearInterval(this.intervalId);
  5100. this.intervalId = null;
  5101. }
  5102. };
  5103. module.exports = LocalStatsCollector;
  5104. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5105. (function (__filename){
  5106. /* global require, ssrc2jid */
  5107. /* jshint -W117 */
  5108. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5109. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5110. var StatisticsEvents = require("../../service/statistics/Events");
  5111. /* Whether we support the browser we are running into for logging statistics */
  5112. var browserSupported = RTCBrowserType.isChrome() ||
  5113. RTCBrowserType.isOpera();
  5114. var keyMap = {};
  5115. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5116. "ssrc": "ssrc",
  5117. "packetsReceived": "packetsReceived",
  5118. "packetsLost": "packetsLost",
  5119. "packetsSent": "packetsSent",
  5120. "bytesReceived": "bytesReceived",
  5121. "bytesSent": "bytesSent"
  5122. };
  5123. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5124. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5125. "sendBandwidth": "googAvailableSendBandwidth",
  5126. "remoteAddress": "googRemoteAddress",
  5127. "transportType": "googTransportType",
  5128. "localAddress": "googLocalAddress",
  5129. "activeConnection": "googActiveConnection",
  5130. "ssrc": "ssrc",
  5131. "packetsReceived": "packetsReceived",
  5132. "packetsSent": "packetsSent",
  5133. "packetsLost": "packetsLost",
  5134. "bytesReceived": "bytesReceived",
  5135. "bytesSent": "bytesSent",
  5136. "googFrameHeightReceived": "googFrameHeightReceived",
  5137. "googFrameWidthReceived": "googFrameWidthReceived",
  5138. "googFrameHeightSent": "googFrameHeightSent",
  5139. "googFrameWidthSent": "googFrameWidthSent",
  5140. "audioInputLevel": "audioInputLevel",
  5141. "audioOutputLevel": "audioOutputLevel"
  5142. };
  5143. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5144. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5145. /**
  5146. * Calculates packet lost percent using the number of lost packets and the
  5147. * number of all packet.
  5148. * @param lostPackets the number of lost packets
  5149. * @param totalPackets the number of all packets.
  5150. * @returns {number} packet loss percent
  5151. */
  5152. function calculatePacketLoss(lostPackets, totalPackets) {
  5153. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5154. return 0;
  5155. return Math.round((lostPackets/totalPackets)*100);
  5156. }
  5157. function getStatValue(item, name) {
  5158. var browserType = RTCBrowserType.getBrowserType();
  5159. if (!keyMap[browserType][name])
  5160. throw "The property isn't supported!";
  5161. var key = keyMap[browserType][name];
  5162. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5163. item.stat(key) : item[key];
  5164. }
  5165. function formatAudioLevel(audioLevel) {
  5166. return Math.min(Math.max(audioLevel, 0), 1);
  5167. }
  5168. /**
  5169. * Checks whether a certain record should be included in the logged statistics.
  5170. */
  5171. function acceptStat(reportId, reportType, statName) {
  5172. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5173. return false;
  5174. if (reportType == "ssrc") {
  5175. if (statName == "googTrackId" ||
  5176. statName == "transportId" ||
  5177. statName == "ssrc")
  5178. return false;
  5179. }
  5180. return true;
  5181. }
  5182. /**
  5183. * Checks whether a certain record should be included in the logged statistics.
  5184. */
  5185. function acceptReport(id, type) {
  5186. if (id.substring(0, 15) == "googCertificate" ||
  5187. id.substring(0, 9) == "googTrack" ||
  5188. id.substring(0, 20) == "googLibjingleSession")
  5189. return false;
  5190. if (type == "googComponent")
  5191. return false;
  5192. return true;
  5193. }
  5194. /**
  5195. * Peer statistics data holder.
  5196. * @constructor
  5197. */
  5198. function PeerStats()
  5199. {
  5200. this.ssrc2Loss = {};
  5201. this.ssrc2AudioLevel = {};
  5202. this.ssrc2bitrate = {};
  5203. this.ssrc2resolution = {};
  5204. }
  5205. /**
  5206. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5207. * represented by this instance.
  5208. * @param lossRate new packet loss rate value to be set.
  5209. */
  5210. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5211. {
  5212. this.ssrc2Loss = lossRate;
  5213. };
  5214. /**
  5215. * Sets resolution that belong to the ssrc
  5216. * represented by this instance.
  5217. * @param resolution new resolution value to be set.
  5218. */
  5219. PeerStats.prototype.setSsrcResolution = function (resolution)
  5220. {
  5221. if(resolution === null && this.ssrc2resolution[ssrc])
  5222. {
  5223. delete this.ssrc2resolution[ssrc];
  5224. }
  5225. else if(resolution !== null)
  5226. this.ssrc2resolution[ssrc] = resolution;
  5227. };
  5228. /**
  5229. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5230. * represented by this instance.
  5231. * @param ssrc audio or video RTP stream SSRC.
  5232. * @param bitrate new bitrate value to be set.
  5233. */
  5234. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5235. {
  5236. if(this.ssrc2bitrate[ssrc])
  5237. {
  5238. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5239. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5240. }
  5241. else {
  5242. this.ssrc2bitrate[ssrc] = bitrate;
  5243. }
  5244. };
  5245. /**
  5246. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5247. * the stream which belongs to the peer represented by this instance.
  5248. * @param ssrc RTP stream SSRC for which current audio level value will be
  5249. * updated.
  5250. * @param audioLevel the new audio level value to be set. Value is truncated to
  5251. * fit the range from 0 to 1.
  5252. */
  5253. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5254. {
  5255. // Range limit 0 - 1
  5256. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5257. };
  5258. function ConferenceStats() {
  5259. /**
  5260. * The bandwidth
  5261. * @type {{}}
  5262. */
  5263. this.bandwidth = {};
  5264. /**
  5265. * The bit rate
  5266. * @type {{}}
  5267. */
  5268. this.bitrate = {};
  5269. /**
  5270. * The packet loss rate
  5271. * @type {{}}
  5272. */
  5273. this.packetLoss = null;
  5274. /**
  5275. * Array with the transport information.
  5276. * @type {Array}
  5277. */
  5278. this.transport = [];
  5279. }
  5280. /**
  5281. * <tt>StatsCollector</tt> registers for stats updates of given
  5282. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5283. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5284. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5285. * instance as an event source.
  5286. *
  5287. * @param peerconnection webRTC peer connection object.
  5288. * @param interval stats refresh interval given in ms.
  5289. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5290. * called on stats update.
  5291. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5292. * @constructor
  5293. */
  5294. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5295. {
  5296. this.peerconnection = peerconnection;
  5297. this.baselineAudioLevelsReport = null;
  5298. this.currentAudioLevelsReport = null;
  5299. this.currentStatsReport = null;
  5300. this.baselineStatsReport = null;
  5301. this.audioLevelsIntervalId = null;
  5302. this.eventEmitter = eventEmitter;
  5303. this.config = config || {};
  5304. this.conferenceStats = new ConferenceStats();
  5305. /**
  5306. * Gather PeerConnection stats once every this many milliseconds.
  5307. */
  5308. this.GATHER_INTERVAL = 15000;
  5309. /**
  5310. * Log stats via the focus once every this many milliseconds.
  5311. */
  5312. this.LOG_INTERVAL = 60000;
  5313. /**
  5314. * Gather stats and store them in this.statsToBeLogged.
  5315. */
  5316. this.gatherStatsIntervalId = null;
  5317. /**
  5318. * Send the stats already saved in this.statsToBeLogged to be logged via
  5319. * the focus.
  5320. */
  5321. this.logStatsIntervalId = null;
  5322. /**
  5323. * Stores the statistics which will be send to the focus to be logged.
  5324. */
  5325. this.statsToBeLogged =
  5326. {
  5327. timestamps: [],
  5328. stats: {}
  5329. };
  5330. // Updates stats interval
  5331. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5332. this.statsIntervalId = null;
  5333. this.statsIntervalMilis = statsInterval;
  5334. // Map of ssrcs to PeerStats
  5335. this.ssrc2stats = {};
  5336. }
  5337. module.exports = StatsCollector;
  5338. /**
  5339. * Stops stats updates.
  5340. */
  5341. StatsCollector.prototype.stop = function () {
  5342. if (this.audioLevelsIntervalId) {
  5343. clearInterval(this.audioLevelsIntervalId);
  5344. this.audioLevelsIntervalId = null;
  5345. }
  5346. if (this.statsIntervalId)
  5347. {
  5348. clearInterval(this.statsIntervalId);
  5349. this.statsIntervalId = null;
  5350. }
  5351. if(this.logStatsIntervalId)
  5352. {
  5353. clearInterval(this.logStatsIntervalId);
  5354. this.logStatsIntervalId = null;
  5355. }
  5356. if(this.gatherStatsIntervalId)
  5357. {
  5358. clearInterval(this.gatherStatsIntervalId);
  5359. this.gatherStatsIntervalId = null;
  5360. }
  5361. };
  5362. /**
  5363. * Callback passed to <tt>getStats</tt> method.
  5364. * @param error an error that occurred on <tt>getStats</tt> call.
  5365. */
  5366. StatsCollector.prototype.errorCallback = function (error)
  5367. {
  5368. logger.error("Get stats error", error);
  5369. this.stop();
  5370. };
  5371. /**
  5372. * Starts stats updates.
  5373. */
  5374. StatsCollector.prototype.start = function ()
  5375. {
  5376. var self = this;
  5377. this.audioLevelsIntervalId = setInterval(
  5378. function () {
  5379. // Interval updates
  5380. self.peerconnection.getStats(
  5381. function (report) {
  5382. var results = null;
  5383. if (!report || !report.result ||
  5384. typeof report.result != 'function') {
  5385. results = report;
  5386. }
  5387. else {
  5388. results = report.result();
  5389. }
  5390. //logger.error("Got interval report", results);
  5391. self.currentAudioLevelsReport = results;
  5392. self.processAudioLevelReport();
  5393. self.baselineAudioLevelsReport =
  5394. self.currentAudioLevelsReport;
  5395. },
  5396. self.errorCallback
  5397. );
  5398. },
  5399. self.audioLevelsIntervalMilis
  5400. );
  5401. // if (!this.config.disableStats && browserSupported) {
  5402. // this.statsIntervalId = setInterval(
  5403. // function () {
  5404. // // Interval updates
  5405. // self.peerconnection.getStats(
  5406. // function (report) {
  5407. // var results = null;
  5408. // if (!report || !report.result ||
  5409. // typeof report.result != 'function') {
  5410. // //firefox
  5411. // results = report;
  5412. // }
  5413. // else {
  5414. // //chrome
  5415. // results = report.result();
  5416. // }
  5417. // //logger.error("Got interval report", results);
  5418. // self.currentStatsReport = results;
  5419. // try {
  5420. // self.processStatsReport();
  5421. // }
  5422. // catch (e) {
  5423. // logger.error("Unsupported key:" + e, e);
  5424. // }
  5425. //
  5426. // self.baselineStatsReport = self.currentStatsReport;
  5427. // },
  5428. // self.errorCallback
  5429. // );
  5430. // },
  5431. // self.statsIntervalMilis
  5432. // );
  5433. // }
  5434. //
  5435. // if (this.config.logStats && browserSupported) {
  5436. // this.gatherStatsIntervalId = setInterval(
  5437. // function () {
  5438. // self.peerconnection.getStats(
  5439. // function (report) {
  5440. // self.addStatsToBeLogged(report.result());
  5441. // },
  5442. // function () {
  5443. // }
  5444. // );
  5445. // },
  5446. // this.GATHER_INTERVAL
  5447. // );
  5448. //
  5449. // this.logStatsIntervalId = setInterval(
  5450. // function() { self.logStats(); },
  5451. // this.LOG_INTERVAL);
  5452. // }
  5453. };
  5454. /**
  5455. * Converts the stats to the format used for logging, and saves the data in
  5456. * this.statsToBeLogged.
  5457. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5458. */
  5459. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5460. var self = this;
  5461. var num_records = this.statsToBeLogged.timestamps.length;
  5462. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5463. reports.map(function (report) {
  5464. if (!acceptReport(report.id, report.type))
  5465. return;
  5466. var stat = self.statsToBeLogged.stats[report.id];
  5467. if (!stat) {
  5468. stat = self.statsToBeLogged.stats[report.id] = {};
  5469. }
  5470. stat.type = report.type;
  5471. report.names().map(function (name) {
  5472. if (!acceptStat(report.id, report.type, name))
  5473. return;
  5474. var values = stat[name];
  5475. if (!values) {
  5476. values = stat[name] = [];
  5477. }
  5478. while (values.length < num_records) {
  5479. values.push(null);
  5480. }
  5481. values.push(report.stat(name));
  5482. });
  5483. });
  5484. };
  5485. //FIXME:
  5486. //StatsCollector.prototype.logStats = function () {
  5487. //
  5488. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5489. // return;
  5490. // // Reset the stats
  5491. // this.statsToBeLogged.stats = {};
  5492. // this.statsToBeLogged.timestamps = [];
  5493. //};
  5494. /**
  5495. * Stats processing logic.
  5496. */
  5497. StatsCollector.prototype.processStatsReport = function () {
  5498. if (!this.baselineStatsReport) {
  5499. return;
  5500. }
  5501. for (var idx in this.currentStatsReport) {
  5502. var now = this.currentStatsReport[idx];
  5503. try {
  5504. if (getStatValue(now, 'receiveBandwidth') ||
  5505. getStatValue(now, 'sendBandwidth')) {
  5506. this.conferenceStats.bandwidth = {
  5507. "download": Math.round(
  5508. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5509. "upload": Math.round(
  5510. (getStatValue(now, 'sendBandwidth')) / 1000)
  5511. };
  5512. }
  5513. }
  5514. catch(e){/*not supported*/}
  5515. if(now.type == 'googCandidatePair')
  5516. {
  5517. var ip, type, localIP, active;
  5518. try {
  5519. ip = getStatValue(now, 'remoteAddress');
  5520. type = getStatValue(now, "transportType");
  5521. localIP = getStatValue(now, "localAddress");
  5522. active = getStatValue(now, "activeConnection");
  5523. }
  5524. catch(e){/*not supported*/}
  5525. if(!ip || !type || !localIP || active != "true")
  5526. continue;
  5527. var addressSaved = false;
  5528. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5529. {
  5530. if(this.conferenceStats.transport[i].ip == ip &&
  5531. this.conferenceStats.transport[i].type == type &&
  5532. this.conferenceStats.transport[i].localip == localIP)
  5533. {
  5534. addressSaved = true;
  5535. }
  5536. }
  5537. if(addressSaved)
  5538. continue;
  5539. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5540. continue;
  5541. }
  5542. if(now.type == "candidatepair")
  5543. {
  5544. if(now.state == "succeeded")
  5545. continue;
  5546. var local = this.currentStatsReport[now.localCandidateId];
  5547. var remote = this.currentStatsReport[now.remoteCandidateId];
  5548. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5549. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5550. }
  5551. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5552. now.type != "inboundrtp") {
  5553. continue;
  5554. }
  5555. var before = this.baselineStatsReport[idx];
  5556. if (!before) {
  5557. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5558. continue;
  5559. }
  5560. var ssrc = getStatValue(now, 'ssrc');
  5561. if(!ssrc)
  5562. continue;
  5563. var ssrcStats = this.ssrc2stats[ssrc];
  5564. if (!ssrcStats) {
  5565. ssrcStats = new PeerStats();
  5566. this.ssrc2stats[ssrc] = ssrcStats;
  5567. }
  5568. var isDownloadStream = true;
  5569. var key = 'packetsReceived';
  5570. var packetsNow = getStatValue(now, key);
  5571. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5572. isDownloadStream = false;
  5573. key = 'packetsSent';
  5574. packetsNow = getStatValue(now, key);
  5575. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5576. console.warn("No packetsReceived nor packetsSent stat found");
  5577. continue;
  5578. }
  5579. }
  5580. if (!packetsNow || packetsNow < 0)
  5581. packetsNow = 0;
  5582. var packetsBefore = getStatValue(before, key);
  5583. if (!packetsBefore || packetsBefore < 0)
  5584. packetsBefore = 0;
  5585. var packetRate = packetsNow - packetsBefore;
  5586. if (!packetRate || packetRate < 0)
  5587. packetRate = 0;
  5588. var currentLoss = getStatValue(now, 'packetsLost');
  5589. if (!currentLoss || currentLoss < 0)
  5590. currentLoss = 0;
  5591. var previousLoss = getStatValue(before, 'packetsLost');
  5592. if (!previousLoss || previousLoss < 0)
  5593. previousLoss = 0;
  5594. var lossRate = currentLoss - previousLoss;
  5595. if (!lossRate || lossRate < 0)
  5596. lossRate = 0;
  5597. var packetsTotal = (packetRate + lossRate);
  5598. ssrcStats.setSsrcLoss(ssrc,
  5599. {"packetsTotal": packetsTotal,
  5600. "packetsLost": lossRate,
  5601. "isDownloadStream": isDownloadStream});
  5602. var bytesReceived = 0, bytesSent = 0;
  5603. if(getStatValue(now, "bytesReceived")) {
  5604. bytesReceived = getStatValue(now, "bytesReceived") -
  5605. getStatValue(before, "bytesReceived");
  5606. }
  5607. if (getStatValue(now, "bytesSent")) {
  5608. bytesSent = getStatValue(now, "bytesSent") -
  5609. getStatValue(before, "bytesSent");
  5610. }
  5611. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5612. if (bytesReceived <= 0 || time <= 0) {
  5613. bytesReceived = 0;
  5614. } else {
  5615. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5616. }
  5617. if (bytesSent <= 0 || time <= 0) {
  5618. bytesSent = 0;
  5619. } else {
  5620. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5621. }
  5622. ssrcStats.setSsrcBitrate(ssrc, {
  5623. "download": bytesReceived,
  5624. "upload": bytesSent});
  5625. var resolution = {height: null, width: null};
  5626. try {
  5627. if (getStatValue(now, "googFrameHeightReceived") &&
  5628. getStatValue(now, "googFrameWidthReceived")) {
  5629. resolution.height =
  5630. getStatValue(now, "googFrameHeightReceived");
  5631. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5632. }
  5633. else if (getStatValue(now, "googFrameHeightSent") &&
  5634. getStatValue(now, "googFrameWidthSent")) {
  5635. resolution.height = getStatValue(now, "googFrameHeightSent");
  5636. resolution.width = getStatValue(now, "googFrameWidthSent");
  5637. }
  5638. }
  5639. catch(e){/*not supported*/}
  5640. if (resolution.height && resolution.width) {
  5641. ssrcStats.setSsrcResolution(ssrc, resolution);
  5642. } else {
  5643. ssrcStats.setSsrcResolution(ssrc, null);
  5644. }
  5645. }
  5646. var self = this;
  5647. // Jid stats
  5648. var totalPackets = {download: 0, upload: 0};
  5649. var lostPackets = {download: 0, upload: 0};
  5650. var bitrateDownload = 0;
  5651. var bitrateUpload = 0;
  5652. var resolutions = {};
  5653. Object.keys(this.ssrc2stats).forEach(
  5654. function (jid) {
  5655. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5656. function (ssrc) {
  5657. var type = "upload";
  5658. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5659. type = "download";
  5660. totalPackets[type] +=
  5661. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5662. lostPackets[type] +=
  5663. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5664. }
  5665. );
  5666. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5667. function (ssrc) {
  5668. bitrateDownload +=
  5669. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5670. bitrateUpload +=
  5671. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5672. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5673. }
  5674. );
  5675. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5676. }
  5677. );
  5678. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5679. this.conferenceStats.packetLoss = {
  5680. total:
  5681. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5682. totalPackets.download + totalPackets.upload),
  5683. download:
  5684. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5685. upload:
  5686. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5687. };
  5688. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5689. {
  5690. "bitrate": this.conferenceStats.bitrate,
  5691. "packetLoss": this.conferenceStats.packetLoss,
  5692. "bandwidth": this.conferenceStats.bandwidth,
  5693. "resolution": resolutions,
  5694. "transport": this.conferenceStats.transport
  5695. });
  5696. this.conferenceStats.transport = [];
  5697. };
  5698. /**
  5699. * Stats processing logic.
  5700. */
  5701. StatsCollector.prototype.processAudioLevelReport = function () {
  5702. if (!this.baselineAudioLevelsReport) {
  5703. return;
  5704. }
  5705. for (var idx in this.currentAudioLevelsReport) {
  5706. var now = this.currentAudioLevelsReport[idx];
  5707. //if we don't have "packetsReceived" this is local stream
  5708. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5709. continue;
  5710. }
  5711. var before = this.baselineAudioLevelsReport[idx];
  5712. if (!before) {
  5713. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5714. continue;
  5715. }
  5716. var ssrc = getStatValue(now, 'ssrc');
  5717. if (!ssrc) {
  5718. if((Date.now() - now.timestamp) < 3000)
  5719. logger.warn("No ssrc: ");
  5720. continue;
  5721. }
  5722. var ssrcStats = this.ssrc2stats[ssrc];
  5723. if (!ssrcStats) {
  5724. ssrcStats = new PeerStats();
  5725. this.ssrc2stats[ssrc] = ssrcStats;
  5726. }
  5727. // Audio level
  5728. var audioLevel = null;
  5729. try {
  5730. audioLevel = getStatValue(now, 'audioInputLevel');
  5731. if (!audioLevel)
  5732. audioLevel = getStatValue(now, 'audioOutputLevel');
  5733. }
  5734. catch(e) {/*not supported*/
  5735. logger.warn("Audio Levels are not available in the statistics.");
  5736. clearInterval(this.audioLevelsIntervalId);
  5737. return;
  5738. }
  5739. if (audioLevel) {
  5740. // TODO: can't find specs about what this value really is,
  5741. // but it seems to vary between 0 and around 32k.
  5742. audioLevel = audioLevel / 32767;
  5743. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5744. this.eventEmitter.emit(
  5745. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5746. }
  5747. }
  5748. };
  5749. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5750. },{"../../service/statistics/Events":140,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],25:[function(require,module,exports){
  5751. /* global require, APP */
  5752. var LocalStats = require("./LocalStatsCollector.js");
  5753. var RTPStats = require("./RTPStatsCollector.js");
  5754. var EventEmitter = require("events");
  5755. var StatisticsEvents = require("../../service/statistics/Events");
  5756. var CallStats = require("./CallStats");
  5757. // Since callstats.io is a third party, we cannot guarantee the quality of
  5758. // their service. More specifically, their server may take noticeably long
  5759. // time to respond. Consequently, it is in our best interest (in the sense
  5760. // that the intergration of callstats.io is pretty important to us but not
  5761. // enough to allow it to prevent people from joining a conference) to (1)
  5762. // start downloading their API as soon as possible and (2) do the
  5763. // downloading asynchronously.
  5764. function loadCallStatsAPI() {
  5765. (function (d, src) {
  5766. var elementName = 'script';
  5767. var newScript = d.createElement(elementName);
  5768. var referenceNode = d.getElementsByTagName(elementName)[0];
  5769. newScript.async = true;
  5770. newScript.src = src;
  5771. referenceNode.parentNode.insertBefore(newScript, referenceNode);
  5772. })(document, 'https://api.callstats.io/static/callstats.min.js');
  5773. // FIXME At the time of this writing, we hope that the callstats.io API will
  5774. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5775. }
  5776. var eventEmitter = new EventEmitter();
  5777. function Statistics(options) {
  5778. this.rtpStats = null;
  5779. this.eventEmitter = new EventEmitter();
  5780. this.options = options || {};
  5781. this.callStatsIntegrationEnabled
  5782. = this.options.callStatsID && this.options.callStatsSecret
  5783. // Even though AppID and AppSecret may be specified, the integration of
  5784. // callstats.io may be disabled because of globally-disallowed requests
  5785. // to any third parties.
  5786. && (this.options.disableThirdPartyRequests !== true);
  5787. if(this.callStatsIntegrationEnabled)
  5788. loadCallStatsAPI();
  5789. this.callStats = null;
  5790. }
  5791. Statistics.audioLevelsEnabled = false;
  5792. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5793. if(!Statistics.audioLevelsEnabled)
  5794. return;
  5795. if (this.rtpStats) {
  5796. this.rtpStats.stop();
  5797. }
  5798. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5799. this.rtpStats.start();
  5800. }
  5801. Statistics.localStats = [];
  5802. Statistics.startLocalStats = function (stream, callback) {
  5803. if(!Statistics.audioLevelsEnabled)
  5804. return;
  5805. var localStats = new LocalStats(stream, 200, callback);
  5806. this.localStats.push(localStats);
  5807. localStats.start();
  5808. }
  5809. Statistics.prototype.addAudioLevelListener = function(listener)
  5810. {
  5811. if(!Statistics.audioLevelsEnabled)
  5812. return;
  5813. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5814. }
  5815. Statistics.prototype.removeAudioLevelListener = function(listener)
  5816. {
  5817. if(!Statistics.audioLevelsEnabled)
  5818. return;
  5819. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5820. }
  5821. Statistics.prototype.dispose = function () {
  5822. if(Statistics.audioLevelsEnabled) {
  5823. Statistics.stopAllLocalStats();
  5824. this.stopRemote();
  5825. if(this.eventEmitter)
  5826. this.eventEmitter.removeAllListeners();
  5827. if(eventEmitter)
  5828. eventEmitter.removeAllListeners();
  5829. }
  5830. if(this.callstats)
  5831. {
  5832. this.callstats.sendTerminateEvent();
  5833. this.callstats = null;
  5834. }
  5835. }
  5836. Statistics.stopAllLocalStats = function () {
  5837. if(!Statistics.audioLevelsEnabled)
  5838. return;
  5839. for(var i = 0; i < this.localStats.length; i++)
  5840. this.localStats[i].stop();
  5841. this.localStats = [];
  5842. }
  5843. Statistics.stopLocalStats = function (stream) {
  5844. if(!Statistics.audioLevelsEnabled)
  5845. return;
  5846. for(var i = 0; i < Statistics.localStats.length; i++)
  5847. if(Statistics.localStats[i].stream === stream){
  5848. var localStats = Statistics.localStats.splice(i, 1);
  5849. localStats.stop();
  5850. break;
  5851. }
  5852. }
  5853. Statistics.prototype.stopRemote = function () {
  5854. if (this.rtpStats && Statistics.audioLevelsEnabled) {
  5855. this.rtpStats.stop();
  5856. this.eventEmitter.emit(StatisticsEvents.STOP);
  5857. this.rtpStats = null;
  5858. }
  5859. };
  5860. /**
  5861. * Obtains audio level reported in the stats for specified peer.
  5862. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5863. * audio level.
  5864. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5865. * level.
  5866. * @returns {*} a float form 0 to 1 that represents current audio level or
  5867. * <tt>null</tt> if for any reason the value is not available
  5868. * at this time.
  5869. */
  5870. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5871. if(!Statistics.audioLevelsEnabled)
  5872. return;
  5873. var peerStats = this.rtpStats.jid2stats[peerJid];
  5874. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5875. };
  5876. //CALSTATS METHODS
  5877. /**
  5878. * Initializes the callstats.io API.
  5879. * @param peerConnection {JingleSessionPC} the session object
  5880. * @param Settings {Settings} the settings instance. Declared in
  5881. * /modules/settings/Settings.js
  5882. */
  5883. Statistics.prototype.startCallStats = function (session, settings) {
  5884. if(this.callStatsIntegrationEnabled && !this.callstats) {
  5885. this.callstats = new CallStats(session, settings, this.options);
  5886. }
  5887. }
  5888. /**
  5889. * Returns true if the callstats integration is enabled, otherwise returns
  5890. * false.
  5891. *
  5892. * @returns true if the callstats integration is enabled, otherwise returns
  5893. * false.
  5894. */
  5895. Statistics.prototype.isCallstatsEnabled = function () {
  5896. return this.callStatsIntegrationEnabled;
  5897. }
  5898. /**
  5899. * Notifies CallStats for connection setup errors
  5900. */
  5901. Statistics.prototype.sendSetupFailedEvent = function () {
  5902. if(this.callStatsIntegrationEnabled && this.callstats)
  5903. this.callstats.sendSetupFailedEvent();
  5904. }
  5905. /**
  5906. * Notifies CallStats for mute events
  5907. * @param mute {boolean} true for muted and false for not muted
  5908. * @param type {String} "audio"/"video"
  5909. */
  5910. Statistics.prototype.sendMuteEvent = function (muted, type) {
  5911. if(this.callStatsIntegrationEnabled && this.callstats)
  5912. this.callstats.sendMuteEvent(muted, type);
  5913. }
  5914. /**
  5915. * Notifies CallStats that getUserMedia failed.
  5916. *
  5917. * @param {Error} e error to send
  5918. */
  5919. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  5920. if(this.callStatsIntegrationEnabled)
  5921. CallStats.sendGetUserMediaFailed(e, this.callstats);
  5922. };
  5923. /**
  5924. * Notifies CallStats that getUserMedia failed.
  5925. *
  5926. * @param {Error} e error to send
  5927. */
  5928. Statistics.sendGetUserMediaFailed = function (e) {
  5929. CallStats.sendGetUserMediaFailed(e, null);
  5930. };
  5931. /**
  5932. * Notifies CallStats that peer connection failed to create offer.
  5933. *
  5934. * @param {Error} e error to send
  5935. * @param {RTCPeerConnection} pc connection on which failure occured.
  5936. */
  5937. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  5938. if(this.callStatsIntegrationEnabled)
  5939. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  5940. };
  5941. /**
  5942. * Notifies CallStats that peer connection failed to create answer.
  5943. *
  5944. * @param {Error} e error to send
  5945. * @param {RTCPeerConnection} pc connection on which failure occured.
  5946. */
  5947. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  5948. if(this.callStatsIntegrationEnabled)
  5949. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  5950. };
  5951. /**
  5952. * Notifies CallStats that peer connection failed to set local description.
  5953. *
  5954. * @param {Error} e error to send
  5955. * @param {RTCPeerConnection} pc connection on which failure occured.
  5956. */
  5957. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  5958. if(this.callStatsIntegrationEnabled)
  5959. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  5960. }
  5961. /**
  5962. * Notifies CallStats that peer connection failed to set remote description.
  5963. *
  5964. * @param {Error} e error to send
  5965. * @param {RTCPeerConnection} pc connection on which failure occured.
  5966. */
  5967. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  5968. if(this.callStatsIntegrationEnabled)
  5969. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  5970. }
  5971. /**
  5972. * Notifies CallStats that peer connection failed to add ICE candidate.
  5973. *
  5974. * @param {Error} e error to send
  5975. * @param {RTCPeerConnection} pc connection on which failure occured.
  5976. */
  5977. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  5978. if(this.callStatsIntegrationEnabled)
  5979. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  5980. }
  5981. /**
  5982. * Sends the given feedback through CallStats.
  5983. *
  5984. * @param overallFeedback an integer between 1 and 5 indicating the
  5985. * user feedback
  5986. * @param detailedFeedback detailed feedback from the user. Not yet used
  5987. */
  5988. Statistics.prototype.sendFeedback =
  5989. function(overallFeedback, detailedFeedback){
  5990. if(this.callStatsIntegrationEnabled && this.callstats)
  5991. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  5992. }
  5993. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5994. module.exports = Statistics;
  5995. },{"../../service/statistics/Events":140,"../../service/statistics/constants":141,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":45}],26:[function(require,module,exports){
  5996. /**
  5997. /**
  5998. * @const
  5999. */
  6000. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6001. /**
  6002. * Hexadecimal digits.
  6003. * @const
  6004. */
  6005. var HEX_DIGITS = '0123456789abcdef';
  6006. /**
  6007. * Generates random int within the range [min, max]
  6008. * @param min the minimum value for the generated number
  6009. * @param max the maximum value for the generated number
  6010. * @returns random int number
  6011. */
  6012. function randomInt(min, max) {
  6013. return Math.floor(Math.random() * (max - min + 1)) + min;
  6014. }
  6015. /**
  6016. * Get random element from array or string.
  6017. * @param {Array|string} arr source
  6018. * @returns array element or string character
  6019. */
  6020. function randomElement(arr) {
  6021. return arr[randomInt(0, arr.length - 1)];
  6022. }
  6023. /**
  6024. * Generate random alphanumeric string.
  6025. * @param {number} length expected string length
  6026. * @returns {string} random string of specified length
  6027. */
  6028. function randomAlphanumStr(length) {
  6029. var result = '';
  6030. for (var i = 0; i < length; i += 1) {
  6031. result += randomElement(ALPHANUM);
  6032. }
  6033. return result;
  6034. }
  6035. /**
  6036. * Exported interface.
  6037. */
  6038. var RandomUtil = {
  6039. /**
  6040. * Returns a random hex digit.
  6041. * @returns {*}
  6042. */
  6043. randomHexDigit: function() {
  6044. return randomElement(HEX_DIGITS);
  6045. },
  6046. /**
  6047. * Returns a random string of hex digits with length 'len'.
  6048. * @param len the length.
  6049. */
  6050. randomHexString: function (len) {
  6051. var ret = '';
  6052. while (len--) {
  6053. ret += this.randomHexDigit();
  6054. }
  6055. return ret;
  6056. },
  6057. randomElement: randomElement,
  6058. randomAlphanumStr: randomAlphanumStr,
  6059. randomInt: randomInt
  6060. };
  6061. module.exports = RandomUtil;
  6062. },{}],27:[function(require,module,exports){
  6063. var RandomUtil = require('./RandomUtil');
  6064. /**
  6065. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6066. * MIT License
  6067. * http://github.com/marak/faker.js/
  6068. *
  6069. * @const
  6070. */
  6071. var names = [
  6072. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6073. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6074. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6075. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6076. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6077. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6078. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6079. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6080. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6081. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6082. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6083. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6084. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6085. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6086. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6087. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6088. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6089. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6090. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6091. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6092. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6093. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6094. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6095. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6096. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6097. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6098. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6099. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6100. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6101. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6102. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6103. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6104. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6105. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6106. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6107. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6108. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6109. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6110. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6111. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6112. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6113. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6114. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6115. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6116. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6117. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6118. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6119. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6120. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6121. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6122. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6123. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6124. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6125. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6126. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6127. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6128. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6129. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6130. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6131. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6132. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6133. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6134. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6135. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6136. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6137. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6138. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6139. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6140. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6141. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6142. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6143. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6144. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6145. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6146. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6147. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6148. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6149. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6150. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6151. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6152. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6153. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6154. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6155. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6156. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6157. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6158. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6159. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6160. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6161. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6162. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6163. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6164. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6165. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6166. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6167. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6168. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6169. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6170. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6171. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6172. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6173. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6174. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6175. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6176. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6177. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6178. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6179. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6180. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6181. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6182. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6183. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6184. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6185. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6186. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6187. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6188. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6189. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6190. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6191. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6192. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6193. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6194. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6195. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6196. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6197. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6198. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6199. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6200. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6201. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6202. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6203. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6204. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6205. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6206. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6207. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6208. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6209. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6210. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6211. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6212. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6213. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6214. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6215. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6216. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6217. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6218. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6219. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6220. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6221. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6222. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6223. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6224. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6225. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6226. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6227. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6228. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6229. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6230. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6231. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6232. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6233. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6234. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6235. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6236. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6237. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6238. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6239. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6240. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6241. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6242. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6243. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6244. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6245. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6246. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6247. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6248. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6249. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6250. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6251. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6252. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6253. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6254. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6255. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6256. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6257. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6258. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6259. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6260. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6261. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6262. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6263. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6264. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6265. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6266. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6267. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6268. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6269. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6270. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6271. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6272. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6273. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6274. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6275. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6276. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6277. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6278. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6279. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6280. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6281. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6282. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6283. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6284. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6285. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6286. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6287. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6288. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6289. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6290. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6291. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6292. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6293. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6294. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6295. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6296. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6297. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6298. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6299. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6300. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6301. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6302. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6303. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6304. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6305. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6306. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6307. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6308. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6309. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6310. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6311. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6312. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6313. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6314. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6315. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6316. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6317. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6318. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6319. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6320. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6321. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6322. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6323. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6324. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6325. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6326. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6327. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6328. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6329. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6330. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6331. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6332. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6333. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6334. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6335. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6336. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6337. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6338. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6339. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6340. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6341. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6342. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6343. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6344. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6345. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6346. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6347. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6348. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6349. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6350. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6351. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6352. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6353. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6354. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6355. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6356. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6357. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6358. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6359. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6360. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6361. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6362. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6363. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6364. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6365. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6366. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6367. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6368. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6369. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6370. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6371. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6372. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6373. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6374. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6375. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6376. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6377. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6378. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6379. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6380. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6381. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6382. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6383. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6384. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6385. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6386. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6387. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6388. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6389. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6390. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6391. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6392. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6393. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6394. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6395. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6396. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6397. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6398. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6399. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6400. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6401. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6402. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6403. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6404. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6405. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6406. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6407. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6408. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6409. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6410. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6411. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6412. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6413. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6414. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6415. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6416. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6417. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6418. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6419. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6420. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6421. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6422. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6423. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6424. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6425. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6426. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6427. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6428. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6429. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6430. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6431. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6432. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6433. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6434. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6435. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6436. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6437. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6438. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6439. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6440. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6441. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6442. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6443. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6444. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6445. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6446. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6447. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6448. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6449. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6450. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6451. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6452. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6453. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6454. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6455. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6456. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6457. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6458. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6459. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6460. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6461. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6462. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6463. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6464. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6465. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6466. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6467. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6468. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6469. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6470. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6471. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6472. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6473. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6474. "Zora", "Zula"
  6475. ];
  6476. /**
  6477. * Generate random username.
  6478. * @returns {string} random username
  6479. */
  6480. function generateUsername () {
  6481. var name = RandomUtil.randomElement(names);
  6482. var suffix = RandomUtil.randomAlphanumStr(3);
  6483. return name + '-' + suffix;
  6484. }
  6485. module.exports = {
  6486. generateUsername: generateUsername
  6487. };
  6488. },{"./RandomUtil":26}],28:[function(require,module,exports){
  6489. (function (__filename){
  6490. /* global Strophe, $, $pres, $iq, $msg */
  6491. /* jshint -W101,-W069 */
  6492. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6493. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6494. var Moderator = require("./moderator");
  6495. var EventEmitter = require("events");
  6496. var Recorder = require("./recording");
  6497. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6498. var parser = {
  6499. packet2JSON: function (packet, nodes) {
  6500. var self = this;
  6501. $(packet).children().each(function (index) {
  6502. var tagName = $(this).prop("tagName");
  6503. var node = {
  6504. tagName: tagName
  6505. };
  6506. node.attributes = {};
  6507. $($(this)[0].attributes).each(function( index, attr ) {
  6508. node.attributes[ attr.name ] = attr.value;
  6509. });
  6510. var text = Strophe.getText($(this)[0]);
  6511. if (text) {
  6512. node.value = text;
  6513. }
  6514. node.children = [];
  6515. nodes.push(node);
  6516. self.packet2JSON($(this), node.children);
  6517. });
  6518. },
  6519. JSON2packet: function (nodes, packet) {
  6520. for(var i = 0; i < nodes.length; i++) {
  6521. var node = nodes[i];
  6522. if(!node || node === null){
  6523. continue;
  6524. }
  6525. packet.c(node.tagName, node.attributes);
  6526. if(node.value)
  6527. packet.t(node.value);
  6528. if(node.children)
  6529. this.JSON2packet(node.children, packet);
  6530. packet.up();
  6531. }
  6532. // packet.up();
  6533. }
  6534. };
  6535. /**
  6536. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6537. * @param pres the presence JSON
  6538. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6539. */
  6540. function filterNodeFromPresenceJSON(pres, nodeName){
  6541. var res = [];
  6542. for(var i = 0; i < pres.length; i++)
  6543. if(pres[i].tagName === nodeName)
  6544. res.push(pres[i]);
  6545. return res;
  6546. }
  6547. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6548. this.eventEmitter = new EventEmitter();
  6549. this.xmpp = XMPP;
  6550. this.connection = connection;
  6551. this.roomjid = Strophe.getBareJidFromJid(jid);
  6552. this.myroomjid = jid;
  6553. this.password = password;
  6554. logger.info("Joined MUC as " + this.myroomjid);
  6555. this.members = {};
  6556. this.presMap = {};
  6557. this.presHandlers = {};
  6558. this.joined = false;
  6559. this.role = 'none';
  6560. this.focusMucJid = null;
  6561. this.bridgeIsDown = false;
  6562. this.options = options || {};
  6563. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6564. settings);
  6565. this.initPresenceMap();
  6566. this.session = null;
  6567. var self = this;
  6568. this.lastPresences = {};
  6569. this.phoneNumber = null;
  6570. this.phonePin = null;
  6571. }
  6572. ChatRoom.prototype.initPresenceMap = function () {
  6573. this.presMap['to'] = this.myroomjid;
  6574. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6575. this.presMap["nodes"] = [];
  6576. this.presMap["nodes"].push( {
  6577. "tagName": "user-agent",
  6578. "value": navigator.userAgent,
  6579. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6580. });
  6581. };
  6582. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6583. this.presMap["nodes"].push( {
  6584. "tagName": "devices",
  6585. "children": [
  6586. {
  6587. "tagName": "audio",
  6588. "value": devices.audio,
  6589. },
  6590. {
  6591. "tagName": "video",
  6592. "value": devices.video,
  6593. }
  6594. ]
  6595. });
  6596. };
  6597. ChatRoom.prototype.join = function (password) {
  6598. if(password)
  6599. this.password = password;
  6600. var self = this;
  6601. this.moderator.allocateConferenceFocus(function()
  6602. {
  6603. self.sendPresence(true);
  6604. }.bind(this));
  6605. };
  6606. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6607. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6608. // Too early to send presence - not initialized
  6609. return;
  6610. }
  6611. var pres = $pres({to: this.presMap['to'] });
  6612. pres.c('x', {xmlns: this.presMap['xns']});
  6613. if (this.password) {
  6614. pres.c('password').t(this.password).up();
  6615. }
  6616. pres.up();
  6617. // Send XEP-0115 'c' stanza that contains our capabilities info
  6618. if (this.connection.caps) {
  6619. this.connection.caps.node = this.xmpp.options.clientNode;
  6620. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6621. }
  6622. parser.JSON2packet(this.presMap.nodes, pres);
  6623. this.connection.send(pres);
  6624. };
  6625. ChatRoom.prototype.doLeave = function () {
  6626. logger.log("do leave", this.myroomjid);
  6627. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6628. this.presMap.length = 0;
  6629. this.connection.send(pres);
  6630. };
  6631. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6632. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6633. var getForm = $iq({type: 'get', to: this.roomjid})
  6634. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6635. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6636. var self = this;
  6637. this.connection.sendIQ(getForm, function (form) {
  6638. if (!$(form).find(
  6639. '>query>x[xmlns="jabber:x:data"]' +
  6640. '>field[var="muc#roomconfig_whois"]').length) {
  6641. logger.error('non-anonymous rooms not supported');
  6642. return;
  6643. }
  6644. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6645. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6646. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6647. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6648. .c('value')
  6649. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6650. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6651. .c('value').t('anyone').up().up();
  6652. self.connection.sendIQ(formSubmit);
  6653. }, function (error) {
  6654. logger.error("Error getting room configuration form");
  6655. });
  6656. };
  6657. ChatRoom.prototype.onPresence = function (pres) {
  6658. var from = pres.getAttribute('from');
  6659. // Parse roles.
  6660. var member = {};
  6661. member.show = $(pres).find('>show').text();
  6662. member.status = $(pres).find('>status').text();
  6663. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6664. member.affiliation = tmp.attr('affiliation');
  6665. member.role = tmp.attr('role');
  6666. // Focus recognition
  6667. member.jid = tmp.attr('jid');
  6668. member.isFocus = false;
  6669. if (member.jid
  6670. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6671. member.isFocus = true;
  6672. }
  6673. $(pres).find(">x").remove();
  6674. var nodes = [];
  6675. parser.packet2JSON(pres, nodes);
  6676. this.lastPresences[from] = nodes;
  6677. var jibri = null;
  6678. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6679. // events
  6680. for(var i = 0; i < nodes.length; i++)
  6681. {
  6682. var node = nodes[i];
  6683. switch(node.tagName)
  6684. {
  6685. case "nick":
  6686. member.nick = node.value;
  6687. break;
  6688. case "userId":
  6689. member.id = node.value;
  6690. break;
  6691. }
  6692. }
  6693. if (from == this.myroomjid) {
  6694. if (member.affiliation == 'owner'
  6695. && this.role !== member.role) {
  6696. this.role = member.role;
  6697. this.eventEmitter.emit(
  6698. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6699. }
  6700. if (!this.joined) {
  6701. this.joined = true;
  6702. console.log("(TIME) MUC joined:\t", window.performance.now());
  6703. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6704. }
  6705. } else if (this.members[from] === undefined) {
  6706. // new participant
  6707. this.members[from] = member;
  6708. logger.log('entered', from, member);
  6709. if (member.isFocus) {
  6710. this.focusMucJid = from;
  6711. if(!this.recording) {
  6712. this.recording = new Recorder(this.options.recordingType,
  6713. this.eventEmitter, this.connection, this.focusMucJid,
  6714. this.options.jirecon, this.roomjid);
  6715. if(this.lastJibri)
  6716. this.recording.handleJibriPresence(this.lastJibri);
  6717. }
  6718. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6719. }
  6720. else {
  6721. this.eventEmitter.emit(
  6722. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6723. }
  6724. } else {
  6725. // Presence update for existing participant
  6726. // Watch role change:
  6727. if (this.members[from].role != member.role) {
  6728. this.members[from].role = member.role;
  6729. this.eventEmitter.emit(
  6730. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6731. }
  6732. // store the new display name
  6733. if(member.displayName)
  6734. this.members[from].displayName = member.displayName;
  6735. }
  6736. // after we had fired member or room joined events, lets fire events
  6737. // for the rest info we got in presence
  6738. for(var i = 0; i < nodes.length; i++)
  6739. {
  6740. var node = nodes[i];
  6741. switch(node.tagName)
  6742. {
  6743. case "nick":
  6744. if(!member.isFocus) {
  6745. var displayName = !this.xmpp.options.displayJids
  6746. ? member.nick : Strophe.getResourceFromJid(from);
  6747. if (displayName && displayName.length > 0) {
  6748. this.eventEmitter.emit(
  6749. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6750. }
  6751. }
  6752. break;
  6753. case "bridgeIsDown":
  6754. if(!this.bridgeIsDown) {
  6755. this.bridgeIsDown = true;
  6756. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6757. }
  6758. break;
  6759. case "jibri-recording-status":
  6760. var jibri = node;
  6761. break;
  6762. case "call-control":
  6763. var att = node.attributes;
  6764. if(!att)
  6765. break;
  6766. this.phoneNumber = att.phone || null;
  6767. this.phonePin = att.pin || null;
  6768. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  6769. break;
  6770. default :
  6771. this.processNode(node, from);
  6772. }
  6773. }
  6774. if(!member.isFocus)
  6775. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  6776. // Trigger status message update
  6777. if (member.status) {
  6778. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  6779. }
  6780. if(jibri)
  6781. {
  6782. this.lastJibri = jibri;
  6783. if(this.recording)
  6784. this.recording.handleJibriPresence(jibri);
  6785. }
  6786. };
  6787. ChatRoom.prototype.processNode = function (node, from) {
  6788. if(this.presHandlers[node.tagName])
  6789. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  6790. };
  6791. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6792. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6793. msg.c('body', body).up();
  6794. if (nickname) {
  6795. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6796. }
  6797. this.connection.send(msg);
  6798. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6799. };
  6800. ChatRoom.prototype.setSubject = function (subject) {
  6801. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6802. msg.c('subject', subject);
  6803. this.connection.send(msg);
  6804. };
  6805. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6806. delete this.lastPresences[jid];
  6807. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6808. this.moderator.onMucMemberLeft(jid);
  6809. };
  6810. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6811. // room destroyed ?
  6812. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6813. '>destroy').length) {
  6814. var reason;
  6815. var reasonSelect = $(pres).find(
  6816. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6817. '>destroy>reason');
  6818. if (reasonSelect.length) {
  6819. reason = reasonSelect.text();
  6820. }
  6821. this.xmpp.leaveRoom(this.roomjid);
  6822. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  6823. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  6824. return true;
  6825. }
  6826. // Status code 110 indicates that this notification is "self-presence".
  6827. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  6828. delete this.members[from];
  6829. this.onParticipantLeft(from);
  6830. }
  6831. // If the status code is 110 this means we're leaving and we would like
  6832. // to remove everyone else from our view, so we trigger the event.
  6833. else if (Object.keys(this.members).length > 1) {
  6834. for (var i in this.members) {
  6835. var member = this.members[i];
  6836. delete this.members[i];
  6837. this.onParticipantLeft(member);
  6838. }
  6839. }
  6840. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  6841. if (this.myroomjid === from) {
  6842. this.xmpp.leaveRoom(this.roomjid);
  6843. this.eventEmitter.emit(XMPPEvents.KICKED);
  6844. }
  6845. }
  6846. };
  6847. ChatRoom.prototype.onMessage = function (msg, from) {
  6848. var nick =
  6849. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  6850. .text() ||
  6851. Strophe.getResourceFromJid(from);
  6852. var txt = $(msg).find('>body').text();
  6853. var type = msg.getAttribute("type");
  6854. if (type == "error") {
  6855. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  6856. $(msg).find('>text').text(), txt);
  6857. return true;
  6858. }
  6859. var subject = $(msg).find('>subject');
  6860. if (subject.length) {
  6861. var subjectText = subject.text();
  6862. if (subjectText || subjectText === "") {
  6863. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  6864. logger.log("Subject is changed to " + subjectText);
  6865. }
  6866. }
  6867. // xep-0203 delay
  6868. var stamp = $(msg).find('>delay').attr('stamp');
  6869. if (!stamp) {
  6870. // or xep-0091 delay, UTC timestamp
  6871. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  6872. if (stamp) {
  6873. // the format is CCYYMMDDThh:mm:ss
  6874. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  6875. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  6876. }
  6877. }
  6878. if (txt) {
  6879. logger.log('chat', nick, txt);
  6880. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  6881. from, nick, txt, this.myroomjid, stamp);
  6882. }
  6883. };
  6884. ChatRoom.prototype.onPresenceError = function (pres, from) {
  6885. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6886. logger.log('on password required', from);
  6887. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  6888. } else if ($(pres).find(
  6889. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6890. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  6891. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  6892. // enter the room by replying with 'not-authorized'. This would
  6893. // result in reconnection from authorized domain.
  6894. // We're either missing Jicofo/Prosody config for anonymous
  6895. // domains or something is wrong.
  6896. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  6897. } else {
  6898. logger.warn('onPresError ', pres);
  6899. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6900. }
  6901. } else {
  6902. logger.warn('onPresError ', pres);
  6903. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6904. }
  6905. };
  6906. ChatRoom.prototype.kick = function (jid) {
  6907. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  6908. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  6909. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  6910. .c('reason').t('You have been kicked.').up().up().up();
  6911. this.connection.sendIQ(
  6912. kickIQ,
  6913. function (result) {
  6914. logger.log('Kick participant with jid: ', jid, result);
  6915. },
  6916. function (error) {
  6917. logger.log('Kick participant error: ', error);
  6918. });
  6919. };
  6920. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6921. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6922. var ob = this;
  6923. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6924. function (res) {
  6925. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6926. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6927. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6928. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6929. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6930. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6931. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6932. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6933. ob.connection.sendIQ(formsubmit,
  6934. onSuccess,
  6935. onError);
  6936. } else {
  6937. onNotSupported();
  6938. }
  6939. }, onError);
  6940. };
  6941. ChatRoom.prototype.addToPresence = function (key, values) {
  6942. values.tagName = key;
  6943. this.presMap["nodes"].push(values);
  6944. };
  6945. ChatRoom.prototype.removeFromPresence = function (key) {
  6946. for(var i = 0; i < this.presMap.nodes.length; i++)
  6947. {
  6948. if(key === this.presMap.nodes[i].tagName)
  6949. this.presMap.nodes.splice(i, 1);
  6950. }
  6951. };
  6952. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  6953. this.presHandlers[name] = handler;
  6954. };
  6955. ChatRoom.prototype.removePresenceListener = function (name) {
  6956. delete this.presHandlers[name];
  6957. };
  6958. ChatRoom.prototype.isModerator = function () {
  6959. return this.role === 'moderator';
  6960. };
  6961. ChatRoom.prototype.getMemberRole = function (peerJid) {
  6962. if (this.members[peerJid]) {
  6963. return this.members[peerJid].role;
  6964. }
  6965. return null;
  6966. };
  6967. ChatRoom.prototype.setJingleSession = function(session){
  6968. this.session = session;
  6969. this.session.room = this;
  6970. };
  6971. ChatRoom.prototype.removeStream = function (stream, callback) {
  6972. if(!this.session)
  6973. return;
  6974. this.session.removeStream(stream, callback);
  6975. };
  6976. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  6977. if(this.session) {
  6978. // FIXME: will block switchInProgress on true value in case of exception
  6979. this.session.switchStreams(stream, oldStream, callback, isAudio);
  6980. } else {
  6981. // We are done immediately
  6982. logger.warn("No conference handler or conference not started yet");
  6983. callback();
  6984. }
  6985. };
  6986. ChatRoom.prototype.addStream = function (stream, callback) {
  6987. if(this.session) {
  6988. // FIXME: will block switchInProgress on true value in case of exception
  6989. this.session.addStream(stream, callback);
  6990. } else {
  6991. // We are done immediately
  6992. logger.warn("No conference handler or conference not started yet");
  6993. callback();
  6994. }
  6995. };
  6996. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  6997. var self = this;
  6998. var localCallback = function (mute) {
  6999. self.sendVideoInfoPresence(mute);
  7000. if(callback)
  7001. callback(mute);
  7002. };
  7003. if(this.session)
  7004. {
  7005. this.session.setVideoMute(
  7006. mute, localCallback, options);
  7007. }
  7008. else {
  7009. localCallback(mute);
  7010. }
  7011. };
  7012. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  7013. //This will be for remote streams only
  7014. // if (this.forceMuted && !mute) {
  7015. // logger.info("Asking focus for unmute");
  7016. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  7017. // // FIXME: wait for result before resetting muted status
  7018. // this.forceMuted = false;
  7019. // }
  7020. return this.sendAudioInfoPresence(mute, callback);
  7021. };
  7022. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  7023. this.removeFromPresence("audiomuted");
  7024. this.addToPresence("audiomuted",
  7025. {attributes:
  7026. {"audions": "http://jitsi.org/jitmeet/audio"},
  7027. value: mute.toString()});
  7028. };
  7029. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7030. this.addAudioInfoToPresence(mute);
  7031. if(this.connection) {
  7032. this.sendPresence();
  7033. }
  7034. if(callback)
  7035. callback();
  7036. };
  7037. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7038. this.removeFromPresence("videomuted");
  7039. this.addToPresence("videomuted",
  7040. {attributes:
  7041. {"videons": "http://jitsi.org/jitmeet/video"},
  7042. value: mute.toString()});
  7043. };
  7044. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7045. this.addVideoInfoToPresence(mute);
  7046. if(!this.connection)
  7047. return;
  7048. this.sendPresence();
  7049. };
  7050. ChatRoom.prototype.addListener = function(type, listener) {
  7051. this.eventEmitter.on(type, listener);
  7052. };
  7053. ChatRoom.prototype.removeListener = function (type, listener) {
  7054. this.eventEmitter.removeListener(type, listener);
  7055. };
  7056. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7057. if(this.lastPresences[data.peerjid])
  7058. {
  7059. var pres = this.lastPresences[data.peerjid];
  7060. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7061. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7062. data.videomuted = ((videomuted.length > 0
  7063. && videomuted[0]
  7064. && videomuted[0]["value"] === "true")? true : false);
  7065. data.audiomuted = ((audiomuted.length > 0
  7066. && audiomuted[0]
  7067. && audiomuted[0]["value"] === "true")? true : false);
  7068. }
  7069. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7070. };
  7071. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7072. if (!this.session)
  7073. return null;
  7074. return this.session.getSsrcOwner(ssrc);
  7075. };
  7076. /**
  7077. * Returns true if the recording is supproted and false if not.
  7078. */
  7079. ChatRoom.prototype.isRecordingSupported = function () {
  7080. if(this.recording)
  7081. return this.recording.isSupported();
  7082. return false;
  7083. };
  7084. /**
  7085. * Returns null if the recording is not supported, "on" if the recording started
  7086. * and "off" if the recording is not started.
  7087. */
  7088. ChatRoom.prototype.getRecordingState = function () {
  7089. if(this.recording)
  7090. return this.recording.getState();
  7091. return "off";
  7092. }
  7093. /**
  7094. * Returns the url of the recorded video.
  7095. */
  7096. ChatRoom.prototype.getRecordingURL = function () {
  7097. if(this.recording)
  7098. return this.recording.getURL();
  7099. return null;
  7100. }
  7101. /**
  7102. * Starts/stops the recording
  7103. * @param token token for authentication
  7104. * @param statusChangeHandler {function} receives the new status as argument.
  7105. */
  7106. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7107. if(this.recording)
  7108. return this.recording.toggleRecording(options, statusChangeHandler);
  7109. return statusChangeHandler("error",
  7110. new Error("The conference is not created yet!"));
  7111. }
  7112. /**
  7113. * Returns true if the SIP calls are supported and false otherwise
  7114. */
  7115. ChatRoom.prototype.isSIPCallingSupported = function () {
  7116. if(this.moderator)
  7117. return this.moderator.isSipGatewayEnabled();
  7118. return false;
  7119. }
  7120. /**
  7121. * Dials a number.
  7122. * @param number the number
  7123. */
  7124. ChatRoom.prototype.dial = function (number) {
  7125. return this.connection.rayo.dial(number, "fromnumber",
  7126. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7127. this.focusMucJid);
  7128. }
  7129. /**
  7130. * Hangup an existing call
  7131. */
  7132. ChatRoom.prototype.hangup = function () {
  7133. return this.connection.rayo.hangup();
  7134. }
  7135. /**
  7136. * Returns the phone number for joining the conference.
  7137. */
  7138. ChatRoom.prototype.getPhoneNumber = function () {
  7139. return this.phoneNumber;
  7140. }
  7141. /**
  7142. * Returns the pin for joining the conference with phone.
  7143. */
  7144. ChatRoom.prototype.getPhonePin = function () {
  7145. return this.phonePin;
  7146. }
  7147. /**
  7148. * Returns the connection state for the current session.
  7149. */
  7150. ChatRoom.prototype.getConnectionState = function () {
  7151. if(!this.session)
  7152. return null;
  7153. return this.session.getIceConnectionState();
  7154. }
  7155. /**
  7156. * Mutes remote participant.
  7157. * @param jid of the participant
  7158. * @param mute
  7159. */
  7160. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7161. logger.info("set mute", mute);
  7162. var iqToFocus = $iq(
  7163. {to: this.focusMucJid, type: 'set'})
  7164. .c('mute', {
  7165. xmlns: 'http://jitsi.org/jitmeet/audio',
  7166. jid: jid
  7167. })
  7168. .t(mute.toString())
  7169. .up();
  7170. this.connection.sendIQ(
  7171. iqToFocus,
  7172. function (result) {
  7173. logger.log('set mute', result);
  7174. },
  7175. function (error) {
  7176. logger.log('set mute error', error);
  7177. });
  7178. }
  7179. ChatRoom.prototype.onMute = function (iq) {
  7180. var from = iq.getAttribute('from');
  7181. if (from !== this.focusMucJid) {
  7182. logger.warn("Ignored mute from non focus peer");
  7183. return false;
  7184. }
  7185. var mute = $(iq).find('mute');
  7186. if (mute.length) {
  7187. var doMuteAudio = mute.text() === "true";
  7188. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7189. }
  7190. return true;
  7191. }
  7192. module.exports = ChatRoom;
  7193. }).call(this,"/modules/xmpp/ChatRoom.js")
  7194. },{"../../service/xmpp/XMPPEvents":142,"./moderator":35,"./recording":36,"events":45,"jitsi-meet-logger":49}],29:[function(require,module,exports){
  7195. (function (__filename){
  7196. /*
  7197. * JingleSession provides an API to manage a single Jingle session. We will
  7198. * have different implementations depending on the underlying interface used
  7199. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7200. */
  7201. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7202. function JingleSession(me, sid, connection, service, eventEmitter) {
  7203. /**
  7204. * Our JID.
  7205. */
  7206. this.me = me;
  7207. /**
  7208. * The Jingle session identifier.
  7209. */
  7210. this.sid = sid;
  7211. /**
  7212. * The XMPP connection.
  7213. */
  7214. this.connection = connection;
  7215. /**
  7216. * The XMPP service.
  7217. */
  7218. this.service = service;
  7219. /**
  7220. * The event emitter.
  7221. */
  7222. this.eventEmitter = eventEmitter;
  7223. /**
  7224. * Whether to use dripping or not. Dripping is sending trickle candidates
  7225. * not one-by-one.
  7226. * Note: currently we do not support 'false'.
  7227. */
  7228. this.usedrip = true;
  7229. /**
  7230. * When dripping is used, stores ICE candidates which are to be sent.
  7231. */
  7232. this.drip_container = [];
  7233. // Media constraints. Is this WebRTC only?
  7234. this.media_constraints = null;
  7235. // ICE servers config (RTCConfiguration?).
  7236. this.ice_config = {};
  7237. // The chat room instance associated with the session.
  7238. this.room = null;
  7239. }
  7240. /**
  7241. * Prepares this object to initiate a session.
  7242. * @param peerjid the JID of the remote peer.
  7243. * @param isInitiator whether we will be the Jingle initiator.
  7244. * @param media_constraints
  7245. * @param ice_config
  7246. */
  7247. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7248. media_constraints, ice_config) {
  7249. this.media_constraints = media_constraints;
  7250. this.ice_config = ice_config;
  7251. if (this.state !== null) {
  7252. logger.error('attempt to initiate on session ' + this.sid +
  7253. 'in state ' + this.state);
  7254. return;
  7255. }
  7256. this.state = 'pending';
  7257. this.initiator = isInitiator ? this.me : peerjid;
  7258. this.responder = !isInitiator ? this.me : peerjid;
  7259. this.peerjid = peerjid;
  7260. this.doInitialize();
  7261. };
  7262. /**
  7263. * Finishes initialization.
  7264. */
  7265. JingleSession.prototype.doInitialize = function() {};
  7266. /**
  7267. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7268. * Note: currently only used on transport-info
  7269. */
  7270. JingleSession.prototype.addIceCandidates = function(contents) {};
  7271. /**
  7272. * Handles an 'add-source' event.
  7273. *
  7274. * @param contents an array of Jingle 'content' elements.
  7275. */
  7276. JingleSession.prototype.addSources = function(contents) {};
  7277. /**
  7278. * Handles a 'remove-source' event.
  7279. *
  7280. * @param contents an array of Jingle 'content' elements.
  7281. */
  7282. JingleSession.prototype.removeSources = function(contents) {};
  7283. /**
  7284. * Terminates this Jingle session (stops sending media and closes the streams?)
  7285. */
  7286. JingleSession.prototype.terminate = function() {};
  7287. /**
  7288. * Sends a Jingle session-terminate message to the peer and terminates the
  7289. * session.
  7290. * @param reason
  7291. * @param text
  7292. */
  7293. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7294. /**
  7295. * Handles an offer from the remote peer (prepares to accept a session).
  7296. * @param jingle the 'jingle' XML element.
  7297. */
  7298. JingleSession.prototype.setOffer = function(jingle) {};
  7299. /**
  7300. * Handles an answer from the remote peer (prepares to accept a session).
  7301. * @param jingle the 'jingle' XML element.
  7302. */
  7303. JingleSession.prototype.setAnswer = function(jingle) {};
  7304. module.exports = JingleSession;
  7305. }).call(this,"/modules/xmpp/JingleSession.js")
  7306. },{"jitsi-meet-logger":49}],30:[function(require,module,exports){
  7307. (function (__filename){
  7308. /* jshint -W117 */
  7309. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7310. var JingleSession = require("./JingleSession");
  7311. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7312. var SDPDiffer = require("./SDPDiffer");
  7313. var SDPUtil = require("./SDPUtil");
  7314. var SDP = require("./SDP");
  7315. var async = require("async");
  7316. var transform = require("sdp-transform");
  7317. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7318. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7319. var RTC = require("../RTC/RTC");
  7320. // Jingle stuff
  7321. function JingleSessionPC(me, sid, connection, service) {
  7322. JingleSession.call(this, me, sid, connection, service);
  7323. this.initiator = null;
  7324. this.responder = null;
  7325. this.peerjid = null;
  7326. this.state = null;
  7327. this.localSDP = null;
  7328. this.remoteSDP = null;
  7329. this.relayedStreams = [];
  7330. this.usetrickle = true;
  7331. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7332. this.hadstuncandidate = false;
  7333. this.hadturncandidate = false;
  7334. this.lasticecandidate = false;
  7335. this.statsinterval = null;
  7336. this.reason = null;
  7337. this.addssrc = [];
  7338. this.removessrc = [];
  7339. this.pendingop = null;
  7340. this.switchstreams = false;
  7341. this.addingStreams = false;
  7342. this.wait = true;
  7343. /**
  7344. * A map that stores SSRCs of local streams
  7345. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7346. */
  7347. this.localStreamsSSRC = {};
  7348. this.ssrcOwners = {};
  7349. this.ssrcVideoTypes = {};
  7350. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7351. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7352. /**
  7353. * The indicator which determines whether the (local) video has been muted
  7354. * in response to a user command in contrast to an automatic decision made
  7355. * by the application logic.
  7356. */
  7357. this.videoMuteByUser = false;
  7358. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7359. // We start with the queue paused. We resume it when the signaling state is
  7360. // stable and the ice connection state is connected.
  7361. this.modifySourcesQueue.pause();
  7362. }
  7363. //XXX this is badly broken...
  7364. JingleSessionPC.prototype = JingleSession.prototype;
  7365. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7366. JingleSessionPC.prototype.setOffer = function(offer) {
  7367. this.setRemoteDescription(offer, 'offer');
  7368. };
  7369. JingleSessionPC.prototype.setAnswer = function(answer) {
  7370. this.setRemoteDescription(answer, 'answer');
  7371. };
  7372. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7373. var signalingState = this.peerconnection.signalingState;
  7374. var iceConnectionState = this.peerconnection.iceConnectionState;
  7375. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7376. this.modifySourcesQueue.resume();
  7377. } else {
  7378. this.modifySourcesQueue.pause();
  7379. }
  7380. };
  7381. JingleSessionPC.prototype.doInitialize = function () {
  7382. var self = this;
  7383. this.hadstuncandidate = false;
  7384. this.hadturncandidate = false;
  7385. this.lasticecandidate = false;
  7386. // True if reconnect is in progress
  7387. this.isreconnect = false;
  7388. // Set to true if the connection was ever stable
  7389. this.wasstable = false;
  7390. this.peerconnection = new TraceablePeerConnection(
  7391. this.connection.jingle.ice_config,
  7392. RTC.getPCConstraints(),
  7393. this);
  7394. this.peerconnection.onicecandidate = function (event) {
  7395. var protocol;
  7396. if (event && event.candidate) {
  7397. protocol = (typeof event.candidate.protocol === 'string')
  7398. ? event.candidate.protocol.toLowerCase() : '';
  7399. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7400. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7401. return;
  7402. }
  7403. }
  7404. self.sendIceCandidate(event.candidate);
  7405. };
  7406. this.peerconnection.onaddstream = function (event) {
  7407. if (event.stream.id !== 'default') {
  7408. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7409. self.remoteStreamAdded(event);
  7410. } else {
  7411. // This is a recvonly stream. Clients that implement Unified Plan,
  7412. // such as Firefox use recvonly "streams/channels/tracks" for
  7413. // receiving remote stream/tracks, as opposed to Plan B where there
  7414. // are only 3 channels: audio, video and data.
  7415. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7416. }
  7417. };
  7418. this.peerconnection.onremovestream = function (event) {
  7419. // Remove the stream from remoteStreams
  7420. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7421. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7422. };
  7423. this.peerconnection.onsignalingstatechange = function (event) {
  7424. if (!(self && self.peerconnection)) return;
  7425. if (self.peerconnection.signalingState === 'stable') {
  7426. self.wasstable = true;
  7427. }
  7428. self.updateModifySourcesQueue();
  7429. };
  7430. /**
  7431. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7432. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7433. * RTCPeerConnection.iceConnectionState changes.
  7434. *
  7435. * @param event the event containing information about the change
  7436. */
  7437. this.peerconnection.oniceconnectionstatechange = function (event) {
  7438. if (!(self && self.peerconnection)) return;
  7439. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7440. ":\t", window.performance.now());
  7441. self.updateModifySourcesQueue();
  7442. switch (self.peerconnection.iceConnectionState) {
  7443. case 'connected':
  7444. // Informs interested parties that the connection has been restored.
  7445. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7446. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7447. self.isreconnect = false;
  7448. break;
  7449. case 'disconnected':
  7450. self.isreconnect = true;
  7451. // Informs interested parties that the connection has been interrupted.
  7452. if (self.wasstable)
  7453. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7454. break;
  7455. case 'failed':
  7456. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7457. break;
  7458. }
  7459. onIceConnectionStateChange(self.sid, self);
  7460. };
  7461. this.peerconnection.onnegotiationneeded = function (event) {
  7462. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7463. };
  7464. this.relayedStreams.forEach(function(stream) {
  7465. self.peerconnection.addStream(stream);
  7466. });
  7467. };
  7468. function onIceConnectionStateChange(sid, session) {
  7469. switch (session.peerconnection.iceConnectionState) {
  7470. case 'checking':
  7471. session.timeChecking = (new Date()).getTime();
  7472. session.firstconnect = true;
  7473. break;
  7474. case 'completed': // on caller side
  7475. case 'connected':
  7476. if (session.firstconnect) {
  7477. session.firstconnect = false;
  7478. var metadata = {};
  7479. metadata.setupTime
  7480. = (new Date()).getTime() - session.timeChecking;
  7481. session.peerconnection.getStats(function (res) {
  7482. if(res && res.result) {
  7483. res.result().forEach(function (report) {
  7484. if (report.type == 'googCandidatePair' &&
  7485. report.stat('googActiveConnection') == 'true') {
  7486. metadata.localCandidateType
  7487. = report.stat('googLocalCandidateType');
  7488. metadata.remoteCandidateType
  7489. = report.stat('googRemoteCandidateType');
  7490. // log pair as well so we can get nice pie
  7491. // charts
  7492. metadata.candidatePair
  7493. = report.stat('googLocalCandidateType') +
  7494. ';' +
  7495. report.stat('googRemoteCandidateType');
  7496. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7497. {
  7498. metadata.ipv6 = true;
  7499. }
  7500. }
  7501. });
  7502. }
  7503. });
  7504. }
  7505. break;
  7506. }
  7507. }
  7508. JingleSessionPC.prototype.accept = function () {
  7509. this.state = 'active';
  7510. var pranswer = this.peerconnection.localDescription;
  7511. if (!pranswer || pranswer.type != 'pranswer') {
  7512. return;
  7513. }
  7514. logger.log('going from pranswer to answer');
  7515. if (this.usetrickle) {
  7516. // remove candidates already sent from session-accept
  7517. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7518. for (var i = 0; i < lines.length; i++) {
  7519. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7520. }
  7521. }
  7522. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7523. // FIXME: change any inactive to sendrecv or whatever they were originally
  7524. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7525. }
  7526. var prsdp = new SDP(pranswer.sdp);
  7527. if (this.webrtcIceTcpDisable) {
  7528. prsdp.removeTcpCandidates = true;
  7529. }
  7530. if (this.webrtcIceUdpDisable) {
  7531. prsdp.removeUdpCandidates = true;
  7532. }
  7533. var accept = $iq({to: this.peerjid,
  7534. type: 'set'})
  7535. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7536. action: 'session-accept',
  7537. initiator: this.initiator,
  7538. responder: this.responder,
  7539. sid: this.sid });
  7540. // FIXME why do we generate session-accept in 3 different places ?
  7541. prsdp.toJingle(
  7542. accept,
  7543. this.initiator == this.me ? 'initiator' : 'responder');
  7544. var sdp = this.peerconnection.localDescription.sdp;
  7545. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7546. // FIXME: change any inactive to sendrecv or whatever they were originally
  7547. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7548. }
  7549. var self = this;
  7550. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7551. function () {
  7552. //logger.log('setLocalDescription success');
  7553. self.setLocalDescription();
  7554. self.connection.sendIQ(accept,
  7555. function () {
  7556. var ack = {};
  7557. ack.source = 'answer';
  7558. $(document).trigger('ack.jingle', [self.sid, ack]);
  7559. },
  7560. function (stanza) {
  7561. var error = ($(stanza).find('error').length) ? {
  7562. code: $(stanza).find('error').attr('code'),
  7563. reason: $(stanza).find('error :first')[0].tagName
  7564. }:{};
  7565. error.source = 'answer';
  7566. JingleSessionPC.onJingleError(self.sid, error);
  7567. },
  7568. 10000);
  7569. },
  7570. function (e) {
  7571. logger.error('setLocalDescription failed', e);
  7572. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7573. }
  7574. );
  7575. };
  7576. JingleSessionPC.prototype.terminate = function (reason) {
  7577. this.state = 'ended';
  7578. this.reason = reason;
  7579. this.peerconnection.close();
  7580. if (this.statsinterval !== null) {
  7581. window.clearInterval(this.statsinterval);
  7582. this.statsinterval = null;
  7583. }
  7584. };
  7585. JingleSessionPC.prototype.active = function () {
  7586. return this.state == 'active';
  7587. };
  7588. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7589. var self = this;
  7590. if (candidate && !this.lasticecandidate) {
  7591. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7592. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7593. if (!(ice && jcand)) {
  7594. logger.error('failed to get ice && jcand');
  7595. return;
  7596. }
  7597. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7598. if (jcand.type === 'srflx') {
  7599. this.hadstuncandidate = true;
  7600. } else if (jcand.type === 'relay') {
  7601. this.hadturncandidate = true;
  7602. }
  7603. if (this.usetrickle) {
  7604. if (this.usedrip) {
  7605. if (this.drip_container.length === 0) {
  7606. // start 20ms callout
  7607. window.setTimeout(function () {
  7608. if (self.drip_container.length === 0) return;
  7609. self.sendIceCandidates(self.drip_container);
  7610. self.drip_container = [];
  7611. }, 20);
  7612. }
  7613. this.drip_container.push(candidate);
  7614. return;
  7615. } else {
  7616. self.sendIceCandidate([candidate]);
  7617. }
  7618. }
  7619. } else {
  7620. //logger.log('sendIceCandidate: last candidate.');
  7621. if (!this.usetrickle) {
  7622. //logger.log('should send full offer now...');
  7623. //FIXME why do we generate session-accept in 3 different places ?
  7624. var init = $iq({to: this.peerjid,
  7625. type: 'set'})
  7626. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7627. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7628. initiator: this.initiator,
  7629. sid: this.sid});
  7630. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7631. if (self.webrtcIceTcpDisable) {
  7632. this.localSDP.removeTcpCandidates = true;
  7633. }
  7634. if (self.webrtcIceUdpDisable) {
  7635. this.localSDP.removeUdpCandidates = true;
  7636. }
  7637. var sendJingle = function (ssrc) {
  7638. if(!ssrc)
  7639. ssrc = {};
  7640. self.localSDP.toJingle(
  7641. init,
  7642. self.initiator == self.me ? 'initiator' : 'responder',
  7643. ssrc);
  7644. self.connection.sendIQ(init,
  7645. function () {
  7646. //logger.log('session initiate ack');
  7647. var ack = {};
  7648. ack.source = 'offer';
  7649. $(document).trigger('ack.jingle', [self.sid, ack]);
  7650. },
  7651. function (stanza) {
  7652. self.state = 'error';
  7653. self.peerconnection.close();
  7654. var error = ($(stanza).find('error').length) ? {
  7655. code: $(stanza).find('error').attr('code'),
  7656. reason: $(stanza).find('error :first')[0].tagName,
  7657. }:{};
  7658. error.source = 'offer';
  7659. JingleSessionPC.onJingleError(self.sid, error);
  7660. },
  7661. 10000);
  7662. };
  7663. sendJingle();
  7664. }
  7665. this.lasticecandidate = true;
  7666. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7667. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7668. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7669. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7670. }
  7671. }
  7672. };
  7673. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7674. logger.log('sendIceCandidates', candidates);
  7675. var cand = $iq({to: this.peerjid, type: 'set'})
  7676. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7677. action: 'transport-info',
  7678. initiator: this.initiator,
  7679. sid: this.sid});
  7680. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7681. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7682. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7683. if (cands.length > 0) {
  7684. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7685. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7686. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7687. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7688. }).c('transport', ice);
  7689. for (var i = 0; i < cands.length; i++) {
  7690. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7691. }
  7692. // add fingerprint
  7693. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7694. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7695. tmp.required = true;
  7696. cand.c(
  7697. 'fingerprint',
  7698. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7699. .t(tmp.fingerprint);
  7700. delete tmp.fingerprint;
  7701. cand.attrs(tmp);
  7702. cand.up();
  7703. }
  7704. cand.up(); // transport
  7705. cand.up(); // content
  7706. }
  7707. }
  7708. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7709. //logger.log('was this the last candidate', this.lasticecandidate);
  7710. this.connection.sendIQ(cand,
  7711. function () {
  7712. var ack = {};
  7713. ack.source = 'transportinfo';
  7714. $(document).trigger('ack.jingle', [this.sid, ack]);
  7715. },
  7716. function (stanza) {
  7717. var error = ($(stanza).find('error').length) ? {
  7718. code: $(stanza).find('error').attr('code'),
  7719. reason: $(stanza).find('error :first')[0].tagName,
  7720. }:{};
  7721. error.source = 'transportinfo';
  7722. JingleSessionPC.onJingleError(this.sid, error);
  7723. },
  7724. 10000);
  7725. };
  7726. JingleSessionPC.prototype.sendOffer = function () {
  7727. //logger.log('sendOffer...');
  7728. var self = this;
  7729. this.peerconnection.createOffer(function (sdp) {
  7730. self.createdOffer(sdp);
  7731. },
  7732. function (e) {
  7733. logger.error('createOffer failed', e);
  7734. },
  7735. this.media_constraints
  7736. );
  7737. };
  7738. // FIXME createdOffer is never used in jitsi-meet
  7739. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7740. //logger.log('createdOffer', sdp);
  7741. var self = this;
  7742. this.localSDP = new SDP(sdp.sdp);
  7743. //this.localSDP.mangle();
  7744. var sendJingle = function () {
  7745. var init = $iq({to: this.peerjid,
  7746. type: 'set'})
  7747. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7748. action: 'session-initiate',
  7749. initiator: this.initiator,
  7750. sid: this.sid});
  7751. self.localSDP.toJingle(
  7752. init,
  7753. this.initiator == this.me ? 'initiator' : 'responder');
  7754. self.connection.sendIQ(init,
  7755. function () {
  7756. var ack = {};
  7757. ack.source = 'offer';
  7758. $(document).trigger('ack.jingle', [self.sid, ack]);
  7759. },
  7760. function (stanza) {
  7761. self.state = 'error';
  7762. self.peerconnection.close();
  7763. var error = ($(stanza).find('error').length) ? {
  7764. code: $(stanza).find('error').attr('code'),
  7765. reason: $(stanza).find('error :first')[0].tagName,
  7766. }:{};
  7767. error.source = 'offer';
  7768. JingleSessionPC.onJingleError(self.sid, error);
  7769. },
  7770. 10000);
  7771. }
  7772. sdp.sdp = this.localSDP.raw;
  7773. this.peerconnection.setLocalDescription(sdp,
  7774. function () {
  7775. if(self.usetrickle)
  7776. {
  7777. sendJingle();
  7778. }
  7779. self.setLocalDescription();
  7780. //logger.log('setLocalDescription success');
  7781. },
  7782. function (e) {
  7783. logger.error('setLocalDescription failed', e);
  7784. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7785. }
  7786. );
  7787. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7788. for (var i = 0; i < cands.length; i++) {
  7789. var cand = SDPUtil.parse_icecandidate(cands[i]);
  7790. if (cand.type == 'srflx') {
  7791. this.hadstuncandidate = true;
  7792. } else if (cand.type == 'relay') {
  7793. this.hadturncandidate = true;
  7794. }
  7795. }
  7796. };
  7797. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  7798. var self = this;
  7799. $(contents).each(function (idx, content) {
  7800. var name = $(content).attr('name');
  7801. var mediaType = this.getAttribute('name');
  7802. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7803. ssrcs.each(function () {
  7804. var ssrc = this.getAttribute('ssrc');
  7805. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  7806. function () {
  7807. var owner = this.getAttribute('owner');
  7808. self.ssrcOwners[ssrc] = owner;
  7809. }
  7810. );
  7811. });
  7812. });
  7813. };
  7814. /**
  7815. * Returns the SSRC of local audio stream.
  7816. * @param mediaType 'audio' or 'video' media type
  7817. * @returns {*} the SSRC number of local audio or video stream.
  7818. */
  7819. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  7820. return this.localStreamsSSRC[mediaType];
  7821. };
  7822. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  7823. return this.ssrcOwners[ssrc];
  7824. };
  7825. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  7826. //logger.log('setting remote description... ', desctype);
  7827. this.remoteSDP = new SDP('');
  7828. if (this.webrtcIceTcpDisable) {
  7829. this.remoteSDP.removeTcpCandidates = true;
  7830. }
  7831. if (this.webrtcIceUdpDisable) {
  7832. this.remoteSDP.removeUdpCandidates = true;
  7833. }
  7834. this.remoteSDP.fromJingle(elem);
  7835. this.readSsrcInfo($(elem).find(">content"));
  7836. if (this.peerconnection.remoteDescription) {
  7837. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  7838. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  7839. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  7840. for (var i = 0; i < pranswer.media.length; i++) {
  7841. // make sure we have ice ufrag and pwd
  7842. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  7843. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  7844. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  7845. } else {
  7846. logger.warn('no ice ufrag?');
  7847. }
  7848. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  7849. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  7850. } else {
  7851. logger.warn('no ice pwd?');
  7852. }
  7853. }
  7854. // copy over candidates
  7855. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  7856. for (var j = 0; j < lines.length; j++) {
  7857. this.remoteSDP.media[i] += lines[j] + '\r\n';
  7858. }
  7859. }
  7860. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7861. }
  7862. }
  7863. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  7864. this.peerconnection.setRemoteDescription(remotedesc,
  7865. function () {
  7866. //logger.log('setRemoteDescription success');
  7867. },
  7868. function (e) {
  7869. logger.error('setRemoteDescription error', e);
  7870. JingleSessionPC.onJingleFatalError(self, e);
  7871. }
  7872. );
  7873. };
  7874. /**
  7875. * Adds remote ICE candidates to this Jingle session.
  7876. * @param elem An array of Jingle "content" elements?
  7877. */
  7878. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  7879. var self = this;
  7880. if (this.peerconnection.signalingState == 'closed') {
  7881. return;
  7882. }
  7883. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  7884. logger.log('trickle ice candidate arriving before session accept...');
  7885. // create a PRANSWER for setRemoteDescription
  7886. if (!this.remoteSDP) {
  7887. var cobbled = 'v=0\r\n' +
  7888. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7889. 's=-\r\n' +
  7890. 't=0 0\r\n';
  7891. // first, take some things from the local description
  7892. for (var i = 0; i < this.localSDP.media.length; i++) {
  7893. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  7894. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  7895. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  7896. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  7897. }
  7898. cobbled += 'a=inactive\r\n';
  7899. }
  7900. this.remoteSDP = new SDP(cobbled);
  7901. }
  7902. // then add things like ice and dtls from remote candidate
  7903. elem.each(function () {
  7904. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  7905. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7906. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7907. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  7908. var tmp = $(this).find('transport');
  7909. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  7910. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  7911. tmp = $(this).find('transport>fingerprint');
  7912. if (tmp.length) {
  7913. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  7914. } else {
  7915. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  7916. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  7917. }
  7918. break;
  7919. }
  7920. }
  7921. }
  7922. });
  7923. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7924. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  7925. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  7926. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  7927. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  7928. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  7929. }).length == this.remoteSDP.media.length;
  7930. if (iscomplete) {
  7931. logger.log('setting pranswer');
  7932. try {
  7933. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  7934. function() {
  7935. },
  7936. function(e) {
  7937. logger.log('setRemoteDescription pranswer failed', e.toString());
  7938. });
  7939. } catch (e) {
  7940. logger.error('setting pranswer failed', e);
  7941. }
  7942. } else {
  7943. //logger.log('not yet setting pranswer');
  7944. }
  7945. }
  7946. // operate on each content element
  7947. elem.each(function () {
  7948. // would love to deactivate this, but firefox still requires it
  7949. var idx = -1;
  7950. var i;
  7951. for (i = 0; i < self.remoteSDP.media.length; i++) {
  7952. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7953. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7954. idx = i;
  7955. break;
  7956. }
  7957. }
  7958. if (idx == -1) { // fall back to localdescription
  7959. for (i = 0; i < self.localSDP.media.length; i++) {
  7960. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7961. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7962. idx = i;
  7963. break;
  7964. }
  7965. }
  7966. }
  7967. var name = $(this).attr('name');
  7968. // TODO: check ice-pwd and ice-ufrag?
  7969. $(this).find('transport>candidate').each(function () {
  7970. var line, candidate;
  7971. var protocol = this.getAttribute('protocol');
  7972. protocol =
  7973. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  7974. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7975. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7976. return;
  7977. }
  7978. line = SDPUtil.candidateFromJingle(this);
  7979. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  7980. sdpMid: name,
  7981. candidate: line});
  7982. try {
  7983. self.peerconnection.addIceCandidate(candidate);
  7984. } catch (e) {
  7985. logger.error('addIceCandidate failed', e.toString(), line);
  7986. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  7987. err, self.peerconnection);
  7988. }
  7989. });
  7990. });
  7991. };
  7992. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  7993. //logger.log('createAnswer', provisional);
  7994. var self = this;
  7995. this.peerconnection.createAnswer(
  7996. function (sdp) {
  7997. self.createdAnswer(sdp, provisional);
  7998. },
  7999. function (e) {
  8000. logger.error('createAnswer failed', e);
  8001. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8002. },
  8003. this.media_constraints
  8004. );
  8005. };
  8006. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  8007. //logger.log('createAnswer callback');
  8008. var self = this;
  8009. this.localSDP = new SDP(sdp.sdp);
  8010. //this.localSDP.mangle();
  8011. this.usepranswer = provisional === true;
  8012. if (this.usetrickle) {
  8013. if (this.usepranswer) {
  8014. sdp.type = 'pranswer';
  8015. for (var i = 0; i < this.localSDP.media.length; i++) {
  8016. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  8017. }
  8018. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  8019. }
  8020. }
  8021. var self = this;
  8022. var sendJingle = function (ssrcs) {
  8023. // FIXME why do we generate session-accept in 3 different places ?
  8024. var accept = $iq({to: self.peerjid,
  8025. type: 'set'})
  8026. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8027. action: 'session-accept',
  8028. initiator: self.initiator,
  8029. responder: self.responder,
  8030. sid: self.sid });
  8031. if (self.webrtcIceTcpDisable) {
  8032. self.localSDP.removeTcpCandidates = true;
  8033. }
  8034. if (self.webrtcIceUdpDisable) {
  8035. self.localSDP.removeUdpCandidates = true;
  8036. }
  8037. self.localSDP.toJingle(
  8038. accept,
  8039. self.initiator == self.me ? 'initiator' : 'responder',
  8040. ssrcs);
  8041. self.connection.sendIQ(accept,
  8042. function () {
  8043. var ack = {};
  8044. ack.source = 'answer';
  8045. $(document).trigger('ack.jingle', [self.sid, ack]);
  8046. },
  8047. function (stanza) {
  8048. var error = ($(stanza).find('error').length) ? {
  8049. code: $(stanza).find('error').attr('code'),
  8050. reason: $(stanza).find('error :first')[0].tagName,
  8051. }:{};
  8052. error.source = 'answer';
  8053. JingleSessionPC.onJingleError(self.sid, error);
  8054. },
  8055. 10000);
  8056. }
  8057. sdp.sdp = this.localSDP.raw;
  8058. this.peerconnection.setLocalDescription(sdp,
  8059. function () {
  8060. //logger.log('setLocalDescription success');
  8061. if (self.usetrickle && !self.usepranswer) {
  8062. sendJingle();
  8063. }
  8064. self.setLocalDescription();
  8065. },
  8066. function (e) {
  8067. logger.error('setLocalDescription failed', e);
  8068. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8069. }
  8070. );
  8071. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8072. for (var j = 0; j < cands.length; j++) {
  8073. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8074. if (cand.type == 'srflx') {
  8075. this.hadstuncandidate = true;
  8076. } else if (cand.type == 'relay') {
  8077. this.hadturncandidate = true;
  8078. }
  8079. }
  8080. };
  8081. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8082. var self = this,
  8083. term = $iq({to: this.peerjid,
  8084. type: 'set'})
  8085. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8086. action: 'session-terminate',
  8087. initiator: this.initiator,
  8088. sid: this.sid})
  8089. .c('reason')
  8090. .c(reason || 'success');
  8091. if (text) {
  8092. term.up().c('text').t(text);
  8093. }
  8094. this.connection.sendIQ(term,
  8095. function () {
  8096. self.peerconnection.close();
  8097. self.peerconnection = null;
  8098. self.terminate();
  8099. var ack = {};
  8100. ack.source = 'terminate';
  8101. $(document).trigger('ack.jingle', [self.sid, ack]);
  8102. },
  8103. function (stanza) {
  8104. var error = ($(stanza).find('error').length) ? {
  8105. code: $(stanza).find('error').attr('code'),
  8106. reason: $(stanza).find('error :first')[0].tagName,
  8107. }:{};
  8108. $(document).trigger('ack.jingle', [self.sid, error]);
  8109. },
  8110. 10000);
  8111. if (this.statsinterval !== null) {
  8112. window.clearInterval(this.statsinterval);
  8113. this.statsinterval = null;
  8114. }
  8115. };
  8116. /**
  8117. * Handles a Jingle source-add message for this Jingle session.
  8118. * @param elem An array of Jingle "content" elements.
  8119. */
  8120. JingleSessionPC.prototype.addSource = function (elem) {
  8121. var self = this;
  8122. // FIXME: dirty waiting
  8123. if (!this.peerconnection.localDescription)
  8124. {
  8125. logger.warn("addSource - localDescription not ready yet")
  8126. setTimeout(function()
  8127. {
  8128. self.addSource(elem);
  8129. },
  8130. 200
  8131. );
  8132. return;
  8133. }
  8134. logger.log('addssrc', new Date().getTime());
  8135. logger.log('ice', this.peerconnection.iceConnectionState);
  8136. this.readSsrcInfo(elem);
  8137. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8138. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8139. $(elem).each(function (idx, content) {
  8140. var name = $(content).attr('name');
  8141. var lines = '';
  8142. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8143. var semantics = this.getAttribute('semantics');
  8144. var ssrcs = $(this).find('>source').map(function () {
  8145. return this.getAttribute('ssrc');
  8146. }).get();
  8147. if (ssrcs.length) {
  8148. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8149. }
  8150. });
  8151. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8152. tmp.each(function () {
  8153. var ssrc = $(this).attr('ssrc');
  8154. if(mySdp.containsSSRC(ssrc)){
  8155. /**
  8156. * This happens when multiple participants change their streams at the same time and
  8157. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8158. * addssrc are scheduled for update IQ. See
  8159. */
  8160. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8161. return;
  8162. }
  8163. if (sdp.containsSSRC(ssrc)) {
  8164. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8165. return;
  8166. }
  8167. $(this).find('>parameter').each(function () {
  8168. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8169. if ($(this).attr('value') && $(this).attr('value').length)
  8170. lines += ':' + $(this).attr('value');
  8171. lines += '\r\n';
  8172. });
  8173. });
  8174. sdp.media.forEach(function(media, idx) {
  8175. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8176. return;
  8177. sdp.media[idx] += lines;
  8178. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8179. self.addssrc[idx] += lines;
  8180. });
  8181. sdp.raw = sdp.session + sdp.media.join('');
  8182. });
  8183. this.modifySourcesQueue.push(function() {
  8184. // When a source is added and if this is FF, a new channel is allocated
  8185. // for receiving the added source. We need to diffuse the SSRC of this
  8186. // new recvonly channel to the rest of the peers.
  8187. logger.log('modify sources done');
  8188. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8189. logger.log("SDPs", mySdp, newSdp);
  8190. self.notifyMySSRCUpdate(mySdp, newSdp);
  8191. });
  8192. };
  8193. /**
  8194. * Handles a Jingle source-remove message for this Jingle session.
  8195. * @param elem An array of Jingle "content" elements.
  8196. */
  8197. JingleSessionPC.prototype.removeSource = function (elem) {
  8198. var self = this;
  8199. // FIXME: dirty waiting
  8200. if (!this.peerconnection.localDescription) {
  8201. logger.warn("removeSource - localDescription not ready yet");
  8202. setTimeout(function() {
  8203. self.removeSource(elem);
  8204. },
  8205. 200
  8206. );
  8207. return;
  8208. }
  8209. logger.log('removessrc', new Date().getTime());
  8210. logger.log('ice', this.peerconnection.iceConnectionState);
  8211. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8212. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8213. $(elem).each(function (idx, content) {
  8214. var name = $(content).attr('name');
  8215. var lines = '';
  8216. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8217. var semantics = this.getAttribute('semantics');
  8218. var ssrcs = $(this).find('>source').map(function () {
  8219. return this.getAttribute('ssrc');
  8220. }).get();
  8221. if (ssrcs.length) {
  8222. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8223. }
  8224. });
  8225. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8226. tmp.each(function () {
  8227. var ssrc = $(this).attr('ssrc');
  8228. // This should never happen, but can be useful for bug detection
  8229. if(mySdp.containsSSRC(ssrc)){
  8230. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8231. return;
  8232. }
  8233. $(this).find('>parameter').each(function () {
  8234. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8235. if ($(this).attr('value') && $(this).attr('value').length)
  8236. lines += ':' + $(this).attr('value');
  8237. lines += '\r\n';
  8238. });
  8239. });
  8240. sdp.media.forEach(function(media, idx) {
  8241. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8242. return;
  8243. sdp.media[idx] += lines;
  8244. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8245. self.removessrc[idx] += lines;
  8246. });
  8247. sdp.raw = sdp.session + sdp.media.join('');
  8248. });
  8249. this.modifySourcesQueue.push(function() {
  8250. // When a source is removed and if this is FF, the recvonly channel that
  8251. // receives the remote stream is deactivated . We need to diffuse the
  8252. // recvonly SSRC removal to the rest of the peers.
  8253. logger.log('modify sources done');
  8254. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8255. logger.log("SDPs", mySdp, newSdp);
  8256. self.notifyMySSRCUpdate(mySdp, newSdp);
  8257. });
  8258. };
  8259. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8260. var self = this;
  8261. if (this.peerconnection.signalingState == 'closed') return;
  8262. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8263. || this.switchstreams || this.addingStreams)){
  8264. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8265. this.setLocalDescription();
  8266. if(successCallback){
  8267. successCallback();
  8268. }
  8269. queueCallback();
  8270. return;
  8271. }
  8272. // Reset switch streams flags
  8273. this.switchstreams = false;
  8274. this.addingStreams = false;
  8275. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8276. // add sources
  8277. this.addssrc.forEach(function(lines, idx) {
  8278. sdp.media[idx] += lines;
  8279. });
  8280. this.addssrc = [];
  8281. // remove sources
  8282. this.removessrc.forEach(function(lines, idx) {
  8283. lines = lines.split('\r\n');
  8284. lines.pop(); // remove empty last element;
  8285. lines.forEach(function(line) {
  8286. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8287. });
  8288. });
  8289. this.removessrc = [];
  8290. sdp.raw = sdp.session + sdp.media.join('');
  8291. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8292. function() {
  8293. if(self.signalingState == 'closed') {
  8294. logger.error("createAnswer attempt on closed state");
  8295. queueCallback("createAnswer attempt on closed state");
  8296. return;
  8297. }
  8298. self.peerconnection.createAnswer(
  8299. function(modifiedAnswer) {
  8300. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8301. if (self.pendingop !== null) {
  8302. var sdp = new SDP(modifiedAnswer.sdp);
  8303. if (sdp.media.length > 1) {
  8304. switch(self.pendingop) {
  8305. case 'mute':
  8306. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8307. break;
  8308. case 'unmute':
  8309. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8310. break;
  8311. }
  8312. sdp.raw = sdp.session + sdp.media.join('');
  8313. modifiedAnswer.sdp = sdp.raw;
  8314. }
  8315. self.pendingop = null;
  8316. }
  8317. // FIXME: pushing down an answer while ice connection state
  8318. // is still checking is bad...
  8319. //logger.log(self.peerconnection.iceConnectionState);
  8320. // trying to work around another chrome bug
  8321. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8322. self.peerconnection.setLocalDescription(modifiedAnswer,
  8323. function() {
  8324. //logger.log('modified setLocalDescription ok');
  8325. self.setLocalDescription();
  8326. if(successCallback){
  8327. successCallback();
  8328. }
  8329. queueCallback();
  8330. },
  8331. function(error) {
  8332. logger.error('modified setLocalDescription failed', error);
  8333. queueCallback(error);
  8334. }
  8335. );
  8336. },
  8337. function(error) {
  8338. logger.error('modified answer failed', error);
  8339. queueCallback(error);
  8340. }
  8341. );
  8342. },
  8343. function(error) {
  8344. logger.error('modify failed', error);
  8345. queueCallback(error);
  8346. }
  8347. );
  8348. };
  8349. /**
  8350. * Switches video streams.
  8351. * @param newStream new stream that will be used as video of this session.
  8352. * @param oldStream old video stream of this session.
  8353. * @param successCallback callback executed after successful stream switch.
  8354. * @param isAudio whether the streams are audio (if true) or video (if false).
  8355. */
  8356. JingleSessionPC.prototype.switchStreams =
  8357. function (newStream, oldStream, successCallback, isAudio) {
  8358. var self = this;
  8359. var sender, newTrack;
  8360. var senderKind = isAudio ? 'audio' : 'video';
  8361. // Remember SDP to figure out added/removed SSRCs
  8362. var oldSdp = null;
  8363. if (self.peerconnection) {
  8364. if (self.peerconnection.localDescription) {
  8365. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8366. }
  8367. if (RTCBrowserType.getBrowserType() ===
  8368. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8369. // On Firefox we don't replace MediaStreams as this messes up the
  8370. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8371. // of complications. Instead, we use the RTPSender and replace just
  8372. // the track.
  8373. // Find the right sender (for audio or video)
  8374. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8375. if (s.track && s.track.kind === senderKind) {
  8376. sender = s;
  8377. return true;
  8378. }
  8379. });
  8380. if (sender) {
  8381. // We assume that our streams have a single track, either audio
  8382. // or video.
  8383. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8384. newStream.getVideoTracks()[0];
  8385. sender.replaceTrack(newTrack)
  8386. .then(function() {
  8387. console.log("Replaced a track, isAudio=" + isAudio);
  8388. })
  8389. .catch(function(err) {
  8390. console.log("Failed to replace a track: " + err);
  8391. });
  8392. } else {
  8393. console.log("Cannot switch tracks: no RTPSender.");
  8394. }
  8395. } else {
  8396. self.peerconnection.removeStream(oldStream, true);
  8397. if (newStream) {
  8398. self.peerconnection.addStream(newStream);
  8399. }
  8400. }
  8401. }
  8402. // Conference is not active
  8403. if (!oldSdp) {
  8404. successCallback();
  8405. return;
  8406. }
  8407. self.switchstreams = true;
  8408. self.modifySourcesQueue.push(function() {
  8409. logger.log('modify sources done');
  8410. successCallback();
  8411. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8412. logger.log("SDPs", oldSdp, newSdp);
  8413. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8414. });
  8415. };
  8416. /**
  8417. * Adds streams.
  8418. * @param stream new stream that will be added.
  8419. * @param success_callback callback executed after successful stream addition.
  8420. */
  8421. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8422. var self = this;
  8423. // Remember SDP to figure out added/removed SSRCs
  8424. var oldSdp = null;
  8425. if(this.peerconnection) {
  8426. if(this.peerconnection.localDescription) {
  8427. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8428. }
  8429. if(stream)
  8430. this.peerconnection.addStream(stream);
  8431. }
  8432. // Conference is not active
  8433. if(!oldSdp || !this.peerconnection) {
  8434. callback();
  8435. return;
  8436. }
  8437. this.addingStreams = true;
  8438. this.modifySourcesQueue.push(function() {
  8439. logger.log('modify sources done');
  8440. callback();
  8441. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8442. logger.log("SDPs", oldSdp, newSdp);
  8443. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8444. });
  8445. }
  8446. /**
  8447. * Remove streams.
  8448. * @param stream stream that will be removed.
  8449. * @param success_callback callback executed after successful stream addition.
  8450. */
  8451. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8452. var self = this;
  8453. // Remember SDP to figure out added/removed SSRCs
  8454. var oldSdp = null;
  8455. if(this.peerconnection) {
  8456. if(this.peerconnection.localDescription) {
  8457. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8458. }
  8459. if (RTCBrowserType.getBrowserType() ===
  8460. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8461. var sender = null;
  8462. // On Firefox we don't replace MediaStreams as this messes up the
  8463. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8464. // of complications. Instead, we use the RTPSender and replace just
  8465. // the track.
  8466. var track = null;
  8467. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8468. track = stream.getAudioTracks()[0];
  8469. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8470. {
  8471. track = stream.getVideoTracks()[0];
  8472. }
  8473. if(!track) {
  8474. console.log("Cannot switch tracks: no tracks.");
  8475. return;
  8476. }
  8477. // Find the right sender (for audio or video)
  8478. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8479. if (s.track === track) {
  8480. sender = s;
  8481. return true;
  8482. }
  8483. });
  8484. if (sender) {
  8485. self.peerconnection.peerconnection.removeTrack(sender);
  8486. // .then(function() {
  8487. // console.log("Replaced a track, isAudio=" + isAudio);
  8488. // })
  8489. // .catch(function(err) {
  8490. // console.log("Failed to replace a track: " + err);
  8491. // });
  8492. } else {
  8493. console.log("Cannot switch tracks: no RTPSender.");
  8494. }
  8495. } else if(stream)
  8496. this.peerconnection.removeStream(stream);
  8497. }
  8498. // Conference is not active
  8499. if(!oldSdp || !this.peerconnection) {
  8500. callback();
  8501. return;
  8502. }
  8503. this.addingStreams = true;
  8504. this.modifySourcesQueue.push(function() {
  8505. logger.log('modify sources done');
  8506. callback();
  8507. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8508. logger.log("SDPs", oldSdp, newSdp);
  8509. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8510. });
  8511. }
  8512. /**
  8513. * Figures out added/removed ssrcs and send update IQs.
  8514. * @param old_sdp SDP object for old description.
  8515. * @param new_sdp SDP object for new description.
  8516. */
  8517. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8518. if (!(this.peerconnection.signalingState == 'stable' &&
  8519. this.peerconnection.iceConnectionState == 'connected')){
  8520. logger.log("Too early to send updates");
  8521. return;
  8522. }
  8523. // send source-remove IQ.
  8524. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8525. var remove = $iq({to: this.peerjid, type: 'set'})
  8526. .c('jingle', {
  8527. xmlns: 'urn:xmpp:jingle:1',
  8528. action: 'source-remove',
  8529. initiator: this.initiator,
  8530. sid: this.sid
  8531. }
  8532. );
  8533. var removed = sdpDiffer.toJingle(remove);
  8534. if (removed && remove) {
  8535. logger.info("Sending source-remove", remove);
  8536. this.connection.sendIQ(remove,
  8537. function (res) {
  8538. logger.info('got remove result', res);
  8539. },
  8540. function (err) {
  8541. logger.error('got remove error', err);
  8542. }
  8543. );
  8544. } else {
  8545. logger.log('removal not necessary');
  8546. }
  8547. // send source-add IQ.
  8548. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8549. var add = $iq({to: this.peerjid, type: 'set'})
  8550. .c('jingle', {
  8551. xmlns: 'urn:xmpp:jingle:1',
  8552. action: 'source-add',
  8553. initiator: this.initiator,
  8554. sid: this.sid
  8555. }
  8556. );
  8557. var added = sdpDiffer.toJingle(add);
  8558. if (added && add) {
  8559. logger.info("Sending source-add", add);
  8560. this.connection.sendIQ(add,
  8561. function (res) {
  8562. logger.info('got add result', res);
  8563. },
  8564. function (err) {
  8565. logger.error('got add error', err);
  8566. }
  8567. );
  8568. } else {
  8569. logger.log('addition not necessary');
  8570. }
  8571. };
  8572. /**
  8573. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  8574. *
  8575. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  8576. * tracks; otherwise, <tt>false</tt>
  8577. * @param callback a function to be invoked with <tt>mute</tt> after all video
  8578. * tracks have been enabled/disabled. The function may, optionally, return
  8579. * another function which is to be invoked after the whole mute/unmute operation
  8580. * has completed successfully.
  8581. * @param options an object which specifies optional arguments such as the
  8582. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  8583. * specifies whether the method was initiated in response to a user command (in
  8584. * contrast to an automatic decision made by the application logic)
  8585. */
  8586. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  8587. var byUser;
  8588. if (options) {
  8589. byUser = options.byUser;
  8590. if (typeof byUser === 'undefined') {
  8591. byUser = true;
  8592. }
  8593. } else {
  8594. byUser = true;
  8595. }
  8596. // The user's command to mute the (local) video takes precedence over any
  8597. // automatic decision made by the application logic.
  8598. if (byUser) {
  8599. this.videoMuteByUser = mute;
  8600. } else if (this.videoMuteByUser) {
  8601. return;
  8602. }
  8603. this.hardMuteVideo(mute);
  8604. var self = this;
  8605. var oldSdp = null;
  8606. if(self.peerconnection) {
  8607. if(self.peerconnection.localDescription) {
  8608. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8609. }
  8610. }
  8611. this.modifySourcesQueue.push(function() {
  8612. logger.log('modify sources done');
  8613. callback(mute);
  8614. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8615. logger.log("SDPs", oldSdp, newSdp);
  8616. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8617. });
  8618. };
  8619. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  8620. this.pendingop = muted ? 'mute' : 'unmute';
  8621. };
  8622. JingleSessionPC.prototype.sendMute = function (muted, content) {
  8623. var info = $iq({to: this.peerjid,
  8624. type: 'set'})
  8625. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8626. action: 'session-info',
  8627. initiator: this.initiator,
  8628. sid: this.sid });
  8629. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8630. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  8631. if (content) {
  8632. info.attrs({'name': content});
  8633. }
  8634. this.connection.send(info);
  8635. };
  8636. JingleSessionPC.prototype.sendRinging = function () {
  8637. var info = $iq({to: this.peerjid,
  8638. type: 'set'})
  8639. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8640. action: 'session-info',
  8641. initiator: this.initiator,
  8642. sid: this.sid });
  8643. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8644. this.connection.send(info);
  8645. };
  8646. JingleSessionPC.prototype.getStats = function (interval) {
  8647. var self = this;
  8648. var recv = {audio: 0, video: 0};
  8649. var lost = {audio: 0, video: 0};
  8650. var lastrecv = {audio: 0, video: 0};
  8651. var lastlost = {audio: 0, video: 0};
  8652. var loss = {audio: 0, video: 0};
  8653. var delta = {audio: 0, video: 0};
  8654. this.statsinterval = window.setInterval(function () {
  8655. if (self && self.peerconnection && self.peerconnection.getStats) {
  8656. self.peerconnection.getStats(function (stats) {
  8657. var results = stats.result();
  8658. // TODO: there are so much statistics you can get from this..
  8659. for (var i = 0; i < results.length; ++i) {
  8660. if (results[i].type == 'ssrc') {
  8661. var packetsrecv = results[i].stat('packetsReceived');
  8662. var packetslost = results[i].stat('packetsLost');
  8663. if (packetsrecv && packetslost) {
  8664. packetsrecv = parseInt(packetsrecv, 10);
  8665. packetslost = parseInt(packetslost, 10);
  8666. if (results[i].stat('googFrameRateReceived')) {
  8667. lastlost.video = lost.video;
  8668. lastrecv.video = recv.video;
  8669. recv.video = packetsrecv;
  8670. lost.video = packetslost;
  8671. } else {
  8672. lastlost.audio = lost.audio;
  8673. lastrecv.audio = recv.audio;
  8674. recv.audio = packetsrecv;
  8675. lost.audio = packetslost;
  8676. }
  8677. }
  8678. }
  8679. }
  8680. delta.audio = recv.audio - lastrecv.audio;
  8681. delta.video = recv.video - lastrecv.video;
  8682. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8683. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8684. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8685. });
  8686. }
  8687. }, interval || 3000);
  8688. return this.statsinterval;
  8689. };
  8690. JingleSessionPC.onJingleError = function (session, error)
  8691. {
  8692. logger.error("Jingle error", error);
  8693. }
  8694. JingleSessionPC.onJingleFatalError = function (session, error)
  8695. {
  8696. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8697. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8698. }
  8699. JingleSessionPC.prototype.setLocalDescription = function () {
  8700. var self = this;
  8701. var newssrcs = [];
  8702. if(!this.peerconnection.localDescription)
  8703. return;
  8704. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8705. var i;
  8706. session.media.forEach(function (media) {
  8707. if (media.ssrcs && media.ssrcs.length > 0) {
  8708. // TODO(gp) maybe exclude FID streams?
  8709. media.ssrcs.forEach(function (ssrc) {
  8710. if (ssrc.attribute !== 'cname') {
  8711. return;
  8712. }
  8713. newssrcs.push({
  8714. 'ssrc': ssrc.id,
  8715. 'type': media.type
  8716. });
  8717. // FIXME allows for only one SSRC per media type
  8718. self.localStreamsSSRC[media.type] = ssrc.id;
  8719. });
  8720. }
  8721. });
  8722. logger.log('new ssrcs', newssrcs);
  8723. // Bind us as local SSRCs owner
  8724. if (newssrcs.length > 0) {
  8725. for (i = 0; i < newssrcs.length; i++) {
  8726. var ssrc = newssrcs[i].ssrc;
  8727. var myJid = self.me;
  8728. self.ssrcOwners[ssrc] = myJid;
  8729. }
  8730. }
  8731. }
  8732. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8733. JingleSessionPC.prototype.sendKeyframe = function () {
  8734. var pc = this.peerconnection;
  8735. logger.log('sendkeyframe', pc.iceConnectionState);
  8736. if (pc.iceConnectionState !== 'connected') return; // safe...
  8737. var self = this;
  8738. pc.setRemoteDescription(
  8739. pc.remoteDescription,
  8740. function () {
  8741. pc.createAnswer(
  8742. function (modifiedAnswer) {
  8743. pc.setLocalDescription(
  8744. modifiedAnswer,
  8745. function () {
  8746. // noop
  8747. },
  8748. function (error) {
  8749. logger.log('triggerKeyframe setLocalDescription failed', error);
  8750. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8751. }
  8752. );
  8753. },
  8754. function (error) {
  8755. logger.log('triggerKeyframe createAnswer failed', error);
  8756. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8757. }
  8758. );
  8759. },
  8760. function (error) {
  8761. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8762. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8763. }
  8764. );
  8765. }
  8766. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8767. var self = this;
  8768. var thessrc;
  8769. var streamId = RTC.getStreamID(data.stream);
  8770. // look up an associated JID for a stream id
  8771. if (!streamId) {
  8772. logger.error("No stream ID for", data.stream);
  8773. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8774. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8775. var ssrclines = this.peerconnection.remoteDescription?
  8776. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8777. ssrclines = ssrclines.filter(function (line) {
  8778. // NOTE(gp) previously we filtered on the mslabel, but that property
  8779. // is not always present.
  8780. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8781. if (RTCBrowserType.isTemasysPluginUsed()) {
  8782. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8783. } else {
  8784. return ((line.indexOf('msid:' + streamId) !== -1));
  8785. }
  8786. });
  8787. if (ssrclines.length) {
  8788. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8789. if (!self.ssrcOwners[thessrc]) {
  8790. logger.error("No SSRC owner known for: " + thessrc);
  8791. return;
  8792. }
  8793. data.peerjid = self.ssrcOwners[thessrc];
  8794. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8795. } else {
  8796. logger.error("No SSRC lines for ", streamId);
  8797. }
  8798. }
  8799. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8800. var isVideo = data.stream.getVideoTracks().length > 0;
  8801. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8802. if (isVideo &&
  8803. data.peerjid && this.peerjid === data.peerjid &&
  8804. data.stream.getVideoTracks().length === 0 &&
  8805. RTC.localVideo.getTracks().length > 0) {
  8806. window.setTimeout(function () {
  8807. self.sendKeyframe();
  8808. }, 3000);
  8809. }
  8810. }
  8811. /**
  8812. * Returns the ice connection state for the peer connection.
  8813. * @returns the ice connection state for the peer connection.
  8814. */
  8815. JingleSessionPC.prototype.getIceConnectionState = function () {
  8816. return this.peerconnection.iceConnectionState;
  8817. }
  8818. module.exports = JingleSessionPC;
  8819. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  8820. },{"../../service/xmpp/XMPPEvents":142,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":29,"./SDP":31,"./SDPDiffer":32,"./SDPUtil":33,"./TraceablePeerConnection":34,"async":44,"jitsi-meet-logger":49,"sdp-transform":82}],31:[function(require,module,exports){
  8821. (function (__filename){
  8822. /* jshint -W117 */
  8823. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8824. var SDPUtil = require("./SDPUtil");
  8825. // SDP STUFF
  8826. function SDP(sdp) {
  8827. /**
  8828. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8829. * @type {boolean}
  8830. */
  8831. this.removeTcpCandidates = false;
  8832. /**
  8833. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8834. * @type {boolean}
  8835. */
  8836. this.removeUdpCandidates = false;
  8837. this.media = sdp.split('\r\nm=');
  8838. for (var i = 1; i < this.media.length; i++) {
  8839. this.media[i] = 'm=' + this.media[i];
  8840. if (i != this.media.length - 1) {
  8841. this.media[i] += '\r\n';
  8842. }
  8843. }
  8844. this.session = this.media.shift() + '\r\n';
  8845. this.raw = this.session + this.media.join('');
  8846. }
  8847. /**
  8848. * Returns map of MediaChannel mapped per channel idx.
  8849. */
  8850. SDP.prototype.getMediaSsrcMap = function() {
  8851. var self = this;
  8852. var media_ssrcs = {};
  8853. var tmp;
  8854. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8855. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8856. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8857. var media = {
  8858. mediaindex: mediaindex,
  8859. mid: mid,
  8860. ssrcs: {},
  8861. ssrcGroups: []
  8862. };
  8863. media_ssrcs[mediaindex] = media;
  8864. tmp.forEach(function (line) {
  8865. var linessrc = line.substring(7).split(' ')[0];
  8866. // allocate new ChannelSsrc
  8867. if(!media.ssrcs[linessrc]) {
  8868. media.ssrcs[linessrc] = {
  8869. ssrc: linessrc,
  8870. lines: []
  8871. };
  8872. }
  8873. media.ssrcs[linessrc].lines.push(line);
  8874. });
  8875. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8876. tmp.forEach(function(line){
  8877. var idx = line.indexOf(' ');
  8878. var semantics = line.substr(0, idx).substr(13);
  8879. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8880. if (ssrcs.length) {
  8881. media.ssrcGroups.push({
  8882. semantics: semantics,
  8883. ssrcs: ssrcs
  8884. });
  8885. }
  8886. });
  8887. }
  8888. return media_ssrcs;
  8889. };
  8890. /**
  8891. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8892. * @param ssrc the ssrc to check.
  8893. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8894. */
  8895. SDP.prototype.containsSSRC = function (ssrc) {
  8896. // FIXME this code is really strange - improve it if you can
  8897. var medias = this.getMediaSsrcMap();
  8898. var result = false;
  8899. Object.keys(medias).forEach(function (mediaindex) {
  8900. if (result)
  8901. return;
  8902. if (medias[mediaindex].ssrcs[ssrc]) {
  8903. result = true;
  8904. }
  8905. });
  8906. return result;
  8907. };
  8908. // remove iSAC and CN from SDP
  8909. SDP.prototype.mangle = function () {
  8910. var i, j, mline, lines, rtpmap, newdesc;
  8911. for (i = 0; i < this.media.length; i++) {
  8912. lines = this.media[i].split('\r\n');
  8913. lines.pop(); // remove empty last element
  8914. mline = SDPUtil.parse_mline(lines.shift());
  8915. if (mline.media != 'audio')
  8916. continue;
  8917. newdesc = '';
  8918. mline.fmt.length = 0;
  8919. for (j = 0; j < lines.length; j++) {
  8920. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8921. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8922. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8923. continue;
  8924. mline.fmt.push(rtpmap.id);
  8925. newdesc += lines[j] + '\r\n';
  8926. } else {
  8927. newdesc += lines[j] + '\r\n';
  8928. }
  8929. }
  8930. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8931. this.media[i] += newdesc;
  8932. }
  8933. this.raw = this.session + this.media.join('');
  8934. };
  8935. // remove lines matching prefix from session section
  8936. SDP.prototype.removeSessionLines = function(prefix) {
  8937. var self = this;
  8938. var lines = SDPUtil.find_lines(this.session, prefix);
  8939. lines.forEach(function(line) {
  8940. self.session = self.session.replace(line + '\r\n', '');
  8941. });
  8942. this.raw = this.session + this.media.join('');
  8943. return lines;
  8944. }
  8945. // remove lines matching prefix from a media section specified by mediaindex
  8946. // TODO: non-numeric mediaindex could match mid
  8947. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8948. var self = this;
  8949. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  8950. lines.forEach(function(line) {
  8951. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  8952. });
  8953. this.raw = this.session + this.media.join('');
  8954. return lines;
  8955. }
  8956. // add content's to a jingle element
  8957. SDP.prototype.toJingle = function (elem, thecreator) {
  8958. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  8959. var self = this;
  8960. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  8961. // new bundle plan
  8962. if (SDPUtil.find_line(this.session, 'a=group:')) {
  8963. lines = SDPUtil.find_lines(this.session, 'a=group:');
  8964. for (i = 0; i < lines.length; i++) {
  8965. tmp = lines[i].split(' ');
  8966. var semantics = tmp.shift().substr(8);
  8967. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  8968. for (j = 0; j < tmp.length; j++) {
  8969. elem.c('content', {name: tmp[j]}).up();
  8970. }
  8971. elem.up();
  8972. }
  8973. }
  8974. for (i = 0; i < this.media.length; i++) {
  8975. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  8976. if (!(mline.media === 'audio' ||
  8977. mline.media === 'video' ||
  8978. mline.media === 'application'))
  8979. {
  8980. continue;
  8981. }
  8982. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  8983. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  8984. } else {
  8985. ssrc = false;
  8986. }
  8987. elem.c('content', {creator: thecreator, name: mline.media});
  8988. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  8989. // prefer identifier from a=mid if present
  8990. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  8991. elem.attrs({ name: mid });
  8992. }
  8993. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  8994. elem.c('description',
  8995. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  8996. media: mline.media });
  8997. if (ssrc) {
  8998. elem.attrs({ssrc: ssrc});
  8999. }
  9000. for (j = 0; j < mline.fmt.length; j++) {
  9001. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  9002. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  9003. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  9004. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  9005. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  9006. for (k = 0; k < tmp.length; k++) {
  9007. elem.c('parameter', tmp[k]).up();
  9008. }
  9009. }
  9010. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  9011. elem.up();
  9012. }
  9013. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  9014. elem.c('encryption', {required: 1});
  9015. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  9016. crypto.forEach(function(line) {
  9017. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  9018. });
  9019. elem.up(); // end of encryption
  9020. }
  9021. if (ssrc) {
  9022. // new style mapping
  9023. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9024. // FIXME: group by ssrc and support multiple different ssrcs
  9025. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  9026. if(ssrclines.length > 0) {
  9027. ssrclines.forEach(function (line) {
  9028. var idx = line.indexOf(' ');
  9029. var linessrc = line.substr(0, idx).substr(7);
  9030. if (linessrc != ssrc) {
  9031. elem.up();
  9032. ssrc = linessrc;
  9033. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9034. }
  9035. var kv = line.substr(idx + 1);
  9036. elem.c('parameter');
  9037. if (kv.indexOf(':') == -1) {
  9038. elem.attrs({ name: kv });
  9039. } else {
  9040. var k = kv.split(':', 2)[0];
  9041. elem.attrs({ name: k });
  9042. var v = kv.split(':', 2)[1];
  9043. v = SDPUtil.filter_special_chars(v);
  9044. elem.attrs({ value: v });
  9045. }
  9046. elem.up();
  9047. });
  9048. } else {
  9049. elem.up();
  9050. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9051. elem.c('parameter');
  9052. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9053. elem.up();
  9054. var msid = null;
  9055. if(mline.media == "audio")
  9056. {
  9057. msid = APP.RTC.localAudio._getId();
  9058. }
  9059. else
  9060. {
  9061. msid = APP.RTC.localVideo._getId();
  9062. }
  9063. if(msid != null)
  9064. {
  9065. msid = SDPUtil.filter_special_chars(msid);
  9066. elem.c('parameter');
  9067. elem.attrs({name: "msid", value:msid});
  9068. elem.up();
  9069. elem.c('parameter');
  9070. elem.attrs({name: "mslabel", value:msid});
  9071. elem.up();
  9072. elem.c('parameter');
  9073. elem.attrs({name: "label", value:msid});
  9074. elem.up();
  9075. }
  9076. }
  9077. elem.up();
  9078. // XEP-0339 handle ssrc-group attributes
  9079. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9080. ssrc_group_lines.forEach(function(line) {
  9081. var idx = line.indexOf(' ');
  9082. var semantics = line.substr(0, idx).substr(13);
  9083. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9084. if (ssrcs.length) {
  9085. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9086. ssrcs.forEach(function(ssrc) {
  9087. elem.c('source', { ssrc: ssrc })
  9088. .up();
  9089. });
  9090. elem.up();
  9091. }
  9092. });
  9093. }
  9094. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9095. elem.c('rtcp-mux').up();
  9096. }
  9097. // XEP-0293 -- map a=rtcp-fb:*
  9098. this.rtcpFbToJingle(i, elem, '*');
  9099. // XEP-0294
  9100. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9101. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9102. for (j = 0; j < lines.length; j++) {
  9103. tmp = SDPUtil.parse_extmap(lines[j]);
  9104. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9105. uri: tmp.uri,
  9106. id: tmp.value });
  9107. if (tmp.hasOwnProperty('direction')) {
  9108. switch (tmp.direction) {
  9109. case 'sendonly':
  9110. elem.attrs({senders: 'responder'});
  9111. break;
  9112. case 'recvonly':
  9113. elem.attrs({senders: 'initiator'});
  9114. break;
  9115. case 'sendrecv':
  9116. elem.attrs({senders: 'both'});
  9117. break;
  9118. case 'inactive':
  9119. elem.attrs({senders: 'none'});
  9120. break;
  9121. }
  9122. }
  9123. // TODO: handle params
  9124. elem.up();
  9125. }
  9126. }
  9127. elem.up(); // end of description
  9128. }
  9129. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9130. this.transportToJingle(i, elem);
  9131. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9132. elem.attrs({senders: 'both'});
  9133. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9134. elem.attrs({senders: 'initiator'});
  9135. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9136. elem.attrs({senders: 'responder'});
  9137. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9138. elem.attrs({senders: 'none'});
  9139. }
  9140. if (mline.port == '0') {
  9141. // estos hack to reject an m-line
  9142. elem.attrs({senders: 'rejected'});
  9143. }
  9144. elem.up(); // end of content
  9145. }
  9146. elem.up();
  9147. return elem;
  9148. };
  9149. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9150. var tmp, sctpmap, sctpAttrs, fingerprints;
  9151. var self = this;
  9152. elem.c('transport');
  9153. // XEP-0343 DTLS/SCTP
  9154. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9155. {
  9156. sctpmap = SDPUtil.find_line(
  9157. this.media[mediaindex], 'a=sctpmap:', self.session);
  9158. if (sctpmap)
  9159. {
  9160. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9161. elem.c('sctpmap',
  9162. {
  9163. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9164. number: sctpAttrs[0], /* SCTP port */
  9165. protocol: sctpAttrs[1] /* protocol */
  9166. });
  9167. // Optional stream count attribute
  9168. if (sctpAttrs.length > 2)
  9169. elem.attrs({ streams: sctpAttrs[2]});
  9170. elem.up();
  9171. }
  9172. }
  9173. // XEP-0320
  9174. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9175. fingerprints.forEach(function(line) {
  9176. tmp = SDPUtil.parse_fingerprint(line);
  9177. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9178. elem.c('fingerprint').t(tmp.fingerprint);
  9179. delete tmp.fingerprint;
  9180. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9181. if (line) {
  9182. tmp.setup = line.substr(8);
  9183. }
  9184. elem.attrs(tmp);
  9185. elem.up(); // end of fingerprint
  9186. });
  9187. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9188. if (tmp) {
  9189. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9190. elem.attrs(tmp);
  9191. // XEP-0176
  9192. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9193. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9194. lines.forEach(function (line) {
  9195. var candidate = SDPUtil.candidateToJingle(line);
  9196. var protocol = (candidate &&
  9197. typeof candidate.protocol === 'string')
  9198. ? candidate.protocol.toLowerCase() : '';
  9199. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9200. (self.removeUdpCandidates && protocol === 'udp')) {
  9201. return;
  9202. }
  9203. elem.c('candidate', candidate).up();
  9204. });
  9205. }
  9206. }
  9207. elem.up(); // end of transport
  9208. }
  9209. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9210. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9211. lines.forEach(function (line) {
  9212. var tmp = SDPUtil.parse_rtcpfb(line);
  9213. if (tmp.type == 'trr-int') {
  9214. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9215. elem.up();
  9216. } else {
  9217. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9218. if (tmp.params.length > 0) {
  9219. elem.attrs({'subtype': tmp.params[0]});
  9220. }
  9221. elem.up();
  9222. }
  9223. });
  9224. };
  9225. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9226. var media = '';
  9227. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9228. if (tmp.length) {
  9229. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9230. if (tmp.attr('value')) {
  9231. media += tmp.attr('value');
  9232. } else {
  9233. media += '0';
  9234. }
  9235. media += '\r\n';
  9236. }
  9237. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9238. tmp.each(function () {
  9239. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9240. if ($(this).attr('subtype')) {
  9241. media += ' ' + $(this).attr('subtype');
  9242. }
  9243. media += '\r\n';
  9244. });
  9245. return media;
  9246. };
  9247. // construct an SDP from a jingle stanza
  9248. SDP.prototype.fromJingle = function (jingle) {
  9249. var self = this;
  9250. this.raw = 'v=0\r\n' +
  9251. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9252. 's=-\r\n' +
  9253. 't=0 0\r\n';
  9254. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9255. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9256. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9257. var contents = $(group).find('>content').map(function (idx, content) {
  9258. return content.getAttribute('name');
  9259. }).get();
  9260. if (contents.length > 0) {
  9261. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9262. }
  9263. });
  9264. }
  9265. this.session = this.raw;
  9266. jingle.find('>content').each(function () {
  9267. var m = self.jingle2media($(this));
  9268. self.media.push(m);
  9269. });
  9270. // reconstruct msid-semantic -- apparently not necessary
  9271. /*
  9272. var msid = SDPUtil.parse_ssrc(this.raw);
  9273. if (msid.hasOwnProperty('mslabel')) {
  9274. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9275. }
  9276. */
  9277. this.raw = this.session + this.media.join('');
  9278. };
  9279. // translate a jingle content element into an an SDP media part
  9280. SDP.prototype.jingle2media = function (content) {
  9281. var media = '',
  9282. desc = content.find('description'),
  9283. ssrc = desc.attr('ssrc'),
  9284. self = this,
  9285. tmp;
  9286. var sctp = content.find(
  9287. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9288. tmp = { media: desc.attr('media') };
  9289. tmp.port = '1';
  9290. if (content.attr('senders') == 'rejected') {
  9291. // estos hack to reject an m-line.
  9292. tmp.port = '0';
  9293. }
  9294. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9295. if (sctp.length)
  9296. tmp.proto = 'DTLS/SCTP';
  9297. else
  9298. tmp.proto = 'RTP/SAVPF';
  9299. } else {
  9300. tmp.proto = 'RTP/AVPF';
  9301. }
  9302. if (!sctp.length) {
  9303. tmp.fmt = desc.find('payload-type').map(
  9304. function () { return this.getAttribute('id'); }).get();
  9305. media += SDPUtil.build_mline(tmp) + '\r\n';
  9306. } else {
  9307. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9308. media += 'a=sctpmap:' + sctp.attr('number') +
  9309. ' ' + sctp.attr('protocol');
  9310. var streamCount = sctp.attr('streams');
  9311. if (streamCount)
  9312. media += ' ' + streamCount + '\r\n';
  9313. else
  9314. media += '\r\n';
  9315. }
  9316. media += 'c=IN IP4 0.0.0.0\r\n';
  9317. if (!sctp.length)
  9318. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9319. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9320. if (tmp.length) {
  9321. if (tmp.attr('ufrag')) {
  9322. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9323. }
  9324. if (tmp.attr('pwd')) {
  9325. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9326. }
  9327. tmp.find('>fingerprint').each(function () {
  9328. // FIXME: check namespace at some point
  9329. media += 'a=fingerprint:' + this.getAttribute('hash');
  9330. media += ' ' + $(this).text();
  9331. media += '\r\n';
  9332. if (this.getAttribute('setup')) {
  9333. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9334. }
  9335. });
  9336. }
  9337. switch (content.attr('senders')) {
  9338. case 'initiator':
  9339. media += 'a=sendonly\r\n';
  9340. break;
  9341. case 'responder':
  9342. media += 'a=recvonly\r\n';
  9343. break;
  9344. case 'none':
  9345. media += 'a=inactive\r\n';
  9346. break;
  9347. case 'both':
  9348. media += 'a=sendrecv\r\n';
  9349. break;
  9350. }
  9351. media += 'a=mid:' + content.attr('name') + '\r\n';
  9352. // <description><rtcp-mux/></description>
  9353. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9354. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9355. if (desc.find('rtcp-mux').length) {
  9356. media += 'a=rtcp-mux\r\n';
  9357. }
  9358. if (desc.find('encryption').length) {
  9359. desc.find('encryption>crypto').each(function () {
  9360. media += 'a=crypto:' + this.getAttribute('tag');
  9361. media += ' ' + this.getAttribute('crypto-suite');
  9362. media += ' ' + this.getAttribute('key-params');
  9363. if (this.getAttribute('session-params')) {
  9364. media += ' ' + this.getAttribute('session-params');
  9365. }
  9366. media += '\r\n';
  9367. });
  9368. }
  9369. desc.find('payload-type').each(function () {
  9370. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9371. if ($(this).find('>parameter').length) {
  9372. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9373. media += $(this).find('parameter').map(function () {
  9374. return (this.getAttribute('name')
  9375. ? (this.getAttribute('name') + '=') : '') +
  9376. this.getAttribute('value');
  9377. }).get().join('; ');
  9378. media += '\r\n';
  9379. }
  9380. // xep-0293
  9381. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9382. });
  9383. // xep-0293
  9384. media += self.rtcpFbFromJingle(desc, '*');
  9385. // xep-0294
  9386. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9387. tmp.each(function () {
  9388. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9389. });
  9390. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9391. var protocol = this.getAttribute('protocol');
  9392. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9393. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9394. (self.removeUdpCandidates && protocol === 'udp')) {
  9395. return;
  9396. }
  9397. media += SDPUtil.candidateFromJingle(this);
  9398. });
  9399. // XEP-0339 handle ssrc-group attributes
  9400. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9401. var semantics = this.getAttribute('semantics');
  9402. var ssrcs = $(this).find('>source').map(function() {
  9403. return this.getAttribute('ssrc');
  9404. }).get();
  9405. if (ssrcs.length) {
  9406. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9407. }
  9408. });
  9409. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9410. tmp.each(function () {
  9411. var ssrc = this.getAttribute('ssrc');
  9412. $(this).find('>parameter').each(function () {
  9413. var name = this.getAttribute('name');
  9414. var value = this.getAttribute('value');
  9415. value = SDPUtil.filter_special_chars(value);
  9416. media += 'a=ssrc:' + ssrc + ' ' + name;
  9417. if (value && value.length)
  9418. media += ':' + value;
  9419. media += '\r\n';
  9420. });
  9421. });
  9422. return media;
  9423. };
  9424. module.exports = SDP;
  9425. }).call(this,"/modules/xmpp/SDP.js")
  9426. },{"./SDPUtil":33,"jitsi-meet-logger":49}],32:[function(require,module,exports){
  9427. var SDPUtil = require("./SDPUtil");
  9428. function SDPDiffer(mySDP, otherSDP)
  9429. {
  9430. this.mySDP = mySDP;
  9431. this.otherSDP = otherSDP;
  9432. }
  9433. /**
  9434. * Returns map of MediaChannel that contains media contained in
  9435. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9436. */
  9437. SDPDiffer.prototype.getNewMedia = function() {
  9438. // this could be useful in Array.prototype.
  9439. function arrayEquals(array) {
  9440. // if the other array is a falsy value, return
  9441. if (!array)
  9442. return false;
  9443. // compare lengths - can save a lot of time
  9444. if (this.length != array.length)
  9445. return false;
  9446. for (var i = 0, l=this.length; i < l; i++) {
  9447. // Check if we have nested arrays
  9448. if (this[i] instanceof Array && array[i] instanceof Array) {
  9449. // recurse into the nested arrays
  9450. if (!this[i].equals(array[i]))
  9451. return false;
  9452. }
  9453. else if (this[i] != array[i]) {
  9454. // Warning - two different object instances will never be
  9455. // equal: {x:20} != {x:20}
  9456. return false;
  9457. }
  9458. }
  9459. return true;
  9460. }
  9461. var myMedias = this.mySDP.getMediaSsrcMap();
  9462. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9463. var newMedia = {};
  9464. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9465. var myMedia = myMedias[othersMediaIdx];
  9466. var othersMedia = othersMedias[othersMediaIdx];
  9467. if(!myMedia && othersMedia) {
  9468. // Add whole channel
  9469. newMedia[othersMediaIdx] = othersMedia;
  9470. return;
  9471. }
  9472. // Look for new ssrcs across the channel
  9473. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9474. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9475. // Allocate channel if we've found ssrc that doesn't exist in
  9476. // our channel
  9477. if(!newMedia[othersMediaIdx]){
  9478. newMedia[othersMediaIdx] = {
  9479. mediaindex: othersMedia.mediaindex,
  9480. mid: othersMedia.mid,
  9481. ssrcs: {},
  9482. ssrcGroups: []
  9483. };
  9484. }
  9485. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9486. }
  9487. });
  9488. // Look for new ssrc groups across the channels
  9489. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9490. // try to match the other ssrc-group with an ssrc-group of ours
  9491. var matched = false;
  9492. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9493. var mySsrcGroup = myMedia.ssrcGroups[i];
  9494. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9495. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9496. [mySsrcGroup.ssrcs])) {
  9497. matched = true;
  9498. break;
  9499. }
  9500. }
  9501. if (!matched) {
  9502. // Allocate channel if we've found an ssrc-group that doesn't
  9503. // exist in our channel
  9504. if(!newMedia[othersMediaIdx]){
  9505. newMedia[othersMediaIdx] = {
  9506. mediaindex: othersMedia.mediaindex,
  9507. mid: othersMedia.mid,
  9508. ssrcs: {},
  9509. ssrcGroups: []
  9510. };
  9511. }
  9512. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9513. }
  9514. });
  9515. });
  9516. return newMedia;
  9517. };
  9518. /**
  9519. * TODO: document!
  9520. */
  9521. SDPDiffer.prototype.toJingle = function(modify) {
  9522. var sdpMediaSsrcs = this.getNewMedia();
  9523. var modified = false;
  9524. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9525. modified = true;
  9526. var media = sdpMediaSsrcs[mediaindex];
  9527. modify.c('content', {name: media.mid});
  9528. modify.c('description',
  9529. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9530. // FIXME: not completely sure this operates on blocks and / or handles
  9531. // different ssrcs correctly
  9532. // generate sources from lines
  9533. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9534. var mediaSsrc = media.ssrcs[ssrcNum];
  9535. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9536. modify.attrs({ssrc: mediaSsrc.ssrc});
  9537. // iterate over ssrc lines
  9538. mediaSsrc.lines.forEach(function (line) {
  9539. var idx = line.indexOf(' ');
  9540. var kv = line.substr(idx + 1);
  9541. modify.c('parameter');
  9542. if (kv.indexOf(':') == -1) {
  9543. modify.attrs({ name: kv });
  9544. } else {
  9545. var nv = kv.split(':', 2);
  9546. var name = nv[0];
  9547. var value = SDPUtil.filter_special_chars(nv[1]);
  9548. modify.attrs({ name: name });
  9549. modify.attrs({ value: value });
  9550. }
  9551. modify.up(); // end of parameter
  9552. });
  9553. modify.up(); // end of source
  9554. });
  9555. // generate source groups from lines
  9556. media.ssrcGroups.forEach(function(ssrcGroup) {
  9557. if (ssrcGroup.ssrcs.length) {
  9558. modify.c('ssrc-group', {
  9559. semantics: ssrcGroup.semantics,
  9560. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9561. });
  9562. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9563. modify.c('source', { ssrc: ssrc })
  9564. .up(); // end of source
  9565. });
  9566. modify.up(); // end of ssrc-group
  9567. }
  9568. });
  9569. modify.up(); // end of description
  9570. modify.up(); // end of content
  9571. });
  9572. return modified;
  9573. };
  9574. module.exports = SDPDiffer;
  9575. },{"./SDPUtil":33}],33:[function(require,module,exports){
  9576. (function (__filename){
  9577. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9578. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9579. SDPUtil = {
  9580. filter_special_chars: function (text) {
  9581. return text.replace(/[\\\/\{,\}\+]/g, "");
  9582. },
  9583. iceparams: function (mediadesc, sessiondesc) {
  9584. var data = null;
  9585. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9586. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9587. data = {
  9588. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9589. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9590. };
  9591. }
  9592. return data;
  9593. },
  9594. parse_iceufrag: function (line) {
  9595. return line.substring(12);
  9596. },
  9597. build_iceufrag: function (frag) {
  9598. return 'a=ice-ufrag:' + frag;
  9599. },
  9600. parse_icepwd: function (line) {
  9601. return line.substring(10);
  9602. },
  9603. build_icepwd: function (pwd) {
  9604. return 'a=ice-pwd:' + pwd;
  9605. },
  9606. parse_mid: function (line) {
  9607. return line.substring(6);
  9608. },
  9609. parse_mline: function (line) {
  9610. var parts = line.substring(2).split(' '),
  9611. data = {};
  9612. data.media = parts.shift();
  9613. data.port = parts.shift();
  9614. data.proto = parts.shift();
  9615. if (parts[parts.length - 1] === '') { // trailing whitespace
  9616. parts.pop();
  9617. }
  9618. data.fmt = parts;
  9619. return data;
  9620. },
  9621. build_mline: function (mline) {
  9622. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9623. },
  9624. parse_rtpmap: function (line) {
  9625. var parts = line.substring(9).split(' '),
  9626. data = {};
  9627. data.id = parts.shift();
  9628. parts = parts[0].split('/');
  9629. data.name = parts.shift();
  9630. data.clockrate = parts.shift();
  9631. data.channels = parts.length ? parts.shift() : '1';
  9632. return data;
  9633. },
  9634. /**
  9635. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9636. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9637. * @returns [SCTP port number, protocol, streams]
  9638. */
  9639. parse_sctpmap: function (line)
  9640. {
  9641. var parts = line.substring(10).split(' ');
  9642. var sctpPort = parts[0];
  9643. var protocol = parts[1];
  9644. // Stream count is optional
  9645. var streamCount = parts.length > 2 ? parts[2] : null;
  9646. return [sctpPort, protocol, streamCount];// SCTP port
  9647. },
  9648. build_rtpmap: function (el) {
  9649. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9650. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9651. line += '/' + el.getAttribute('channels');
  9652. }
  9653. return line;
  9654. },
  9655. parse_crypto: function (line) {
  9656. var parts = line.substring(9).split(' '),
  9657. data = {};
  9658. data.tag = parts.shift();
  9659. data['crypto-suite'] = parts.shift();
  9660. data['key-params'] = parts.shift();
  9661. if (parts.length) {
  9662. data['session-params'] = parts.join(' ');
  9663. }
  9664. return data;
  9665. },
  9666. parse_fingerprint: function (line) { // RFC 4572
  9667. var parts = line.substring(14).split(' '),
  9668. data = {};
  9669. data.hash = parts.shift();
  9670. data.fingerprint = parts.shift();
  9671. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9672. return data;
  9673. },
  9674. parse_fmtp: function (line) {
  9675. var parts = line.split(' '),
  9676. i, key, value,
  9677. data = [];
  9678. parts.shift();
  9679. parts = parts.join(' ').split(';');
  9680. for (i = 0; i < parts.length; i++) {
  9681. key = parts[i].split('=')[0];
  9682. while (key.length && key[0] == ' ') {
  9683. key = key.substring(1);
  9684. }
  9685. value = parts[i].split('=')[1];
  9686. if (key && value) {
  9687. data.push({name: key, value: value});
  9688. } else if (key) {
  9689. // rfc 4733 (DTMF) style stuff
  9690. data.push({name: '', value: key});
  9691. }
  9692. }
  9693. return data;
  9694. },
  9695. parse_icecandidate: function (line) {
  9696. var candidate = {},
  9697. elems = line.split(' ');
  9698. candidate.foundation = elems[0].substring(12);
  9699. candidate.component = elems[1];
  9700. candidate.protocol = elems[2].toLowerCase();
  9701. candidate.priority = elems[3];
  9702. candidate.ip = elems[4];
  9703. candidate.port = elems[5];
  9704. // elems[6] => "typ"
  9705. candidate.type = elems[7];
  9706. candidate.generation = 0; // default value, may be overwritten below
  9707. for (var i = 8; i < elems.length; i += 2) {
  9708. switch (elems[i]) {
  9709. case 'raddr':
  9710. candidate['rel-addr'] = elems[i + 1];
  9711. break;
  9712. case 'rport':
  9713. candidate['rel-port'] = elems[i + 1];
  9714. break;
  9715. case 'generation':
  9716. candidate.generation = elems[i + 1];
  9717. break;
  9718. case 'tcptype':
  9719. candidate.tcptype = elems[i + 1];
  9720. break;
  9721. default: // TODO
  9722. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9723. }
  9724. }
  9725. candidate.network = '1';
  9726. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9727. return candidate;
  9728. },
  9729. build_icecandidate: function (cand) {
  9730. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9731. line += ' ';
  9732. switch (cand.type) {
  9733. case 'srflx':
  9734. case 'prflx':
  9735. case 'relay':
  9736. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9737. line += 'raddr';
  9738. line += ' ';
  9739. line += cand['rel-addr'];
  9740. line += ' ';
  9741. line += 'rport';
  9742. line += ' ';
  9743. line += cand['rel-port'];
  9744. line += ' ';
  9745. }
  9746. break;
  9747. }
  9748. if (cand.hasOwnAttribute('tcptype')) {
  9749. line += 'tcptype';
  9750. line += ' ';
  9751. line += cand.tcptype;
  9752. line += ' ';
  9753. }
  9754. line += 'generation';
  9755. line += ' ';
  9756. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9757. return line;
  9758. },
  9759. parse_ssrc: function (desc) {
  9760. // proprietary mapping of a=ssrc lines
  9761. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9762. // and parse according to that
  9763. var lines = desc.split('\r\n'),
  9764. data = {};
  9765. for (var i = 0; i < lines.length; i++) {
  9766. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9767. var idx = lines[i].indexOf(' ');
  9768. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9769. }
  9770. }
  9771. return data;
  9772. },
  9773. parse_rtcpfb: function (line) {
  9774. var parts = line.substr(10).split(' ');
  9775. var data = {};
  9776. data.pt = parts.shift();
  9777. data.type = parts.shift();
  9778. data.params = parts;
  9779. return data;
  9780. },
  9781. parse_extmap: function (line) {
  9782. var parts = line.substr(9).split(' ');
  9783. var data = {};
  9784. data.value = parts.shift();
  9785. if (data.value.indexOf('/') != -1) {
  9786. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9787. data.value = data.value.substr(0, data.value.indexOf('/'));
  9788. } else {
  9789. data.direction = 'both';
  9790. }
  9791. data.uri = parts.shift();
  9792. data.params = parts;
  9793. return data;
  9794. },
  9795. find_line: function (haystack, needle, sessionpart) {
  9796. var lines = haystack.split('\r\n');
  9797. for (var i = 0; i < lines.length; i++) {
  9798. if (lines[i].substring(0, needle.length) == needle) {
  9799. return lines[i];
  9800. }
  9801. }
  9802. if (!sessionpart) {
  9803. return false;
  9804. }
  9805. // search session part
  9806. lines = sessionpart.split('\r\n');
  9807. for (var j = 0; j < lines.length; j++) {
  9808. if (lines[j].substring(0, needle.length) == needle) {
  9809. return lines[j];
  9810. }
  9811. }
  9812. return false;
  9813. },
  9814. find_lines: function (haystack, needle, sessionpart) {
  9815. var lines = haystack.split('\r\n'),
  9816. needles = [];
  9817. for (var i = 0; i < lines.length; i++) {
  9818. if (lines[i].substring(0, needle.length) == needle)
  9819. needles.push(lines[i]);
  9820. }
  9821. if (needles.length || !sessionpart) {
  9822. return needles;
  9823. }
  9824. // search session part
  9825. lines = sessionpart.split('\r\n');
  9826. for (var j = 0; j < lines.length; j++) {
  9827. if (lines[j].substring(0, needle.length) == needle) {
  9828. needles.push(lines[j]);
  9829. }
  9830. }
  9831. return needles;
  9832. },
  9833. candidateToJingle: function (line) {
  9834. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9835. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9836. if (line.indexOf('candidate:') === 0) {
  9837. line = 'a=' + line;
  9838. } else if (line.substring(0, 12) != 'a=candidate:') {
  9839. logger.log('parseCandidate called with a line that is not a candidate line');
  9840. logger.log(line);
  9841. return null;
  9842. }
  9843. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9844. line = line.substring(0, line.length - 2);
  9845. var candidate = {},
  9846. elems = line.split(' '),
  9847. i;
  9848. if (elems[6] != 'typ') {
  9849. logger.log('did not find typ in the right place');
  9850. logger.log(line);
  9851. return null;
  9852. }
  9853. candidate.foundation = elems[0].substring(12);
  9854. candidate.component = elems[1];
  9855. candidate.protocol = elems[2].toLowerCase();
  9856. candidate.priority = elems[3];
  9857. candidate.ip = elems[4];
  9858. candidate.port = elems[5];
  9859. // elems[6] => "typ"
  9860. candidate.type = elems[7];
  9861. candidate.generation = '0'; // default, may be overwritten below
  9862. for (i = 8; i < elems.length; i += 2) {
  9863. switch (elems[i]) {
  9864. case 'raddr':
  9865. candidate['rel-addr'] = elems[i + 1];
  9866. break;
  9867. case 'rport':
  9868. candidate['rel-port'] = elems[i + 1];
  9869. break;
  9870. case 'generation':
  9871. candidate.generation = elems[i + 1];
  9872. break;
  9873. case 'tcptype':
  9874. candidate.tcptype = elems[i + 1];
  9875. break;
  9876. default: // TODO
  9877. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9878. }
  9879. }
  9880. candidate.network = '1';
  9881. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9882. return candidate;
  9883. },
  9884. candidateFromJingle: function (cand) {
  9885. var line = 'a=candidate:';
  9886. line += cand.getAttribute('foundation');
  9887. line += ' ';
  9888. line += cand.getAttribute('component');
  9889. line += ' ';
  9890. var protocol = cand.getAttribute('protocol');
  9891. // use tcp candidates for FF
  9892. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9893. protocol = 'tcp';
  9894. }
  9895. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9896. line += ' ';
  9897. line += cand.getAttribute('priority');
  9898. line += ' ';
  9899. line += cand.getAttribute('ip');
  9900. line += ' ';
  9901. line += cand.getAttribute('port');
  9902. line += ' ';
  9903. line += 'typ';
  9904. line += ' ' + cand.getAttribute('type');
  9905. line += ' ';
  9906. switch (cand.getAttribute('type')) {
  9907. case 'srflx':
  9908. case 'prflx':
  9909. case 'relay':
  9910. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9911. line += 'raddr';
  9912. line += ' ';
  9913. line += cand.getAttribute('rel-addr');
  9914. line += ' ';
  9915. line += 'rport';
  9916. line += ' ';
  9917. line += cand.getAttribute('rel-port');
  9918. line += ' ';
  9919. }
  9920. break;
  9921. }
  9922. if (protocol.toLowerCase() == 'tcp') {
  9923. line += 'tcptype';
  9924. line += ' ';
  9925. line += cand.getAttribute('tcptype');
  9926. line += ' ';
  9927. }
  9928. line += 'generation';
  9929. line += ' ';
  9930. line += cand.getAttribute('generation') || '0';
  9931. return line + '\r\n';
  9932. }
  9933. };
  9934. module.exports = SDPUtil;
  9935. }).call(this,"/modules/xmpp/SDPUtil.js")
  9936. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],34:[function(require,module,exports){
  9937. (function (__filename){
  9938. /* global $ */
  9939. var RTC = require('../RTC/RTC');
  9940. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9941. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9942. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9943. function TraceablePeerConnection(ice_config, constraints, session) {
  9944. var self = this;
  9945. this.session = session;
  9946. var RTCPeerConnectionType = null;
  9947. if (RTCBrowserType.isFirefox()) {
  9948. RTCPeerConnectionType = mozRTCPeerConnection;
  9949. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  9950. RTCPeerConnectionType = RTCPeerConnection;
  9951. } else {
  9952. RTCPeerConnectionType = webkitRTCPeerConnection;
  9953. }
  9954. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  9955. this.updateLog = [];
  9956. this.stats = {};
  9957. this.statsinterval = null;
  9958. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9959. var Interop = require('sdp-interop').Interop;
  9960. this.interop = new Interop();
  9961. var Simulcast = require('sdp-simulcast');
  9962. this.simulcast = new Simulcast({numOfLayers: 3,
  9963. explodeRemoteSimulcast: false});
  9964. this.eventEmitter = this.session.room.eventEmitter;
  9965. // override as desired
  9966. this.trace = function (what, info) {
  9967. /*logger.warn('WTRACE', what, info);
  9968. if (info && RTCBrowserType.isIExplorer()) {
  9969. if (info.length > 1024) {
  9970. logger.warn('WTRACE', what, info.substr(1024));
  9971. }
  9972. if (info.length > 2048) {
  9973. logger.warn('WTRACE', what, info.substr(2048));
  9974. }
  9975. }*/
  9976. self.updateLog.push({
  9977. time: new Date(),
  9978. type: what,
  9979. value: info || ""
  9980. });
  9981. };
  9982. this.onicecandidate = null;
  9983. this.peerconnection.onicecandidate = function (event) {
  9984. // FIXME: this causes stack overflow with Temasys Plugin
  9985. if (!RTCBrowserType.isTemasysPluginUsed())
  9986. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  9987. if (self.onicecandidate !== null) {
  9988. self.onicecandidate(event);
  9989. }
  9990. };
  9991. this.onaddstream = null;
  9992. this.peerconnection.onaddstream = function (event) {
  9993. self.trace('onaddstream', event.stream.id);
  9994. if (self.onaddstream !== null) {
  9995. self.onaddstream(event);
  9996. }
  9997. };
  9998. this.onremovestream = null;
  9999. this.peerconnection.onremovestream = function (event) {
  10000. self.trace('onremovestream', event.stream.id);
  10001. if (self.onremovestream !== null) {
  10002. self.onremovestream(event);
  10003. }
  10004. };
  10005. this.onsignalingstatechange = null;
  10006. this.peerconnection.onsignalingstatechange = function (event) {
  10007. self.trace('onsignalingstatechange', self.signalingState);
  10008. if (self.onsignalingstatechange !== null) {
  10009. self.onsignalingstatechange(event);
  10010. }
  10011. };
  10012. this.oniceconnectionstatechange = null;
  10013. this.peerconnection.oniceconnectionstatechange = function (event) {
  10014. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  10015. if (self.oniceconnectionstatechange !== null) {
  10016. self.oniceconnectionstatechange(event);
  10017. }
  10018. };
  10019. this.onnegotiationneeded = null;
  10020. this.peerconnection.onnegotiationneeded = function (event) {
  10021. self.trace('onnegotiationneeded');
  10022. if (self.onnegotiationneeded !== null) {
  10023. self.onnegotiationneeded(event);
  10024. }
  10025. };
  10026. self.ondatachannel = null;
  10027. this.peerconnection.ondatachannel = function (event) {
  10028. self.trace('ondatachannel', event);
  10029. if (self.ondatachannel !== null) {
  10030. self.ondatachannel(event);
  10031. }
  10032. };
  10033. // XXX: do all non-firefox browsers which we support also support this?
  10034. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10035. this.statsinterval = window.setInterval(function() {
  10036. self.peerconnection.getStats(function(stats) {
  10037. var results = stats.result();
  10038. var now = new Date();
  10039. for (var i = 0; i < results.length; ++i) {
  10040. results[i].names().forEach(function (name) {
  10041. var id = results[i].id + '-' + name;
  10042. if (!self.stats[id]) {
  10043. self.stats[id] = {
  10044. startTime: now,
  10045. endTime: now,
  10046. values: [],
  10047. times: []
  10048. };
  10049. }
  10050. self.stats[id].values.push(results[i].stat(name));
  10051. self.stats[id].times.push(now.getTime());
  10052. if (self.stats[id].values.length > self.maxstats) {
  10053. self.stats[id].values.shift();
  10054. self.stats[id].times.shift();
  10055. }
  10056. self.stats[id].endTime = now;
  10057. });
  10058. }
  10059. });
  10060. }, 1000);
  10061. }
  10062. }
  10063. /**
  10064. * Returns a string representation of a SessionDescription object.
  10065. */
  10066. var dumpSDP = function(description) {
  10067. if (typeof description === 'undefined' || description == null) {
  10068. return '';
  10069. }
  10070. return 'type: ' + description.type + '\r\n' + description.sdp;
  10071. };
  10072. var insertRecvOnlySSRC = function (desc) {
  10073. if (typeof desc !== 'object' || desc === null ||
  10074. typeof desc.sdp !== 'string') {
  10075. console.warn('An empty description was passed as an argument.');
  10076. return desc;
  10077. }
  10078. var transform = require('sdp-transform');
  10079. var RandomUtil = require('../util/RandomUtil');
  10080. var session = transform.parse(desc.sdp);
  10081. if (!Array.isArray(session.media))
  10082. {
  10083. return;
  10084. }
  10085. var modded = false;
  10086. session.media.forEach(function (bLine) {
  10087. if (bLine.direction != 'recvonly')
  10088. {
  10089. return;
  10090. }
  10091. modded = true;
  10092. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10093. {
  10094. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  10095. bLine.ssrcs = [{
  10096. id: ssrc,
  10097. attribute: 'cname',
  10098. value: ['recvonly-', ssrc].join('')
  10099. }];
  10100. }
  10101. });
  10102. return (!modded) ? desc : new RTCSessionDescription({
  10103. type: desc.type,
  10104. sdp: transform.write(session),
  10105. });
  10106. };
  10107. /**
  10108. * Takes a SessionDescription object and returns a "normalized" version.
  10109. * Currently it only takes care of ordering the a=ssrc lines.
  10110. */
  10111. var normalizePlanB = function(desc) {
  10112. if (typeof desc !== 'object' || desc === null ||
  10113. typeof desc.sdp !== 'string') {
  10114. logger.warn('An empty description was passed as an argument.');
  10115. return desc;
  10116. }
  10117. var transform = require('sdp-transform');
  10118. var session = transform.parse(desc.sdp);
  10119. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10120. Array.isArray(session.media)) {
  10121. session.media.forEach(function (mLine) {
  10122. // Chrome appears to be picky about the order in which a=ssrc lines
  10123. // are listed in an m-line when rtx is enabled (and thus there are
  10124. // a=ssrc-group lines with FID semantics). Specifically if we have
  10125. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10126. // the "a=ssrc:S1" lines, SRD fails.
  10127. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10128. // first.
  10129. var firstSsrcs = [];
  10130. var newSsrcLines = [];
  10131. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10132. mLine.ssrcGroups.forEach(function (group) {
  10133. if (typeof group.semantics !== 'undefined' &&
  10134. group.semantics === 'FID') {
  10135. if (typeof group.ssrcs !== 'undefined') {
  10136. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10137. }
  10138. }
  10139. });
  10140. }
  10141. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10142. var i;
  10143. for (i = 0; i<mLine.ssrcs.length; i++){
  10144. if (typeof mLine.ssrcs[i] === 'object'
  10145. && typeof mLine.ssrcs[i].id !== 'undefined'
  10146. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10147. newSsrcLines.push(mLine.ssrcs[i]);
  10148. delete mLine.ssrcs[i];
  10149. }
  10150. }
  10151. for (i = 0; i<mLine.ssrcs.length; i++){
  10152. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10153. newSsrcLines.push(mLine.ssrcs[i]);
  10154. }
  10155. }
  10156. mLine.ssrcs = newSsrcLines;
  10157. }
  10158. });
  10159. }
  10160. var resStr = transform.write(session);
  10161. return new RTCSessionDescription({
  10162. type: desc.type,
  10163. sdp: resStr
  10164. });
  10165. };
  10166. var getters = {
  10167. signalingState: function () {
  10168. return this.peerconnection.signalingState;
  10169. },
  10170. iceConnectionState: function () {
  10171. return this.peerconnection.iceConnectionState;
  10172. },
  10173. localDescription: function() {
  10174. var desc = this.peerconnection.localDescription;
  10175. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10176. // if we're running on FF, transform to Plan B first.
  10177. if (RTCBrowserType.usesUnifiedPlan()) {
  10178. desc = this.interop.toPlanB(desc);
  10179. this.trace('getLocalDescription::postTransform (Plan B)',
  10180. dumpSDP(desc));
  10181. }
  10182. return desc;
  10183. },
  10184. remoteDescription: function() {
  10185. var desc = this.peerconnection.remoteDescription;
  10186. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10187. // if we're running on FF, transform to Plan B first.
  10188. if (RTCBrowserType.usesUnifiedPlan()) {
  10189. desc = this.interop.toPlanB(desc);
  10190. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10191. }
  10192. return desc;
  10193. }
  10194. };
  10195. Object.keys(getters).forEach(function (prop) {
  10196. Object.defineProperty(
  10197. TraceablePeerConnection.prototype,
  10198. prop, {
  10199. get: getters[prop]
  10200. }
  10201. );
  10202. });
  10203. TraceablePeerConnection.prototype.addStream = function (stream) {
  10204. this.trace('addStream', stream.id);
  10205. try
  10206. {
  10207. this.peerconnection.addStream(stream);
  10208. }
  10209. catch (e)
  10210. {
  10211. logger.error(e);
  10212. }
  10213. };
  10214. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10215. this.trace('removeStream', stream.id);
  10216. if(stopStreams) {
  10217. RTC.stopMediaStream(stream);
  10218. }
  10219. try {
  10220. // FF doesn't support this yet.
  10221. if (this.peerconnection.removeStream)
  10222. this.peerconnection.removeStream(stream);
  10223. } catch (e) {
  10224. logger.error(e);
  10225. }
  10226. };
  10227. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10228. this.trace('createDataChannel', label, opts);
  10229. return this.peerconnection.createDataChannel(label, opts);
  10230. };
  10231. TraceablePeerConnection.prototype.setLocalDescription
  10232. = function (description, successCallback, failureCallback) {
  10233. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10234. // if we're running on FF, transform to Plan A first.
  10235. if (RTCBrowserType.usesUnifiedPlan()) {
  10236. description = this.interop.toUnifiedPlan(description);
  10237. this.trace('setLocalDescription::postTransform (Plan A)',
  10238. dumpSDP(description));
  10239. }
  10240. var self = this;
  10241. this.peerconnection.setLocalDescription(description,
  10242. function () {
  10243. self.trace('setLocalDescriptionOnSuccess');
  10244. successCallback();
  10245. },
  10246. function (err) {
  10247. self.trace('setLocalDescriptionOnFailure', err);
  10248. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10249. err, self.peerconnection);
  10250. failureCallback(err);
  10251. }
  10252. );
  10253. };
  10254. TraceablePeerConnection.prototype.setRemoteDescription
  10255. = function (description, successCallback, failureCallback) {
  10256. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10257. // TODO the focus should squeze or explode the remote simulcast
  10258. description = this.simulcast.mungeRemoteDescription(description);
  10259. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10260. // if we're running on FF, transform to Plan A first.
  10261. if (RTCBrowserType.usesUnifiedPlan()) {
  10262. description = this.interop.toUnifiedPlan(description);
  10263. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10264. }
  10265. if (RTCBrowserType.usesPlanB()) {
  10266. description = normalizePlanB(description);
  10267. }
  10268. var self = this;
  10269. this.peerconnection.setRemoteDescription(description,
  10270. function () {
  10271. self.trace('setRemoteDescriptionOnSuccess');
  10272. successCallback();
  10273. },
  10274. function (err) {
  10275. self.trace('setRemoteDescriptionOnFailure', err);
  10276. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10277. err, self.peerconnection);
  10278. failureCallback(err);
  10279. }
  10280. );
  10281. /*
  10282. if (this.statsinterval === null && this.maxstats > 0) {
  10283. // start gathering stats
  10284. }
  10285. */
  10286. };
  10287. TraceablePeerConnection.prototype.close = function () {
  10288. this.trace('stop');
  10289. if (this.statsinterval !== null) {
  10290. window.clearInterval(this.statsinterval);
  10291. this.statsinterval = null;
  10292. }
  10293. this.peerconnection.close();
  10294. };
  10295. TraceablePeerConnection.prototype.createOffer
  10296. = function (successCallback, failureCallback, constraints) {
  10297. var self = this;
  10298. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10299. this.peerconnection.createOffer(
  10300. function (offer) {
  10301. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10302. // NOTE this is not tested because in meet the focus generates the
  10303. // offer.
  10304. // if we're running on FF, transform to Plan B first.
  10305. if (RTCBrowserType.usesUnifiedPlan()) {
  10306. offer = self.interop.toPlanB(offer);
  10307. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10308. }
  10309. if (RTCBrowserType.isChrome())
  10310. {
  10311. offer = insertRecvOnlySSRC(offer);
  10312. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  10313. }
  10314. if (!self.session.room.options.disableSimulcast
  10315. && self.simulcast.isSupported()) {
  10316. offer = self.simulcast.mungeLocalDescription(offer);
  10317. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10318. dumpSDP(offer));
  10319. }
  10320. successCallback(offer);
  10321. },
  10322. function(err) {
  10323. self.trace('createOfferOnFailure', err);
  10324. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10325. self.peerconnection);
  10326. failureCallback(err);
  10327. },
  10328. constraints
  10329. );
  10330. };
  10331. TraceablePeerConnection.prototype.createAnswer
  10332. = function (successCallback, failureCallback, constraints) {
  10333. var self = this;
  10334. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10335. this.peerconnection.createAnswer(
  10336. function (answer) {
  10337. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10338. // if we're running on FF, transform to Plan A first.
  10339. if (RTCBrowserType.usesUnifiedPlan()) {
  10340. answer = self.interop.toPlanB(answer);
  10341. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10342. dumpSDP(answer));
  10343. }
  10344. if (RTCBrowserType.isChrome())
  10345. {
  10346. answer = insertRecvOnlySSRC(answer);
  10347. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  10348. }
  10349. if (!self.session.room.options.disableSimulcast
  10350. && self.simulcast.isSupported()) {
  10351. answer = self.simulcast.mungeLocalDescription(answer);
  10352. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10353. dumpSDP(answer));
  10354. }
  10355. successCallback(answer);
  10356. },
  10357. function(err) {
  10358. self.trace('createAnswerOnFailure', err);
  10359. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10360. self.peerconnection);
  10361. failureCallback(err);
  10362. },
  10363. constraints
  10364. );
  10365. };
  10366. TraceablePeerConnection.prototype.addIceCandidate
  10367. = function (candidate, successCallback, failureCallback) {
  10368. //var self = this;
  10369. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10370. this.peerconnection.addIceCandidate(candidate);
  10371. /* maybe later
  10372. this.peerconnection.addIceCandidate(candidate,
  10373. function () {
  10374. self.trace('addIceCandidateOnSuccess');
  10375. successCallback();
  10376. },
  10377. function (err) {
  10378. self.trace('addIceCandidateOnFailure', err);
  10379. failureCallback(err);
  10380. }
  10381. );
  10382. */
  10383. };
  10384. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10385. // TODO: Is this the correct way to handle Opera, Temasys?
  10386. if (RTCBrowserType.isFirefox()) {
  10387. // ignore for now...
  10388. if(!errback)
  10389. errback = function () {};
  10390. this.peerconnection.getStats(null, callback, errback);
  10391. } else {
  10392. this.peerconnection.getStats(callback);
  10393. }
  10394. };
  10395. module.exports = TraceablePeerConnection;
  10396. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10397. },{"../../service/xmpp/XMPPEvents":142,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":49,"sdp-interop":68,"sdp-simulcast":75,"sdp-transform":82}],35:[function(require,module,exports){
  10398. (function (__filename){
  10399. /* global $, $iq, Promise, Strophe */
  10400. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10401. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10402. var AuthenticationEvents
  10403. = require("../../service/authentication/AuthenticationEvents");
  10404. function createExpBackoffTimer(step) {
  10405. var count = 1;
  10406. return function (reset) {
  10407. // Reset call
  10408. if (reset) {
  10409. count = 1;
  10410. return;
  10411. }
  10412. // Calculate next timeout
  10413. var timeout = Math.pow(2, count - 1);
  10414. count += 1;
  10415. return timeout * step;
  10416. };
  10417. }
  10418. function Moderator(roomName, xmpp, emitter, settings) {
  10419. this.roomName = roomName;
  10420. this.xmppService = xmpp;
  10421. this.getNextTimeout = createExpBackoffTimer(1000);
  10422. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10423. // External authentication stuff
  10424. this.externalAuthEnabled = false;
  10425. this.settings = settings;
  10426. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10427. // it will be enabled automatically if focus detects the component through
  10428. // service discovery.
  10429. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10430. this.xmppService.options.hosts.call_control !== undefined;
  10431. this.eventEmitter = emitter;
  10432. this.connection = this.xmppService.connection;
  10433. this.focusUserJid;
  10434. //FIXME:
  10435. // Message listener that talks to POPUP window
  10436. function listener(event) {
  10437. if (event.data && event.data.sessionId) {
  10438. if (event.origin !== window.location.origin) {
  10439. logger.warn("Ignoring sessionId from different origin: " +
  10440. event.origin);
  10441. return;
  10442. }
  10443. localStorage.setItem('sessionId', event.data.sessionId);
  10444. // After popup is closed we will authenticate
  10445. }
  10446. }
  10447. // Register
  10448. if (window.addEventListener) {
  10449. window.addEventListener("message", listener, false);
  10450. } else {
  10451. window.attachEvent("onmessage", listener);
  10452. }
  10453. }
  10454. Moderator.prototype.isExternalAuthEnabled = function () {
  10455. return this.externalAuthEnabled;
  10456. };
  10457. Moderator.prototype.isSipGatewayEnabled = function () {
  10458. return this.sipGatewayEnabled;
  10459. };
  10460. Moderator.prototype.onMucMemberLeft = function (jid) {
  10461. logger.info("Someone left is it focus ? " + jid);
  10462. var resource = Strophe.getResourceFromJid(jid);
  10463. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10464. logger.info(
  10465. "Focus has left the room - leaving conference");
  10466. //hangUp();
  10467. // We'd rather reload to have everything re-initialized
  10468. //FIXME: show some message before reload
  10469. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10470. }
  10471. };
  10472. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10473. if (!this.focusUserJid) {
  10474. this.focusUserJid = focusJid;
  10475. logger.info("Focus jid set to: " + this.focusUserJid);
  10476. }
  10477. };
  10478. Moderator.prototype.getFocusUserJid = function () {
  10479. return this.focusUserJid;
  10480. };
  10481. Moderator.prototype.getFocusComponent = function () {
  10482. // Get focus component address
  10483. var focusComponent = this.xmppService.options.hosts.focus;
  10484. // If not specified use default: 'focus.domain'
  10485. if (!focusComponent) {
  10486. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10487. }
  10488. return focusComponent;
  10489. };
  10490. Moderator.prototype.createConferenceIq = function () {
  10491. // Generate create conference IQ
  10492. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10493. // Session Id used for authentication
  10494. var sessionId = localStorage.getItem('sessionId');
  10495. var machineUID = this.settings.getSettings().uid;
  10496. logger.info(
  10497. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10498. elem.c('conference', {
  10499. xmlns: 'http://jitsi.org/protocol/focus',
  10500. room: this.roomName,
  10501. 'machine-uid': machineUID
  10502. });
  10503. if (sessionId) {
  10504. elem.attrs({ 'session-id': sessionId});
  10505. }
  10506. if (this.xmppService.options.hosts.bridge !== undefined) {
  10507. elem.c(
  10508. 'property', {
  10509. name: 'bridge',
  10510. value: this.xmppService.options.hosts.bridge
  10511. }).up();
  10512. }
  10513. if (this.xmppService.options.enforcedBridge !== undefined) {
  10514. elem.c(
  10515. 'property', {
  10516. name: 'enforcedBridge',
  10517. value: this.xmppService.options.enforcedBridge
  10518. }).up();
  10519. }
  10520. // Tell the focus we have Jigasi configured
  10521. if (this.xmppService.options.hosts.call_control !== undefined) {
  10522. elem.c(
  10523. 'property', {
  10524. name: 'call_control',
  10525. value: this.xmppService.options.hosts.call_control
  10526. }).up();
  10527. }
  10528. if (this.xmppService.options.channelLastN !== undefined) {
  10529. elem.c(
  10530. 'property', {
  10531. name: 'channelLastN',
  10532. value: this.xmppService.options.channelLastN
  10533. }).up();
  10534. }
  10535. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10536. elem.c(
  10537. 'property', {
  10538. name: 'adaptiveLastN',
  10539. value: this.xmppService.options.adaptiveLastN
  10540. }).up();
  10541. }
  10542. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10543. elem.c(
  10544. 'property', {
  10545. name: 'adaptiveSimulcast',
  10546. value: this.xmppService.options.adaptiveSimulcast
  10547. }).up();
  10548. }
  10549. if (this.xmppService.options.openSctp !== undefined) {
  10550. elem.c(
  10551. 'property', {
  10552. name: 'openSctp',
  10553. value: this.xmppService.options.openSctp
  10554. }).up();
  10555. }
  10556. if (this.xmppService.options.startAudioMuted !== undefined)
  10557. {
  10558. elem.c(
  10559. 'property', {
  10560. name: 'startAudioMuted',
  10561. value: this.xmppService.options.startAudioMuted
  10562. }).up();
  10563. }
  10564. if (this.xmppService.options.startVideoMuted !== undefined)
  10565. {
  10566. elem.c(
  10567. 'property', {
  10568. name: 'startVideoMuted',
  10569. value: this.xmppService.options.startVideoMuted
  10570. }).up();
  10571. }
  10572. elem.c(
  10573. 'property', {
  10574. name: 'simulcastMode',
  10575. value: 'rewriting'
  10576. }).up();
  10577. elem.up();
  10578. return elem;
  10579. };
  10580. Moderator.prototype.parseSessionId = function (resultIq) {
  10581. var sessionId = $(resultIq).find('conference').attr('session-id');
  10582. if (sessionId) {
  10583. logger.info('Received sessionId: ' + sessionId);
  10584. localStorage.setItem('sessionId', sessionId);
  10585. }
  10586. };
  10587. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10588. this.setFocusUserJid(
  10589. $(resultIq).find('conference').attr('focusjid'));
  10590. var authenticationEnabled
  10591. = $(resultIq).find(
  10592. '>conference>property' +
  10593. '[name=\'authentication\'][value=\'true\']').length > 0;
  10594. logger.info("Authentication enabled: " + authenticationEnabled);
  10595. this.externalAuthEnabled = $(resultIq).find(
  10596. '>conference>property' +
  10597. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10598. console.info(
  10599. 'External authentication enabled: ' + this.externalAuthEnabled);
  10600. if (!this.externalAuthEnabled) {
  10601. // We expect to receive sessionId in 'internal' authentication mode
  10602. this.parseSessionId(resultIq);
  10603. }
  10604. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10605. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10606. authenticationEnabled, authIdentity);
  10607. // Check if focus has auto-detected Jigasi component(this will be also
  10608. // included if we have passed our host from the config)
  10609. if ($(resultIq).find(
  10610. '>conference>property' +
  10611. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10612. this.sipGatewayEnabled = true;
  10613. }
  10614. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10615. };
  10616. // FIXME = we need to show the fact that we're waiting for the focus
  10617. // to the user(or that focus is not available)
  10618. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10619. // Try to use focus user JID from the config
  10620. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10621. // Send create conference IQ
  10622. var iq = this.createConferenceIq();
  10623. var self = this;
  10624. this.connection.sendIQ(
  10625. iq,
  10626. function (result) {
  10627. // Setup config options
  10628. self.parseConfigOptions(result);
  10629. if ('true' === $(result).find('conference').attr('ready')) {
  10630. // Reset both timers
  10631. self.getNextTimeout(true);
  10632. self.getNextErrorTimeout(true);
  10633. // Exec callback
  10634. callback();
  10635. } else {
  10636. var waitMs = self.getNextTimeout();
  10637. logger.info("Waiting for the focus... " + waitMs);
  10638. // Reset error timeout
  10639. self.getNextErrorTimeout(true);
  10640. window.setTimeout(
  10641. function () {
  10642. self.allocateConferenceFocus(callback);
  10643. }, waitMs);
  10644. }
  10645. },
  10646. function (error) {
  10647. // Invalid session ? remove and try again
  10648. // without session ID to get a new one
  10649. var invalidSession
  10650. = $(error).find('>error>session-invalid').length;
  10651. if (invalidSession) {
  10652. logger.info("Session expired! - removing");
  10653. localStorage.removeItem("sessionId");
  10654. }
  10655. if ($(error).find('>error>graceful-shutdown').length) {
  10656. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10657. return;
  10658. }
  10659. // Check for error returned by the reservation system
  10660. var reservationErr = $(error).find('>error>reservation-error');
  10661. if (reservationErr.length) {
  10662. // Trigger error event
  10663. var errorCode = reservationErr.attr('error-code');
  10664. var errorMsg;
  10665. if ($(error).find('>error>text')) {
  10666. errorMsg = $(error).find('>error>text').text();
  10667. }
  10668. self.eventEmitter.emit(
  10669. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10670. return;
  10671. }
  10672. // Not authorized to create new room
  10673. if ($(error).find('>error>not-authorized').length) {
  10674. logger.warn("Unauthorized to start the conference", error);
  10675. var toDomain
  10676. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10677. if (toDomain !==
  10678. this.xmppService.options.hosts.anonymousdomain) {
  10679. //FIXME: "is external" should come either from
  10680. // the focus or config.js
  10681. self.externalAuthEnabled = true;
  10682. }
  10683. self.eventEmitter.emit(
  10684. XMPPEvents.AUTHENTICATION_REQUIRED,
  10685. function () {
  10686. self.allocateConferenceFocus(
  10687. callback);
  10688. });
  10689. return;
  10690. }
  10691. var waitMs = self.getNextErrorTimeout();
  10692. logger.error("Focus error, retry after " + waitMs, error);
  10693. // Show message
  10694. var focusComponent = self.getFocusComponent();
  10695. var retrySec = waitMs / 1000;
  10696. //FIXME: message is duplicated ?
  10697. // Do not show in case of session invalid
  10698. // which means just a retry
  10699. if (!invalidSession) {
  10700. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10701. focusComponent, retrySec);
  10702. }
  10703. // Reset response timeout
  10704. self.getNextTimeout(true);
  10705. window.setTimeout(
  10706. function () {
  10707. self.allocateConferenceFocus(callback);
  10708. }, waitMs);
  10709. }
  10710. );
  10711. };
  10712. Moderator.prototype.authenticate = function () {
  10713. var self = this;
  10714. return new Promise(function (resolve, reject) {
  10715. self.connection.sendIQ(
  10716. self.createConferenceIq(),
  10717. function (result) {
  10718. self.parseSessionId(result);
  10719. resolve();
  10720. }, function (error) {
  10721. var code = $(error).find('>error').attr('code');
  10722. reject(error, code);
  10723. }
  10724. );
  10725. });
  10726. };
  10727. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10728. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10729. iq.c('login-url', {
  10730. xmlns: 'http://jitsi.org/protocol/focus',
  10731. room: this.roomName,
  10732. 'machine-uid': this.settings.getSettings().uid
  10733. });
  10734. this.connection.sendIQ(
  10735. iq,
  10736. function (result) {
  10737. var url = $(result).find('login-url').attr('url');
  10738. url = url = decodeURIComponent(url);
  10739. if (url) {
  10740. logger.info("Got auth url: " + url);
  10741. urlCallback(url);
  10742. } else {
  10743. logger.error(
  10744. "Failed to get auth url from the focus", result);
  10745. failureCallback(result);
  10746. }
  10747. },
  10748. function (error) {
  10749. logger.error("Get auth url error", error);
  10750. failureCallback(error);
  10751. }
  10752. );
  10753. };
  10754. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10755. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10756. iq.c('login-url', {
  10757. xmlns: 'http://jitsi.org/protocol/focus',
  10758. room: this.roomName,
  10759. 'machine-uid': this.settings.getSettings().uid,
  10760. popup: true
  10761. });
  10762. this.connection.sendIQ(
  10763. iq,
  10764. function (result) {
  10765. var url = $(result).find('login-url').attr('url');
  10766. url = url = decodeURIComponent(url);
  10767. if (url) {
  10768. logger.info("Got POPUP auth url: " + url);
  10769. urlCallback(url);
  10770. } else {
  10771. logger.error(
  10772. "Failed to get POPUP auth url from the focus", result);
  10773. failureCallback(result);
  10774. }
  10775. },
  10776. function (error) {
  10777. logger.error('Get POPUP auth url error', error);
  10778. failureCallback(error);
  10779. }
  10780. );
  10781. };
  10782. Moderator.prototype.logout = function (callback) {
  10783. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10784. var sessionId = localStorage.getItem('sessionId');
  10785. if (!sessionId) {
  10786. callback();
  10787. return;
  10788. }
  10789. iq.c('logout', {
  10790. xmlns: 'http://jitsi.org/protocol/focus',
  10791. 'session-id': sessionId
  10792. });
  10793. this.connection.sendIQ(
  10794. iq,
  10795. function (result) {
  10796. var logoutUrl = $(result).find('logout').attr('logout-url');
  10797. if (logoutUrl) {
  10798. logoutUrl = decodeURIComponent(logoutUrl);
  10799. }
  10800. logger.info("Log out OK, url: " + logoutUrl, result);
  10801. localStorage.removeItem('sessionId');
  10802. callback(logoutUrl);
  10803. },
  10804. function (error) {
  10805. logger.error("Logout error", error);
  10806. }
  10807. );
  10808. };
  10809. module.exports = Moderator;
  10810. }).call(this,"/modules/xmpp/moderator.js")
  10811. },{"../../service/authentication/AuthenticationEvents":138,"../../service/xmpp/XMPPEvents":142,"jitsi-meet-logger":49}],36:[function(require,module,exports){
  10812. (function (__filename){
  10813. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10814. Toolbar, Util, Promise */
  10815. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10816. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10817. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10818. roomjid) {
  10819. this.eventEmitter = eventEmitter;
  10820. this.connection = connection;
  10821. this.state = "off";
  10822. this.focusMucJid = focusMucJid;
  10823. this.jirecon = jirecon;
  10824. this.url = null;
  10825. this.type = type;
  10826. this._isSupported = ((type === Recording.types.JIBRI)
  10827. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10828. /**
  10829. * The ID of the jirecon recording session. Jirecon generates it when we
  10830. * initially start recording, and it needs to be used in subsequent requests
  10831. * to jirecon.
  10832. */
  10833. this.jireconRid = null;
  10834. this.roomjid = roomjid;
  10835. }
  10836. Recording.types = {
  10837. COLIBRI: "colibri",
  10838. JIRECON: "jirecon",
  10839. JIBRI: "jibri"
  10840. };
  10841. Recording.prototype.handleJibriPresence = function (jibri) {
  10842. var attributes = jibri.attributes;
  10843. if(!attributes)
  10844. return;
  10845. this._isSupported =
  10846. (attributes.status && attributes.status !== "undefined");
  10847. if(this._isSupported) {
  10848. this.url = attributes.url || null;
  10849. this.state = attributes.status || "off";
  10850. }
  10851. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  10852. };
  10853. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  10854. options) {
  10855. if (state == this.state){
  10856. errCallback(new Error("Invalid state!"));
  10857. }
  10858. options = options || {};
  10859. // FIXME jibri does not accept IQ without 'url' attribute set ?
  10860. var iq = $iq({to: this.focusMucJid, type: 'set'})
  10861. .c('jibri', {
  10862. "xmlns": 'http://jitsi.org/protocol/jibri',
  10863. "action": (state === 'on') ? 'start' : 'stop',
  10864. "streamid": options.streamId,
  10865. "follow-entity": options.followEntity
  10866. }).up();
  10867. logger.log('Set jibri recording: '+state, iq.nodeTree);
  10868. console.log(iq.nodeTree);
  10869. this.connection.sendIQ(
  10870. iq,
  10871. function (result) {
  10872. callback($(result).find('jibri').attr('state'),
  10873. $(result).find('jibri').attr('url'));
  10874. },
  10875. function (error) {
  10876. logger.log('Failed to start recording, error: ', error);
  10877. errCallback(error);
  10878. });
  10879. };
  10880. Recording.prototype.setRecordingJirecon =
  10881. function (state, callback, errCallback, options) {
  10882. if (state == this.state){
  10883. errCallback(new Error("Invalid state!"));
  10884. }
  10885. var iq = $iq({to: this.jirecon, type: 'set'})
  10886. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  10887. action: (state === 'on') ? 'start' : 'stop',
  10888. mucjid: this.roomjid});
  10889. if (state === 'off'){
  10890. iq.attrs({rid: this.jireconRid});
  10891. }
  10892. console.log('Start recording');
  10893. var self = this;
  10894. this.connection.sendIQ(
  10895. iq,
  10896. function (result) {
  10897. // TODO wait for an IQ with the real status, since this is
  10898. // provisional?
  10899. self.jireconRid = $(result).find('recording').attr('rid');
  10900. console.log('Recording ' +
  10901. ((state === 'on') ? 'started' : 'stopped') +
  10902. '(jirecon)' + result);
  10903. self.state = state;
  10904. if (state === 'off'){
  10905. self.jireconRid = null;
  10906. }
  10907. callback(state);
  10908. },
  10909. function (error) {
  10910. console.log('Failed to start recording, error: ', error);
  10911. errCallback(error);
  10912. });
  10913. };
  10914. // Sends a COLIBRI message which enables or disables (according to 'state')
  10915. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10916. // with the new recording state, according to the IQ.
  10917. Recording.prototype.setRecordingColibri =
  10918. function (state, callback, errCallback, options) {
  10919. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10920. elem.c('conference', {
  10921. xmlns: 'http://jitsi.org/protocol/colibri'
  10922. });
  10923. elem.c('recording', {state: state, token: options.token});
  10924. var self = this;
  10925. this.connection.sendIQ(elem,
  10926. function (result) {
  10927. console.log('Set recording "', state, '". Result:', result);
  10928. var recordingElem = $(result).find('>conference>recording');
  10929. var newState = recordingElem.attr('state');
  10930. self.state = newState;
  10931. callback(newState);
  10932. if (newState === 'pending') {
  10933. self.connection.addHandler(function(iq){
  10934. var state = $(iq).find('recording').attr('state');
  10935. if (state) {
  10936. self.state = newState;
  10937. callback(state);
  10938. }
  10939. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10940. }
  10941. },
  10942. function (error) {
  10943. console.warn(error);
  10944. errCallback(error);
  10945. }
  10946. );
  10947. };
  10948. Recording.prototype.setRecording =
  10949. function (state, callback, errCallback, options) {
  10950. switch(this.type){
  10951. case Recording.types.JIRECON:
  10952. this.setRecordingJirecon(state, callback, errCallback, options);
  10953. break;
  10954. case Recording.types.COLIBRI:
  10955. this.setRecordingColibri(state, callback, errCallback, options);
  10956. break;
  10957. case Recording.types.JIBRI:
  10958. this.setRecordingJibri(state, callback, errCallback, options);
  10959. break;
  10960. default:
  10961. console.error("Unknown recording type!");
  10962. return;
  10963. }
  10964. };
  10965. /**
  10966. *Starts/stops the recording
  10967. * @param token token for authentication
  10968. * @param statusChangeHandler {function} receives the new status as argument.
  10969. */
  10970. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  10971. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  10972. (!options.streamId && this.type === Recording.types.JIBRI)){
  10973. statusChangeHandler("error", new Error("No token passed!"));
  10974. logger.error("No token passed!");
  10975. return;
  10976. }
  10977. var oldState = this.state;
  10978. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  10979. var self = this;
  10980. this.setRecording(newState,
  10981. function (state, url) {
  10982. logger.log("New recording state: ", state);
  10983. if (state && state !== oldState) {
  10984. self.state = state;
  10985. self.url = url;
  10986. statusChangeHandler(state);
  10987. } else {
  10988. statusChangeHandler("error", new Error("Status not changed!"));
  10989. }
  10990. }, function (error) {
  10991. statusChangeHandler("error", error);
  10992. }, options);
  10993. };
  10994. /**
  10995. * Returns true if the recording is supproted and false if not.
  10996. */
  10997. Recording.prototype.isSupported = function () {
  10998. return this._isSupported;
  10999. };
  11000. /**
  11001. * Returns null if the recording is not supported, "on" if the recording started
  11002. * and "off" if the recording is not started.
  11003. */
  11004. Recording.prototype.getState = function () {
  11005. return this.state;
  11006. };
  11007. /**
  11008. * Returns the url of the recorded video.
  11009. */
  11010. Recording.prototype.getURL = function () {
  11011. return this.url;
  11012. };
  11013. module.exports = Recording;
  11014. }).call(this,"/modules/xmpp/recording.js")
  11015. },{"../../service/xmpp/XMPPEvents":142,"jitsi-meet-logger":49}],37:[function(require,module,exports){
  11016. (function (__filename){
  11017. /* jshint -W117 */
  11018. /* a simple MUC connection plugin
  11019. * can only handle a single MUC room
  11020. */
  11021. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11022. var ChatRoom = require("./ChatRoom");
  11023. module.exports = function(XMPP) {
  11024. Strophe.addConnectionPlugin('emuc', {
  11025. connection: null,
  11026. rooms: {},//map with the rooms
  11027. init: function (conn) {
  11028. this.connection = conn;
  11029. // add handlers (just once)
  11030. this.connection.addHandler(this.onPresence.bind(this), null,
  11031. 'presence', null, null, null, null);
  11032. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11033. null, 'presence', 'unavailable', null);
  11034. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11035. 'presence', 'error', null);
  11036. this.connection.addHandler(this.onMessage.bind(this), null,
  11037. 'message', null, null);
  11038. this.connection.addHandler(this.onMute.bind(this),
  11039. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11040. },
  11041. createRoom: function (jid, password, options, settings) {
  11042. var roomJid = Strophe.getBareJidFromJid(jid);
  11043. if (this.rooms[roomJid]) {
  11044. logger.error("You are already in the room!");
  11045. return;
  11046. }
  11047. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11048. password, XMPP, options, settings);
  11049. return this.rooms[roomJid];
  11050. },
  11051. doLeave: function (jid) {
  11052. this.rooms[jid].doLeave();
  11053. delete this.rooms[jid];
  11054. },
  11055. onPresence: function (pres) {
  11056. var from = pres.getAttribute('from');
  11057. // What is this for? A workaround for something?
  11058. if (pres.getAttribute('type')) {
  11059. return true;
  11060. }
  11061. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11062. if(!room)
  11063. return;
  11064. // Parse status.
  11065. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11066. room.createNonAnonymousRoom();
  11067. }
  11068. room.onPresence(pres);
  11069. return true;
  11070. },
  11071. onPresenceUnavailable: function (pres) {
  11072. var from = pres.getAttribute('from');
  11073. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11074. if(!room)
  11075. return;
  11076. room.onPresenceUnavailable(pres, from);
  11077. return true;
  11078. },
  11079. onPresenceError: function (pres) {
  11080. var from = pres.getAttribute('from');
  11081. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11082. if(!room)
  11083. return;
  11084. room.onPresenceError(pres, from);
  11085. return true;
  11086. },
  11087. onMessage: function (msg) {
  11088. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11089. var from = msg.getAttribute('from');
  11090. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11091. if(!room)
  11092. return;
  11093. room.onMessage(msg, from);
  11094. return true;
  11095. },
  11096. setJingleSession: function (from, session) {
  11097. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11098. if(!room)
  11099. return;
  11100. room.setJingleSession(session);
  11101. },
  11102. onMute: function(iq) {
  11103. var from = iq.getAttribute('from');
  11104. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11105. if(!room)
  11106. return;
  11107. room.onMute(iq);
  11108. return true;
  11109. }
  11110. });
  11111. };
  11112. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11113. },{"./ChatRoom":28,"jitsi-meet-logger":49}],38:[function(require,module,exports){
  11114. (function (__filename){
  11115. /* jshint -W117 */
  11116. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11117. var JingleSession = require("./JingleSessionPC");
  11118. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11119. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11120. module.exports = function(XMPP, eventEmitter) {
  11121. Strophe.addConnectionPlugin('jingle', {
  11122. connection: null,
  11123. sessions: {},
  11124. jid2session: {},
  11125. ice_config: {iceServers: []},
  11126. media_constraints: {
  11127. mandatory: {
  11128. 'OfferToReceiveAudio': true,
  11129. 'OfferToReceiveVideo': true
  11130. }
  11131. // MozDontOfferDataChannel: true when this is firefox
  11132. },
  11133. init: function (conn) {
  11134. this.connection = conn;
  11135. if (this.connection.disco) {
  11136. // http://xmpp.org/extensions/xep-0167.html#support
  11137. // http://xmpp.org/extensions/xep-0176.html#support
  11138. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11139. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11140. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11141. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11142. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11143. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11144. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11145. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11146. || RTCBrowserType.isTemasysPluginUsed()) {
  11147. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11148. }
  11149. // this is dealt with by SDP O/A so we don't need to announce this
  11150. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11151. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11152. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11153. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11154. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11155. }
  11156. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11157. },
  11158. onJingle: function (iq) {
  11159. var sid = $(iq).find('jingle').attr('sid');
  11160. var action = $(iq).find('jingle').attr('action');
  11161. var fromJid = iq.getAttribute('from');
  11162. // send ack first
  11163. var ack = $iq({type: 'result',
  11164. to: fromJid,
  11165. id: iq.getAttribute('id')
  11166. });
  11167. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11168. var sess = this.sessions[sid];
  11169. if ('session-initiate' != action) {
  11170. if (sess === null) {
  11171. ack.type = 'error';
  11172. ack.c('error', {type: 'cancel'})
  11173. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11174. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11175. this.connection.send(ack);
  11176. return true;
  11177. }
  11178. // local jid is not checked
  11179. if (fromJid != sess.peerjid) {
  11180. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11181. ack.type = 'error';
  11182. ack.c('error', {type: 'cancel'})
  11183. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11184. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11185. this.connection.send(ack);
  11186. return true;
  11187. }
  11188. } else if (sess !== undefined) {
  11189. // existing session with same session id
  11190. // this might be out-of-order if the sess.peerjid is the same as from
  11191. ack.type = 'error';
  11192. ack.c('error', {type: 'cancel'})
  11193. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11194. logger.warn('duplicate session id', sid);
  11195. this.connection.send(ack);
  11196. return true;
  11197. }
  11198. // FIXME: check for a defined action
  11199. this.connection.send(ack);
  11200. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11201. switch (action) {
  11202. case 'session-initiate':
  11203. console.log("(TIME) received session-initiate:\t",
  11204. window.performance.now());
  11205. var startMuted = $(iq).find('jingle>startmuted');
  11206. if (startMuted && startMuted.length > 0) {
  11207. var audioMuted = startMuted.attr("audio");
  11208. var videoMuted = startMuted.attr("video");
  11209. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11210. audioMuted === "true", videoMuted === "true");
  11211. }
  11212. sess = new JingleSession(
  11213. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11214. this.connection, XMPP);
  11215. // configure session
  11216. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11217. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11218. sess.media_constraints = this.media_constraints;
  11219. sess.ice_config = this.ice_config;
  11220. sess.initialize(fromJid, false);
  11221. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11222. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11223. sess.setOffer($(iq).find('>jingle'));
  11224. this.sessions[sess.sid] = sess;
  11225. this.jid2session[sess.peerjid] = sess;
  11226. // the callback should either
  11227. // .sendAnswer and .accept
  11228. // or .sendTerminate -- not necessarily synchronous
  11229. sess.sendAnswer();
  11230. sess.accept();
  11231. break;
  11232. case 'session-accept':
  11233. sess.setAnswer($(iq).find('>jingle'));
  11234. sess.accept();
  11235. break;
  11236. case 'session-terminate':
  11237. // If this is not the focus sending the terminate, we have
  11238. // nothing more to do here.
  11239. if (Object.keys(this.sessions).length < 1
  11240. || !(this.sessions[Object.keys(this.sessions)[0]]
  11241. instanceof JingleSession))
  11242. {
  11243. break;
  11244. }
  11245. logger.log('terminating...', sess.sid);
  11246. sess.terminate();
  11247. this.terminate(sess.sid);
  11248. if ($(iq).find('>jingle>reason').length) {
  11249. $(document).trigger('callterminated.jingle', [
  11250. sess.sid,
  11251. sess.peerjid,
  11252. $(iq).find('>jingle>reason>:first')[0].tagName,
  11253. $(iq).find('>jingle>reason>text').text()
  11254. ]);
  11255. } else {
  11256. $(document).trigger('callterminated.jingle',
  11257. [sess.sid, sess.peerjid]);
  11258. }
  11259. break;
  11260. case 'transport-info':
  11261. sess.addIceCandidate($(iq).find('>jingle>content'));
  11262. break;
  11263. case 'session-info':
  11264. var affected;
  11265. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11266. $(document).trigger('ringing.jingle', [sess.sid]);
  11267. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11268. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11269. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11270. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11271. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11272. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11273. }
  11274. break;
  11275. case 'addsource': // FIXME: proprietary, un-jingleish
  11276. case 'source-add': // FIXME: proprietary
  11277. sess.addSource($(iq).find('>jingle>content'));
  11278. break;
  11279. case 'removesource': // FIXME: proprietary, un-jingleish
  11280. case 'source-remove': // FIXME: proprietary
  11281. sess.removeSource($(iq).find('>jingle>content'));
  11282. break;
  11283. default:
  11284. logger.warn('jingle action not implemented', action);
  11285. break;
  11286. }
  11287. return true;
  11288. },
  11289. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11290. if (sid === null || sid === undefined) {
  11291. for (sid in this.sessions) {
  11292. if (this.sessions[sid].state != 'ended') {
  11293. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11294. this.sessions[sid].terminate();
  11295. }
  11296. delete this.jid2session[this.sessions[sid].peerjid];
  11297. delete this.sessions[sid];
  11298. }
  11299. } else if (this.sessions.hasOwnProperty(sid)) {
  11300. if (this.sessions[sid].state != 'ended') {
  11301. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11302. this.sessions[sid].terminate();
  11303. }
  11304. delete this.jid2session[this.sessions[sid].peerjid];
  11305. delete this.sessions[sid];
  11306. }
  11307. },
  11308. getStunAndTurnCredentials: function () {
  11309. // get stun and turn configuration from server via xep-0215
  11310. // uses time-limited credentials as described in
  11311. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11312. //
  11313. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11314. // for a prosody module which implements this
  11315. //
  11316. // currently, this doesn't work with updateIce and therefore credentials with a long
  11317. // validity have to be fetched before creating the peerconnection
  11318. // TODO: implement refresh via updateIce as described in
  11319. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11320. var self = this;
  11321. this.connection.sendIQ(
  11322. $iq({type: 'get', to: this.connection.domain})
  11323. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11324. function (res) {
  11325. var iceservers = [];
  11326. $(res).find('>services>service').each(function (idx, el) {
  11327. el = $(el);
  11328. var dict = {};
  11329. var type = el.attr('type');
  11330. switch (type) {
  11331. case 'stun':
  11332. dict.url = 'stun:' + el.attr('host');
  11333. if (el.attr('port')) {
  11334. dict.url += ':' + el.attr('port');
  11335. }
  11336. iceservers.push(dict);
  11337. break;
  11338. case 'turn':
  11339. case 'turns':
  11340. dict.url = type + ':';
  11341. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11342. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11343. dict.url += el.attr('username') + '@';
  11344. } else {
  11345. dict.username = el.attr('username'); // only works in M28
  11346. }
  11347. }
  11348. dict.url += el.attr('host');
  11349. if (el.attr('port') && el.attr('port') != '3478') {
  11350. dict.url += ':' + el.attr('port');
  11351. }
  11352. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11353. dict.url += '?transport=' + el.attr('transport');
  11354. }
  11355. if (el.attr('password')) {
  11356. dict.credential = el.attr('password');
  11357. }
  11358. iceservers.push(dict);
  11359. break;
  11360. }
  11361. });
  11362. self.ice_config.iceServers = iceservers;
  11363. },
  11364. function (err) {
  11365. logger.warn('getting turn credentials failed', err);
  11366. logger.warn('is mod_turncredentials or similar installed?');
  11367. }
  11368. );
  11369. // implement push?
  11370. },
  11371. /**
  11372. * Returns the data saved in 'updateLog' in a format to be logged.
  11373. */
  11374. getLog: function () {
  11375. var data = {};
  11376. var self = this;
  11377. Object.keys(this.sessions).forEach(function (sid) {
  11378. var session = self.sessions[sid];
  11379. if (session.peerconnection && session.peerconnection.updateLog) {
  11380. // FIXME: should probably be a .dump call
  11381. data["jingle_" + session.sid] = {
  11382. updateLog: session.peerconnection.updateLog,
  11383. stats: session.peerconnection.stats,
  11384. url: window.location.href
  11385. };
  11386. }
  11387. });
  11388. return data;
  11389. }
  11390. });
  11391. };
  11392. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11393. },{"../../service/xmpp/XMPPEvents":142,"../RTC/RTCBrowserType":17,"./JingleSessionPC":30,"jitsi-meet-logger":49}],39:[function(require,module,exports){
  11394. /* global Strophe */
  11395. module.exports = function () {
  11396. Strophe.addConnectionPlugin('logger', {
  11397. // logs raw stanzas and makes them available for download as JSON
  11398. connection: null,
  11399. log: [],
  11400. init: function (conn) {
  11401. this.connection = conn;
  11402. this.connection.rawInput = this.log_incoming.bind(this);
  11403. this.connection.rawOutput = this.log_outgoing.bind(this);
  11404. },
  11405. log_incoming: function (stanza) {
  11406. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11407. },
  11408. log_outgoing: function (stanza) {
  11409. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11410. }
  11411. });
  11412. };
  11413. },{}],40:[function(require,module,exports){
  11414. (function (__filename){
  11415. /* global $, $iq, Strophe */
  11416. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11417. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11418. /**
  11419. * Ping every 10 sec
  11420. */
  11421. var PING_INTERVAL = 10000;
  11422. /**
  11423. * Ping timeout error after 15 sec of waiting.
  11424. */
  11425. var PING_TIMEOUT = 15000;
  11426. /**
  11427. * Will close the connection after 3 consecutive ping errors.
  11428. */
  11429. var PING_THRESHOLD = 3;
  11430. /**
  11431. * XEP-0199 ping plugin.
  11432. *
  11433. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11434. */
  11435. module.exports = function (XMPP, eventEmitter) {
  11436. Strophe.addConnectionPlugin('ping', {
  11437. connection: null,
  11438. failedPings: 0,
  11439. /**
  11440. * Initializes the plugin. Method called by Strophe.
  11441. * @param connection Strophe connection instance.
  11442. */
  11443. init: function (connection) {
  11444. this.connection = connection;
  11445. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11446. },
  11447. /**
  11448. * Sends "ping" to given <tt>jid</tt>
  11449. * @param jid the JID to which ping request will be sent.
  11450. * @param success callback called on success.
  11451. * @param error callback called on error.
  11452. * @param timeout ms how long are we going to wait for the response. On
  11453. * timeout <tt>error<//t> callback is called with undefined error
  11454. * argument.
  11455. */
  11456. ping: function (jid, success, error, timeout) {
  11457. var iq = $iq({type: 'get', to: jid});
  11458. iq.c('ping', {xmlns: Strophe.NS.PING});
  11459. this.connection.sendIQ(iq, success, error, timeout);
  11460. },
  11461. /**
  11462. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11463. * @param jid the JID to be checked for ping support.
  11464. * @param callback function with boolean argument which will be
  11465. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11466. */
  11467. hasPingSupport: function (jid, callback) {
  11468. this.connection.disco.info(
  11469. jid, null,
  11470. function (result) {
  11471. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11472. callback(ping.length > 0);
  11473. },
  11474. function (error) {
  11475. logger.error("Ping feature discovery error", error);
  11476. callback(false);
  11477. }
  11478. );
  11479. },
  11480. /**
  11481. * Starts to send ping in given interval to specified remote JID.
  11482. * This plugin supports only one such task and <tt>stopInterval</tt>
  11483. * must be called before starting a new one.
  11484. * @param remoteJid remote JID to which ping requests will be sent to.
  11485. * @param interval task interval in ms.
  11486. */
  11487. startInterval: function (remoteJid, interval) {
  11488. if (this.intervalId) {
  11489. logger.error("Ping task scheduled already");
  11490. return;
  11491. }
  11492. if (!interval)
  11493. interval = PING_INTERVAL;
  11494. var self = this;
  11495. this.intervalId = window.setInterval(function () {
  11496. self.ping(remoteJid,
  11497. function (result) {
  11498. // Ping OK
  11499. self.failedPings = 0;
  11500. },
  11501. function (error) {
  11502. self.failedPings += 1;
  11503. logger.error(
  11504. "Ping " + (error ? "error" : "timeout"), error);
  11505. if (self.failedPings >= PING_THRESHOLD) {
  11506. self.connection.disconnect();
  11507. }
  11508. }, PING_TIMEOUT);
  11509. }, interval);
  11510. logger.info("XMPP pings will be sent every " + interval + " ms");
  11511. },
  11512. /**
  11513. * Stops current "ping" interval task.
  11514. */
  11515. stopInterval: function () {
  11516. if (this.intervalId) {
  11517. window.clearInterval(this.intervalId);
  11518. this.intervalId = null;
  11519. this.failedPings = 0;
  11520. logger.info("Ping interval cleared");
  11521. }
  11522. }
  11523. });
  11524. };
  11525. }).call(this,"/modules/xmpp/strophe.ping.js")
  11526. },{"../../service/xmpp/XMPPEvents":142,"jitsi-meet-logger":49}],41:[function(require,module,exports){
  11527. (function (__filename){
  11528. /* jshint -W117 */
  11529. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11530. module.exports = function() {
  11531. Strophe.addConnectionPlugin('rayo',
  11532. {
  11533. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11534. connection: null,
  11535. init: function (conn) {
  11536. this.connection = conn;
  11537. if (this.connection.disco) {
  11538. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11539. }
  11540. this.connection.addHandler(
  11541. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11542. null, null);
  11543. },
  11544. onRayo: function (iq) {
  11545. logger.info("Rayo IQ", iq);
  11546. },
  11547. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11548. var self = this;
  11549. return new Promise(function (resolve, reject) {
  11550. if(!focusMucJid) {
  11551. reject(new Error("Internal error!"));
  11552. return;
  11553. }
  11554. var req = $iq(
  11555. {
  11556. type: 'set',
  11557. to: focusMucJid
  11558. }
  11559. );
  11560. req.c('dial',
  11561. {
  11562. xmlns: self.RAYO_XMLNS,
  11563. to: to,
  11564. from: from
  11565. });
  11566. req.c('header',
  11567. {
  11568. name: 'JvbRoomName',
  11569. value: roomName
  11570. }).up();
  11571. if (roomPass !== null && roomPass.length) {
  11572. req.c('header',
  11573. {
  11574. name: 'JvbRoomPassword',
  11575. value: roomPass
  11576. }).up();
  11577. }
  11578. self.connection.sendIQ(
  11579. req,
  11580. function (result) {
  11581. logger.info('Dial result ', result);
  11582. var resource = $(result).find('ref').attr('uri');
  11583. self.call_resource =
  11584. resource.substr('xmpp:'.length);
  11585. logger.info(
  11586. "Received call resource: " +
  11587. self.call_resource);
  11588. resolve();
  11589. },
  11590. function (error) {
  11591. logger.info('Dial error ', error);
  11592. reject(error);
  11593. }
  11594. );
  11595. });
  11596. },
  11597. hangup: function () {
  11598. var self = this;
  11599. return new Promise(function (resolve, reject) {
  11600. if (!self.call_resource) {
  11601. reject(new Error("No call in progress"));
  11602. logger.warn("No call in progress");
  11603. return;
  11604. }
  11605. var req = $iq(
  11606. {
  11607. type: 'set',
  11608. to: self.call_resource
  11609. }
  11610. );
  11611. req.c('hangup',
  11612. {
  11613. xmlns: self.RAYO_XMLNS
  11614. });
  11615. self.connection.sendIQ(
  11616. req,
  11617. function (result) {
  11618. logger.info('Hangup result ', result);
  11619. self.call_resource = null;
  11620. resolve();
  11621. },
  11622. function (error) {
  11623. logger.info('Hangup error ', error);
  11624. self.call_resource = null;
  11625. reject(new Error('Hangup error '));
  11626. }
  11627. );
  11628. });
  11629. }
  11630. }
  11631. );
  11632. };
  11633. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11634. },{"jitsi-meet-logger":49}],42:[function(require,module,exports){
  11635. (function (__filename){
  11636. /* global Strophe */
  11637. /**
  11638. * Strophe logger implementation. Logs from level WARN and above.
  11639. */
  11640. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11641. module.exports = function () {
  11642. Strophe.log = function (level, msg) {
  11643. switch (level) {
  11644. case Strophe.LogLevel.WARN:
  11645. logger.warn("Strophe: " + msg);
  11646. break;
  11647. case Strophe.LogLevel.ERROR:
  11648. case Strophe.LogLevel.FATAL:
  11649. logger.error("Strophe: " + msg);
  11650. break;
  11651. }
  11652. };
  11653. Strophe.getStatusString = function (status) {
  11654. switch (status) {
  11655. case Strophe.Status.ERROR:
  11656. return "ERROR";
  11657. case Strophe.Status.CONNECTING:
  11658. return "CONNECTING";
  11659. case Strophe.Status.CONNFAIL:
  11660. return "CONNFAIL";
  11661. case Strophe.Status.AUTHENTICATING:
  11662. return "AUTHENTICATING";
  11663. case Strophe.Status.AUTHFAIL:
  11664. return "AUTHFAIL";
  11665. case Strophe.Status.CONNECTED:
  11666. return "CONNECTED";
  11667. case Strophe.Status.DISCONNECTED:
  11668. return "DISCONNECTED";
  11669. case Strophe.Status.DISCONNECTING:
  11670. return "DISCONNECTING";
  11671. case Strophe.Status.ATTACHED:
  11672. return "ATTACHED";
  11673. default:
  11674. return "unknown";
  11675. }
  11676. };
  11677. };
  11678. }).call(this,"/modules/xmpp/strophe.util.js")
  11679. },{"jitsi-meet-logger":49}],43:[function(require,module,exports){
  11680. (function (__filename){
  11681. /* global $, APP, config, Strophe*/
  11682. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11683. var EventEmitter = require("events");
  11684. var Pako = require("pako");
  11685. var RTCEvents = require("../../service/RTC/RTCEvents");
  11686. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11687. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11688. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11689. var RTC = require("../RTC/RTC");
  11690. var authenticatedUser = false;
  11691. function createConnection(bosh) {
  11692. bosh = bosh || '/http-bind';
  11693. // Append token as URL param
  11694. if (this.token) {
  11695. bosh += bosh.indexOf('?') == -1 ?
  11696. '?token=' + this.token : '&token=' + this.token;
  11697. }
  11698. return new Strophe.Connection(bosh);
  11699. };
  11700. //!!!!!!!!!! FIXME: ...
  11701. function initStrophePlugins(XMPP)
  11702. {
  11703. require("./strophe.emuc")(XMPP);
  11704. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11705. // require("./strophe.moderate")(XMPP, eventEmitter);
  11706. require("./strophe.util")();
  11707. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11708. require("./strophe.rayo")();
  11709. require("./strophe.logger")();
  11710. }
  11711. //!!!!!!!!!! FIXME: ...
  11712. ///**
  11713. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11714. // * video type in MUC presence.
  11715. // * @param localStream new or modified <tt>LocalStream</tt>.
  11716. // */
  11717. //function broadcastLocalVideoType(localStream) {
  11718. // if (localStream.videoType)
  11719. // XMPP.addToPresence('videoType', localStream.videoType);
  11720. //}
  11721. //
  11722. //function registerListeners() {
  11723. // RTC.addStreamListener(
  11724. // broadcastLocalVideoType,
  11725. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11726. // );
  11727. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  11728. // XMPP.addToPresence("devices", devices);
  11729. // });
  11730. //}
  11731. function XMPP(options) {
  11732. this.eventEmitter = new EventEmitter();
  11733. this.connection = null;
  11734. this.disconnectInProgress = false;
  11735. this.forceMuted = false;
  11736. this.options = options;
  11737. initStrophePlugins(this);
  11738. // registerListeners();
  11739. this.connection = createConnection(options.bosh);
  11740. }
  11741. XMPP.prototype.getConnection = function(){ return connection; };
  11742. XMPP.prototype._connect = function (jid, password) {
  11743. var self = this;
  11744. // connection.connect() starts the connection process.
  11745. //
  11746. // As the connection process proceeds, the user supplied callback will
  11747. // be triggered multiple times with status updates. The callback should
  11748. // take two arguments - the status code and the error condition.
  11749. //
  11750. // The status code will be one of the values in the Strophe.Status
  11751. // constants. The error condition will be one of the conditions defined
  11752. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11753. //
  11754. // The Parameters wait, hold and route are optional and only relevant
  11755. // for BOSH connections. Please see XEP 124 for a more detailed
  11756. // explanation of the optional parameters.
  11757. //
  11758. // Connection status constants for use by the connection handler
  11759. // callback.
  11760. //
  11761. // Status.ERROR - An error has occurred (websockets specific)
  11762. // Status.CONNECTING - The connection is currently being made
  11763. // Status.CONNFAIL - The connection attempt failed
  11764. // Status.AUTHENTICATING - The connection is authenticating
  11765. // Status.AUTHFAIL - The authentication attempt failed
  11766. // Status.CONNECTED - The connection has succeeded
  11767. // Status.DISCONNECTED - The connection has been terminated
  11768. // Status.DISCONNECTING - The connection is currently being terminated
  11769. // Status.ATTACHED - The connection has been attached
  11770. var anonymousConnectionFailed = false;
  11771. var connectionFailed = false;
  11772. var lastErrorMsg;
  11773. this.connection.connect(jid, password, function (status, msg) {
  11774. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11775. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11776. if (status === Strophe.Status.CONNECTED) {
  11777. if (self.options.useStunTurn) {
  11778. self.connection.jingle.getStunAndTurnCredentials();
  11779. }
  11780. logger.info("My Jabber ID: " + self.connection.jid);
  11781. // Schedule ping ?
  11782. var pingJid = self.connection.domain;
  11783. self.connection.ping.hasPingSupport(
  11784. pingJid,
  11785. function (hasPing) {
  11786. if (hasPing)
  11787. self.connection.ping.startInterval(pingJid);
  11788. else
  11789. logger.warn("Ping NOT supported by " + pingJid);
  11790. }
  11791. );
  11792. if (password)
  11793. authenticatedUser = true;
  11794. if (self.connection && self.connection.connected &&
  11795. Strophe.getResourceFromJid(self.connection.jid)) {
  11796. // .connected is true while connecting?
  11797. // self.connection.send($pres());
  11798. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11799. Strophe.getResourceFromJid(self.connection.jid));
  11800. }
  11801. } else if (status === Strophe.Status.CONNFAIL) {
  11802. if (msg === 'x-strophe-bad-non-anon-jid') {
  11803. anonymousConnectionFailed = true;
  11804. }
  11805. else
  11806. {
  11807. connectionFailed = true;
  11808. }
  11809. lastErrorMsg = msg;
  11810. } else if (status === Strophe.Status.DISCONNECTED) {
  11811. // Stop ping interval
  11812. self.connection.ping.stopInterval();
  11813. self.disconnectInProgress = false;
  11814. if (anonymousConnectionFailed) {
  11815. // prompt user for username and password
  11816. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11817. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11818. } else if(connectionFailed) {
  11819. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11820. JitsiConnectionErrors.OTHER_ERROR,
  11821. msg ? msg : lastErrorMsg);
  11822. } else {
  11823. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11824. msg ? msg : lastErrorMsg);
  11825. }
  11826. } else if (status === Strophe.Status.AUTHFAIL) {
  11827. // wrong password or username, prompt user
  11828. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11829. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11830. }
  11831. });
  11832. }
  11833. XMPP.prototype.connect = function (jid, password) {
  11834. if(!jid) {
  11835. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11836. // Force authenticated domain if room is appended with '?login=true'
  11837. if (this.options.hosts.anonymousdomain &&
  11838. window.location.search.indexOf("login=true") !== -1) {
  11839. configDomain = this.options.hosts.domain;
  11840. }
  11841. jid = configDomain || window.location.hostname;
  11842. }
  11843. return this._connect(jid, password);
  11844. };
  11845. XMPP.prototype.createRoom = function (roomName, options, settings) {
  11846. var roomjid = roomName + '@' + this.options.hosts.muc;
  11847. if (options.useNicks) {
  11848. if (options.nick) {
  11849. roomjid += '/' + options.nick;
  11850. } else {
  11851. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  11852. }
  11853. } else {
  11854. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  11855. if(!authenticatedUser)
  11856. tmpJid = tmpJid.substr(0, 8);
  11857. roomjid += '/' + tmpJid;
  11858. }
  11859. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  11860. }
  11861. XMPP.prototype.addListener = function(type, listener) {
  11862. this.eventEmitter.on(type, listener);
  11863. };
  11864. XMPP.prototype.removeListener = function (type, listener) {
  11865. this.eventEmitter.removeListener(type, listener);
  11866. };
  11867. //FIXME: this should work with the room
  11868. XMPP.prototype.leaveRoom = function (jid) {
  11869. var handler = this.connection.jingle.jid2session[jid];
  11870. if (handler && handler.peerconnection) {
  11871. // FIXME: probably removing streams is not required and close() should
  11872. // be enough
  11873. if (RTC.localAudio) {
  11874. handler.peerconnection.removeStream(
  11875. RTC.localAudio.getOriginalStream(), true);
  11876. }
  11877. if (RTC.localVideo) {
  11878. handler.peerconnection.removeStream(
  11879. RTC.localVideo.getOriginalStream(), true);
  11880. }
  11881. handler.peerconnection.close();
  11882. }
  11883. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  11884. this.connection.emuc.doLeave(jid);
  11885. };
  11886. /**
  11887. * Sends 'data' as a log message to the focus. Returns true iff a message
  11888. * was sent.
  11889. * @param data
  11890. * @returns {boolean} true iff a message was sent.
  11891. */
  11892. XMPP.prototype.sendLogs = function (data) {
  11893. if(!this.connection.emuc.focusMucJid)
  11894. return false;
  11895. var deflate = true;
  11896. var content = JSON.stringify(data);
  11897. if (deflate) {
  11898. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  11899. }
  11900. content = Base64.encode(content);
  11901. // XEP-0337-ish
  11902. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11903. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11904. id: 'PeerConnectionStats'});
  11905. message.c('message').t(content).up();
  11906. if (deflate) {
  11907. message.c('tag', {name: "deflated", value: "true"}).up();
  11908. }
  11909. message.up();
  11910. this.connection.send(message);
  11911. return true;
  11912. };
  11913. // Gets the logs from strophe.jingle.
  11914. XMPP.prototype.getJingleLog = function () {
  11915. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11916. };
  11917. // Gets the logs from strophe.
  11918. XMPP.prototype.getXmppLog = function () {
  11919. return this.connection.logger ? this.connection.logger.log : null;
  11920. };
  11921. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11922. this.connection.rayo.dial(to, from, roomName,roomPass);
  11923. };
  11924. XMPP.prototype.setMute = function (jid, mute) {
  11925. this.connection.moderate.setMute(jid, mute);
  11926. };
  11927. XMPP.prototype.eject = function (jid) {
  11928. this.connection.moderate.eject(jid);
  11929. };
  11930. XMPP.prototype.getSessions = function () {
  11931. return this.connection.jingle.sessions;
  11932. };
  11933. XMPP.prototype.disconnect = function () {
  11934. if (this.disconnectInProgress || !this.connection || !this.connection.connected)
  11935. {
  11936. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11937. return;
  11938. }
  11939. this.disconnectInProgress = true;
  11940. this.connection.disconnect();
  11941. };
  11942. module.exports = XMPP;
  11943. }).call(this,"/modules/xmpp/xmpp.js")
  11944. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":136,"../../service/xmpp/XMPPEvents":142,"../RTC/RTC":16,"./strophe.emuc":37,"./strophe.jingle":38,"./strophe.logger":39,"./strophe.ping":40,"./strophe.rayo":41,"./strophe.util":42,"events":45,"jitsi-meet-logger":49,"pako":51}],44:[function(require,module,exports){
  11945. (function (process){
  11946. /*!
  11947. * async
  11948. * https://github.com/caolan/async
  11949. *
  11950. * Copyright 2010-2014 Caolan McMahon
  11951. * Released under the MIT license
  11952. */
  11953. /*jshint onevar: false, indent:4 */
  11954. /*global setImmediate: false, setTimeout: false, console: false */
  11955. (function () {
  11956. var async = {};
  11957. // global on the server, window in the browser
  11958. var root, previous_async;
  11959. root = this;
  11960. if (root != null) {
  11961. previous_async = root.async;
  11962. }
  11963. async.noConflict = function () {
  11964. root.async = previous_async;
  11965. return async;
  11966. };
  11967. function only_once(fn) {
  11968. var called = false;
  11969. return function() {
  11970. if (called) throw new Error("Callback was already called.");
  11971. called = true;
  11972. fn.apply(root, arguments);
  11973. }
  11974. }
  11975. //// cross-browser compatiblity functions ////
  11976. var _toString = Object.prototype.toString;
  11977. var _isArray = Array.isArray || function (obj) {
  11978. return _toString.call(obj) === '[object Array]';
  11979. };
  11980. var _each = function (arr, iterator) {
  11981. if (arr.forEach) {
  11982. return arr.forEach(iterator);
  11983. }
  11984. for (var i = 0; i < arr.length; i += 1) {
  11985. iterator(arr[i], i, arr);
  11986. }
  11987. };
  11988. var _map = function (arr, iterator) {
  11989. if (arr.map) {
  11990. return arr.map(iterator);
  11991. }
  11992. var results = [];
  11993. _each(arr, function (x, i, a) {
  11994. results.push(iterator(x, i, a));
  11995. });
  11996. return results;
  11997. };
  11998. var _reduce = function (arr, iterator, memo) {
  11999. if (arr.reduce) {
  12000. return arr.reduce(iterator, memo);
  12001. }
  12002. _each(arr, function (x, i, a) {
  12003. memo = iterator(memo, x, i, a);
  12004. });
  12005. return memo;
  12006. };
  12007. var _keys = function (obj) {
  12008. if (Object.keys) {
  12009. return Object.keys(obj);
  12010. }
  12011. var keys = [];
  12012. for (var k in obj) {
  12013. if (obj.hasOwnProperty(k)) {
  12014. keys.push(k);
  12015. }
  12016. }
  12017. return keys;
  12018. };
  12019. //// exported async module functions ////
  12020. //// nextTick implementation with browser-compatible fallback ////
  12021. if (typeof process === 'undefined' || !(process.nextTick)) {
  12022. if (typeof setImmediate === 'function') {
  12023. async.nextTick = function (fn) {
  12024. // not a direct alias for IE10 compatibility
  12025. setImmediate(fn);
  12026. };
  12027. async.setImmediate = async.nextTick;
  12028. }
  12029. else {
  12030. async.nextTick = function (fn) {
  12031. setTimeout(fn, 0);
  12032. };
  12033. async.setImmediate = async.nextTick;
  12034. }
  12035. }
  12036. else {
  12037. async.nextTick = process.nextTick;
  12038. if (typeof setImmediate !== 'undefined') {
  12039. async.setImmediate = function (fn) {
  12040. // not a direct alias for IE10 compatibility
  12041. setImmediate(fn);
  12042. };
  12043. }
  12044. else {
  12045. async.setImmediate = async.nextTick;
  12046. }
  12047. }
  12048. async.each = function (arr, iterator, callback) {
  12049. callback = callback || function () {};
  12050. if (!arr.length) {
  12051. return callback();
  12052. }
  12053. var completed = 0;
  12054. _each(arr, function (x) {
  12055. iterator(x, only_once(done) );
  12056. });
  12057. function done(err) {
  12058. if (err) {
  12059. callback(err);
  12060. callback = function () {};
  12061. }
  12062. else {
  12063. completed += 1;
  12064. if (completed >= arr.length) {
  12065. callback();
  12066. }
  12067. }
  12068. }
  12069. };
  12070. async.forEach = async.each;
  12071. async.eachSeries = function (arr, iterator, callback) {
  12072. callback = callback || function () {};
  12073. if (!arr.length) {
  12074. return callback();
  12075. }
  12076. var completed = 0;
  12077. var iterate = function () {
  12078. iterator(arr[completed], function (err) {
  12079. if (err) {
  12080. callback(err);
  12081. callback = function () {};
  12082. }
  12083. else {
  12084. completed += 1;
  12085. if (completed >= arr.length) {
  12086. callback();
  12087. }
  12088. else {
  12089. iterate();
  12090. }
  12091. }
  12092. });
  12093. };
  12094. iterate();
  12095. };
  12096. async.forEachSeries = async.eachSeries;
  12097. async.eachLimit = function (arr, limit, iterator, callback) {
  12098. var fn = _eachLimit(limit);
  12099. fn.apply(null, [arr, iterator, callback]);
  12100. };
  12101. async.forEachLimit = async.eachLimit;
  12102. var _eachLimit = function (limit) {
  12103. return function (arr, iterator, callback) {
  12104. callback = callback || function () {};
  12105. if (!arr.length || limit <= 0) {
  12106. return callback();
  12107. }
  12108. var completed = 0;
  12109. var started = 0;
  12110. var running = 0;
  12111. (function replenish () {
  12112. if (completed >= arr.length) {
  12113. return callback();
  12114. }
  12115. while (running < limit && started < arr.length) {
  12116. started += 1;
  12117. running += 1;
  12118. iterator(arr[started - 1], function (err) {
  12119. if (err) {
  12120. callback(err);
  12121. callback = function () {};
  12122. }
  12123. else {
  12124. completed += 1;
  12125. running -= 1;
  12126. if (completed >= arr.length) {
  12127. callback();
  12128. }
  12129. else {
  12130. replenish();
  12131. }
  12132. }
  12133. });
  12134. }
  12135. })();
  12136. };
  12137. };
  12138. var doParallel = function (fn) {
  12139. return function () {
  12140. var args = Array.prototype.slice.call(arguments);
  12141. return fn.apply(null, [async.each].concat(args));
  12142. };
  12143. };
  12144. var doParallelLimit = function(limit, fn) {
  12145. return function () {
  12146. var args = Array.prototype.slice.call(arguments);
  12147. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12148. };
  12149. };
  12150. var doSeries = function (fn) {
  12151. return function () {
  12152. var args = Array.prototype.slice.call(arguments);
  12153. return fn.apply(null, [async.eachSeries].concat(args));
  12154. };
  12155. };
  12156. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12157. arr = _map(arr, function (x, i) {
  12158. return {index: i, value: x};
  12159. });
  12160. if (!callback) {
  12161. eachfn(arr, function (x, callback) {
  12162. iterator(x.value, function (err) {
  12163. callback(err);
  12164. });
  12165. });
  12166. } else {
  12167. var results = [];
  12168. eachfn(arr, function (x, callback) {
  12169. iterator(x.value, function (err, v) {
  12170. results[x.index] = v;
  12171. callback(err);
  12172. });
  12173. }, function (err) {
  12174. callback(err, results);
  12175. });
  12176. }
  12177. };
  12178. async.map = doParallel(_asyncMap);
  12179. async.mapSeries = doSeries(_asyncMap);
  12180. async.mapLimit = function (arr, limit, iterator, callback) {
  12181. return _mapLimit(limit)(arr, iterator, callback);
  12182. };
  12183. var _mapLimit = function(limit) {
  12184. return doParallelLimit(limit, _asyncMap);
  12185. };
  12186. // reduce only has a series version, as doing reduce in parallel won't
  12187. // work in many situations.
  12188. async.reduce = function (arr, memo, iterator, callback) {
  12189. async.eachSeries(arr, function (x, callback) {
  12190. iterator(memo, x, function (err, v) {
  12191. memo = v;
  12192. callback(err);
  12193. });
  12194. }, function (err) {
  12195. callback(err, memo);
  12196. });
  12197. };
  12198. // inject alias
  12199. async.inject = async.reduce;
  12200. // foldl alias
  12201. async.foldl = async.reduce;
  12202. async.reduceRight = function (arr, memo, iterator, callback) {
  12203. var reversed = _map(arr, function (x) {
  12204. return x;
  12205. }).reverse();
  12206. async.reduce(reversed, memo, iterator, callback);
  12207. };
  12208. // foldr alias
  12209. async.foldr = async.reduceRight;
  12210. var _filter = function (eachfn, arr, iterator, callback) {
  12211. var results = [];
  12212. arr = _map(arr, function (x, i) {
  12213. return {index: i, value: x};
  12214. });
  12215. eachfn(arr, function (x, callback) {
  12216. iterator(x.value, function (v) {
  12217. if (v) {
  12218. results.push(x);
  12219. }
  12220. callback();
  12221. });
  12222. }, function (err) {
  12223. callback(_map(results.sort(function (a, b) {
  12224. return a.index - b.index;
  12225. }), function (x) {
  12226. return x.value;
  12227. }));
  12228. });
  12229. };
  12230. async.filter = doParallel(_filter);
  12231. async.filterSeries = doSeries(_filter);
  12232. // select alias
  12233. async.select = async.filter;
  12234. async.selectSeries = async.filterSeries;
  12235. var _reject = function (eachfn, arr, iterator, callback) {
  12236. var results = [];
  12237. arr = _map(arr, function (x, i) {
  12238. return {index: i, value: x};
  12239. });
  12240. eachfn(arr, function (x, callback) {
  12241. iterator(x.value, function (v) {
  12242. if (!v) {
  12243. results.push(x);
  12244. }
  12245. callback();
  12246. });
  12247. }, function (err) {
  12248. callback(_map(results.sort(function (a, b) {
  12249. return a.index - b.index;
  12250. }), function (x) {
  12251. return x.value;
  12252. }));
  12253. });
  12254. };
  12255. async.reject = doParallel(_reject);
  12256. async.rejectSeries = doSeries(_reject);
  12257. var _detect = function (eachfn, arr, iterator, main_callback) {
  12258. eachfn(arr, function (x, callback) {
  12259. iterator(x, function (result) {
  12260. if (result) {
  12261. main_callback(x);
  12262. main_callback = function () {};
  12263. }
  12264. else {
  12265. callback();
  12266. }
  12267. });
  12268. }, function (err) {
  12269. main_callback();
  12270. });
  12271. };
  12272. async.detect = doParallel(_detect);
  12273. async.detectSeries = doSeries(_detect);
  12274. async.some = function (arr, iterator, main_callback) {
  12275. async.each(arr, function (x, callback) {
  12276. iterator(x, function (v) {
  12277. if (v) {
  12278. main_callback(true);
  12279. main_callback = function () {};
  12280. }
  12281. callback();
  12282. });
  12283. }, function (err) {
  12284. main_callback(false);
  12285. });
  12286. };
  12287. // any alias
  12288. async.any = async.some;
  12289. async.every = function (arr, iterator, main_callback) {
  12290. async.each(arr, function (x, callback) {
  12291. iterator(x, function (v) {
  12292. if (!v) {
  12293. main_callback(false);
  12294. main_callback = function () {};
  12295. }
  12296. callback();
  12297. });
  12298. }, function (err) {
  12299. main_callback(true);
  12300. });
  12301. };
  12302. // all alias
  12303. async.all = async.every;
  12304. async.sortBy = function (arr, iterator, callback) {
  12305. async.map(arr, function (x, callback) {
  12306. iterator(x, function (err, criteria) {
  12307. if (err) {
  12308. callback(err);
  12309. }
  12310. else {
  12311. callback(null, {value: x, criteria: criteria});
  12312. }
  12313. });
  12314. }, function (err, results) {
  12315. if (err) {
  12316. return callback(err);
  12317. }
  12318. else {
  12319. var fn = function (left, right) {
  12320. var a = left.criteria, b = right.criteria;
  12321. return a < b ? -1 : a > b ? 1 : 0;
  12322. };
  12323. callback(null, _map(results.sort(fn), function (x) {
  12324. return x.value;
  12325. }));
  12326. }
  12327. });
  12328. };
  12329. async.auto = function (tasks, callback) {
  12330. callback = callback || function () {};
  12331. var keys = _keys(tasks);
  12332. var remainingTasks = keys.length
  12333. if (!remainingTasks) {
  12334. return callback();
  12335. }
  12336. var results = {};
  12337. var listeners = [];
  12338. var addListener = function (fn) {
  12339. listeners.unshift(fn);
  12340. };
  12341. var removeListener = function (fn) {
  12342. for (var i = 0; i < listeners.length; i += 1) {
  12343. if (listeners[i] === fn) {
  12344. listeners.splice(i, 1);
  12345. return;
  12346. }
  12347. }
  12348. };
  12349. var taskComplete = function () {
  12350. remainingTasks--
  12351. _each(listeners.slice(0), function (fn) {
  12352. fn();
  12353. });
  12354. };
  12355. addListener(function () {
  12356. if (!remainingTasks) {
  12357. var theCallback = callback;
  12358. // prevent final callback from calling itself if it errors
  12359. callback = function () {};
  12360. theCallback(null, results);
  12361. }
  12362. });
  12363. _each(keys, function (k) {
  12364. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12365. var taskCallback = function (err) {
  12366. var args = Array.prototype.slice.call(arguments, 1);
  12367. if (args.length <= 1) {
  12368. args = args[0];
  12369. }
  12370. if (err) {
  12371. var safeResults = {};
  12372. _each(_keys(results), function(rkey) {
  12373. safeResults[rkey] = results[rkey];
  12374. });
  12375. safeResults[k] = args;
  12376. callback(err, safeResults);
  12377. // stop subsequent errors hitting callback multiple times
  12378. callback = function () {};
  12379. }
  12380. else {
  12381. results[k] = args;
  12382. async.setImmediate(taskComplete);
  12383. }
  12384. };
  12385. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12386. var ready = function () {
  12387. return _reduce(requires, function (a, x) {
  12388. return (a && results.hasOwnProperty(x));
  12389. }, true) && !results.hasOwnProperty(k);
  12390. };
  12391. if (ready()) {
  12392. task[task.length - 1](taskCallback, results);
  12393. }
  12394. else {
  12395. var listener = function () {
  12396. if (ready()) {
  12397. removeListener(listener);
  12398. task[task.length - 1](taskCallback, results);
  12399. }
  12400. };
  12401. addListener(listener);
  12402. }
  12403. });
  12404. };
  12405. async.retry = function(times, task, callback) {
  12406. var DEFAULT_TIMES = 5;
  12407. var attempts = [];
  12408. // Use defaults if times not passed
  12409. if (typeof times === 'function') {
  12410. callback = task;
  12411. task = times;
  12412. times = DEFAULT_TIMES;
  12413. }
  12414. // Make sure times is a number
  12415. times = parseInt(times, 10) || DEFAULT_TIMES;
  12416. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12417. var retryAttempt = function(task, finalAttempt) {
  12418. return function(seriesCallback) {
  12419. task(function(err, result){
  12420. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12421. }, wrappedResults);
  12422. };
  12423. };
  12424. while (times) {
  12425. attempts.push(retryAttempt(task, !(times-=1)));
  12426. }
  12427. async.series(attempts, function(done, data){
  12428. data = data[data.length - 1];
  12429. (wrappedCallback || callback)(data.err, data.result);
  12430. });
  12431. }
  12432. // If a callback is passed, run this as a controll flow
  12433. return callback ? wrappedTask() : wrappedTask
  12434. };
  12435. async.waterfall = function (tasks, callback) {
  12436. callback = callback || function () {};
  12437. if (!_isArray(tasks)) {
  12438. var err = new Error('First argument to waterfall must be an array of functions');
  12439. return callback(err);
  12440. }
  12441. if (!tasks.length) {
  12442. return callback();
  12443. }
  12444. var wrapIterator = function (iterator) {
  12445. return function (err) {
  12446. if (err) {
  12447. callback.apply(null, arguments);
  12448. callback = function () {};
  12449. }
  12450. else {
  12451. var args = Array.prototype.slice.call(arguments, 1);
  12452. var next = iterator.next();
  12453. if (next) {
  12454. args.push(wrapIterator(next));
  12455. }
  12456. else {
  12457. args.push(callback);
  12458. }
  12459. async.setImmediate(function () {
  12460. iterator.apply(null, args);
  12461. });
  12462. }
  12463. };
  12464. };
  12465. wrapIterator(async.iterator(tasks))();
  12466. };
  12467. var _parallel = function(eachfn, tasks, callback) {
  12468. callback = callback || function () {};
  12469. if (_isArray(tasks)) {
  12470. eachfn.map(tasks, function (fn, callback) {
  12471. if (fn) {
  12472. fn(function (err) {
  12473. var args = Array.prototype.slice.call(arguments, 1);
  12474. if (args.length <= 1) {
  12475. args = args[0];
  12476. }
  12477. callback.call(null, err, args);
  12478. });
  12479. }
  12480. }, callback);
  12481. }
  12482. else {
  12483. var results = {};
  12484. eachfn.each(_keys(tasks), function (k, callback) {
  12485. tasks[k](function (err) {
  12486. var args = Array.prototype.slice.call(arguments, 1);
  12487. if (args.length <= 1) {
  12488. args = args[0];
  12489. }
  12490. results[k] = args;
  12491. callback(err);
  12492. });
  12493. }, function (err) {
  12494. callback(err, results);
  12495. });
  12496. }
  12497. };
  12498. async.parallel = function (tasks, callback) {
  12499. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12500. };
  12501. async.parallelLimit = function(tasks, limit, callback) {
  12502. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12503. };
  12504. async.series = function (tasks, callback) {
  12505. callback = callback || function () {};
  12506. if (_isArray(tasks)) {
  12507. async.mapSeries(tasks, function (fn, callback) {
  12508. if (fn) {
  12509. fn(function (err) {
  12510. var args = Array.prototype.slice.call(arguments, 1);
  12511. if (args.length <= 1) {
  12512. args = args[0];
  12513. }
  12514. callback.call(null, err, args);
  12515. });
  12516. }
  12517. }, callback);
  12518. }
  12519. else {
  12520. var results = {};
  12521. async.eachSeries(_keys(tasks), function (k, callback) {
  12522. tasks[k](function (err) {
  12523. var args = Array.prototype.slice.call(arguments, 1);
  12524. if (args.length <= 1) {
  12525. args = args[0];
  12526. }
  12527. results[k] = args;
  12528. callback(err);
  12529. });
  12530. }, function (err) {
  12531. callback(err, results);
  12532. });
  12533. }
  12534. };
  12535. async.iterator = function (tasks) {
  12536. var makeCallback = function (index) {
  12537. var fn = function () {
  12538. if (tasks.length) {
  12539. tasks[index].apply(null, arguments);
  12540. }
  12541. return fn.next();
  12542. };
  12543. fn.next = function () {
  12544. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12545. };
  12546. return fn;
  12547. };
  12548. return makeCallback(0);
  12549. };
  12550. async.apply = function (fn) {
  12551. var args = Array.prototype.slice.call(arguments, 1);
  12552. return function () {
  12553. return fn.apply(
  12554. null, args.concat(Array.prototype.slice.call(arguments))
  12555. );
  12556. };
  12557. };
  12558. var _concat = function (eachfn, arr, fn, callback) {
  12559. var r = [];
  12560. eachfn(arr, function (x, cb) {
  12561. fn(x, function (err, y) {
  12562. r = r.concat(y || []);
  12563. cb(err);
  12564. });
  12565. }, function (err) {
  12566. callback(err, r);
  12567. });
  12568. };
  12569. async.concat = doParallel(_concat);
  12570. async.concatSeries = doSeries(_concat);
  12571. async.whilst = function (test, iterator, callback) {
  12572. if (test()) {
  12573. iterator(function (err) {
  12574. if (err) {
  12575. return callback(err);
  12576. }
  12577. async.whilst(test, iterator, callback);
  12578. });
  12579. }
  12580. else {
  12581. callback();
  12582. }
  12583. };
  12584. async.doWhilst = function (iterator, test, callback) {
  12585. iterator(function (err) {
  12586. if (err) {
  12587. return callback(err);
  12588. }
  12589. var args = Array.prototype.slice.call(arguments, 1);
  12590. if (test.apply(null, args)) {
  12591. async.doWhilst(iterator, test, callback);
  12592. }
  12593. else {
  12594. callback();
  12595. }
  12596. });
  12597. };
  12598. async.until = function (test, iterator, callback) {
  12599. if (!test()) {
  12600. iterator(function (err) {
  12601. if (err) {
  12602. return callback(err);
  12603. }
  12604. async.until(test, iterator, callback);
  12605. });
  12606. }
  12607. else {
  12608. callback();
  12609. }
  12610. };
  12611. async.doUntil = function (iterator, test, callback) {
  12612. iterator(function (err) {
  12613. if (err) {
  12614. return callback(err);
  12615. }
  12616. var args = Array.prototype.slice.call(arguments, 1);
  12617. if (!test.apply(null, args)) {
  12618. async.doUntil(iterator, test, callback);
  12619. }
  12620. else {
  12621. callback();
  12622. }
  12623. });
  12624. };
  12625. async.queue = function (worker, concurrency) {
  12626. if (concurrency === undefined) {
  12627. concurrency = 1;
  12628. }
  12629. function _insert(q, data, pos, callback) {
  12630. if (!q.started){
  12631. q.started = true;
  12632. }
  12633. if (!_isArray(data)) {
  12634. data = [data];
  12635. }
  12636. if(data.length == 0) {
  12637. // call drain immediately if there are no tasks
  12638. return async.setImmediate(function() {
  12639. if (q.drain) {
  12640. q.drain();
  12641. }
  12642. });
  12643. }
  12644. _each(data, function(task) {
  12645. var item = {
  12646. data: task,
  12647. callback: typeof callback === 'function' ? callback : null
  12648. };
  12649. if (pos) {
  12650. q.tasks.unshift(item);
  12651. } else {
  12652. q.tasks.push(item);
  12653. }
  12654. if (q.saturated && q.tasks.length === q.concurrency) {
  12655. q.saturated();
  12656. }
  12657. async.setImmediate(q.process);
  12658. });
  12659. }
  12660. var workers = 0;
  12661. var q = {
  12662. tasks: [],
  12663. concurrency: concurrency,
  12664. saturated: null,
  12665. empty: null,
  12666. drain: null,
  12667. started: false,
  12668. paused: false,
  12669. push: function (data, callback) {
  12670. _insert(q, data, false, callback);
  12671. },
  12672. kill: function () {
  12673. q.drain = null;
  12674. q.tasks = [];
  12675. },
  12676. unshift: function (data, callback) {
  12677. _insert(q, data, true, callback);
  12678. },
  12679. process: function () {
  12680. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12681. var task = q.tasks.shift();
  12682. if (q.empty && q.tasks.length === 0) {
  12683. q.empty();
  12684. }
  12685. workers += 1;
  12686. var next = function () {
  12687. workers -= 1;
  12688. if (task.callback) {
  12689. task.callback.apply(task, arguments);
  12690. }
  12691. if (q.drain && q.tasks.length + workers === 0) {
  12692. q.drain();
  12693. }
  12694. q.process();
  12695. };
  12696. var cb = only_once(next);
  12697. worker(task.data, cb);
  12698. }
  12699. },
  12700. length: function () {
  12701. return q.tasks.length;
  12702. },
  12703. running: function () {
  12704. return workers;
  12705. },
  12706. idle: function() {
  12707. return q.tasks.length + workers === 0;
  12708. },
  12709. pause: function () {
  12710. if (q.paused === true) { return; }
  12711. q.paused = true;
  12712. q.process();
  12713. },
  12714. resume: function () {
  12715. if (q.paused === false) { return; }
  12716. q.paused = false;
  12717. q.process();
  12718. }
  12719. };
  12720. return q;
  12721. };
  12722. async.priorityQueue = function (worker, concurrency) {
  12723. function _compareTasks(a, b){
  12724. return a.priority - b.priority;
  12725. };
  12726. function _binarySearch(sequence, item, compare) {
  12727. var beg = -1,
  12728. end = sequence.length - 1;
  12729. while (beg < end) {
  12730. var mid = beg + ((end - beg + 1) >>> 1);
  12731. if (compare(item, sequence[mid]) >= 0) {
  12732. beg = mid;
  12733. } else {
  12734. end = mid - 1;
  12735. }
  12736. }
  12737. return beg;
  12738. }
  12739. function _insert(q, data, priority, callback) {
  12740. if (!q.started){
  12741. q.started = true;
  12742. }
  12743. if (!_isArray(data)) {
  12744. data = [data];
  12745. }
  12746. if(data.length == 0) {
  12747. // call drain immediately if there are no tasks
  12748. return async.setImmediate(function() {
  12749. if (q.drain) {
  12750. q.drain();
  12751. }
  12752. });
  12753. }
  12754. _each(data, function(task) {
  12755. var item = {
  12756. data: task,
  12757. priority: priority,
  12758. callback: typeof callback === 'function' ? callback : null
  12759. };
  12760. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12761. if (q.saturated && q.tasks.length === q.concurrency) {
  12762. q.saturated();
  12763. }
  12764. async.setImmediate(q.process);
  12765. });
  12766. }
  12767. // Start with a normal queue
  12768. var q = async.queue(worker, concurrency);
  12769. // Override push to accept second parameter representing priority
  12770. q.push = function (data, priority, callback) {
  12771. _insert(q, data, priority, callback);
  12772. };
  12773. // Remove unshift function
  12774. delete q.unshift;
  12775. return q;
  12776. };
  12777. async.cargo = function (worker, payload) {
  12778. var working = false,
  12779. tasks = [];
  12780. var cargo = {
  12781. tasks: tasks,
  12782. payload: payload,
  12783. saturated: null,
  12784. empty: null,
  12785. drain: null,
  12786. drained: true,
  12787. push: function (data, callback) {
  12788. if (!_isArray(data)) {
  12789. data = [data];
  12790. }
  12791. _each(data, function(task) {
  12792. tasks.push({
  12793. data: task,
  12794. callback: typeof callback === 'function' ? callback : null
  12795. });
  12796. cargo.drained = false;
  12797. if (cargo.saturated && tasks.length === payload) {
  12798. cargo.saturated();
  12799. }
  12800. });
  12801. async.setImmediate(cargo.process);
  12802. },
  12803. process: function process() {
  12804. if (working) return;
  12805. if (tasks.length === 0) {
  12806. if(cargo.drain && !cargo.drained) cargo.drain();
  12807. cargo.drained = true;
  12808. return;
  12809. }
  12810. var ts = typeof payload === 'number'
  12811. ? tasks.splice(0, payload)
  12812. : tasks.splice(0, tasks.length);
  12813. var ds = _map(ts, function (task) {
  12814. return task.data;
  12815. });
  12816. if(cargo.empty) cargo.empty();
  12817. working = true;
  12818. worker(ds, function () {
  12819. working = false;
  12820. var args = arguments;
  12821. _each(ts, function (data) {
  12822. if (data.callback) {
  12823. data.callback.apply(null, args);
  12824. }
  12825. });
  12826. process();
  12827. });
  12828. },
  12829. length: function () {
  12830. return tasks.length;
  12831. },
  12832. running: function () {
  12833. return working;
  12834. }
  12835. };
  12836. return cargo;
  12837. };
  12838. var _console_fn = function (name) {
  12839. return function (fn) {
  12840. var args = Array.prototype.slice.call(arguments, 1);
  12841. fn.apply(null, args.concat([function (err) {
  12842. var args = Array.prototype.slice.call(arguments, 1);
  12843. if (typeof console !== 'undefined') {
  12844. if (err) {
  12845. if (console.error) {
  12846. console.error(err);
  12847. }
  12848. }
  12849. else if (console[name]) {
  12850. _each(args, function (x) {
  12851. console[name](x);
  12852. });
  12853. }
  12854. }
  12855. }]));
  12856. };
  12857. };
  12858. async.log = _console_fn('log');
  12859. async.dir = _console_fn('dir');
  12860. /*async.info = _console_fn('info');
  12861. async.warn = _console_fn('warn');
  12862. async.error = _console_fn('error');*/
  12863. async.memoize = function (fn, hasher) {
  12864. var memo = {};
  12865. var queues = {};
  12866. hasher = hasher || function (x) {
  12867. return x;
  12868. };
  12869. var memoized = function () {
  12870. var args = Array.prototype.slice.call(arguments);
  12871. var callback = args.pop();
  12872. var key = hasher.apply(null, args);
  12873. if (key in memo) {
  12874. async.nextTick(function () {
  12875. callback.apply(null, memo[key]);
  12876. });
  12877. }
  12878. else if (key in queues) {
  12879. queues[key].push(callback);
  12880. }
  12881. else {
  12882. queues[key] = [callback];
  12883. fn.apply(null, args.concat([function () {
  12884. memo[key] = arguments;
  12885. var q = queues[key];
  12886. delete queues[key];
  12887. for (var i = 0, l = q.length; i < l; i++) {
  12888. q[i].apply(null, arguments);
  12889. }
  12890. }]));
  12891. }
  12892. };
  12893. memoized.memo = memo;
  12894. memoized.unmemoized = fn;
  12895. return memoized;
  12896. };
  12897. async.unmemoize = function (fn) {
  12898. return function () {
  12899. return (fn.unmemoized || fn).apply(null, arguments);
  12900. };
  12901. };
  12902. async.times = function (count, iterator, callback) {
  12903. var counter = [];
  12904. for (var i = 0; i < count; i++) {
  12905. counter.push(i);
  12906. }
  12907. return async.map(counter, iterator, callback);
  12908. };
  12909. async.timesSeries = function (count, iterator, callback) {
  12910. var counter = [];
  12911. for (var i = 0; i < count; i++) {
  12912. counter.push(i);
  12913. }
  12914. return async.mapSeries(counter, iterator, callback);
  12915. };
  12916. async.seq = function (/* functions... */) {
  12917. var fns = arguments;
  12918. return function () {
  12919. var that = this;
  12920. var args = Array.prototype.slice.call(arguments);
  12921. var callback = args.pop();
  12922. async.reduce(fns, args, function (newargs, fn, cb) {
  12923. fn.apply(that, newargs.concat([function () {
  12924. var err = arguments[0];
  12925. var nextargs = Array.prototype.slice.call(arguments, 1);
  12926. cb(err, nextargs);
  12927. }]))
  12928. },
  12929. function (err, results) {
  12930. callback.apply(that, [err].concat(results));
  12931. });
  12932. };
  12933. };
  12934. async.compose = function (/* functions... */) {
  12935. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  12936. };
  12937. var _applyEach = function (eachfn, fns /*args...*/) {
  12938. var go = function () {
  12939. var that = this;
  12940. var args = Array.prototype.slice.call(arguments);
  12941. var callback = args.pop();
  12942. return eachfn(fns, function (fn, cb) {
  12943. fn.apply(that, args.concat([cb]));
  12944. },
  12945. callback);
  12946. };
  12947. if (arguments.length > 2) {
  12948. var args = Array.prototype.slice.call(arguments, 2);
  12949. return go.apply(this, args);
  12950. }
  12951. else {
  12952. return go;
  12953. }
  12954. };
  12955. async.applyEach = doParallel(_applyEach);
  12956. async.applyEachSeries = doSeries(_applyEach);
  12957. async.forever = function (fn, callback) {
  12958. function next(err) {
  12959. if (err) {
  12960. if (callback) {
  12961. return callback(err);
  12962. }
  12963. throw err;
  12964. }
  12965. fn(next);
  12966. }
  12967. next();
  12968. };
  12969. // Node.js
  12970. if (typeof module !== 'undefined' && module.exports) {
  12971. module.exports = async;
  12972. }
  12973. // AMD / RequireJS
  12974. else if (typeof define !== 'undefined' && define.amd) {
  12975. define([], function () {
  12976. return async;
  12977. });
  12978. }
  12979. // included directly via <script> tag
  12980. else {
  12981. root.async = async;
  12982. }
  12983. }());
  12984. }).call(this,require('_process'))
  12985. },{"_process":46}],45:[function(require,module,exports){
  12986. // Copyright Joyent, Inc. and other Node contributors.
  12987. //
  12988. // Permission is hereby granted, free of charge, to any person obtaining a
  12989. // copy of this software and associated documentation files (the
  12990. // "Software"), to deal in the Software without restriction, including
  12991. // without limitation the rights to use, copy, modify, merge, publish,
  12992. // distribute, sublicense, and/or sell copies of the Software, and to permit
  12993. // persons to whom the Software is furnished to do so, subject to the
  12994. // following conditions:
  12995. //
  12996. // The above copyright notice and this permission notice shall be included
  12997. // in all copies or substantial portions of the Software.
  12998. //
  12999. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13000. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13001. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13002. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13003. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13004. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13005. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13006. function EventEmitter() {
  13007. this._events = this._events || {};
  13008. this._maxListeners = this._maxListeners || undefined;
  13009. }
  13010. module.exports = EventEmitter;
  13011. // Backwards-compat with node 0.10.x
  13012. EventEmitter.EventEmitter = EventEmitter;
  13013. EventEmitter.prototype._events = undefined;
  13014. EventEmitter.prototype._maxListeners = undefined;
  13015. // By default EventEmitters will print a warning if more than 10 listeners are
  13016. // added to it. This is a useful default which helps finding memory leaks.
  13017. EventEmitter.defaultMaxListeners = 10;
  13018. // Obviously not all Emitters should be limited to 10. This function allows
  13019. // that to be increased. Set to zero for unlimited.
  13020. EventEmitter.prototype.setMaxListeners = function(n) {
  13021. if (!isNumber(n) || n < 0 || isNaN(n))
  13022. throw TypeError('n must be a positive number');
  13023. this._maxListeners = n;
  13024. return this;
  13025. };
  13026. EventEmitter.prototype.emit = function(type) {
  13027. var er, handler, len, args, i, listeners;
  13028. if (!this._events)
  13029. this._events = {};
  13030. // If there is no 'error' event listener then throw.
  13031. if (type === 'error') {
  13032. if (!this._events.error ||
  13033. (isObject(this._events.error) && !this._events.error.length)) {
  13034. er = arguments[1];
  13035. if (er instanceof Error) {
  13036. throw er; // Unhandled 'error' event
  13037. }
  13038. throw TypeError('Uncaught, unspecified "error" event.');
  13039. }
  13040. }
  13041. handler = this._events[type];
  13042. if (isUndefined(handler))
  13043. return false;
  13044. if (isFunction(handler)) {
  13045. switch (arguments.length) {
  13046. // fast cases
  13047. case 1:
  13048. handler.call(this);
  13049. break;
  13050. case 2:
  13051. handler.call(this, arguments[1]);
  13052. break;
  13053. case 3:
  13054. handler.call(this, arguments[1], arguments[2]);
  13055. break;
  13056. // slower
  13057. default:
  13058. len = arguments.length;
  13059. args = new Array(len - 1);
  13060. for (i = 1; i < len; i++)
  13061. args[i - 1] = arguments[i];
  13062. handler.apply(this, args);
  13063. }
  13064. } else if (isObject(handler)) {
  13065. len = arguments.length;
  13066. args = new Array(len - 1);
  13067. for (i = 1; i < len; i++)
  13068. args[i - 1] = arguments[i];
  13069. listeners = handler.slice();
  13070. len = listeners.length;
  13071. for (i = 0; i < len; i++)
  13072. listeners[i].apply(this, args);
  13073. }
  13074. return true;
  13075. };
  13076. EventEmitter.prototype.addListener = function(type, listener) {
  13077. var m;
  13078. if (!isFunction(listener))
  13079. throw TypeError('listener must be a function');
  13080. if (!this._events)
  13081. this._events = {};
  13082. // To avoid recursion in the case that type === "newListener"! Before
  13083. // adding it to the listeners, first emit "newListener".
  13084. if (this._events.newListener)
  13085. this.emit('newListener', type,
  13086. isFunction(listener.listener) ?
  13087. listener.listener : listener);
  13088. if (!this._events[type])
  13089. // Optimize the case of one listener. Don't need the extra array object.
  13090. this._events[type] = listener;
  13091. else if (isObject(this._events[type]))
  13092. // If we've already got an array, just append.
  13093. this._events[type].push(listener);
  13094. else
  13095. // Adding the second element, need to change to array.
  13096. this._events[type] = [this._events[type], listener];
  13097. // Check for listener leak
  13098. if (isObject(this._events[type]) && !this._events[type].warned) {
  13099. var m;
  13100. if (!isUndefined(this._maxListeners)) {
  13101. m = this._maxListeners;
  13102. } else {
  13103. m = EventEmitter.defaultMaxListeners;
  13104. }
  13105. if (m && m > 0 && this._events[type].length > m) {
  13106. this._events[type].warned = true;
  13107. console.error('(node) warning: possible EventEmitter memory ' +
  13108. 'leak detected. %d listeners added. ' +
  13109. 'Use emitter.setMaxListeners() to increase limit.',
  13110. this._events[type].length);
  13111. if (typeof console.trace === 'function') {
  13112. // not supported in IE 10
  13113. console.trace();
  13114. }
  13115. }
  13116. }
  13117. return this;
  13118. };
  13119. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13120. EventEmitter.prototype.once = function(type, listener) {
  13121. if (!isFunction(listener))
  13122. throw TypeError('listener must be a function');
  13123. var fired = false;
  13124. function g() {
  13125. this.removeListener(type, g);
  13126. if (!fired) {
  13127. fired = true;
  13128. listener.apply(this, arguments);
  13129. }
  13130. }
  13131. g.listener = listener;
  13132. this.on(type, g);
  13133. return this;
  13134. };
  13135. // emits a 'removeListener' event iff the listener was removed
  13136. EventEmitter.prototype.removeListener = function(type, listener) {
  13137. var list, position, length, i;
  13138. if (!isFunction(listener))
  13139. throw TypeError('listener must be a function');
  13140. if (!this._events || !this._events[type])
  13141. return this;
  13142. list = this._events[type];
  13143. length = list.length;
  13144. position = -1;
  13145. if (list === listener ||
  13146. (isFunction(list.listener) && list.listener === listener)) {
  13147. delete this._events[type];
  13148. if (this._events.removeListener)
  13149. this.emit('removeListener', type, listener);
  13150. } else if (isObject(list)) {
  13151. for (i = length; i-- > 0;) {
  13152. if (list[i] === listener ||
  13153. (list[i].listener && list[i].listener === listener)) {
  13154. position = i;
  13155. break;
  13156. }
  13157. }
  13158. if (position < 0)
  13159. return this;
  13160. if (list.length === 1) {
  13161. list.length = 0;
  13162. delete this._events[type];
  13163. } else {
  13164. list.splice(position, 1);
  13165. }
  13166. if (this._events.removeListener)
  13167. this.emit('removeListener', type, listener);
  13168. }
  13169. return this;
  13170. };
  13171. EventEmitter.prototype.removeAllListeners = function(type) {
  13172. var key, listeners;
  13173. if (!this._events)
  13174. return this;
  13175. // not listening for removeListener, no need to emit
  13176. if (!this._events.removeListener) {
  13177. if (arguments.length === 0)
  13178. this._events = {};
  13179. else if (this._events[type])
  13180. delete this._events[type];
  13181. return this;
  13182. }
  13183. // emit removeListener for all listeners on all events
  13184. if (arguments.length === 0) {
  13185. for (key in this._events) {
  13186. if (key === 'removeListener') continue;
  13187. this.removeAllListeners(key);
  13188. }
  13189. this.removeAllListeners('removeListener');
  13190. this._events = {};
  13191. return this;
  13192. }
  13193. listeners = this._events[type];
  13194. if (isFunction(listeners)) {
  13195. this.removeListener(type, listeners);
  13196. } else {
  13197. // LIFO order
  13198. while (listeners.length)
  13199. this.removeListener(type, listeners[listeners.length - 1]);
  13200. }
  13201. delete this._events[type];
  13202. return this;
  13203. };
  13204. EventEmitter.prototype.listeners = function(type) {
  13205. var ret;
  13206. if (!this._events || !this._events[type])
  13207. ret = [];
  13208. else if (isFunction(this._events[type]))
  13209. ret = [this._events[type]];
  13210. else
  13211. ret = this._events[type].slice();
  13212. return ret;
  13213. };
  13214. EventEmitter.listenerCount = function(emitter, type) {
  13215. var ret;
  13216. if (!emitter._events || !emitter._events[type])
  13217. ret = 0;
  13218. else if (isFunction(emitter._events[type]))
  13219. ret = 1;
  13220. else
  13221. ret = emitter._events[type].length;
  13222. return ret;
  13223. };
  13224. function isFunction(arg) {
  13225. return typeof arg === 'function';
  13226. }
  13227. function isNumber(arg) {
  13228. return typeof arg === 'number';
  13229. }
  13230. function isObject(arg) {
  13231. return typeof arg === 'object' && arg !== null;
  13232. }
  13233. function isUndefined(arg) {
  13234. return arg === void 0;
  13235. }
  13236. },{}],46:[function(require,module,exports){
  13237. // shim for using process in browser
  13238. var process = module.exports = {};
  13239. var queue = [];
  13240. var draining = false;
  13241. var currentQueue;
  13242. var queueIndex = -1;
  13243. function cleanUpNextTick() {
  13244. draining = false;
  13245. if (currentQueue.length) {
  13246. queue = currentQueue.concat(queue);
  13247. } else {
  13248. queueIndex = -1;
  13249. }
  13250. if (queue.length) {
  13251. drainQueue();
  13252. }
  13253. }
  13254. function drainQueue() {
  13255. if (draining) {
  13256. return;
  13257. }
  13258. var timeout = setTimeout(cleanUpNextTick);
  13259. draining = true;
  13260. var len = queue.length;
  13261. while(len) {
  13262. currentQueue = queue;
  13263. queue = [];
  13264. while (++queueIndex < len) {
  13265. if (currentQueue) {
  13266. currentQueue[queueIndex].run();
  13267. }
  13268. }
  13269. queueIndex = -1;
  13270. len = queue.length;
  13271. }
  13272. currentQueue = null;
  13273. draining = false;
  13274. clearTimeout(timeout);
  13275. }
  13276. process.nextTick = function (fun) {
  13277. var args = new Array(arguments.length - 1);
  13278. if (arguments.length > 1) {
  13279. for (var i = 1; i < arguments.length; i++) {
  13280. args[i - 1] = arguments[i];
  13281. }
  13282. }
  13283. queue.push(new Item(fun, args));
  13284. if (queue.length === 1 && !draining) {
  13285. setTimeout(drainQueue, 0);
  13286. }
  13287. };
  13288. // v8 likes predictible objects
  13289. function Item(fun, array) {
  13290. this.fun = fun;
  13291. this.array = array;
  13292. }
  13293. Item.prototype.run = function () {
  13294. this.fun.apply(null, this.array);
  13295. };
  13296. process.title = 'browser';
  13297. process.browser = true;
  13298. process.env = {};
  13299. process.argv = [];
  13300. process.version = ''; // empty string to avoid regexp issues
  13301. process.versions = {};
  13302. function noop() {}
  13303. process.on = noop;
  13304. process.addListener = noop;
  13305. process.once = noop;
  13306. process.off = noop;
  13307. process.removeListener = noop;
  13308. process.removeAllListeners = noop;
  13309. process.emit = noop;
  13310. process.binding = function (name) {
  13311. throw new Error('process.binding is not supported');
  13312. };
  13313. process.cwd = function () { return '/' };
  13314. process.chdir = function (dir) {
  13315. throw new Error('process.chdir is not supported');
  13316. };
  13317. process.umask = function() { return 0; };
  13318. },{}],47:[function(require,module,exports){
  13319. (function (process,global){
  13320. /*!
  13321. * @overview es6-promise - a tiny implementation of Promises/A+.
  13322. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13323. * @license Licensed under MIT license
  13324. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13325. * @version 3.0.2
  13326. */
  13327. (function() {
  13328. "use strict";
  13329. function lib$es6$promise$utils$$objectOrFunction(x) {
  13330. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  13331. }
  13332. function lib$es6$promise$utils$$isFunction(x) {
  13333. return typeof x === 'function';
  13334. }
  13335. function lib$es6$promise$utils$$isMaybeThenable(x) {
  13336. return typeof x === 'object' && x !== null;
  13337. }
  13338. var lib$es6$promise$utils$$_isArray;
  13339. if (!Array.isArray) {
  13340. lib$es6$promise$utils$$_isArray = function (x) {
  13341. return Object.prototype.toString.call(x) === '[object Array]';
  13342. };
  13343. } else {
  13344. lib$es6$promise$utils$$_isArray = Array.isArray;
  13345. }
  13346. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  13347. var lib$es6$promise$asap$$len = 0;
  13348. var lib$es6$promise$asap$$toString = {}.toString;
  13349. var lib$es6$promise$asap$$vertxNext;
  13350. var lib$es6$promise$asap$$customSchedulerFn;
  13351. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  13352. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  13353. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  13354. lib$es6$promise$asap$$len += 2;
  13355. if (lib$es6$promise$asap$$len === 2) {
  13356. // If len is 2, that means that we need to schedule an async flush.
  13357. // If additional callbacks are queued before the queue is flushed, they
  13358. // will be processed by this flush that we are scheduling.
  13359. if (lib$es6$promise$asap$$customSchedulerFn) {
  13360. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  13361. } else {
  13362. lib$es6$promise$asap$$scheduleFlush();
  13363. }
  13364. }
  13365. }
  13366. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  13367. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  13368. }
  13369. function lib$es6$promise$asap$$setAsap(asapFn) {
  13370. lib$es6$promise$asap$$asap = asapFn;
  13371. }
  13372. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  13373. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  13374. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  13375. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  13376. // test for web worker but not in IE10
  13377. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  13378. typeof importScripts !== 'undefined' &&
  13379. typeof MessageChannel !== 'undefined';
  13380. // node
  13381. function lib$es6$promise$asap$$useNextTick() {
  13382. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  13383. // see https://github.com/cujojs/when/issues/410 for details
  13384. return function() {
  13385. process.nextTick(lib$es6$promise$asap$$flush);
  13386. };
  13387. }
  13388. // vertx
  13389. function lib$es6$promise$asap$$useVertxTimer() {
  13390. return function() {
  13391. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  13392. };
  13393. }
  13394. function lib$es6$promise$asap$$useMutationObserver() {
  13395. var iterations = 0;
  13396. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  13397. var node = document.createTextNode('');
  13398. observer.observe(node, { characterData: true });
  13399. return function() {
  13400. node.data = (iterations = ++iterations % 2);
  13401. };
  13402. }
  13403. // web worker
  13404. function lib$es6$promise$asap$$useMessageChannel() {
  13405. var channel = new MessageChannel();
  13406. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  13407. return function () {
  13408. channel.port2.postMessage(0);
  13409. };
  13410. }
  13411. function lib$es6$promise$asap$$useSetTimeout() {
  13412. return function() {
  13413. setTimeout(lib$es6$promise$asap$$flush, 1);
  13414. };
  13415. }
  13416. var lib$es6$promise$asap$$queue = new Array(1000);
  13417. function lib$es6$promise$asap$$flush() {
  13418. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  13419. var callback = lib$es6$promise$asap$$queue[i];
  13420. var arg = lib$es6$promise$asap$$queue[i+1];
  13421. callback(arg);
  13422. lib$es6$promise$asap$$queue[i] = undefined;
  13423. lib$es6$promise$asap$$queue[i+1] = undefined;
  13424. }
  13425. lib$es6$promise$asap$$len = 0;
  13426. }
  13427. function lib$es6$promise$asap$$attemptVertx() {
  13428. try {
  13429. var r = require;
  13430. var vertx = r('vertx');
  13431. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  13432. return lib$es6$promise$asap$$useVertxTimer();
  13433. } catch(e) {
  13434. return lib$es6$promise$asap$$useSetTimeout();
  13435. }
  13436. }
  13437. var lib$es6$promise$asap$$scheduleFlush;
  13438. // Decide what async method to use to triggering processing of queued callbacks:
  13439. if (lib$es6$promise$asap$$isNode) {
  13440. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  13441. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  13442. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  13443. } else if (lib$es6$promise$asap$$isWorker) {
  13444. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  13445. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  13446. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  13447. } else {
  13448. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  13449. }
  13450. function lib$es6$promise$$internal$$noop() {}
  13451. var lib$es6$promise$$internal$$PENDING = void 0;
  13452. var lib$es6$promise$$internal$$FULFILLED = 1;
  13453. var lib$es6$promise$$internal$$REJECTED = 2;
  13454. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13455. function lib$es6$promise$$internal$$selfFulfillment() {
  13456. return new TypeError("You cannot resolve a promise with itself");
  13457. }
  13458. function lib$es6$promise$$internal$$cannotReturnOwn() {
  13459. return new TypeError('A promises callback cannot return that same promise.');
  13460. }
  13461. function lib$es6$promise$$internal$$getThen(promise) {
  13462. try {
  13463. return promise.then;
  13464. } catch(error) {
  13465. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  13466. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  13467. }
  13468. }
  13469. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  13470. try {
  13471. then.call(value, fulfillmentHandler, rejectionHandler);
  13472. } catch(e) {
  13473. return e;
  13474. }
  13475. }
  13476. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  13477. lib$es6$promise$asap$$asap(function(promise) {
  13478. var sealed = false;
  13479. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  13480. if (sealed) { return; }
  13481. sealed = true;
  13482. if (thenable !== value) {
  13483. lib$es6$promise$$internal$$resolve(promise, value);
  13484. } else {
  13485. lib$es6$promise$$internal$$fulfill(promise, value);
  13486. }
  13487. }, function(reason) {
  13488. if (sealed) { return; }
  13489. sealed = true;
  13490. lib$es6$promise$$internal$$reject(promise, reason);
  13491. }, 'Settle: ' + (promise._label || ' unknown promise'));
  13492. if (!sealed && error) {
  13493. sealed = true;
  13494. lib$es6$promise$$internal$$reject(promise, error);
  13495. }
  13496. }, promise);
  13497. }
  13498. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  13499. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  13500. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  13501. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  13502. lib$es6$promise$$internal$$reject(promise, thenable._result);
  13503. } else {
  13504. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  13505. lib$es6$promise$$internal$$resolve(promise, value);
  13506. }, function(reason) {
  13507. lib$es6$promise$$internal$$reject(promise, reason);
  13508. });
  13509. }
  13510. }
  13511. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  13512. if (maybeThenable.constructor === promise.constructor) {
  13513. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  13514. } else {
  13515. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  13516. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  13517. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  13518. } else if (then === undefined) {
  13519. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13520. } else if (lib$es6$promise$utils$$isFunction(then)) {
  13521. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  13522. } else {
  13523. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13524. }
  13525. }
  13526. }
  13527. function lib$es6$promise$$internal$$resolve(promise, value) {
  13528. if (promise === value) {
  13529. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  13530. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  13531. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  13532. } else {
  13533. lib$es6$promise$$internal$$fulfill(promise, value);
  13534. }
  13535. }
  13536. function lib$es6$promise$$internal$$publishRejection(promise) {
  13537. if (promise._onerror) {
  13538. promise._onerror(promise._result);
  13539. }
  13540. lib$es6$promise$$internal$$publish(promise);
  13541. }
  13542. function lib$es6$promise$$internal$$fulfill(promise, value) {
  13543. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13544. promise._result = value;
  13545. promise._state = lib$es6$promise$$internal$$FULFILLED;
  13546. if (promise._subscribers.length !== 0) {
  13547. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  13548. }
  13549. }
  13550. function lib$es6$promise$$internal$$reject(promise, reason) {
  13551. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13552. promise._state = lib$es6$promise$$internal$$REJECTED;
  13553. promise._result = reason;
  13554. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  13555. }
  13556. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  13557. var subscribers = parent._subscribers;
  13558. var length = subscribers.length;
  13559. parent._onerror = null;
  13560. subscribers[length] = child;
  13561. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  13562. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  13563. if (length === 0 && parent._state) {
  13564. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  13565. }
  13566. }
  13567. function lib$es6$promise$$internal$$publish(promise) {
  13568. var subscribers = promise._subscribers;
  13569. var settled = promise._state;
  13570. if (subscribers.length === 0) { return; }
  13571. var child, callback, detail = promise._result;
  13572. for (var i = 0; i < subscribers.length; i += 3) {
  13573. child = subscribers[i];
  13574. callback = subscribers[i + settled];
  13575. if (child) {
  13576. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  13577. } else {
  13578. callback(detail);
  13579. }
  13580. }
  13581. promise._subscribers.length = 0;
  13582. }
  13583. function lib$es6$promise$$internal$$ErrorObject() {
  13584. this.error = null;
  13585. }
  13586. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13587. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  13588. try {
  13589. return callback(detail);
  13590. } catch(e) {
  13591. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  13592. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  13593. }
  13594. }
  13595. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  13596. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  13597. value, error, succeeded, failed;
  13598. if (hasCallback) {
  13599. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  13600. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  13601. failed = true;
  13602. error = value.error;
  13603. value = null;
  13604. } else {
  13605. succeeded = true;
  13606. }
  13607. if (promise === value) {
  13608. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  13609. return;
  13610. }
  13611. } else {
  13612. value = detail;
  13613. succeeded = true;
  13614. }
  13615. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  13616. // noop
  13617. } else if (hasCallback && succeeded) {
  13618. lib$es6$promise$$internal$$resolve(promise, value);
  13619. } else if (failed) {
  13620. lib$es6$promise$$internal$$reject(promise, error);
  13621. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  13622. lib$es6$promise$$internal$$fulfill(promise, value);
  13623. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  13624. lib$es6$promise$$internal$$reject(promise, value);
  13625. }
  13626. }
  13627. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  13628. try {
  13629. resolver(function resolvePromise(value){
  13630. lib$es6$promise$$internal$$resolve(promise, value);
  13631. }, function rejectPromise(reason) {
  13632. lib$es6$promise$$internal$$reject(promise, reason);
  13633. });
  13634. } catch(e) {
  13635. lib$es6$promise$$internal$$reject(promise, e);
  13636. }
  13637. }
  13638. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  13639. var enumerator = this;
  13640. enumerator._instanceConstructor = Constructor;
  13641. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  13642. if (enumerator._validateInput(input)) {
  13643. enumerator._input = input;
  13644. enumerator.length = input.length;
  13645. enumerator._remaining = input.length;
  13646. enumerator._init();
  13647. if (enumerator.length === 0) {
  13648. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13649. } else {
  13650. enumerator.length = enumerator.length || 0;
  13651. enumerator._enumerate();
  13652. if (enumerator._remaining === 0) {
  13653. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13654. }
  13655. }
  13656. } else {
  13657. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  13658. }
  13659. }
  13660. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  13661. return lib$es6$promise$utils$$isArray(input);
  13662. };
  13663. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  13664. return new Error('Array Methods must be provided an Array');
  13665. };
  13666. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13667. this._result = new Array(this.length);
  13668. };
  13669. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13670. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13671. var enumerator = this;
  13672. var length = enumerator.length;
  13673. var promise = enumerator.promise;
  13674. var input = enumerator._input;
  13675. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13676. enumerator._eachEntry(input[i], i);
  13677. }
  13678. };
  13679. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13680. var enumerator = this;
  13681. var c = enumerator._instanceConstructor;
  13682. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13683. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13684. entry._onerror = null;
  13685. enumerator._settledAt(entry._state, i, entry._result);
  13686. } else {
  13687. enumerator._willSettleAt(c.resolve(entry), i);
  13688. }
  13689. } else {
  13690. enumerator._remaining--;
  13691. enumerator._result[i] = entry;
  13692. }
  13693. };
  13694. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13695. var enumerator = this;
  13696. var promise = enumerator.promise;
  13697. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13698. enumerator._remaining--;
  13699. if (state === lib$es6$promise$$internal$$REJECTED) {
  13700. lib$es6$promise$$internal$$reject(promise, value);
  13701. } else {
  13702. enumerator._result[i] = value;
  13703. }
  13704. }
  13705. if (enumerator._remaining === 0) {
  13706. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13707. }
  13708. };
  13709. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13710. var enumerator = this;
  13711. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13712. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13713. }, function(reason) {
  13714. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13715. });
  13716. };
  13717. function lib$es6$promise$promise$all$$all(entries) {
  13718. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13719. }
  13720. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13721. function lib$es6$promise$promise$race$$race(entries) {
  13722. /*jshint validthis:true */
  13723. var Constructor = this;
  13724. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13725. if (!lib$es6$promise$utils$$isArray(entries)) {
  13726. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13727. return promise;
  13728. }
  13729. var length = entries.length;
  13730. function onFulfillment(value) {
  13731. lib$es6$promise$$internal$$resolve(promise, value);
  13732. }
  13733. function onRejection(reason) {
  13734. lib$es6$promise$$internal$$reject(promise, reason);
  13735. }
  13736. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13737. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13738. }
  13739. return promise;
  13740. }
  13741. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13742. function lib$es6$promise$promise$resolve$$resolve(object) {
  13743. /*jshint validthis:true */
  13744. var Constructor = this;
  13745. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13746. return object;
  13747. }
  13748. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13749. lib$es6$promise$$internal$$resolve(promise, object);
  13750. return promise;
  13751. }
  13752. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13753. function lib$es6$promise$promise$reject$$reject(reason) {
  13754. /*jshint validthis:true */
  13755. var Constructor = this;
  13756. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13757. lib$es6$promise$$internal$$reject(promise, reason);
  13758. return promise;
  13759. }
  13760. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13761. var lib$es6$promise$promise$$counter = 0;
  13762. function lib$es6$promise$promise$$needsResolver() {
  13763. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13764. }
  13765. function lib$es6$promise$promise$$needsNew() {
  13766. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13767. }
  13768. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13769. /**
  13770. Promise objects represent the eventual result of an asynchronous operation. The
  13771. primary way of interacting with a promise is through its `then` method, which
  13772. registers callbacks to receive either a promise's eventual value or the reason
  13773. why the promise cannot be fulfilled.
  13774. Terminology
  13775. -----------
  13776. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13777. - `thenable` is an object or function that defines a `then` method.
  13778. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13779. - `exception` is a value that is thrown using the throw statement.
  13780. - `reason` is a value that indicates why a promise was rejected.
  13781. - `settled` the final resting state of a promise, fulfilled or rejected.
  13782. A promise can be in one of three states: pending, fulfilled, or rejected.
  13783. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13784. state. Promises that are rejected have a rejection reason and are in the
  13785. rejected state. A fulfillment value is never a thenable.
  13786. Promises can also be said to *resolve* a value. If this value is also a
  13787. promise, then the original promise's settled state will match the value's
  13788. settled state. So a promise that *resolves* a promise that rejects will
  13789. itself reject, and a promise that *resolves* a promise that fulfills will
  13790. itself fulfill.
  13791. Basic Usage:
  13792. ------------
  13793. ```js
  13794. var promise = new Promise(function(resolve, reject) {
  13795. // on success
  13796. resolve(value);
  13797. // on failure
  13798. reject(reason);
  13799. });
  13800. promise.then(function(value) {
  13801. // on fulfillment
  13802. }, function(reason) {
  13803. // on rejection
  13804. });
  13805. ```
  13806. Advanced Usage:
  13807. ---------------
  13808. Promises shine when abstracting away asynchronous interactions such as
  13809. `XMLHttpRequest`s.
  13810. ```js
  13811. function getJSON(url) {
  13812. return new Promise(function(resolve, reject){
  13813. var xhr = new XMLHttpRequest();
  13814. xhr.open('GET', url);
  13815. xhr.onreadystatechange = handler;
  13816. xhr.responseType = 'json';
  13817. xhr.setRequestHeader('Accept', 'application/json');
  13818. xhr.send();
  13819. function handler() {
  13820. if (this.readyState === this.DONE) {
  13821. if (this.status === 200) {
  13822. resolve(this.response);
  13823. } else {
  13824. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  13825. }
  13826. }
  13827. };
  13828. });
  13829. }
  13830. getJSON('/posts.json').then(function(json) {
  13831. // on fulfillment
  13832. }, function(reason) {
  13833. // on rejection
  13834. });
  13835. ```
  13836. Unlike callbacks, promises are great composable primitives.
  13837. ```js
  13838. Promise.all([
  13839. getJSON('/posts'),
  13840. getJSON('/comments')
  13841. ]).then(function(values){
  13842. values[0] // => postsJSON
  13843. values[1] // => commentsJSON
  13844. return values;
  13845. });
  13846. ```
  13847. @class Promise
  13848. @param {function} resolver
  13849. Useful for tooling.
  13850. @constructor
  13851. */
  13852. function lib$es6$promise$promise$$Promise(resolver) {
  13853. this._id = lib$es6$promise$promise$$counter++;
  13854. this._state = undefined;
  13855. this._result = undefined;
  13856. this._subscribers = [];
  13857. if (lib$es6$promise$$internal$$noop !== resolver) {
  13858. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  13859. lib$es6$promise$promise$$needsResolver();
  13860. }
  13861. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  13862. lib$es6$promise$promise$$needsNew();
  13863. }
  13864. lib$es6$promise$$internal$$initializePromise(this, resolver);
  13865. }
  13866. }
  13867. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  13868. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  13869. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  13870. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  13871. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  13872. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  13873. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  13874. lib$es6$promise$promise$$Promise.prototype = {
  13875. constructor: lib$es6$promise$promise$$Promise,
  13876. /**
  13877. The primary way of interacting with a promise is through its `then` method,
  13878. which registers callbacks to receive either a promise's eventual value or the
  13879. reason why the promise cannot be fulfilled.
  13880. ```js
  13881. findUser().then(function(user){
  13882. // user is available
  13883. }, function(reason){
  13884. // user is unavailable, and you are given the reason why
  13885. });
  13886. ```
  13887. Chaining
  13888. --------
  13889. The return value of `then` is itself a promise. This second, 'downstream'
  13890. promise is resolved with the return value of the first promise's fulfillment
  13891. or rejection handler, or rejected if the handler throws an exception.
  13892. ```js
  13893. findUser().then(function (user) {
  13894. return user.name;
  13895. }, function (reason) {
  13896. return 'default name';
  13897. }).then(function (userName) {
  13898. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  13899. // will be `'default name'`
  13900. });
  13901. findUser().then(function (user) {
  13902. throw new Error('Found user, but still unhappy');
  13903. }, function (reason) {
  13904. throw new Error('`findUser` rejected and we're unhappy');
  13905. }).then(function (value) {
  13906. // never reached
  13907. }, function (reason) {
  13908. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  13909. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  13910. });
  13911. ```
  13912. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  13913. ```js
  13914. findUser().then(function (user) {
  13915. throw new PedagogicalException('Upstream error');
  13916. }).then(function (value) {
  13917. // never reached
  13918. }).then(function (value) {
  13919. // never reached
  13920. }, function (reason) {
  13921. // The `PedgagocialException` is propagated all the way down to here
  13922. });
  13923. ```
  13924. Assimilation
  13925. ------------
  13926. Sometimes the value you want to propagate to a downstream promise can only be
  13927. retrieved asynchronously. This can be achieved by returning a promise in the
  13928. fulfillment or rejection handler. The downstream promise will then be pending
  13929. until the returned promise is settled. This is called *assimilation*.
  13930. ```js
  13931. findUser().then(function (user) {
  13932. return findCommentsByAuthor(user);
  13933. }).then(function (comments) {
  13934. // The user's comments are now available
  13935. });
  13936. ```
  13937. If the assimliated promise rejects, then the downstream promise will also reject.
  13938. ```js
  13939. findUser().then(function (user) {
  13940. return findCommentsByAuthor(user);
  13941. }).then(function (comments) {
  13942. // If `findCommentsByAuthor` fulfills, we'll have the value here
  13943. }, function (reason) {
  13944. // If `findCommentsByAuthor` rejects, we'll have the reason here
  13945. });
  13946. ```
  13947. Simple Example
  13948. --------------
  13949. Synchronous Example
  13950. ```javascript
  13951. var result;
  13952. try {
  13953. result = findResult();
  13954. // success
  13955. } catch(reason) {
  13956. // failure
  13957. }
  13958. ```
  13959. Errback Example
  13960. ```js
  13961. findResult(function(result, err){
  13962. if (err) {
  13963. // failure
  13964. } else {
  13965. // success
  13966. }
  13967. });
  13968. ```
  13969. Promise Example;
  13970. ```javascript
  13971. findResult().then(function(result){
  13972. // success
  13973. }, function(reason){
  13974. // failure
  13975. });
  13976. ```
  13977. Advanced Example
  13978. --------------
  13979. Synchronous Example
  13980. ```javascript
  13981. var author, books;
  13982. try {
  13983. author = findAuthor();
  13984. books = findBooksByAuthor(author);
  13985. // success
  13986. } catch(reason) {
  13987. // failure
  13988. }
  13989. ```
  13990. Errback Example
  13991. ```js
  13992. function foundBooks(books) {
  13993. }
  13994. function failure(reason) {
  13995. }
  13996. findAuthor(function(author, err){
  13997. if (err) {
  13998. failure(err);
  13999. // failure
  14000. } else {
  14001. try {
  14002. findBoooksByAuthor(author, function(books, err) {
  14003. if (err) {
  14004. failure(err);
  14005. } else {
  14006. try {
  14007. foundBooks(books);
  14008. } catch(reason) {
  14009. failure(reason);
  14010. }
  14011. }
  14012. });
  14013. } catch(error) {
  14014. failure(err);
  14015. }
  14016. // success
  14017. }
  14018. });
  14019. ```
  14020. Promise Example;
  14021. ```javascript
  14022. findAuthor().
  14023. then(findBooksByAuthor).
  14024. then(function(books){
  14025. // found books
  14026. }).catch(function(reason){
  14027. // something went wrong
  14028. });
  14029. ```
  14030. @method then
  14031. @param {Function} onFulfilled
  14032. @param {Function} onRejected
  14033. Useful for tooling.
  14034. @return {Promise}
  14035. */
  14036. then: function(onFulfillment, onRejection) {
  14037. var parent = this;
  14038. var state = parent._state;
  14039. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  14040. return this;
  14041. }
  14042. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  14043. var result = parent._result;
  14044. if (state) {
  14045. var callback = arguments[state - 1];
  14046. lib$es6$promise$asap$$asap(function(){
  14047. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  14048. });
  14049. } else {
  14050. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  14051. }
  14052. return child;
  14053. },
  14054. /**
  14055. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  14056. as the catch block of a try/catch statement.
  14057. ```js
  14058. function findAuthor(){
  14059. throw new Error('couldn't find that author');
  14060. }
  14061. // synchronous
  14062. try {
  14063. findAuthor();
  14064. } catch(reason) {
  14065. // something went wrong
  14066. }
  14067. // async with promises
  14068. findAuthor().catch(function(reason){
  14069. // something went wrong
  14070. });
  14071. ```
  14072. @method catch
  14073. @param {Function} onRejection
  14074. Useful for tooling.
  14075. @return {Promise}
  14076. */
  14077. 'catch': function(onRejection) {
  14078. return this.then(null, onRejection);
  14079. }
  14080. };
  14081. function lib$es6$promise$polyfill$$polyfill() {
  14082. var local;
  14083. if (typeof global !== 'undefined') {
  14084. local = global;
  14085. } else if (typeof self !== 'undefined') {
  14086. local = self;
  14087. } else {
  14088. try {
  14089. local = Function('return this')();
  14090. } catch (e) {
  14091. throw new Error('polyfill failed because global object is unavailable in this environment');
  14092. }
  14093. }
  14094. var P = local.Promise;
  14095. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  14096. return;
  14097. }
  14098. local.Promise = lib$es6$promise$promise$$default;
  14099. }
  14100. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  14101. var lib$es6$promise$umd$$ES6Promise = {
  14102. 'Promise': lib$es6$promise$promise$$default,
  14103. 'polyfill': lib$es6$promise$polyfill$$default
  14104. };
  14105. /* global define:true module:true window: true */
  14106. if (typeof define === 'function' && define['amd']) {
  14107. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  14108. } else if (typeof module !== 'undefined' && module['exports']) {
  14109. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  14110. } else if (typeof this !== 'undefined') {
  14111. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  14112. }
  14113. lib$es6$promise$polyfill$$default();
  14114. }).call(this);
  14115. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14116. },{"_process":46}],48:[function(require,module,exports){
  14117. /* Copyright @ 2015 Atlassian Pty Ltd
  14118. *
  14119. * Licensed under the Apache License, Version 2.0 (the "License");
  14120. * you may not use this file except in compliance with the License.
  14121. * You may obtain a copy of the License at
  14122. *
  14123. * http://www.apache.org/licenses/LICENSE-2.0
  14124. *
  14125. * Unless required by applicable law or agreed to in writing, software
  14126. * distributed under the License is distributed on an "AS IS" BASIS,
  14127. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14128. * See the License for the specific language governing permissions and
  14129. * limitations under the License.
  14130. */
  14131. /**
  14132. * Ordered log levels.
  14133. */
  14134. var levels = {
  14135. "trace": 0,
  14136. "debug": 1,
  14137. "info": 2,
  14138. "log": 3,
  14139. "warn": 4,
  14140. "error": 5
  14141. };
  14142. /**
  14143. * Parses Error's object stack trace and extracts information about the last
  14144. * caller before the log method was called.
  14145. * @returns JS object with info about the caller - method name, file location,
  14146. * line and column.
  14147. */
  14148. function getCallerInfo() {
  14149. var callerInfo = {
  14150. methodName: "",
  14151. fileLocation: "",
  14152. line: null,
  14153. column: null
  14154. };
  14155. //gets the part of the stack without the logger wrappers
  14156. var error = new Error();
  14157. var stack = error.stack? error.stack.split("\n") : [];
  14158. if(!stack || stack.length < 1) {
  14159. return callerInfo;
  14160. }
  14161. var m = null;
  14162. if(stack[3]) {
  14163. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  14164. }
  14165. if(!m || m.length <= 4) {
  14166. //Firefox && Safari
  14167. if(stack[2].indexOf("log@") === 0){
  14168. //Safari
  14169. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  14170. } else {
  14171. //Firefox
  14172. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  14173. }
  14174. return callerInfo;
  14175. }
  14176. callerInfo.methodName = m[1];
  14177. callerInfo.fileLocation = m[2];
  14178. callerInfo.line = m[3];
  14179. callerInfo.column = m[4];
  14180. return callerInfo;
  14181. }
  14182. /**
  14183. * Logs messages using the transports and level from the logger.
  14184. * @param logger a logger instance.
  14185. * @param level the log level of the message. See the levels variable.
  14186. * @param arguments array with arguments that will be logged.
  14187. */
  14188. function log() {
  14189. var logger = arguments[0], level = arguments[1],
  14190. args = Array.prototype.slice.call(arguments, 2);
  14191. if(levels[level] <= logger.level) {
  14192. return;
  14193. }
  14194. var callerInfo = getCallerInfo();
  14195. for(var i = 0; i < logger.transports.length; i++) {
  14196. var t = logger.transports[i];
  14197. var l = t[level];
  14198. if(l && typeof(l) === "function") {
  14199. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  14200. .apply(t, args);
  14201. }
  14202. }
  14203. }
  14204. /**
  14205. *
  14206. * Constructs new logger object.
  14207. * @param level the logging level for the new logger
  14208. * @param id optional identifier for the logger instance.
  14209. * @param transports optional list of handlers(objects) for the logs.
  14210. * The handlers must support - log, warn, error, debug, info, trace.
  14211. * @param format optional (NOT implemented) string.
  14212. */
  14213. function Logger(level, id, transports, format) {
  14214. this.id = id;
  14215. this.format = format;
  14216. if(!this.transports) {
  14217. this.transports = [];
  14218. this.transports.push(Logger.consoleTransport);
  14219. }
  14220. this.level = levels[level];
  14221. var methods = Object.keys(levels);
  14222. for(var i = 0; i < methods.length; i++){
  14223. this[methods[i]] =
  14224. log.bind(null, this, methods[i]);
  14225. }
  14226. }
  14227. /**
  14228. * Sets the log level for the logger.
  14229. * @param level the new log level.
  14230. */
  14231. Logger.prototype.setLevel = function (level) {
  14232. this.level = levels[level];
  14233. };
  14234. module.exports = Logger;
  14235. /**
  14236. * The default transport - console
  14237. */
  14238. Logger.consoleTransport = console;
  14239. /**
  14240. * Enum for the supported log levels.
  14241. */
  14242. Logger.levels = {
  14243. TRACE: "trace",
  14244. DEBUG: "debug",
  14245. INFO: "info",
  14246. LOG: "log",
  14247. WARN: "warn",
  14248. ERROR: "error"
  14249. };
  14250. },{}],49:[function(require,module,exports){
  14251. /* Copyright @ 2015 Atlassian Pty Ltd
  14252. *
  14253. * Licensed under the Apache License, Version 2.0 (the "License");
  14254. * you may not use this file except in compliance with the License.
  14255. * You may obtain a copy of the License at
  14256. *
  14257. * http://www.apache.org/licenses/LICENSE-2.0
  14258. *
  14259. * Unless required by applicable law or agreed to in writing, software
  14260. * distributed under the License is distributed on an "AS IS" BASIS,
  14261. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14262. * See the License for the specific language governing permissions and
  14263. * limitations under the License.
  14264. */
  14265. var Logger = require("./Logger");
  14266. /**
  14267. * Map with the created loggers with ID.
  14268. */
  14269. var idLoggers = {};
  14270. /**
  14271. * Array with the loggers without id.
  14272. */
  14273. var loggers = [];
  14274. /**
  14275. * Log level for the lbrary.
  14276. */
  14277. var curLevel = Logger.levels.TRACE;
  14278. module.exports = {
  14279. /**
  14280. * Creates new logger.
  14281. * @arguments the same as Logger constructor
  14282. */
  14283. getLogger: function(id, transports, format) {
  14284. var logger = new Logger(curLevel, id, transports, format);
  14285. if(id) {
  14286. idLoggers[id] = idLoggers[id] || [];
  14287. idLoggers[id].push(logger);
  14288. } else {
  14289. loggers.push(logger);
  14290. }
  14291. return logger;
  14292. },
  14293. /**
  14294. * Changes the log level for the existing loggers by id.
  14295. * @param level the new log level.
  14296. * @param id if specified the level will be changed only for loggers with the
  14297. * same id. Otherwise the operation will affect all loggers that don't
  14298. * have id.
  14299. */
  14300. setLogLevelById: function(level, id) {
  14301. var l = id? (idLoggers[id] || []) : loggers;
  14302. for(var i = 0; i < l.length; i++) {
  14303. l[i].setLevel(level);
  14304. }
  14305. },
  14306. /**
  14307. * Changes the log level for all existing loggers.
  14308. * @param level the new log level.
  14309. */
  14310. setLogLevel: function (level) {
  14311. curLevel = level;
  14312. var i = 0;
  14313. for(; i < loggers.length; i++) {
  14314. loggers[i].setLevel(level);
  14315. }
  14316. for(var id in idLoggers) {
  14317. var l = idLoggers[id] || [];
  14318. for(i = 0; i < l.length; i++) {
  14319. l[i].setLevel(level);
  14320. }
  14321. }
  14322. },
  14323. /**
  14324. * The supported log levels.
  14325. */
  14326. levels: Logger.levels
  14327. };
  14328. },{"./Logger":48}],50:[function(require,module,exports){
  14329. /*
  14330. A JavaScript implementation of the SHA family of hashes, as
  14331. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  14332. as defined in FIPS PUB 198a
  14333. Copyright Brian Turek 2008-2013
  14334. Distributed under the BSD License
  14335. See http://caligatio.github.com/jsSHA/ for more information
  14336. Several functions taken from Paul Johnston
  14337. */
  14338. (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"!==
  14339. 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";
  14340. 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"===
  14341. 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|
  14342. (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,
  14343. 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,
  14344. 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=
  14345. {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):
  14346. 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,
  14347. 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>>>
  14348. 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>>>
  14349. 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>>>
  14350. 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-
  14351. 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,
  14352. 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,
  14353. 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],
  14354. 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),
  14355. 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),
  14356. 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,
  14357. 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,
  14358. 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?
  14359. 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,
  14360. 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);
  14361. },{}],51:[function(require,module,exports){
  14362. // Top level file is just a mixin of submodules & constants
  14363. 'use strict';
  14364. var assign = require('./lib/utils/common').assign;
  14365. var deflate = require('./lib/deflate');
  14366. var inflate = require('./lib/inflate');
  14367. var constants = require('./lib/zlib/constants');
  14368. var pako = {};
  14369. assign(pako, deflate, inflate, constants);
  14370. module.exports = pako;
  14371. },{"./lib/deflate":52,"./lib/inflate":53,"./lib/utils/common":54,"./lib/zlib/constants":57}],52:[function(require,module,exports){
  14372. 'use strict';
  14373. var zlib_deflate = require('./zlib/deflate.js');
  14374. var utils = require('./utils/common');
  14375. var strings = require('./utils/strings');
  14376. var msg = require('./zlib/messages');
  14377. var zstream = require('./zlib/zstream');
  14378. var toString = Object.prototype.toString;
  14379. /* Public constants ==========================================================*/
  14380. /* ===========================================================================*/
  14381. var Z_NO_FLUSH = 0;
  14382. var Z_FINISH = 4;
  14383. var Z_OK = 0;
  14384. var Z_STREAM_END = 1;
  14385. var Z_SYNC_FLUSH = 2;
  14386. var Z_DEFAULT_COMPRESSION = -1;
  14387. var Z_DEFAULT_STRATEGY = 0;
  14388. var Z_DEFLATED = 8;
  14389. /* ===========================================================================*/
  14390. /**
  14391. * class Deflate
  14392. *
  14393. * Generic JS-style wrapper for zlib calls. If you don't need
  14394. * streaming behaviour - use more simple functions: [[deflate]],
  14395. * [[deflateRaw]] and [[gzip]].
  14396. **/
  14397. /* internal
  14398. * Deflate.chunks -> Array
  14399. *
  14400. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14401. **/
  14402. /**
  14403. * Deflate.result -> Uint8Array|Array
  14404. *
  14405. * Compressed result, generated by default [[Deflate#onData]]
  14406. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14407. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14408. * push a chunk with explicit flush (call [[Deflate#push]] with
  14409. * `Z_SYNC_FLUSH` param).
  14410. **/
  14411. /**
  14412. * Deflate.err -> Number
  14413. *
  14414. * Error code after deflate finished. 0 (Z_OK) on success.
  14415. * You will not need it in real life, because deflate errors
  14416. * are possible only on wrong options or bad `onData` / `onEnd`
  14417. * custom handlers.
  14418. **/
  14419. /**
  14420. * Deflate.msg -> String
  14421. *
  14422. * Error message, if [[Deflate.err]] != 0
  14423. **/
  14424. /**
  14425. * new Deflate(options)
  14426. * - options (Object): zlib deflate options.
  14427. *
  14428. * Creates new deflator instance with specified params. Throws exception
  14429. * on bad params. Supported options:
  14430. *
  14431. * - `level`
  14432. * - `windowBits`
  14433. * - `memLevel`
  14434. * - `strategy`
  14435. *
  14436. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14437. * for more information on these.
  14438. *
  14439. * Additional options, for internal needs:
  14440. *
  14441. * - `chunkSize` - size of generated data chunks (16K by default)
  14442. * - `raw` (Boolean) - do raw deflate
  14443. * - `gzip` (Boolean) - create gzip wrapper
  14444. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14445. * (each char code [0..255])
  14446. * - `header` (Object) - custom header for gzip
  14447. * - `text` (Boolean) - true if compressed data believed to be text
  14448. * - `time` (Number) - modification time, unix timestamp
  14449. * - `os` (Number) - operation system code
  14450. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14451. * - `name` (String) - file name (binary string)
  14452. * - `comment` (String) - comment (binary string)
  14453. * - `hcrc` (Boolean) - true if header crc should be added
  14454. *
  14455. * ##### Example:
  14456. *
  14457. * ```javascript
  14458. * var pako = require('pako')
  14459. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14460. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14461. *
  14462. * var deflate = new pako.Deflate({ level: 3});
  14463. *
  14464. * deflate.push(chunk1, false);
  14465. * deflate.push(chunk2, true); // true -> last chunk
  14466. *
  14467. * if (deflate.err) { throw new Error(deflate.err); }
  14468. *
  14469. * console.log(deflate.result);
  14470. * ```
  14471. **/
  14472. var Deflate = function(options) {
  14473. this.options = utils.assign({
  14474. level: Z_DEFAULT_COMPRESSION,
  14475. method: Z_DEFLATED,
  14476. chunkSize: 16384,
  14477. windowBits: 15,
  14478. memLevel: 8,
  14479. strategy: Z_DEFAULT_STRATEGY,
  14480. to: ''
  14481. }, options || {});
  14482. var opt = this.options;
  14483. if (opt.raw && (opt.windowBits > 0)) {
  14484. opt.windowBits = -opt.windowBits;
  14485. }
  14486. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14487. opt.windowBits += 16;
  14488. }
  14489. this.err = 0; // error code, if happens (0 = Z_OK)
  14490. this.msg = ''; // error message
  14491. this.ended = false; // used to avoid multiple onEnd() calls
  14492. this.chunks = []; // chunks of compressed data
  14493. this.strm = new zstream();
  14494. this.strm.avail_out = 0;
  14495. var status = zlib_deflate.deflateInit2(
  14496. this.strm,
  14497. opt.level,
  14498. opt.method,
  14499. opt.windowBits,
  14500. opt.memLevel,
  14501. opt.strategy
  14502. );
  14503. if (status !== Z_OK) {
  14504. throw new Error(msg[status]);
  14505. }
  14506. if (opt.header) {
  14507. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14508. }
  14509. };
  14510. /**
  14511. * Deflate#push(data[, mode]) -> Boolean
  14512. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  14513. * converted to utf8 byte sequence.
  14514. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14515. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14516. *
  14517. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14518. * new compressed chunks. Returns `true` on success. The last data block must have
  14519. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14520. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14521. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  14522. *
  14523. * On fail call [[Deflate#onEnd]] with error code and return false.
  14524. *
  14525. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14526. * array format is detected automatically). Also, don't skip last param and always
  14527. * use the same type in your code (boolean or number). That will improve JS speed.
  14528. *
  14529. * For regular `Array`-s make sure all elements are [0..255].
  14530. *
  14531. * ##### Example
  14532. *
  14533. * ```javascript
  14534. * push(chunk, false); // push one of data chunks
  14535. * ...
  14536. * push(chunk, true); // push last chunk
  14537. * ```
  14538. **/
  14539. Deflate.prototype.push = function(data, mode) {
  14540. var strm = this.strm;
  14541. var chunkSize = this.options.chunkSize;
  14542. var status, _mode;
  14543. if (this.ended) { return false; }
  14544. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14545. // Convert data if needed
  14546. if (typeof data === 'string') {
  14547. // If we need to compress text, change encoding to utf8.
  14548. strm.input = strings.string2buf(data);
  14549. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14550. strm.input = new Uint8Array(data);
  14551. } else {
  14552. strm.input = data;
  14553. }
  14554. strm.next_in = 0;
  14555. strm.avail_in = strm.input.length;
  14556. do {
  14557. if (strm.avail_out === 0) {
  14558. strm.output = new utils.Buf8(chunkSize);
  14559. strm.next_out = 0;
  14560. strm.avail_out = chunkSize;
  14561. }
  14562. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14563. if (status !== Z_STREAM_END && status !== Z_OK) {
  14564. this.onEnd(status);
  14565. this.ended = true;
  14566. return false;
  14567. }
  14568. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  14569. if (this.options.to === 'string') {
  14570. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14571. } else {
  14572. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14573. }
  14574. }
  14575. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14576. // Finalize on the last chunk.
  14577. if (_mode === Z_FINISH) {
  14578. status = zlib_deflate.deflateEnd(this.strm);
  14579. this.onEnd(status);
  14580. this.ended = true;
  14581. return status === Z_OK;
  14582. }
  14583. // callback interim results if Z_SYNC_FLUSH.
  14584. if (_mode === Z_SYNC_FLUSH) {
  14585. this.onEnd(Z_OK);
  14586. strm.avail_out = 0;
  14587. return true;
  14588. }
  14589. return true;
  14590. };
  14591. /**
  14592. * Deflate#onData(chunk) -> Void
  14593. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14594. * on js engine support. When string output requested, each chunk
  14595. * will be string.
  14596. *
  14597. * By default, stores data blocks in `chunks[]` property and glue
  14598. * those in `onEnd`. Override this handler, if you need another behaviour.
  14599. **/
  14600. Deflate.prototype.onData = function(chunk) {
  14601. this.chunks.push(chunk);
  14602. };
  14603. /**
  14604. * Deflate#onEnd(status) -> Void
  14605. * - status (Number): deflate status. 0 (Z_OK) on success,
  14606. * other if not.
  14607. *
  14608. * Called once after you tell deflate that the input stream is
  14609. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14610. * or if an error happened. By default - join collected chunks,
  14611. * free memory and fill `results` / `err` properties.
  14612. **/
  14613. Deflate.prototype.onEnd = function(status) {
  14614. // On success - join
  14615. if (status === Z_OK) {
  14616. if (this.options.to === 'string') {
  14617. this.result = this.chunks.join('');
  14618. } else {
  14619. this.result = utils.flattenChunks(this.chunks);
  14620. }
  14621. }
  14622. this.chunks = [];
  14623. this.err = status;
  14624. this.msg = this.strm.msg;
  14625. };
  14626. /**
  14627. * deflate(data[, options]) -> Uint8Array|Array|String
  14628. * - data (Uint8Array|Array|String): input data to compress.
  14629. * - options (Object): zlib deflate options.
  14630. *
  14631. * Compress `data` with deflate alrorythm and `options`.
  14632. *
  14633. * Supported options are:
  14634. *
  14635. * - level
  14636. * - windowBits
  14637. * - memLevel
  14638. * - strategy
  14639. *
  14640. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14641. * for more information on these.
  14642. *
  14643. * Sugar (options):
  14644. *
  14645. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14646. * negative windowBits implicitly.
  14647. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14648. * (each char code [0..255])
  14649. *
  14650. * ##### Example:
  14651. *
  14652. * ```javascript
  14653. * var pako = require('pako')
  14654. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14655. *
  14656. * console.log(pako.deflate(data));
  14657. * ```
  14658. **/
  14659. function deflate(input, options) {
  14660. var deflator = new Deflate(options);
  14661. deflator.push(input, true);
  14662. // That will never happens, if you don't cheat with options :)
  14663. if (deflator.err) { throw deflator.msg; }
  14664. return deflator.result;
  14665. }
  14666. /**
  14667. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14668. * - data (Uint8Array|Array|String): input data to compress.
  14669. * - options (Object): zlib deflate options.
  14670. *
  14671. * The same as [[deflate]], but creates raw data, without wrapper
  14672. * (header and adler32 crc).
  14673. **/
  14674. function deflateRaw(input, options) {
  14675. options = options || {};
  14676. options.raw = true;
  14677. return deflate(input, options);
  14678. }
  14679. /**
  14680. * gzip(data[, options]) -> Uint8Array|Array|String
  14681. * - data (Uint8Array|Array|String): input data to compress.
  14682. * - options (Object): zlib deflate options.
  14683. *
  14684. * The same as [[deflate]], but create gzip wrapper instead of
  14685. * deflate one.
  14686. **/
  14687. function gzip(input, options) {
  14688. options = options || {};
  14689. options.gzip = true;
  14690. return deflate(input, options);
  14691. }
  14692. exports.Deflate = Deflate;
  14693. exports.deflate = deflate;
  14694. exports.deflateRaw = deflateRaw;
  14695. exports.gzip = gzip;
  14696. },{"./utils/common":54,"./utils/strings":55,"./zlib/deflate.js":59,"./zlib/messages":64,"./zlib/zstream":66}],53:[function(require,module,exports){
  14697. 'use strict';
  14698. var zlib_inflate = require('./zlib/inflate.js');
  14699. var utils = require('./utils/common');
  14700. var strings = require('./utils/strings');
  14701. var c = require('./zlib/constants');
  14702. var msg = require('./zlib/messages');
  14703. var zstream = require('./zlib/zstream');
  14704. var gzheader = require('./zlib/gzheader');
  14705. var toString = Object.prototype.toString;
  14706. /**
  14707. * class Inflate
  14708. *
  14709. * Generic JS-style wrapper for zlib calls. If you don't need
  14710. * streaming behaviour - use more simple functions: [[inflate]]
  14711. * and [[inflateRaw]].
  14712. **/
  14713. /* internal
  14714. * inflate.chunks -> Array
  14715. *
  14716. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14717. **/
  14718. /**
  14719. * Inflate.result -> Uint8Array|Array|String
  14720. *
  14721. * Uncompressed result, generated by default [[Inflate#onData]]
  14722. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14723. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14724. * push a chunk with explicit flush (call [[Inflate#push]] with
  14725. * `Z_SYNC_FLUSH` param).
  14726. **/
  14727. /**
  14728. * Inflate.err -> Number
  14729. *
  14730. * Error code after inflate finished. 0 (Z_OK) on success.
  14731. * Should be checked if broken data possible.
  14732. **/
  14733. /**
  14734. * Inflate.msg -> String
  14735. *
  14736. * Error message, if [[Inflate.err]] != 0
  14737. **/
  14738. /**
  14739. * new Inflate(options)
  14740. * - options (Object): zlib inflate options.
  14741. *
  14742. * Creates new inflator instance with specified params. Throws exception
  14743. * on bad params. Supported options:
  14744. *
  14745. * - `windowBits`
  14746. *
  14747. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14748. * for more information on these.
  14749. *
  14750. * Additional options, for internal needs:
  14751. *
  14752. * - `chunkSize` - size of generated data chunks (16K by default)
  14753. * - `raw` (Boolean) - do raw inflate
  14754. * - `to` (String) - if equal to 'string', then result will be converted
  14755. * from utf8 to utf16 (javascript) string. When string output requested,
  14756. * chunk length can differ from `chunkSize`, depending on content.
  14757. *
  14758. * By default, when no options set, autodetect deflate/gzip data format via
  14759. * wrapper header.
  14760. *
  14761. * ##### Example:
  14762. *
  14763. * ```javascript
  14764. * var pako = require('pako')
  14765. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14766. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14767. *
  14768. * var inflate = new pako.Inflate({ level: 3});
  14769. *
  14770. * inflate.push(chunk1, false);
  14771. * inflate.push(chunk2, true); // true -> last chunk
  14772. *
  14773. * if (inflate.err) { throw new Error(inflate.err); }
  14774. *
  14775. * console.log(inflate.result);
  14776. * ```
  14777. **/
  14778. var Inflate = function(options) {
  14779. this.options = utils.assign({
  14780. chunkSize: 16384,
  14781. windowBits: 0,
  14782. to: ''
  14783. }, options || {});
  14784. var opt = this.options;
  14785. // Force window size for `raw` data, if not set directly,
  14786. // because we have no header for autodetect.
  14787. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14788. opt.windowBits = -opt.windowBits;
  14789. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14790. }
  14791. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14792. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14793. !(options && options.windowBits)) {
  14794. opt.windowBits += 32;
  14795. }
  14796. // Gzip header has no info about windows size, we can do autodetect only
  14797. // for deflate. So, if window size not set, force it to max when gzip possible
  14798. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14799. // bit 3 (16) -> gzipped data
  14800. // bit 4 (32) -> autodetect gzip/deflate
  14801. if ((opt.windowBits & 15) === 0) {
  14802. opt.windowBits |= 15;
  14803. }
  14804. }
  14805. this.err = 0; // error code, if happens (0 = Z_OK)
  14806. this.msg = ''; // error message
  14807. this.ended = false; // used to avoid multiple onEnd() calls
  14808. this.chunks = []; // chunks of compressed data
  14809. this.strm = new zstream();
  14810. this.strm.avail_out = 0;
  14811. var status = zlib_inflate.inflateInit2(
  14812. this.strm,
  14813. opt.windowBits
  14814. );
  14815. if (status !== c.Z_OK) {
  14816. throw new Error(msg[status]);
  14817. }
  14818. this.header = new gzheader();
  14819. zlib_inflate.inflateGetHeader(this.strm, this.header);
  14820. };
  14821. /**
  14822. * Inflate#push(data[, mode]) -> Boolean
  14823. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  14824. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14825. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14826. *
  14827. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  14828. * new output chunks. Returns `true` on success. The last data block must have
  14829. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14830. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14831. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  14832. *
  14833. * On fail call [[Inflate#onEnd]] with error code and return false.
  14834. *
  14835. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14836. * format is detected automatically). Also, don't skip last param and always
  14837. * use the same type in your code (boolean or number). That will improve JS speed.
  14838. *
  14839. * For regular `Array`-s make sure all elements are [0..255].
  14840. *
  14841. * ##### Example
  14842. *
  14843. * ```javascript
  14844. * push(chunk, false); // push one of data chunks
  14845. * ...
  14846. * push(chunk, true); // push last chunk
  14847. * ```
  14848. **/
  14849. Inflate.prototype.push = function(data, mode) {
  14850. var strm = this.strm;
  14851. var chunkSize = this.options.chunkSize;
  14852. var status, _mode;
  14853. var next_out_utf8, tail, utf8str;
  14854. // Flag to properly process Z_BUF_ERROR on testing inflate call
  14855. // when we check that all output data was flushed.
  14856. var allowBufError = false;
  14857. if (this.ended) { return false; }
  14858. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  14859. // Convert data if needed
  14860. if (typeof data === 'string') {
  14861. // Only binary strings can be decompressed on practice
  14862. strm.input = strings.binstring2buf(data);
  14863. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14864. strm.input = new Uint8Array(data);
  14865. } else {
  14866. strm.input = data;
  14867. }
  14868. strm.next_in = 0;
  14869. strm.avail_in = strm.input.length;
  14870. do {
  14871. if (strm.avail_out === 0) {
  14872. strm.output = new utils.Buf8(chunkSize);
  14873. strm.next_out = 0;
  14874. strm.avail_out = chunkSize;
  14875. }
  14876. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  14877. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  14878. status = c.Z_OK;
  14879. allowBufError = false;
  14880. }
  14881. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  14882. this.onEnd(status);
  14883. this.ended = true;
  14884. return false;
  14885. }
  14886. if (strm.next_out) {
  14887. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  14888. if (this.options.to === 'string') {
  14889. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  14890. tail = strm.next_out - next_out_utf8;
  14891. utf8str = strings.buf2string(strm.output, next_out_utf8);
  14892. // move tail
  14893. strm.next_out = tail;
  14894. strm.avail_out = chunkSize - tail;
  14895. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  14896. this.onData(utf8str);
  14897. } else {
  14898. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14899. }
  14900. }
  14901. }
  14902. // When no more input data, we should check that internal inflate buffers
  14903. // are flushed. The only way to do it when avail_out = 0 - run one more
  14904. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  14905. // Here we set flag to process this error properly.
  14906. //
  14907. // NOTE. Deflate does not return error in this case and does not needs such
  14908. // logic.
  14909. if (strm.avail_in === 0 && strm.avail_out === 0) {
  14910. allowBufError = true;
  14911. }
  14912. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  14913. if (status === c.Z_STREAM_END) {
  14914. _mode = c.Z_FINISH;
  14915. }
  14916. // Finalize on the last chunk.
  14917. if (_mode === c.Z_FINISH) {
  14918. status = zlib_inflate.inflateEnd(this.strm);
  14919. this.onEnd(status);
  14920. this.ended = true;
  14921. return status === c.Z_OK;
  14922. }
  14923. // callback interim results if Z_SYNC_FLUSH.
  14924. if (_mode === c.Z_SYNC_FLUSH) {
  14925. this.onEnd(c.Z_OK);
  14926. strm.avail_out = 0;
  14927. return true;
  14928. }
  14929. return true;
  14930. };
  14931. /**
  14932. * Inflate#onData(chunk) -> Void
  14933. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14934. * on js engine support. When string output requested, each chunk
  14935. * will be string.
  14936. *
  14937. * By default, stores data blocks in `chunks[]` property and glue
  14938. * those in `onEnd`. Override this handler, if you need another behaviour.
  14939. **/
  14940. Inflate.prototype.onData = function(chunk) {
  14941. this.chunks.push(chunk);
  14942. };
  14943. /**
  14944. * Inflate#onEnd(status) -> Void
  14945. * - status (Number): inflate status. 0 (Z_OK) on success,
  14946. * other if not.
  14947. *
  14948. * Called either after you tell inflate that the input stream is
  14949. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14950. * or if an error happened. By default - join collected chunks,
  14951. * free memory and fill `results` / `err` properties.
  14952. **/
  14953. Inflate.prototype.onEnd = function(status) {
  14954. // On success - join
  14955. if (status === c.Z_OK) {
  14956. if (this.options.to === 'string') {
  14957. // Glue & convert here, until we teach pako to send
  14958. // utf8 alligned strings to onData
  14959. this.result = this.chunks.join('');
  14960. } else {
  14961. this.result = utils.flattenChunks(this.chunks);
  14962. }
  14963. }
  14964. this.chunks = [];
  14965. this.err = status;
  14966. this.msg = this.strm.msg;
  14967. };
  14968. /**
  14969. * inflate(data[, options]) -> Uint8Array|Array|String
  14970. * - data (Uint8Array|Array|String): input data to decompress.
  14971. * - options (Object): zlib inflate options.
  14972. *
  14973. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  14974. * format via wrapper header by default. That's why we don't provide
  14975. * separate `ungzip` method.
  14976. *
  14977. * Supported options are:
  14978. *
  14979. * - windowBits
  14980. *
  14981. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14982. * for more information.
  14983. *
  14984. * Sugar (options):
  14985. *
  14986. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14987. * negative windowBits implicitly.
  14988. * - `to` (String) - if equal to 'string', then result will be converted
  14989. * from utf8 to utf16 (javascript) string. When string output requested,
  14990. * chunk length can differ from `chunkSize`, depending on content.
  14991. *
  14992. *
  14993. * ##### Example:
  14994. *
  14995. * ```javascript
  14996. * var pako = require('pako')
  14997. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  14998. * , output;
  14999. *
  15000. * try {
  15001. * output = pako.inflate(input);
  15002. * } catch (err)
  15003. * console.log(err);
  15004. * }
  15005. * ```
  15006. **/
  15007. function inflate(input, options) {
  15008. var inflator = new Inflate(options);
  15009. inflator.push(input, true);
  15010. // That will never happens, if you don't cheat with options :)
  15011. if (inflator.err) { throw inflator.msg; }
  15012. return inflator.result;
  15013. }
  15014. /**
  15015. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15016. * - data (Uint8Array|Array|String): input data to decompress.
  15017. * - options (Object): zlib inflate options.
  15018. *
  15019. * The same as [[inflate]], but creates raw data, without wrapper
  15020. * (header and adler32 crc).
  15021. **/
  15022. function inflateRaw(input, options) {
  15023. options = options || {};
  15024. options.raw = true;
  15025. return inflate(input, options);
  15026. }
  15027. /**
  15028. * ungzip(data[, options]) -> Uint8Array|Array|String
  15029. * - data (Uint8Array|Array|String): input data to decompress.
  15030. * - options (Object): zlib inflate options.
  15031. *
  15032. * Just shortcut to [[inflate]], because it autodetects format
  15033. * by header.content. Done for convenience.
  15034. **/
  15035. exports.Inflate = Inflate;
  15036. exports.inflate = inflate;
  15037. exports.inflateRaw = inflateRaw;
  15038. exports.ungzip = inflate;
  15039. },{"./utils/common":54,"./utils/strings":55,"./zlib/constants":57,"./zlib/gzheader":60,"./zlib/inflate.js":62,"./zlib/messages":64,"./zlib/zstream":66}],54:[function(require,module,exports){
  15040. 'use strict';
  15041. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15042. (typeof Uint16Array !== 'undefined') &&
  15043. (typeof Int32Array !== 'undefined');
  15044. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15045. var sources = Array.prototype.slice.call(arguments, 1);
  15046. while (sources.length) {
  15047. var source = sources.shift();
  15048. if (!source) { continue; }
  15049. if (typeof source !== 'object') {
  15050. throw new TypeError(source + 'must be non-object');
  15051. }
  15052. for (var p in source) {
  15053. if (source.hasOwnProperty(p)) {
  15054. obj[p] = source[p];
  15055. }
  15056. }
  15057. }
  15058. return obj;
  15059. };
  15060. // reduce buffer size, avoiding mem copy
  15061. exports.shrinkBuf = function (buf, size) {
  15062. if (buf.length === size) { return buf; }
  15063. if (buf.subarray) { return buf.subarray(0, size); }
  15064. buf.length = size;
  15065. return buf;
  15066. };
  15067. var fnTyped = {
  15068. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15069. if (src.subarray && dest.subarray) {
  15070. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15071. return;
  15072. }
  15073. // Fallback to ordinary array
  15074. for (var i=0; i<len; i++) {
  15075. dest[dest_offs + i] = src[src_offs + i];
  15076. }
  15077. },
  15078. // Join array of chunks to single array.
  15079. flattenChunks: function(chunks) {
  15080. var i, l, len, pos, chunk, result;
  15081. // calculate data length
  15082. len = 0;
  15083. for (i=0, l=chunks.length; i<l; i++) {
  15084. len += chunks[i].length;
  15085. }
  15086. // join chunks
  15087. result = new Uint8Array(len);
  15088. pos = 0;
  15089. for (i=0, l=chunks.length; i<l; i++) {
  15090. chunk = chunks[i];
  15091. result.set(chunk, pos);
  15092. pos += chunk.length;
  15093. }
  15094. return result;
  15095. }
  15096. };
  15097. var fnUntyped = {
  15098. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15099. for (var i=0; i<len; i++) {
  15100. dest[dest_offs + i] = src[src_offs + i];
  15101. }
  15102. },
  15103. // Join array of chunks to single array.
  15104. flattenChunks: function(chunks) {
  15105. return [].concat.apply([], chunks);
  15106. }
  15107. };
  15108. // Enable/Disable typed arrays use, for testing
  15109. //
  15110. exports.setTyped = function (on) {
  15111. if (on) {
  15112. exports.Buf8 = Uint8Array;
  15113. exports.Buf16 = Uint16Array;
  15114. exports.Buf32 = Int32Array;
  15115. exports.assign(exports, fnTyped);
  15116. } else {
  15117. exports.Buf8 = Array;
  15118. exports.Buf16 = Array;
  15119. exports.Buf32 = Array;
  15120. exports.assign(exports, fnUntyped);
  15121. }
  15122. };
  15123. exports.setTyped(TYPED_OK);
  15124. },{}],55:[function(require,module,exports){
  15125. // String encode/decode helpers
  15126. 'use strict';
  15127. var utils = require('./common');
  15128. // Quick check if we can use fast array to bin string conversion
  15129. //
  15130. // - apply(Array) can fail on Android 2.2
  15131. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15132. //
  15133. var STR_APPLY_OK = true;
  15134. var STR_APPLY_UIA_OK = true;
  15135. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15136. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15137. // Table with utf8 lengths (calculated by first byte of sequence)
  15138. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15139. // because max possible codepoint is 0x10ffff
  15140. var _utf8len = new utils.Buf8(256);
  15141. for (var q=0; q<256; q++) {
  15142. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15143. }
  15144. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15145. // convert string to array (typed, when possible)
  15146. exports.string2buf = function (str) {
  15147. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15148. // count binary size
  15149. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15150. c = str.charCodeAt(m_pos);
  15151. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15152. c2 = str.charCodeAt(m_pos+1);
  15153. if ((c2 & 0xfc00) === 0xdc00) {
  15154. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15155. m_pos++;
  15156. }
  15157. }
  15158. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15159. }
  15160. // allocate buffer
  15161. buf = new utils.Buf8(buf_len);
  15162. // convert
  15163. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15164. c = str.charCodeAt(m_pos);
  15165. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15166. c2 = str.charCodeAt(m_pos+1);
  15167. if ((c2 & 0xfc00) === 0xdc00) {
  15168. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15169. m_pos++;
  15170. }
  15171. }
  15172. if (c < 0x80) {
  15173. /* one byte */
  15174. buf[i++] = c;
  15175. } else if (c < 0x800) {
  15176. /* two bytes */
  15177. buf[i++] = 0xC0 | (c >>> 6);
  15178. buf[i++] = 0x80 | (c & 0x3f);
  15179. } else if (c < 0x10000) {
  15180. /* three bytes */
  15181. buf[i++] = 0xE0 | (c >>> 12);
  15182. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15183. buf[i++] = 0x80 | (c & 0x3f);
  15184. } else {
  15185. /* four bytes */
  15186. buf[i++] = 0xf0 | (c >>> 18);
  15187. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15188. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15189. buf[i++] = 0x80 | (c & 0x3f);
  15190. }
  15191. }
  15192. return buf;
  15193. };
  15194. // Helper (used in 2 places)
  15195. function buf2binstring(buf, len) {
  15196. // use fallback for big arrays to avoid stack overflow
  15197. if (len < 65537) {
  15198. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15199. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15200. }
  15201. }
  15202. var result = '';
  15203. for (var i=0; i < len; i++) {
  15204. result += String.fromCharCode(buf[i]);
  15205. }
  15206. return result;
  15207. }
  15208. // Convert byte array to binary string
  15209. exports.buf2binstring = function(buf) {
  15210. return buf2binstring(buf, buf.length);
  15211. };
  15212. // Convert binary string (typed, when possible)
  15213. exports.binstring2buf = function(str) {
  15214. var buf = new utils.Buf8(str.length);
  15215. for (var i=0, len=buf.length; i < len; i++) {
  15216. buf[i] = str.charCodeAt(i);
  15217. }
  15218. return buf;
  15219. };
  15220. // convert array to string
  15221. exports.buf2string = function (buf, max) {
  15222. var i, out, c, c_len;
  15223. var len = max || buf.length;
  15224. // Reserve max possible length (2 words per char)
  15225. // NB: by unknown reasons, Array is significantly faster for
  15226. // String.fromCharCode.apply than Uint16Array.
  15227. var utf16buf = new Array(len*2);
  15228. for (out=0, i=0; i<len;) {
  15229. c = buf[i++];
  15230. // quick process ascii
  15231. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15232. c_len = _utf8len[c];
  15233. // skip 5 & 6 byte codes
  15234. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15235. // apply mask on first byte
  15236. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15237. // join the rest
  15238. while (c_len > 1 && i < len) {
  15239. c = (c << 6) | (buf[i++] & 0x3f);
  15240. c_len--;
  15241. }
  15242. // terminated by end of string?
  15243. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15244. if (c < 0x10000) {
  15245. utf16buf[out++] = c;
  15246. } else {
  15247. c -= 0x10000;
  15248. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15249. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15250. }
  15251. }
  15252. return buf2binstring(utf16buf, out);
  15253. };
  15254. // Calculate max possible position in utf8 buffer,
  15255. // that will not break sequence. If that's not possible
  15256. // - (very small limits) return max size as is.
  15257. //
  15258. // buf[] - utf8 bytes array
  15259. // max - length limit (mandatory);
  15260. exports.utf8border = function(buf, max) {
  15261. var pos;
  15262. max = max || buf.length;
  15263. if (max > buf.length) { max = buf.length; }
  15264. // go back from last position, until start of sequence found
  15265. pos = max-1;
  15266. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15267. // Fuckup - very small and broken sequence,
  15268. // return max, because we should return something anyway.
  15269. if (pos < 0) { return max; }
  15270. // If we came to start of buffer - that means vuffer is too small,
  15271. // return max too.
  15272. if (pos === 0) { return max; }
  15273. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15274. };
  15275. },{"./common":54}],56:[function(require,module,exports){
  15276. 'use strict';
  15277. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15278. // It doesn't worth to make additional optimizationa as in original.
  15279. // Small size is preferable.
  15280. function adler32(adler, buf, len, pos) {
  15281. var s1 = (adler & 0xffff) |0,
  15282. s2 = ((adler >>> 16) & 0xffff) |0,
  15283. n = 0;
  15284. while (len !== 0) {
  15285. // Set limit ~ twice less than 5552, to keep
  15286. // s2 in 31-bits, because we force signed ints.
  15287. // in other case %= will fail.
  15288. n = len > 2000 ? 2000 : len;
  15289. len -= n;
  15290. do {
  15291. s1 = (s1 + buf[pos++]) |0;
  15292. s2 = (s2 + s1) |0;
  15293. } while (--n);
  15294. s1 %= 65521;
  15295. s2 %= 65521;
  15296. }
  15297. return (s1 | (s2 << 16)) |0;
  15298. }
  15299. module.exports = adler32;
  15300. },{}],57:[function(require,module,exports){
  15301. module.exports = {
  15302. /* Allowed flush values; see deflate() and inflate() below for details */
  15303. Z_NO_FLUSH: 0,
  15304. Z_PARTIAL_FLUSH: 1,
  15305. Z_SYNC_FLUSH: 2,
  15306. Z_FULL_FLUSH: 3,
  15307. Z_FINISH: 4,
  15308. Z_BLOCK: 5,
  15309. Z_TREES: 6,
  15310. /* Return codes for the compression/decompression functions. Negative values
  15311. * are errors, positive values are used for special but normal events.
  15312. */
  15313. Z_OK: 0,
  15314. Z_STREAM_END: 1,
  15315. Z_NEED_DICT: 2,
  15316. Z_ERRNO: -1,
  15317. Z_STREAM_ERROR: -2,
  15318. Z_DATA_ERROR: -3,
  15319. //Z_MEM_ERROR: -4,
  15320. Z_BUF_ERROR: -5,
  15321. //Z_VERSION_ERROR: -6,
  15322. /* compression levels */
  15323. Z_NO_COMPRESSION: 0,
  15324. Z_BEST_SPEED: 1,
  15325. Z_BEST_COMPRESSION: 9,
  15326. Z_DEFAULT_COMPRESSION: -1,
  15327. Z_FILTERED: 1,
  15328. Z_HUFFMAN_ONLY: 2,
  15329. Z_RLE: 3,
  15330. Z_FIXED: 4,
  15331. Z_DEFAULT_STRATEGY: 0,
  15332. /* Possible values of the data_type field (though see inflate()) */
  15333. Z_BINARY: 0,
  15334. Z_TEXT: 1,
  15335. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15336. Z_UNKNOWN: 2,
  15337. /* The deflate compression method */
  15338. Z_DEFLATED: 8
  15339. //Z_NULL: null // Use -1 or null inline, depending on var type
  15340. };
  15341. },{}],58:[function(require,module,exports){
  15342. 'use strict';
  15343. // Note: we can't get significant speed boost here.
  15344. // So write code to minimize size - no pregenerated tables
  15345. // and array tools dependencies.
  15346. // Use ordinary array, since untyped makes no boost here
  15347. function makeTable() {
  15348. var c, table = [];
  15349. for (var n =0; n < 256; n++) {
  15350. c = n;
  15351. for (var k =0; k < 8; k++) {
  15352. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15353. }
  15354. table[n] = c;
  15355. }
  15356. return table;
  15357. }
  15358. // Create table on load. Just 255 signed longs. Not a problem.
  15359. var crcTable = makeTable();
  15360. function crc32(crc, buf, len, pos) {
  15361. var t = crcTable,
  15362. end = pos + len;
  15363. crc = crc ^ (-1);
  15364. for (var i = pos; i < end; i++) {
  15365. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15366. }
  15367. return (crc ^ (-1)); // >>> 0;
  15368. }
  15369. module.exports = crc32;
  15370. },{}],59:[function(require,module,exports){
  15371. 'use strict';
  15372. var utils = require('../utils/common');
  15373. var trees = require('./trees');
  15374. var adler32 = require('./adler32');
  15375. var crc32 = require('./crc32');
  15376. var msg = require('./messages');
  15377. /* Public constants ==========================================================*/
  15378. /* ===========================================================================*/
  15379. /* Allowed flush values; see deflate() and inflate() below for details */
  15380. var Z_NO_FLUSH = 0;
  15381. var Z_PARTIAL_FLUSH = 1;
  15382. //var Z_SYNC_FLUSH = 2;
  15383. var Z_FULL_FLUSH = 3;
  15384. var Z_FINISH = 4;
  15385. var Z_BLOCK = 5;
  15386. //var Z_TREES = 6;
  15387. /* Return codes for the compression/decompression functions. Negative values
  15388. * are errors, positive values are used for special but normal events.
  15389. */
  15390. var Z_OK = 0;
  15391. var Z_STREAM_END = 1;
  15392. //var Z_NEED_DICT = 2;
  15393. //var Z_ERRNO = -1;
  15394. var Z_STREAM_ERROR = -2;
  15395. var Z_DATA_ERROR = -3;
  15396. //var Z_MEM_ERROR = -4;
  15397. var Z_BUF_ERROR = -5;
  15398. //var Z_VERSION_ERROR = -6;
  15399. /* compression levels */
  15400. //var Z_NO_COMPRESSION = 0;
  15401. //var Z_BEST_SPEED = 1;
  15402. //var Z_BEST_COMPRESSION = 9;
  15403. var Z_DEFAULT_COMPRESSION = -1;
  15404. var Z_FILTERED = 1;
  15405. var Z_HUFFMAN_ONLY = 2;
  15406. var Z_RLE = 3;
  15407. var Z_FIXED = 4;
  15408. var Z_DEFAULT_STRATEGY = 0;
  15409. /* Possible values of the data_type field (though see inflate()) */
  15410. //var Z_BINARY = 0;
  15411. //var Z_TEXT = 1;
  15412. //var Z_ASCII = 1; // = Z_TEXT
  15413. var Z_UNKNOWN = 2;
  15414. /* The deflate compression method */
  15415. var Z_DEFLATED = 8;
  15416. /*============================================================================*/
  15417. var MAX_MEM_LEVEL = 9;
  15418. /* Maximum value for memLevel in deflateInit2 */
  15419. var MAX_WBITS = 15;
  15420. /* 32K LZ77 window */
  15421. var DEF_MEM_LEVEL = 8;
  15422. var LENGTH_CODES = 29;
  15423. /* number of length codes, not counting the special END_BLOCK code */
  15424. var LITERALS = 256;
  15425. /* number of literal bytes 0..255 */
  15426. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15427. /* number of Literal or Length codes, including the END_BLOCK code */
  15428. var D_CODES = 30;
  15429. /* number of distance codes */
  15430. var BL_CODES = 19;
  15431. /* number of codes used to transfer the bit lengths */
  15432. var HEAP_SIZE = 2*L_CODES + 1;
  15433. /* maximum heap size */
  15434. var MAX_BITS = 15;
  15435. /* All codes must not exceed MAX_BITS bits */
  15436. var MIN_MATCH = 3;
  15437. var MAX_MATCH = 258;
  15438. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15439. var PRESET_DICT = 0x20;
  15440. var INIT_STATE = 42;
  15441. var EXTRA_STATE = 69;
  15442. var NAME_STATE = 73;
  15443. var COMMENT_STATE = 91;
  15444. var HCRC_STATE = 103;
  15445. var BUSY_STATE = 113;
  15446. var FINISH_STATE = 666;
  15447. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15448. var BS_BLOCK_DONE = 2; /* block flush performed */
  15449. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15450. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15451. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15452. function err(strm, errorCode) {
  15453. strm.msg = msg[errorCode];
  15454. return errorCode;
  15455. }
  15456. function rank(f) {
  15457. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15458. }
  15459. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15460. /* =========================================================================
  15461. * Flush as much pending output as possible. All deflate() output goes
  15462. * through this function so some applications may wish to modify it
  15463. * to avoid allocating a large strm->output buffer and copying into it.
  15464. * (See also read_buf()).
  15465. */
  15466. function flush_pending(strm) {
  15467. var s = strm.state;
  15468. //_tr_flush_bits(s);
  15469. var len = s.pending;
  15470. if (len > strm.avail_out) {
  15471. len = strm.avail_out;
  15472. }
  15473. if (len === 0) { return; }
  15474. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15475. strm.next_out += len;
  15476. s.pending_out += len;
  15477. strm.total_out += len;
  15478. strm.avail_out -= len;
  15479. s.pending -= len;
  15480. if (s.pending === 0) {
  15481. s.pending_out = 0;
  15482. }
  15483. }
  15484. function flush_block_only (s, last) {
  15485. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15486. s.block_start = s.strstart;
  15487. flush_pending(s.strm);
  15488. }
  15489. function put_byte(s, b) {
  15490. s.pending_buf[s.pending++] = b;
  15491. }
  15492. /* =========================================================================
  15493. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15494. * IN assertion: the stream state is correct and there is enough room in
  15495. * pending_buf.
  15496. */
  15497. function putShortMSB(s, b) {
  15498. // put_byte(s, (Byte)(b >> 8));
  15499. // put_byte(s, (Byte)(b & 0xff));
  15500. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15501. s.pending_buf[s.pending++] = b & 0xff;
  15502. }
  15503. /* ===========================================================================
  15504. * Read a new buffer from the current input stream, update the adler32
  15505. * and total number of bytes read. All deflate() input goes through
  15506. * this function so some applications may wish to modify it to avoid
  15507. * allocating a large strm->input buffer and copying from it.
  15508. * (See also flush_pending()).
  15509. */
  15510. function read_buf(strm, buf, start, size) {
  15511. var len = strm.avail_in;
  15512. if (len > size) { len = size; }
  15513. if (len === 0) { return 0; }
  15514. strm.avail_in -= len;
  15515. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15516. if (strm.state.wrap === 1) {
  15517. strm.adler = adler32(strm.adler, buf, len, start);
  15518. }
  15519. else if (strm.state.wrap === 2) {
  15520. strm.adler = crc32(strm.adler, buf, len, start);
  15521. }
  15522. strm.next_in += len;
  15523. strm.total_in += len;
  15524. return len;
  15525. }
  15526. /* ===========================================================================
  15527. * Set match_start to the longest match starting at the given string and
  15528. * return its length. Matches shorter or equal to prev_length are discarded,
  15529. * in which case the result is equal to prev_length and match_start is
  15530. * garbage.
  15531. * IN assertions: cur_match is the head of the hash chain for the current
  15532. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15533. * OUT assertion: the match length is not greater than s->lookahead.
  15534. */
  15535. function longest_match(s, cur_match) {
  15536. var chain_length = s.max_chain_length; /* max hash chain length */
  15537. var scan = s.strstart; /* current string */
  15538. var match; /* matched string */
  15539. var len; /* length of current match */
  15540. var best_len = s.prev_length; /* best match length so far */
  15541. var nice_match = s.nice_match; /* stop if match long enough */
  15542. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15543. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15544. var _win = s.window; // shortcut
  15545. var wmask = s.w_mask;
  15546. var prev = s.prev;
  15547. /* Stop when cur_match becomes <= limit. To simplify the code,
  15548. * we prevent matches with the string of window index 0.
  15549. */
  15550. var strend = s.strstart + MAX_MATCH;
  15551. var scan_end1 = _win[scan + best_len - 1];
  15552. var scan_end = _win[scan + best_len];
  15553. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15554. * It is easy to get rid of this optimization if necessary.
  15555. */
  15556. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15557. /* Do not waste too much time if we already have a good match: */
  15558. if (s.prev_length >= s.good_match) {
  15559. chain_length >>= 2;
  15560. }
  15561. /* Do not look for matches beyond the end of the input. This is necessary
  15562. * to make deflate deterministic.
  15563. */
  15564. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15565. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15566. do {
  15567. // Assert(cur_match < s->strstart, "no future");
  15568. match = cur_match;
  15569. /* Skip to next match if the match length cannot increase
  15570. * or if the match length is less than 2. Note that the checks below
  15571. * for insufficient lookahead only occur occasionally for performance
  15572. * reasons. Therefore uninitialized memory will be accessed, and
  15573. * conditional jumps will be made that depend on those values.
  15574. * However the length of the match is limited to the lookahead, so
  15575. * the output of deflate is not affected by the uninitialized values.
  15576. */
  15577. if (_win[match + best_len] !== scan_end ||
  15578. _win[match + best_len - 1] !== scan_end1 ||
  15579. _win[match] !== _win[scan] ||
  15580. _win[++match] !== _win[scan + 1]) {
  15581. continue;
  15582. }
  15583. /* The check at best_len-1 can be removed because it will be made
  15584. * again later. (This heuristic is not always a win.)
  15585. * It is not necessary to compare scan[2] and match[2] since they
  15586. * are always equal when the other bytes match, given that
  15587. * the hash keys are equal and that HASH_BITS >= 8.
  15588. */
  15589. scan += 2;
  15590. match++;
  15591. // Assert(*scan == *match, "match[2]?");
  15592. /* We check for insufficient lookahead only every 8th comparison;
  15593. * the 256th check will be made at strstart+258.
  15594. */
  15595. do {
  15596. /*jshint noempty:false*/
  15597. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15598. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15599. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15600. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15601. scan < strend);
  15602. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15603. len = MAX_MATCH - (strend - scan);
  15604. scan = strend - MAX_MATCH;
  15605. if (len > best_len) {
  15606. s.match_start = cur_match;
  15607. best_len = len;
  15608. if (len >= nice_match) {
  15609. break;
  15610. }
  15611. scan_end1 = _win[scan + best_len - 1];
  15612. scan_end = _win[scan + best_len];
  15613. }
  15614. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15615. if (best_len <= s.lookahead) {
  15616. return best_len;
  15617. }
  15618. return s.lookahead;
  15619. }
  15620. /* ===========================================================================
  15621. * Fill the window when the lookahead becomes insufficient.
  15622. * Updates strstart and lookahead.
  15623. *
  15624. * IN assertion: lookahead < MIN_LOOKAHEAD
  15625. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15626. * At least one byte has been read, or avail_in == 0; reads are
  15627. * performed for at least two bytes (required for the zip translate_eol
  15628. * option -- not supported here).
  15629. */
  15630. function fill_window(s) {
  15631. var _w_size = s.w_size;
  15632. var p, n, m, more, str;
  15633. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15634. do {
  15635. more = s.window_size - s.lookahead - s.strstart;
  15636. // JS ints have 32 bit, block below not needed
  15637. /* Deal with !@#$% 64K limit: */
  15638. //if (sizeof(int) <= 2) {
  15639. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15640. // more = wsize;
  15641. //
  15642. // } else if (more == (unsigned)(-1)) {
  15643. // /* Very unlikely, but possible on 16 bit machine if
  15644. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15645. // */
  15646. // more--;
  15647. // }
  15648. //}
  15649. /* If the window is almost full and there is insufficient lookahead,
  15650. * move the upper half to the lower one to make room in the upper half.
  15651. */
  15652. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15653. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15654. s.match_start -= _w_size;
  15655. s.strstart -= _w_size;
  15656. /* we now have strstart >= MAX_DIST */
  15657. s.block_start -= _w_size;
  15658. /* Slide the hash table (could be avoided with 32 bit values
  15659. at the expense of memory usage). We slide even when level == 0
  15660. to keep the hash table consistent if we switch back to level > 0
  15661. later. (Using level 0 permanently is not an optimal usage of
  15662. zlib, so we don't care about this pathological case.)
  15663. */
  15664. n = s.hash_size;
  15665. p = n;
  15666. do {
  15667. m = s.head[--p];
  15668. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15669. } while (--n);
  15670. n = _w_size;
  15671. p = n;
  15672. do {
  15673. m = s.prev[--p];
  15674. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15675. /* If n is not on any hash chain, prev[n] is garbage but
  15676. * its value will never be used.
  15677. */
  15678. } while (--n);
  15679. more += _w_size;
  15680. }
  15681. if (s.strm.avail_in === 0) {
  15682. break;
  15683. }
  15684. /* If there was no sliding:
  15685. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15686. * more == window_size - lookahead - strstart
  15687. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15688. * => more >= window_size - 2*WSIZE + 2
  15689. * In the BIG_MEM or MMAP case (not yet supported),
  15690. * window_size == input_size + MIN_LOOKAHEAD &&
  15691. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15692. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15693. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15694. */
  15695. //Assert(more >= 2, "more < 2");
  15696. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15697. s.lookahead += n;
  15698. /* Initialize the hash value now that we have some input: */
  15699. if (s.lookahead + s.insert >= MIN_MATCH) {
  15700. str = s.strstart - s.insert;
  15701. s.ins_h = s.window[str];
  15702. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15703. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15704. //#if MIN_MATCH != 3
  15705. // Call update_hash() MIN_MATCH-3 more times
  15706. //#endif
  15707. while (s.insert) {
  15708. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15709. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15710. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15711. s.head[s.ins_h] = str;
  15712. str++;
  15713. s.insert--;
  15714. if (s.lookahead + s.insert < MIN_MATCH) {
  15715. break;
  15716. }
  15717. }
  15718. }
  15719. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15720. * but this is not important since only literal bytes will be emitted.
  15721. */
  15722. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15723. /* If the WIN_INIT bytes after the end of the current data have never been
  15724. * written, then zero those bytes in order to avoid memory check reports of
  15725. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15726. * the longest match routines. Update the high water mark for the next
  15727. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15728. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15729. */
  15730. // if (s.high_water < s.window_size) {
  15731. // var curr = s.strstart + s.lookahead;
  15732. // var init = 0;
  15733. //
  15734. // if (s.high_water < curr) {
  15735. // /* Previous high water mark below current data -- zero WIN_INIT
  15736. // * bytes or up to end of window, whichever is less.
  15737. // */
  15738. // init = s.window_size - curr;
  15739. // if (init > WIN_INIT)
  15740. // init = WIN_INIT;
  15741. // zmemzero(s->window + curr, (unsigned)init);
  15742. // s->high_water = curr + init;
  15743. // }
  15744. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15745. // /* High water mark at or above current data, but below current data
  15746. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15747. // * to end of window, whichever is less.
  15748. // */
  15749. // init = (ulg)curr + WIN_INIT - s->high_water;
  15750. // if (init > s->window_size - s->high_water)
  15751. // init = s->window_size - s->high_water;
  15752. // zmemzero(s->window + s->high_water, (unsigned)init);
  15753. // s->high_water += init;
  15754. // }
  15755. // }
  15756. //
  15757. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15758. // "not enough room for search");
  15759. }
  15760. /* ===========================================================================
  15761. * Copy without compression as much as possible from the input stream, return
  15762. * the current block state.
  15763. * This function does not insert new strings in the dictionary since
  15764. * uncompressible data is probably not useful. This function is used
  15765. * only for the level=0 compression option.
  15766. * NOTE: this function should be optimized to avoid extra copying from
  15767. * window to pending_buf.
  15768. */
  15769. function deflate_stored(s, flush) {
  15770. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15771. * to pending_buf_size, and each stored block has a 5 byte header:
  15772. */
  15773. var max_block_size = 0xffff;
  15774. if (max_block_size > s.pending_buf_size - 5) {
  15775. max_block_size = s.pending_buf_size - 5;
  15776. }
  15777. /* Copy as much as possible from input to output: */
  15778. for (;;) {
  15779. /* Fill the window as much as possible: */
  15780. if (s.lookahead <= 1) {
  15781. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15782. // s->block_start >= (long)s->w_size, "slide too late");
  15783. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15784. // s.block_start >= s.w_size)) {
  15785. // throw new Error("slide too late");
  15786. // }
  15787. fill_window(s);
  15788. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15789. return BS_NEED_MORE;
  15790. }
  15791. if (s.lookahead === 0) {
  15792. break;
  15793. }
  15794. /* flush the current block */
  15795. }
  15796. //Assert(s->block_start >= 0L, "block gone");
  15797. // if (s.block_start < 0) throw new Error("block gone");
  15798. s.strstart += s.lookahead;
  15799. s.lookahead = 0;
  15800. /* Emit a stored block if pending_buf will be full: */
  15801. var max_start = s.block_start + max_block_size;
  15802. if (s.strstart === 0 || s.strstart >= max_start) {
  15803. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15804. s.lookahead = s.strstart - max_start;
  15805. s.strstart = max_start;
  15806. /*** FLUSH_BLOCK(s, 0); ***/
  15807. flush_block_only(s, false);
  15808. if (s.strm.avail_out === 0) {
  15809. return BS_NEED_MORE;
  15810. }
  15811. /***/
  15812. }
  15813. /* Flush if we may have to slide, otherwise block_start may become
  15814. * negative and the data will be gone:
  15815. */
  15816. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  15817. /*** FLUSH_BLOCK(s, 0); ***/
  15818. flush_block_only(s, false);
  15819. if (s.strm.avail_out === 0) {
  15820. return BS_NEED_MORE;
  15821. }
  15822. /***/
  15823. }
  15824. }
  15825. s.insert = 0;
  15826. if (flush === Z_FINISH) {
  15827. /*** FLUSH_BLOCK(s, 1); ***/
  15828. flush_block_only(s, true);
  15829. if (s.strm.avail_out === 0) {
  15830. return BS_FINISH_STARTED;
  15831. }
  15832. /***/
  15833. return BS_FINISH_DONE;
  15834. }
  15835. if (s.strstart > s.block_start) {
  15836. /*** FLUSH_BLOCK(s, 0); ***/
  15837. flush_block_only(s, false);
  15838. if (s.strm.avail_out === 0) {
  15839. return BS_NEED_MORE;
  15840. }
  15841. /***/
  15842. }
  15843. return BS_NEED_MORE;
  15844. }
  15845. /* ===========================================================================
  15846. * Compress as much as possible from the input stream, return the current
  15847. * block state.
  15848. * This function does not perform lazy evaluation of matches and inserts
  15849. * new strings in the dictionary only for unmatched strings or for short
  15850. * matches. It is used only for the fast compression options.
  15851. */
  15852. function deflate_fast(s, flush) {
  15853. var hash_head; /* head of the hash chain */
  15854. var bflush; /* set if current block must be flushed */
  15855. for (;;) {
  15856. /* Make sure that we always have enough lookahead, except
  15857. * at the end of the input file. We need MAX_MATCH bytes
  15858. * for the next match, plus MIN_MATCH bytes to insert the
  15859. * string following the next match.
  15860. */
  15861. if (s.lookahead < MIN_LOOKAHEAD) {
  15862. fill_window(s);
  15863. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15864. return BS_NEED_MORE;
  15865. }
  15866. if (s.lookahead === 0) {
  15867. break; /* flush the current block */
  15868. }
  15869. }
  15870. /* Insert the string window[strstart .. strstart+2] in the
  15871. * dictionary, and set hash_head to the head of the hash chain:
  15872. */
  15873. hash_head = 0/*NIL*/;
  15874. if (s.lookahead >= MIN_MATCH) {
  15875. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15876. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15877. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15878. s.head[s.ins_h] = s.strstart;
  15879. /***/
  15880. }
  15881. /* Find the longest match, discarding those <= prev_length.
  15882. * At this point we have always match_length < MIN_MATCH
  15883. */
  15884. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  15885. /* To simplify the code, we prevent matches with the string
  15886. * of window index 0 (in particular we have to avoid a match
  15887. * of the string with itself at the start of the input file).
  15888. */
  15889. s.match_length = longest_match(s, hash_head);
  15890. /* longest_match() sets match_start */
  15891. }
  15892. if (s.match_length >= MIN_MATCH) {
  15893. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  15894. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  15895. s.match_length - MIN_MATCH, bflush); ***/
  15896. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  15897. s.lookahead -= s.match_length;
  15898. /* Insert new strings in the hash table only if the match length
  15899. * is not too large. This saves time but degrades compression.
  15900. */
  15901. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  15902. s.match_length--; /* string at strstart already in table */
  15903. do {
  15904. s.strstart++;
  15905. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15906. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15907. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15908. s.head[s.ins_h] = s.strstart;
  15909. /***/
  15910. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  15911. * always MIN_MATCH bytes ahead.
  15912. */
  15913. } while (--s.match_length !== 0);
  15914. s.strstart++;
  15915. } else
  15916. {
  15917. s.strstart += s.match_length;
  15918. s.match_length = 0;
  15919. s.ins_h = s.window[s.strstart];
  15920. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  15921. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  15922. //#if MIN_MATCH != 3
  15923. // Call UPDATE_HASH() MIN_MATCH-3 more times
  15924. //#endif
  15925. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  15926. * matter since it will be recomputed at next deflate call.
  15927. */
  15928. }
  15929. } else {
  15930. /* No match, output a literal byte */
  15931. //Tracevv((stderr,"%c", s.window[s.strstart]));
  15932. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  15933. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  15934. s.lookahead--;
  15935. s.strstart++;
  15936. }
  15937. if (bflush) {
  15938. /*** FLUSH_BLOCK(s, 0); ***/
  15939. flush_block_only(s, false);
  15940. if (s.strm.avail_out === 0) {
  15941. return BS_NEED_MORE;
  15942. }
  15943. /***/
  15944. }
  15945. }
  15946. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  15947. if (flush === Z_FINISH) {
  15948. /*** FLUSH_BLOCK(s, 1); ***/
  15949. flush_block_only(s, true);
  15950. if (s.strm.avail_out === 0) {
  15951. return BS_FINISH_STARTED;
  15952. }
  15953. /***/
  15954. return BS_FINISH_DONE;
  15955. }
  15956. if (s.last_lit) {
  15957. /*** FLUSH_BLOCK(s, 0); ***/
  15958. flush_block_only(s, false);
  15959. if (s.strm.avail_out === 0) {
  15960. return BS_NEED_MORE;
  15961. }
  15962. /***/
  15963. }
  15964. return BS_BLOCK_DONE;
  15965. }
  15966. /* ===========================================================================
  15967. * Same as above, but achieves better compression. We use a lazy
  15968. * evaluation for matches: a match is finally adopted only if there is
  15969. * no better match at the next window position.
  15970. */
  15971. function deflate_slow(s, flush) {
  15972. var hash_head; /* head of hash chain */
  15973. var bflush; /* set if current block must be flushed */
  15974. var max_insert;
  15975. /* Process the input block. */
  15976. for (;;) {
  15977. /* Make sure that we always have enough lookahead, except
  15978. * at the end of the input file. We need MAX_MATCH bytes
  15979. * for the next match, plus MIN_MATCH bytes to insert the
  15980. * string following the next match.
  15981. */
  15982. if (s.lookahead < MIN_LOOKAHEAD) {
  15983. fill_window(s);
  15984. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  15985. return BS_NEED_MORE;
  15986. }
  15987. if (s.lookahead === 0) { break; } /* flush the current block */
  15988. }
  15989. /* Insert the string window[strstart .. strstart+2] in the
  15990. * dictionary, and set hash_head to the head of the hash chain:
  15991. */
  15992. hash_head = 0/*NIL*/;
  15993. if (s.lookahead >= MIN_MATCH) {
  15994. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  15995. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  15996. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  15997. s.head[s.ins_h] = s.strstart;
  15998. /***/
  15999. }
  16000. /* Find the longest match, discarding those <= prev_length.
  16001. */
  16002. s.prev_length = s.match_length;
  16003. s.prev_match = s.match_start;
  16004. s.match_length = MIN_MATCH-1;
  16005. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16006. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16007. /* To simplify the code, we prevent matches with the string
  16008. * of window index 0 (in particular we have to avoid a match
  16009. * of the string with itself at the start of the input file).
  16010. */
  16011. s.match_length = longest_match(s, hash_head);
  16012. /* longest_match() sets match_start */
  16013. if (s.match_length <= 5 &&
  16014. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16015. /* If prev_match is also MIN_MATCH, match_start is garbage
  16016. * but we will ignore the current match anyway.
  16017. */
  16018. s.match_length = MIN_MATCH-1;
  16019. }
  16020. }
  16021. /* If there was a match at the previous step and the current
  16022. * match is not better, output the previous match:
  16023. */
  16024. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16025. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16026. /* Do not insert strings in hash table beyond this. */
  16027. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16028. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16029. s.prev_length - MIN_MATCH, bflush);***/
  16030. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16031. /* Insert in hash table all strings up to the end of the match.
  16032. * strstart-1 and strstart are already inserted. If there is not
  16033. * enough lookahead, the last two strings are not inserted in
  16034. * the hash table.
  16035. */
  16036. s.lookahead -= s.prev_length-1;
  16037. s.prev_length -= 2;
  16038. do {
  16039. if (++s.strstart <= max_insert) {
  16040. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16041. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16042. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16043. s.head[s.ins_h] = s.strstart;
  16044. /***/
  16045. }
  16046. } while (--s.prev_length !== 0);
  16047. s.match_available = 0;
  16048. s.match_length = MIN_MATCH-1;
  16049. s.strstart++;
  16050. if (bflush) {
  16051. /*** FLUSH_BLOCK(s, 0); ***/
  16052. flush_block_only(s, false);
  16053. if (s.strm.avail_out === 0) {
  16054. return BS_NEED_MORE;
  16055. }
  16056. /***/
  16057. }
  16058. } else if (s.match_available) {
  16059. /* If there was no match at the previous position, output a
  16060. * single literal. If there was a match but the current match
  16061. * is longer, truncate the previous match to a single literal.
  16062. */
  16063. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16064. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16065. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16066. if (bflush) {
  16067. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16068. flush_block_only(s, false);
  16069. /***/
  16070. }
  16071. s.strstart++;
  16072. s.lookahead--;
  16073. if (s.strm.avail_out === 0) {
  16074. return BS_NEED_MORE;
  16075. }
  16076. } else {
  16077. /* There is no previous match to compare with, wait for
  16078. * the next step to decide.
  16079. */
  16080. s.match_available = 1;
  16081. s.strstart++;
  16082. s.lookahead--;
  16083. }
  16084. }
  16085. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16086. if (s.match_available) {
  16087. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16088. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16089. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16090. s.match_available = 0;
  16091. }
  16092. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16093. if (flush === Z_FINISH) {
  16094. /*** FLUSH_BLOCK(s, 1); ***/
  16095. flush_block_only(s, true);
  16096. if (s.strm.avail_out === 0) {
  16097. return BS_FINISH_STARTED;
  16098. }
  16099. /***/
  16100. return BS_FINISH_DONE;
  16101. }
  16102. if (s.last_lit) {
  16103. /*** FLUSH_BLOCK(s, 0); ***/
  16104. flush_block_only(s, false);
  16105. if (s.strm.avail_out === 0) {
  16106. return BS_NEED_MORE;
  16107. }
  16108. /***/
  16109. }
  16110. return BS_BLOCK_DONE;
  16111. }
  16112. /* ===========================================================================
  16113. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16114. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16115. * deflate switches away from Z_RLE.)
  16116. */
  16117. function deflate_rle(s, flush) {
  16118. var bflush; /* set if current block must be flushed */
  16119. var prev; /* byte at distance one to match */
  16120. var scan, strend; /* scan goes up to strend for length of run */
  16121. var _win = s.window;
  16122. for (;;) {
  16123. /* Make sure that we always have enough lookahead, except
  16124. * at the end of the input file. We need MAX_MATCH bytes
  16125. * for the longest run, plus one for the unrolled loop.
  16126. */
  16127. if (s.lookahead <= MAX_MATCH) {
  16128. fill_window(s);
  16129. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16130. return BS_NEED_MORE;
  16131. }
  16132. if (s.lookahead === 0) { break; } /* flush the current block */
  16133. }
  16134. /* See how many times the previous byte repeats */
  16135. s.match_length = 0;
  16136. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16137. scan = s.strstart - 1;
  16138. prev = _win[scan];
  16139. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16140. strend = s.strstart + MAX_MATCH;
  16141. do {
  16142. /*jshint noempty:false*/
  16143. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16144. prev === _win[++scan] && prev === _win[++scan] &&
  16145. prev === _win[++scan] && prev === _win[++scan] &&
  16146. prev === _win[++scan] && prev === _win[++scan] &&
  16147. scan < strend);
  16148. s.match_length = MAX_MATCH - (strend - scan);
  16149. if (s.match_length > s.lookahead) {
  16150. s.match_length = s.lookahead;
  16151. }
  16152. }
  16153. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16154. }
  16155. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16156. if (s.match_length >= MIN_MATCH) {
  16157. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16158. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16159. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16160. s.lookahead -= s.match_length;
  16161. s.strstart += s.match_length;
  16162. s.match_length = 0;
  16163. } else {
  16164. /* No match, output a literal byte */
  16165. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16166. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16167. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16168. s.lookahead--;
  16169. s.strstart++;
  16170. }
  16171. if (bflush) {
  16172. /*** FLUSH_BLOCK(s, 0); ***/
  16173. flush_block_only(s, false);
  16174. if (s.strm.avail_out === 0) {
  16175. return BS_NEED_MORE;
  16176. }
  16177. /***/
  16178. }
  16179. }
  16180. s.insert = 0;
  16181. if (flush === Z_FINISH) {
  16182. /*** FLUSH_BLOCK(s, 1); ***/
  16183. flush_block_only(s, true);
  16184. if (s.strm.avail_out === 0) {
  16185. return BS_FINISH_STARTED;
  16186. }
  16187. /***/
  16188. return BS_FINISH_DONE;
  16189. }
  16190. if (s.last_lit) {
  16191. /*** FLUSH_BLOCK(s, 0); ***/
  16192. flush_block_only(s, false);
  16193. if (s.strm.avail_out === 0) {
  16194. return BS_NEED_MORE;
  16195. }
  16196. /***/
  16197. }
  16198. return BS_BLOCK_DONE;
  16199. }
  16200. /* ===========================================================================
  16201. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16202. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16203. */
  16204. function deflate_huff(s, flush) {
  16205. var bflush; /* set if current block must be flushed */
  16206. for (;;) {
  16207. /* Make sure that we have a literal to write. */
  16208. if (s.lookahead === 0) {
  16209. fill_window(s);
  16210. if (s.lookahead === 0) {
  16211. if (flush === Z_NO_FLUSH) {
  16212. return BS_NEED_MORE;
  16213. }
  16214. break; /* flush the current block */
  16215. }
  16216. }
  16217. /* Output a literal byte */
  16218. s.match_length = 0;
  16219. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16220. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16221. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16222. s.lookahead--;
  16223. s.strstart++;
  16224. if (bflush) {
  16225. /*** FLUSH_BLOCK(s, 0); ***/
  16226. flush_block_only(s, false);
  16227. if (s.strm.avail_out === 0) {
  16228. return BS_NEED_MORE;
  16229. }
  16230. /***/
  16231. }
  16232. }
  16233. s.insert = 0;
  16234. if (flush === Z_FINISH) {
  16235. /*** FLUSH_BLOCK(s, 1); ***/
  16236. flush_block_only(s, true);
  16237. if (s.strm.avail_out === 0) {
  16238. return BS_FINISH_STARTED;
  16239. }
  16240. /***/
  16241. return BS_FINISH_DONE;
  16242. }
  16243. if (s.last_lit) {
  16244. /*** FLUSH_BLOCK(s, 0); ***/
  16245. flush_block_only(s, false);
  16246. if (s.strm.avail_out === 0) {
  16247. return BS_NEED_MORE;
  16248. }
  16249. /***/
  16250. }
  16251. return BS_BLOCK_DONE;
  16252. }
  16253. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16254. * the desired pack level (0..9). The values given below have been tuned to
  16255. * exclude worst case performance for pathological files. Better values may be
  16256. * found for specific files.
  16257. */
  16258. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16259. this.good_length = good_length;
  16260. this.max_lazy = max_lazy;
  16261. this.nice_length = nice_length;
  16262. this.max_chain = max_chain;
  16263. this.func = func;
  16264. };
  16265. var configuration_table;
  16266. configuration_table = [
  16267. /* good lazy nice chain */
  16268. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16269. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16270. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16271. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16272. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16273. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16274. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16275. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16276. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16277. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16278. ];
  16279. /* ===========================================================================
  16280. * Initialize the "longest match" routines for a new zlib stream
  16281. */
  16282. function lm_init(s) {
  16283. s.window_size = 2 * s.w_size;
  16284. /*** CLEAR_HASH(s); ***/
  16285. zero(s.head); // Fill with NIL (= 0);
  16286. /* Set the default configuration parameters:
  16287. */
  16288. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16289. s.good_match = configuration_table[s.level].good_length;
  16290. s.nice_match = configuration_table[s.level].nice_length;
  16291. s.max_chain_length = configuration_table[s.level].max_chain;
  16292. s.strstart = 0;
  16293. s.block_start = 0;
  16294. s.lookahead = 0;
  16295. s.insert = 0;
  16296. s.match_length = s.prev_length = MIN_MATCH - 1;
  16297. s.match_available = 0;
  16298. s.ins_h = 0;
  16299. }
  16300. function DeflateState() {
  16301. this.strm = null; /* pointer back to this zlib stream */
  16302. this.status = 0; /* as the name implies */
  16303. this.pending_buf = null; /* output still pending */
  16304. this.pending_buf_size = 0; /* size of pending_buf */
  16305. this.pending_out = 0; /* next pending byte to output to the stream */
  16306. this.pending = 0; /* nb of bytes in the pending buffer */
  16307. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16308. this.gzhead = null; /* gzip header information to write */
  16309. this.gzindex = 0; /* where in extra, name, or comment */
  16310. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16311. this.last_flush = -1; /* value of flush param for previous deflate call */
  16312. this.w_size = 0; /* LZ77 window size (32K by default) */
  16313. this.w_bits = 0; /* log2(w_size) (8..16) */
  16314. this.w_mask = 0; /* w_size - 1 */
  16315. this.window = null;
  16316. /* Sliding window. Input bytes are read into the second half of the window,
  16317. * and move to the first half later to keep a dictionary of at least wSize
  16318. * bytes. With this organization, matches are limited to a distance of
  16319. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16320. * performed with a length multiple of the block size.
  16321. */
  16322. this.window_size = 0;
  16323. /* Actual size of window: 2*wSize, except when the user input buffer
  16324. * is directly used as sliding window.
  16325. */
  16326. this.prev = null;
  16327. /* Link to older string with same hash index. To limit the size of this
  16328. * array to 64K, this link is maintained only for the last 32K strings.
  16329. * An index in this array is thus a window index modulo 32K.
  16330. */
  16331. this.head = null; /* Heads of the hash chains or NIL. */
  16332. this.ins_h = 0; /* hash index of string to be inserted */
  16333. this.hash_size = 0; /* number of elements in hash table */
  16334. this.hash_bits = 0; /* log2(hash_size) */
  16335. this.hash_mask = 0; /* hash_size-1 */
  16336. this.hash_shift = 0;
  16337. /* Number of bits by which ins_h must be shifted at each input
  16338. * step. It must be such that after MIN_MATCH steps, the oldest
  16339. * byte no longer takes part in the hash key, that is:
  16340. * hash_shift * MIN_MATCH >= hash_bits
  16341. */
  16342. this.block_start = 0;
  16343. /* Window position at the beginning of the current output block. Gets
  16344. * negative when the window is moved backwards.
  16345. */
  16346. this.match_length = 0; /* length of best match */
  16347. this.prev_match = 0; /* previous match */
  16348. this.match_available = 0; /* set if previous match exists */
  16349. this.strstart = 0; /* start of string to insert */
  16350. this.match_start = 0; /* start of matching string */
  16351. this.lookahead = 0; /* number of valid bytes ahead in window */
  16352. this.prev_length = 0;
  16353. /* Length of the best match at previous step. Matches not greater than this
  16354. * are discarded. This is used in the lazy match evaluation.
  16355. */
  16356. this.max_chain_length = 0;
  16357. /* To speed up deflation, hash chains are never searched beyond this
  16358. * length. A higher limit improves compression ratio but degrades the
  16359. * speed.
  16360. */
  16361. this.max_lazy_match = 0;
  16362. /* Attempt to find a better match only when the current match is strictly
  16363. * smaller than this value. This mechanism is used only for compression
  16364. * levels >= 4.
  16365. */
  16366. // That's alias to max_lazy_match, don't use directly
  16367. //this.max_insert_length = 0;
  16368. /* Insert new strings in the hash table only if the match length is not
  16369. * greater than this length. This saves time but degrades compression.
  16370. * max_insert_length is used only for compression levels <= 3.
  16371. */
  16372. this.level = 0; /* compression level (1..9) */
  16373. this.strategy = 0; /* favor or force Huffman coding*/
  16374. this.good_match = 0;
  16375. /* Use a faster search when the previous match is longer than this */
  16376. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16377. /* used by trees.c: */
  16378. /* Didn't use ct_data typedef below to suppress compiler warning */
  16379. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16380. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16381. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16382. // Use flat array of DOUBLE size, with interleaved fata,
  16383. // because JS does not support effective
  16384. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16385. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16386. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16387. zero(this.dyn_ltree);
  16388. zero(this.dyn_dtree);
  16389. zero(this.bl_tree);
  16390. this.l_desc = null; /* desc. for literal tree */
  16391. this.d_desc = null; /* desc. for distance tree */
  16392. this.bl_desc = null; /* desc. for bit length tree */
  16393. //ush bl_count[MAX_BITS+1];
  16394. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16395. /* number of codes at each bit length for an optimal tree */
  16396. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16397. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16398. zero(this.heap);
  16399. this.heap_len = 0; /* number of elements in the heap */
  16400. this.heap_max = 0; /* element of largest frequency */
  16401. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16402. * The same heap array is used to build all trees.
  16403. */
  16404. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16405. zero(this.depth);
  16406. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16407. */
  16408. this.l_buf = 0; /* buffer index for literals or lengths */
  16409. this.lit_bufsize = 0;
  16410. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16411. * limiting lit_bufsize to 64K:
  16412. * - frequencies can be kept in 16 bit counters
  16413. * - if compression is not successful for the first block, all input
  16414. * data is still in the window so we can still emit a stored block even
  16415. * when input comes from standard input. (This can also be done for
  16416. * all blocks if lit_bufsize is not greater than 32K.)
  16417. * - if compression is not successful for a file smaller than 64K, we can
  16418. * even emit a stored file instead of a stored block (saving 5 bytes).
  16419. * This is applicable only for zip (not gzip or zlib).
  16420. * - creating new Huffman trees less frequently may not provide fast
  16421. * adaptation to changes in the input data statistics. (Take for
  16422. * example a binary file with poorly compressible code followed by
  16423. * a highly compressible string table.) Smaller buffer sizes give
  16424. * fast adaptation but have of course the overhead of transmitting
  16425. * trees more frequently.
  16426. * - I can't count above 4
  16427. */
  16428. this.last_lit = 0; /* running index in l_buf */
  16429. this.d_buf = 0;
  16430. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16431. * the same number of elements. To use different lengths, an extra flag
  16432. * array would be necessary.
  16433. */
  16434. this.opt_len = 0; /* bit length of current block with optimal trees */
  16435. this.static_len = 0; /* bit length of current block with static trees */
  16436. this.matches = 0; /* number of string matches in current block */
  16437. this.insert = 0; /* bytes at end of window left to insert */
  16438. this.bi_buf = 0;
  16439. /* Output buffer. bits are inserted starting at the bottom (least
  16440. * significant bits).
  16441. */
  16442. this.bi_valid = 0;
  16443. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16444. * are always zero.
  16445. */
  16446. // Used for window memory init. We safely ignore it for JS. That makes
  16447. // sense only for pointers and memory check tools.
  16448. //this.high_water = 0;
  16449. /* High water mark offset in window for initialized bytes -- bytes above
  16450. * this are set to zero in order to avoid memory check warnings when
  16451. * longest match routines access bytes past the input. This is then
  16452. * updated to the new high water mark.
  16453. */
  16454. }
  16455. function deflateResetKeep(strm) {
  16456. var s;
  16457. if (!strm || !strm.state) {
  16458. return err(strm, Z_STREAM_ERROR);
  16459. }
  16460. strm.total_in = strm.total_out = 0;
  16461. strm.data_type = Z_UNKNOWN;
  16462. s = strm.state;
  16463. s.pending = 0;
  16464. s.pending_out = 0;
  16465. if (s.wrap < 0) {
  16466. s.wrap = -s.wrap;
  16467. /* was made negative by deflate(..., Z_FINISH); */
  16468. }
  16469. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16470. strm.adler = (s.wrap === 2) ?
  16471. 0 // crc32(0, Z_NULL, 0)
  16472. :
  16473. 1; // adler32(0, Z_NULL, 0)
  16474. s.last_flush = Z_NO_FLUSH;
  16475. trees._tr_init(s);
  16476. return Z_OK;
  16477. }
  16478. function deflateReset(strm) {
  16479. var ret = deflateResetKeep(strm);
  16480. if (ret === Z_OK) {
  16481. lm_init(strm.state);
  16482. }
  16483. return ret;
  16484. }
  16485. function deflateSetHeader(strm, head) {
  16486. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16487. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16488. strm.state.gzhead = head;
  16489. return Z_OK;
  16490. }
  16491. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16492. if (!strm) { // === Z_NULL
  16493. return Z_STREAM_ERROR;
  16494. }
  16495. var wrap = 1;
  16496. if (level === Z_DEFAULT_COMPRESSION) {
  16497. level = 6;
  16498. }
  16499. if (windowBits < 0) { /* suppress zlib wrapper */
  16500. wrap = 0;
  16501. windowBits = -windowBits;
  16502. }
  16503. else if (windowBits > 15) {
  16504. wrap = 2; /* write gzip wrapper instead */
  16505. windowBits -= 16;
  16506. }
  16507. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16508. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16509. strategy < 0 || strategy > Z_FIXED) {
  16510. return err(strm, Z_STREAM_ERROR);
  16511. }
  16512. if (windowBits === 8) {
  16513. windowBits = 9;
  16514. }
  16515. /* until 256-byte window bug fixed */
  16516. var s = new DeflateState();
  16517. strm.state = s;
  16518. s.strm = strm;
  16519. s.wrap = wrap;
  16520. s.gzhead = null;
  16521. s.w_bits = windowBits;
  16522. s.w_size = 1 << s.w_bits;
  16523. s.w_mask = s.w_size - 1;
  16524. s.hash_bits = memLevel + 7;
  16525. s.hash_size = 1 << s.hash_bits;
  16526. s.hash_mask = s.hash_size - 1;
  16527. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16528. s.window = new utils.Buf8(s.w_size * 2);
  16529. s.head = new utils.Buf16(s.hash_size);
  16530. s.prev = new utils.Buf16(s.w_size);
  16531. // Don't need mem init magic for JS.
  16532. //s.high_water = 0; /* nothing written to s->window yet */
  16533. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16534. s.pending_buf_size = s.lit_bufsize * 4;
  16535. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16536. s.d_buf = s.lit_bufsize >> 1;
  16537. s.l_buf = (1 + 2) * s.lit_bufsize;
  16538. s.level = level;
  16539. s.strategy = strategy;
  16540. s.method = method;
  16541. return deflateReset(strm);
  16542. }
  16543. function deflateInit(strm, level) {
  16544. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16545. }
  16546. function deflate(strm, flush) {
  16547. var old_flush, s;
  16548. var beg, val; // for gzip header write only
  16549. if (!strm || !strm.state ||
  16550. flush > Z_BLOCK || flush < 0) {
  16551. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16552. }
  16553. s = strm.state;
  16554. if (!strm.output ||
  16555. (!strm.input && strm.avail_in !== 0) ||
  16556. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16557. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16558. }
  16559. s.strm = strm; /* just in case */
  16560. old_flush = s.last_flush;
  16561. s.last_flush = flush;
  16562. /* Write the header */
  16563. if (s.status === INIT_STATE) {
  16564. if (s.wrap === 2) { // GZIP header
  16565. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16566. put_byte(s, 31);
  16567. put_byte(s, 139);
  16568. put_byte(s, 8);
  16569. if (!s.gzhead) { // s->gzhead == Z_NULL
  16570. put_byte(s, 0);
  16571. put_byte(s, 0);
  16572. put_byte(s, 0);
  16573. put_byte(s, 0);
  16574. put_byte(s, 0);
  16575. put_byte(s, s.level === 9 ? 2 :
  16576. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16577. 4 : 0));
  16578. put_byte(s, OS_CODE);
  16579. s.status = BUSY_STATE;
  16580. }
  16581. else {
  16582. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16583. (s.gzhead.hcrc ? 2 : 0) +
  16584. (!s.gzhead.extra ? 0 : 4) +
  16585. (!s.gzhead.name ? 0 : 8) +
  16586. (!s.gzhead.comment ? 0 : 16)
  16587. );
  16588. put_byte(s, s.gzhead.time & 0xff);
  16589. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16590. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16591. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16592. put_byte(s, s.level === 9 ? 2 :
  16593. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16594. 4 : 0));
  16595. put_byte(s, s.gzhead.os & 0xff);
  16596. if (s.gzhead.extra && s.gzhead.extra.length) {
  16597. put_byte(s, s.gzhead.extra.length & 0xff);
  16598. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16599. }
  16600. if (s.gzhead.hcrc) {
  16601. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16602. }
  16603. s.gzindex = 0;
  16604. s.status = EXTRA_STATE;
  16605. }
  16606. }
  16607. else // DEFLATE header
  16608. {
  16609. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16610. var level_flags = -1;
  16611. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16612. level_flags = 0;
  16613. } else if (s.level < 6) {
  16614. level_flags = 1;
  16615. } else if (s.level === 6) {
  16616. level_flags = 2;
  16617. } else {
  16618. level_flags = 3;
  16619. }
  16620. header |= (level_flags << 6);
  16621. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16622. header += 31 - (header % 31);
  16623. s.status = BUSY_STATE;
  16624. putShortMSB(s, header);
  16625. /* Save the adler32 of the preset dictionary: */
  16626. if (s.strstart !== 0) {
  16627. putShortMSB(s, strm.adler >>> 16);
  16628. putShortMSB(s, strm.adler & 0xffff);
  16629. }
  16630. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16631. }
  16632. }
  16633. //#ifdef GZIP
  16634. if (s.status === EXTRA_STATE) {
  16635. if (s.gzhead.extra/* != Z_NULL*/) {
  16636. beg = s.pending; /* start of bytes to update crc */
  16637. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16638. if (s.pending === s.pending_buf_size) {
  16639. if (s.gzhead.hcrc && s.pending > beg) {
  16640. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16641. }
  16642. flush_pending(strm);
  16643. beg = s.pending;
  16644. if (s.pending === s.pending_buf_size) {
  16645. break;
  16646. }
  16647. }
  16648. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16649. s.gzindex++;
  16650. }
  16651. if (s.gzhead.hcrc && s.pending > beg) {
  16652. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16653. }
  16654. if (s.gzindex === s.gzhead.extra.length) {
  16655. s.gzindex = 0;
  16656. s.status = NAME_STATE;
  16657. }
  16658. }
  16659. else {
  16660. s.status = NAME_STATE;
  16661. }
  16662. }
  16663. if (s.status === NAME_STATE) {
  16664. if (s.gzhead.name/* != Z_NULL*/) {
  16665. beg = s.pending; /* start of bytes to update crc */
  16666. //int val;
  16667. do {
  16668. if (s.pending === s.pending_buf_size) {
  16669. if (s.gzhead.hcrc && s.pending > beg) {
  16670. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16671. }
  16672. flush_pending(strm);
  16673. beg = s.pending;
  16674. if (s.pending === s.pending_buf_size) {
  16675. val = 1;
  16676. break;
  16677. }
  16678. }
  16679. // JS specific: little magic to add zero terminator to end of string
  16680. if (s.gzindex < s.gzhead.name.length) {
  16681. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16682. } else {
  16683. val = 0;
  16684. }
  16685. put_byte(s, val);
  16686. } while (val !== 0);
  16687. if (s.gzhead.hcrc && s.pending > beg) {
  16688. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16689. }
  16690. if (val === 0) {
  16691. s.gzindex = 0;
  16692. s.status = COMMENT_STATE;
  16693. }
  16694. }
  16695. else {
  16696. s.status = COMMENT_STATE;
  16697. }
  16698. }
  16699. if (s.status === COMMENT_STATE) {
  16700. if (s.gzhead.comment/* != Z_NULL*/) {
  16701. beg = s.pending; /* start of bytes to update crc */
  16702. //int val;
  16703. do {
  16704. if (s.pending === s.pending_buf_size) {
  16705. if (s.gzhead.hcrc && s.pending > beg) {
  16706. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16707. }
  16708. flush_pending(strm);
  16709. beg = s.pending;
  16710. if (s.pending === s.pending_buf_size) {
  16711. val = 1;
  16712. break;
  16713. }
  16714. }
  16715. // JS specific: little magic to add zero terminator to end of string
  16716. if (s.gzindex < s.gzhead.comment.length) {
  16717. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16718. } else {
  16719. val = 0;
  16720. }
  16721. put_byte(s, val);
  16722. } while (val !== 0);
  16723. if (s.gzhead.hcrc && s.pending > beg) {
  16724. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16725. }
  16726. if (val === 0) {
  16727. s.status = HCRC_STATE;
  16728. }
  16729. }
  16730. else {
  16731. s.status = HCRC_STATE;
  16732. }
  16733. }
  16734. if (s.status === HCRC_STATE) {
  16735. if (s.gzhead.hcrc) {
  16736. if (s.pending + 2 > s.pending_buf_size) {
  16737. flush_pending(strm);
  16738. }
  16739. if (s.pending + 2 <= s.pending_buf_size) {
  16740. put_byte(s, strm.adler & 0xff);
  16741. put_byte(s, (strm.adler >> 8) & 0xff);
  16742. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16743. s.status = BUSY_STATE;
  16744. }
  16745. }
  16746. else {
  16747. s.status = BUSY_STATE;
  16748. }
  16749. }
  16750. //#endif
  16751. /* Flush as much pending output as possible */
  16752. if (s.pending !== 0) {
  16753. flush_pending(strm);
  16754. if (strm.avail_out === 0) {
  16755. /* Since avail_out is 0, deflate will be called again with
  16756. * more output space, but possibly with both pending and
  16757. * avail_in equal to zero. There won't be anything to do,
  16758. * but this is not an error situation so make sure we
  16759. * return OK instead of BUF_ERROR at next call of deflate:
  16760. */
  16761. s.last_flush = -1;
  16762. return Z_OK;
  16763. }
  16764. /* Make sure there is something to do and avoid duplicate consecutive
  16765. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16766. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16767. */
  16768. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16769. flush !== Z_FINISH) {
  16770. return err(strm, Z_BUF_ERROR);
  16771. }
  16772. /* User must not provide more input after the first FINISH: */
  16773. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16774. return err(strm, Z_BUF_ERROR);
  16775. }
  16776. /* Start a new block or continue the current one.
  16777. */
  16778. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16779. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16780. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16781. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16782. configuration_table[s.level].func(s, flush));
  16783. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16784. s.status = FINISH_STATE;
  16785. }
  16786. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16787. if (strm.avail_out === 0) {
  16788. s.last_flush = -1;
  16789. /* avoid BUF_ERROR next call, see above */
  16790. }
  16791. return Z_OK;
  16792. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16793. * of deflate should use the same flush parameter to make sure
  16794. * that the flush is complete. So we don't have to output an
  16795. * empty block here, this will be done at next call. This also
  16796. * ensures that for a very small output buffer, we emit at most
  16797. * one empty block.
  16798. */
  16799. }
  16800. if (bstate === BS_BLOCK_DONE) {
  16801. if (flush === Z_PARTIAL_FLUSH) {
  16802. trees._tr_align(s);
  16803. }
  16804. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16805. trees._tr_stored_block(s, 0, 0, false);
  16806. /* For a full flush, this empty block will be recognized
  16807. * as a special marker by inflate_sync().
  16808. */
  16809. if (flush === Z_FULL_FLUSH) {
  16810. /*** CLEAR_HASH(s); ***/ /* forget history */
  16811. zero(s.head); // Fill with NIL (= 0);
  16812. if (s.lookahead === 0) {
  16813. s.strstart = 0;
  16814. s.block_start = 0;
  16815. s.insert = 0;
  16816. }
  16817. }
  16818. }
  16819. flush_pending(strm);
  16820. if (strm.avail_out === 0) {
  16821. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  16822. return Z_OK;
  16823. }
  16824. }
  16825. }
  16826. //Assert(strm->avail_out > 0, "bug2");
  16827. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  16828. if (flush !== Z_FINISH) { return Z_OK; }
  16829. if (s.wrap <= 0) { return Z_STREAM_END; }
  16830. /* Write the trailer */
  16831. if (s.wrap === 2) {
  16832. put_byte(s, strm.adler & 0xff);
  16833. put_byte(s, (strm.adler >> 8) & 0xff);
  16834. put_byte(s, (strm.adler >> 16) & 0xff);
  16835. put_byte(s, (strm.adler >> 24) & 0xff);
  16836. put_byte(s, strm.total_in & 0xff);
  16837. put_byte(s, (strm.total_in >> 8) & 0xff);
  16838. put_byte(s, (strm.total_in >> 16) & 0xff);
  16839. put_byte(s, (strm.total_in >> 24) & 0xff);
  16840. }
  16841. else
  16842. {
  16843. putShortMSB(s, strm.adler >>> 16);
  16844. putShortMSB(s, strm.adler & 0xffff);
  16845. }
  16846. flush_pending(strm);
  16847. /* If avail_out is zero, the application will call deflate again
  16848. * to flush the rest.
  16849. */
  16850. if (s.wrap > 0) { s.wrap = -s.wrap; }
  16851. /* write the trailer only once! */
  16852. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  16853. }
  16854. function deflateEnd(strm) {
  16855. var status;
  16856. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  16857. return Z_STREAM_ERROR;
  16858. }
  16859. status = strm.state.status;
  16860. if (status !== INIT_STATE &&
  16861. status !== EXTRA_STATE &&
  16862. status !== NAME_STATE &&
  16863. status !== COMMENT_STATE &&
  16864. status !== HCRC_STATE &&
  16865. status !== BUSY_STATE &&
  16866. status !== FINISH_STATE
  16867. ) {
  16868. return err(strm, Z_STREAM_ERROR);
  16869. }
  16870. strm.state = null;
  16871. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  16872. }
  16873. /* =========================================================================
  16874. * Copy the source state to the destination state
  16875. */
  16876. //function deflateCopy(dest, source) {
  16877. //
  16878. //}
  16879. exports.deflateInit = deflateInit;
  16880. exports.deflateInit2 = deflateInit2;
  16881. exports.deflateReset = deflateReset;
  16882. exports.deflateResetKeep = deflateResetKeep;
  16883. exports.deflateSetHeader = deflateSetHeader;
  16884. exports.deflate = deflate;
  16885. exports.deflateEnd = deflateEnd;
  16886. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  16887. /* Not implemented
  16888. exports.deflateBound = deflateBound;
  16889. exports.deflateCopy = deflateCopy;
  16890. exports.deflateSetDictionary = deflateSetDictionary;
  16891. exports.deflateParams = deflateParams;
  16892. exports.deflatePending = deflatePending;
  16893. exports.deflatePrime = deflatePrime;
  16894. exports.deflateTune = deflateTune;
  16895. */
  16896. },{"../utils/common":54,"./adler32":56,"./crc32":58,"./messages":64,"./trees":65}],60:[function(require,module,exports){
  16897. 'use strict';
  16898. function GZheader() {
  16899. /* true if compressed data believed to be text */
  16900. this.text = 0;
  16901. /* modification time */
  16902. this.time = 0;
  16903. /* extra flags (not used when writing a gzip file) */
  16904. this.xflags = 0;
  16905. /* operating system */
  16906. this.os = 0;
  16907. /* pointer to extra field or Z_NULL if none */
  16908. this.extra = null;
  16909. /* extra field length (valid if extra != Z_NULL) */
  16910. this.extra_len = 0; // Actually, we don't need it in JS,
  16911. // but leave for few code modifications
  16912. //
  16913. // Setup limits is not necessary because in js we should not preallocate memory
  16914. // for inflate use constant limit in 65536 bytes
  16915. //
  16916. /* space at extra (only when reading header) */
  16917. // this.extra_max = 0;
  16918. /* pointer to zero-terminated file name or Z_NULL */
  16919. this.name = '';
  16920. /* space at name (only when reading header) */
  16921. // this.name_max = 0;
  16922. /* pointer to zero-terminated comment or Z_NULL */
  16923. this.comment = '';
  16924. /* space at comment (only when reading header) */
  16925. // this.comm_max = 0;
  16926. /* true if there was or will be a header crc */
  16927. this.hcrc = 0;
  16928. /* true when done reading gzip header (not used when writing a gzip file) */
  16929. this.done = false;
  16930. }
  16931. module.exports = GZheader;
  16932. },{}],61:[function(require,module,exports){
  16933. 'use strict';
  16934. // See state defs from inflate.js
  16935. var BAD = 30; /* got a data error -- remain here until reset */
  16936. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  16937. /*
  16938. Decode literal, length, and distance codes and write out the resulting
  16939. literal and match bytes until either not enough input or output is
  16940. available, an end-of-block is encountered, or a data error is encountered.
  16941. When large enough input and output buffers are supplied to inflate(), for
  16942. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  16943. inflate execution time is spent in this routine.
  16944. Entry assumptions:
  16945. state.mode === LEN
  16946. strm.avail_in >= 6
  16947. strm.avail_out >= 258
  16948. start >= strm.avail_out
  16949. state.bits < 8
  16950. On return, state.mode is one of:
  16951. LEN -- ran out of enough output space or enough available input
  16952. TYPE -- reached end of block code, inflate() to interpret next block
  16953. BAD -- error in block data
  16954. Notes:
  16955. - The maximum input bits used by a length/distance pair is 15 bits for the
  16956. length code, 5 bits for the length extra, 15 bits for the distance code,
  16957. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  16958. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  16959. checking for available input while decoding.
  16960. - The maximum bytes that a single length/distance pair can output is 258
  16961. bytes, which is the maximum length that can be coded. inflate_fast()
  16962. requires strm.avail_out >= 258 for each loop to avoid checking for
  16963. output space.
  16964. */
  16965. module.exports = function inflate_fast(strm, start) {
  16966. var state;
  16967. var _in; /* local strm.input */
  16968. var last; /* have enough input while in < last */
  16969. var _out; /* local strm.output */
  16970. var beg; /* inflate()'s initial strm.output */
  16971. var end; /* while out < end, enough space available */
  16972. //#ifdef INFLATE_STRICT
  16973. var dmax; /* maximum distance from zlib header */
  16974. //#endif
  16975. var wsize; /* window size or zero if not using window */
  16976. var whave; /* valid bytes in the window */
  16977. var wnext; /* window write index */
  16978. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  16979. var s_window; /* allocated sliding window, if wsize != 0 */
  16980. var hold; /* local strm.hold */
  16981. var bits; /* local strm.bits */
  16982. var lcode; /* local strm.lencode */
  16983. var dcode; /* local strm.distcode */
  16984. var lmask; /* mask for first level of length codes */
  16985. var dmask; /* mask for first level of distance codes */
  16986. var here; /* retrieved table entry */
  16987. var op; /* code bits, operation, extra bits, or */
  16988. /* window position, window bytes to copy */
  16989. var len; /* match length, unused bytes */
  16990. var dist; /* match distance */
  16991. var from; /* where to copy match from */
  16992. var from_source;
  16993. var input, output; // JS specific, because we have no pointers
  16994. /* copy state to local variables */
  16995. state = strm.state;
  16996. //here = state.here;
  16997. _in = strm.next_in;
  16998. input = strm.input;
  16999. last = _in + (strm.avail_in - 5);
  17000. _out = strm.next_out;
  17001. output = strm.output;
  17002. beg = _out - (start - strm.avail_out);
  17003. end = _out + (strm.avail_out - 257);
  17004. //#ifdef INFLATE_STRICT
  17005. dmax = state.dmax;
  17006. //#endif
  17007. wsize = state.wsize;
  17008. whave = state.whave;
  17009. wnext = state.wnext;
  17010. s_window = state.window;
  17011. hold = state.hold;
  17012. bits = state.bits;
  17013. lcode = state.lencode;
  17014. dcode = state.distcode;
  17015. lmask = (1 << state.lenbits) - 1;
  17016. dmask = (1 << state.distbits) - 1;
  17017. /* decode literals and length/distances until end-of-block or not enough
  17018. input data or output space */
  17019. top:
  17020. do {
  17021. if (bits < 15) {
  17022. hold += input[_in++] << bits;
  17023. bits += 8;
  17024. hold += input[_in++] << bits;
  17025. bits += 8;
  17026. }
  17027. here = lcode[hold & lmask];
  17028. dolen:
  17029. for (;;) { // Goto emulation
  17030. op = here >>> 24/*here.bits*/;
  17031. hold >>>= op;
  17032. bits -= op;
  17033. op = (here >>> 16) & 0xff/*here.op*/;
  17034. if (op === 0) { /* literal */
  17035. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17036. // "inflate: literal '%c'\n" :
  17037. // "inflate: literal 0x%02x\n", here.val));
  17038. output[_out++] = here & 0xffff/*here.val*/;
  17039. }
  17040. else if (op & 16) { /* length base */
  17041. len = here & 0xffff/*here.val*/;
  17042. op &= 15; /* number of extra bits */
  17043. if (op) {
  17044. if (bits < op) {
  17045. hold += input[_in++] << bits;
  17046. bits += 8;
  17047. }
  17048. len += hold & ((1 << op) - 1);
  17049. hold >>>= op;
  17050. bits -= op;
  17051. }
  17052. //Tracevv((stderr, "inflate: length %u\n", len));
  17053. if (bits < 15) {
  17054. hold += input[_in++] << bits;
  17055. bits += 8;
  17056. hold += input[_in++] << bits;
  17057. bits += 8;
  17058. }
  17059. here = dcode[hold & dmask];
  17060. dodist:
  17061. for (;;) { // goto emulation
  17062. op = here >>> 24/*here.bits*/;
  17063. hold >>>= op;
  17064. bits -= op;
  17065. op = (here >>> 16) & 0xff/*here.op*/;
  17066. if (op & 16) { /* distance base */
  17067. dist = here & 0xffff/*here.val*/;
  17068. op &= 15; /* number of extra bits */
  17069. if (bits < op) {
  17070. hold += input[_in++] << bits;
  17071. bits += 8;
  17072. if (bits < op) {
  17073. hold += input[_in++] << bits;
  17074. bits += 8;
  17075. }
  17076. }
  17077. dist += hold & ((1 << op) - 1);
  17078. //#ifdef INFLATE_STRICT
  17079. if (dist > dmax) {
  17080. strm.msg = 'invalid distance too far back';
  17081. state.mode = BAD;
  17082. break top;
  17083. }
  17084. //#endif
  17085. hold >>>= op;
  17086. bits -= op;
  17087. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17088. op = _out - beg; /* max distance in output */
  17089. if (dist > op) { /* see if copy from window */
  17090. op = dist - op; /* distance back in window */
  17091. if (op > whave) {
  17092. if (state.sane) {
  17093. strm.msg = 'invalid distance too far back';
  17094. state.mode = BAD;
  17095. break top;
  17096. }
  17097. // (!) This block is disabled in zlib defailts,
  17098. // don't enable it for binary compatibility
  17099. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17100. // if (len <= op - whave) {
  17101. // do {
  17102. // output[_out++] = 0;
  17103. // } while (--len);
  17104. // continue top;
  17105. // }
  17106. // len -= op - whave;
  17107. // do {
  17108. // output[_out++] = 0;
  17109. // } while (--op > whave);
  17110. // if (op === 0) {
  17111. // from = _out - dist;
  17112. // do {
  17113. // output[_out++] = output[from++];
  17114. // } while (--len);
  17115. // continue top;
  17116. // }
  17117. //#endif
  17118. }
  17119. from = 0; // window index
  17120. from_source = s_window;
  17121. if (wnext === 0) { /* very common case */
  17122. from += wsize - op;
  17123. if (op < len) { /* some from window */
  17124. len -= op;
  17125. do {
  17126. output[_out++] = s_window[from++];
  17127. } while (--op);
  17128. from = _out - dist; /* rest from output */
  17129. from_source = output;
  17130. }
  17131. }
  17132. else if (wnext < op) { /* wrap around window */
  17133. from += wsize + wnext - op;
  17134. op -= wnext;
  17135. if (op < len) { /* some from end of window */
  17136. len -= op;
  17137. do {
  17138. output[_out++] = s_window[from++];
  17139. } while (--op);
  17140. from = 0;
  17141. if (wnext < len) { /* some from start of window */
  17142. op = wnext;
  17143. len -= op;
  17144. do {
  17145. output[_out++] = s_window[from++];
  17146. } while (--op);
  17147. from = _out - dist; /* rest from output */
  17148. from_source = output;
  17149. }
  17150. }
  17151. }
  17152. else { /* contiguous in window */
  17153. from += wnext - op;
  17154. if (op < len) { /* some from window */
  17155. len -= op;
  17156. do {
  17157. output[_out++] = s_window[from++];
  17158. } while (--op);
  17159. from = _out - dist; /* rest from output */
  17160. from_source = output;
  17161. }
  17162. }
  17163. while (len > 2) {
  17164. output[_out++] = from_source[from++];
  17165. output[_out++] = from_source[from++];
  17166. output[_out++] = from_source[from++];
  17167. len -= 3;
  17168. }
  17169. if (len) {
  17170. output[_out++] = from_source[from++];
  17171. if (len > 1) {
  17172. output[_out++] = from_source[from++];
  17173. }
  17174. }
  17175. }
  17176. else {
  17177. from = _out - dist; /* copy direct from output */
  17178. do { /* minimum length is three */
  17179. output[_out++] = output[from++];
  17180. output[_out++] = output[from++];
  17181. output[_out++] = output[from++];
  17182. len -= 3;
  17183. } while (len > 2);
  17184. if (len) {
  17185. output[_out++] = output[from++];
  17186. if (len > 1) {
  17187. output[_out++] = output[from++];
  17188. }
  17189. }
  17190. }
  17191. }
  17192. else if ((op & 64) === 0) { /* 2nd level distance code */
  17193. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17194. continue dodist;
  17195. }
  17196. else {
  17197. strm.msg = 'invalid distance code';
  17198. state.mode = BAD;
  17199. break top;
  17200. }
  17201. break; // need to emulate goto via "continue"
  17202. }
  17203. }
  17204. else if ((op & 64) === 0) { /* 2nd level length code */
  17205. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17206. continue dolen;
  17207. }
  17208. else if (op & 32) { /* end-of-block */
  17209. //Tracevv((stderr, "inflate: end of block\n"));
  17210. state.mode = TYPE;
  17211. break top;
  17212. }
  17213. else {
  17214. strm.msg = 'invalid literal/length code';
  17215. state.mode = BAD;
  17216. break top;
  17217. }
  17218. break; // need to emulate goto via "continue"
  17219. }
  17220. } while (_in < last && _out < end);
  17221. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17222. len = bits >> 3;
  17223. _in -= len;
  17224. bits -= len << 3;
  17225. hold &= (1 << bits) - 1;
  17226. /* update state and return */
  17227. strm.next_in = _in;
  17228. strm.next_out = _out;
  17229. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17230. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17231. state.hold = hold;
  17232. state.bits = bits;
  17233. return;
  17234. };
  17235. },{}],62:[function(require,module,exports){
  17236. 'use strict';
  17237. var utils = require('../utils/common');
  17238. var adler32 = require('./adler32');
  17239. var crc32 = require('./crc32');
  17240. var inflate_fast = require('./inffast');
  17241. var inflate_table = require('./inftrees');
  17242. var CODES = 0;
  17243. var LENS = 1;
  17244. var DISTS = 2;
  17245. /* Public constants ==========================================================*/
  17246. /* ===========================================================================*/
  17247. /* Allowed flush values; see deflate() and inflate() below for details */
  17248. //var Z_NO_FLUSH = 0;
  17249. //var Z_PARTIAL_FLUSH = 1;
  17250. //var Z_SYNC_FLUSH = 2;
  17251. //var Z_FULL_FLUSH = 3;
  17252. var Z_FINISH = 4;
  17253. var Z_BLOCK = 5;
  17254. var Z_TREES = 6;
  17255. /* Return codes for the compression/decompression functions. Negative values
  17256. * are errors, positive values are used for special but normal events.
  17257. */
  17258. var Z_OK = 0;
  17259. var Z_STREAM_END = 1;
  17260. var Z_NEED_DICT = 2;
  17261. //var Z_ERRNO = -1;
  17262. var Z_STREAM_ERROR = -2;
  17263. var Z_DATA_ERROR = -3;
  17264. var Z_MEM_ERROR = -4;
  17265. var Z_BUF_ERROR = -5;
  17266. //var Z_VERSION_ERROR = -6;
  17267. /* The deflate compression method */
  17268. var Z_DEFLATED = 8;
  17269. /* STATES ====================================================================*/
  17270. /* ===========================================================================*/
  17271. var HEAD = 1; /* i: waiting for magic header */
  17272. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17273. var TIME = 3; /* i: waiting for modification time (gzip) */
  17274. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17275. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17276. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17277. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17278. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17279. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17280. var DICTID = 10; /* i: waiting for dictionary check value */
  17281. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17282. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17283. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17284. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17285. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17286. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17287. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17288. var LENLENS = 18; /* i: waiting for code length code lengths */
  17289. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17290. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17291. var LEN = 21; /* i: waiting for length/lit/eob code */
  17292. var LENEXT = 22; /* i: waiting for length extra bits */
  17293. var DIST = 23; /* i: waiting for distance code */
  17294. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17295. var MATCH = 25; /* o: waiting for output space to copy string */
  17296. var LIT = 26; /* o: waiting for output space to write literal */
  17297. var CHECK = 27; /* i: waiting for 32-bit check value */
  17298. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17299. var DONE = 29; /* finished check, done -- remain here until reset */
  17300. var BAD = 30; /* got a data error -- remain here until reset */
  17301. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17302. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17303. /* ===========================================================================*/
  17304. var ENOUGH_LENS = 852;
  17305. var ENOUGH_DISTS = 592;
  17306. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17307. var MAX_WBITS = 15;
  17308. /* 32K LZ77 window */
  17309. var DEF_WBITS = MAX_WBITS;
  17310. function ZSWAP32(q) {
  17311. return (((q >>> 24) & 0xff) +
  17312. ((q >>> 8) & 0xff00) +
  17313. ((q & 0xff00) << 8) +
  17314. ((q & 0xff) << 24));
  17315. }
  17316. function InflateState() {
  17317. this.mode = 0; /* current inflate mode */
  17318. this.last = false; /* true if processing last block */
  17319. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17320. this.havedict = false; /* true if dictionary provided */
  17321. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17322. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17323. this.check = 0; /* protected copy of check value */
  17324. this.total = 0; /* protected copy of output count */
  17325. // TODO: may be {}
  17326. this.head = null; /* where to save gzip header information */
  17327. /* sliding window */
  17328. this.wbits = 0; /* log base 2 of requested window size */
  17329. this.wsize = 0; /* window size or zero if not using window */
  17330. this.whave = 0; /* valid bytes in the window */
  17331. this.wnext = 0; /* window write index */
  17332. this.window = null; /* allocated sliding window, if needed */
  17333. /* bit accumulator */
  17334. this.hold = 0; /* input bit accumulator */
  17335. this.bits = 0; /* number of bits in "in" */
  17336. /* for string and stored block copying */
  17337. this.length = 0; /* literal or length of data to copy */
  17338. this.offset = 0; /* distance back to copy string from */
  17339. /* for table and code decoding */
  17340. this.extra = 0; /* extra bits needed */
  17341. /* fixed and dynamic code tables */
  17342. this.lencode = null; /* starting table for length/literal codes */
  17343. this.distcode = null; /* starting table for distance codes */
  17344. this.lenbits = 0; /* index bits for lencode */
  17345. this.distbits = 0; /* index bits for distcode */
  17346. /* dynamic table building */
  17347. this.ncode = 0; /* number of code length code lengths */
  17348. this.nlen = 0; /* number of length code lengths */
  17349. this.ndist = 0; /* number of distance code lengths */
  17350. this.have = 0; /* number of code lengths in lens[] */
  17351. this.next = null; /* next available space in codes[] */
  17352. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17353. this.work = new utils.Buf16(288); /* work area for code table building */
  17354. /*
  17355. because we don't have pointers in js, we use lencode and distcode directly
  17356. as buffers so we don't need codes
  17357. */
  17358. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17359. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17360. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17361. this.sane = 0; /* if false, allow invalid distance too far */
  17362. this.back = 0; /* bits back of last unprocessed length/lit */
  17363. this.was = 0; /* initial length of match */
  17364. }
  17365. function inflateResetKeep(strm) {
  17366. var state;
  17367. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17368. state = strm.state;
  17369. strm.total_in = strm.total_out = state.total = 0;
  17370. strm.msg = ''; /*Z_NULL*/
  17371. if (state.wrap) { /* to support ill-conceived Java test suite */
  17372. strm.adler = state.wrap & 1;
  17373. }
  17374. state.mode = HEAD;
  17375. state.last = 0;
  17376. state.havedict = 0;
  17377. state.dmax = 32768;
  17378. state.head = null/*Z_NULL*/;
  17379. state.hold = 0;
  17380. state.bits = 0;
  17381. //state.lencode = state.distcode = state.next = state.codes;
  17382. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17383. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17384. state.sane = 1;
  17385. state.back = -1;
  17386. //Tracev((stderr, "inflate: reset\n"));
  17387. return Z_OK;
  17388. }
  17389. function inflateReset(strm) {
  17390. var state;
  17391. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17392. state = strm.state;
  17393. state.wsize = 0;
  17394. state.whave = 0;
  17395. state.wnext = 0;
  17396. return inflateResetKeep(strm);
  17397. }
  17398. function inflateReset2(strm, windowBits) {
  17399. var wrap;
  17400. var state;
  17401. /* get the state */
  17402. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17403. state = strm.state;
  17404. /* extract wrap request from windowBits parameter */
  17405. if (windowBits < 0) {
  17406. wrap = 0;
  17407. windowBits = -windowBits;
  17408. }
  17409. else {
  17410. wrap = (windowBits >> 4) + 1;
  17411. if (windowBits < 48) {
  17412. windowBits &= 15;
  17413. }
  17414. }
  17415. /* set number of window bits, free window if different */
  17416. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17417. return Z_STREAM_ERROR;
  17418. }
  17419. if (state.window !== null && state.wbits !== windowBits) {
  17420. state.window = null;
  17421. }
  17422. /* update state and reset the rest of it */
  17423. state.wrap = wrap;
  17424. state.wbits = windowBits;
  17425. return inflateReset(strm);
  17426. }
  17427. function inflateInit2(strm, windowBits) {
  17428. var ret;
  17429. var state;
  17430. if (!strm) { return Z_STREAM_ERROR; }
  17431. //strm.msg = Z_NULL; /* in case we return an error */
  17432. state = new InflateState();
  17433. //if (state === Z_NULL) return Z_MEM_ERROR;
  17434. //Tracev((stderr, "inflate: allocated\n"));
  17435. strm.state = state;
  17436. state.window = null/*Z_NULL*/;
  17437. ret = inflateReset2(strm, windowBits);
  17438. if (ret !== Z_OK) {
  17439. strm.state = null/*Z_NULL*/;
  17440. }
  17441. return ret;
  17442. }
  17443. function inflateInit(strm) {
  17444. return inflateInit2(strm, DEF_WBITS);
  17445. }
  17446. /*
  17447. Return state with length and distance decoding tables and index sizes set to
  17448. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17449. If BUILDFIXED is defined, then instead this routine builds the tables the
  17450. first time it's called, and returns those tables the first time and
  17451. thereafter. This reduces the size of the code by about 2K bytes, in
  17452. exchange for a little execution time. However, BUILDFIXED should not be
  17453. used for threaded applications, since the rewriting of the tables and virgin
  17454. may not be thread-safe.
  17455. */
  17456. var virgin = true;
  17457. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17458. function fixedtables(state) {
  17459. /* build fixed huffman tables if first call (may not be thread safe) */
  17460. if (virgin) {
  17461. var sym;
  17462. lenfix = new utils.Buf32(512);
  17463. distfix = new utils.Buf32(32);
  17464. /* literal/length table */
  17465. sym = 0;
  17466. while (sym < 144) { state.lens[sym++] = 8; }
  17467. while (sym < 256) { state.lens[sym++] = 9; }
  17468. while (sym < 280) { state.lens[sym++] = 7; }
  17469. while (sym < 288) { state.lens[sym++] = 8; }
  17470. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17471. /* distance table */
  17472. sym = 0;
  17473. while (sym < 32) { state.lens[sym++] = 5; }
  17474. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17475. /* do this just once */
  17476. virgin = false;
  17477. }
  17478. state.lencode = lenfix;
  17479. state.lenbits = 9;
  17480. state.distcode = distfix;
  17481. state.distbits = 5;
  17482. }
  17483. /*
  17484. Update the window with the last wsize (normally 32K) bytes written before
  17485. returning. If window does not exist yet, create it. This is only called
  17486. when a window is already in use, or when output has been written during this
  17487. inflate call, but the end of the deflate stream has not been reached yet.
  17488. It is also called to create a window for dictionary data when a dictionary
  17489. is loaded.
  17490. Providing output buffers larger than 32K to inflate() should provide a speed
  17491. advantage, since only the last 32K of output is copied to the sliding window
  17492. upon return from inflate(), and since all distances after the first 32K of
  17493. output will fall in the output data, making match copies simpler and faster.
  17494. The advantage may be dependent on the size of the processor's data caches.
  17495. */
  17496. function updatewindow(strm, src, end, copy) {
  17497. var dist;
  17498. var state = strm.state;
  17499. /* if it hasn't been done already, allocate space for the window */
  17500. if (state.window === null) {
  17501. state.wsize = 1 << state.wbits;
  17502. state.wnext = 0;
  17503. state.whave = 0;
  17504. state.window = new utils.Buf8(state.wsize);
  17505. }
  17506. /* copy state->wsize or less output bytes into the circular window */
  17507. if (copy >= state.wsize) {
  17508. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17509. state.wnext = 0;
  17510. state.whave = state.wsize;
  17511. }
  17512. else {
  17513. dist = state.wsize - state.wnext;
  17514. if (dist > copy) {
  17515. dist = copy;
  17516. }
  17517. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17518. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17519. copy -= dist;
  17520. if (copy) {
  17521. //zmemcpy(state->window, end - copy, copy);
  17522. utils.arraySet(state.window,src, end - copy, copy, 0);
  17523. state.wnext = copy;
  17524. state.whave = state.wsize;
  17525. }
  17526. else {
  17527. state.wnext += dist;
  17528. if (state.wnext === state.wsize) { state.wnext = 0; }
  17529. if (state.whave < state.wsize) { state.whave += dist; }
  17530. }
  17531. }
  17532. return 0;
  17533. }
  17534. function inflate(strm, flush) {
  17535. var state;
  17536. var input, output; // input/output buffers
  17537. var next; /* next input INDEX */
  17538. var put; /* next output INDEX */
  17539. var have, left; /* available input and output */
  17540. var hold; /* bit buffer */
  17541. var bits; /* bits in bit buffer */
  17542. var _in, _out; /* save starting available input and output */
  17543. var copy; /* number of stored or match bytes to copy */
  17544. var from; /* where to copy match bytes from */
  17545. var from_source;
  17546. var here = 0; /* current decoding table entry */
  17547. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17548. //var last; /* parent table entry */
  17549. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17550. var len; /* length to copy for repeats, bits to drop */
  17551. var ret; /* return code */
  17552. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17553. var opts;
  17554. var n; // temporary var for NEED_BITS
  17555. var order = /* permutation of code lengths */
  17556. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17557. if (!strm || !strm.state || !strm.output ||
  17558. (!strm.input && strm.avail_in !== 0)) {
  17559. return Z_STREAM_ERROR;
  17560. }
  17561. state = strm.state;
  17562. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17563. //--- LOAD() ---
  17564. put = strm.next_out;
  17565. output = strm.output;
  17566. left = strm.avail_out;
  17567. next = strm.next_in;
  17568. input = strm.input;
  17569. have = strm.avail_in;
  17570. hold = state.hold;
  17571. bits = state.bits;
  17572. //---
  17573. _in = have;
  17574. _out = left;
  17575. ret = Z_OK;
  17576. inf_leave: // goto emulation
  17577. for (;;) {
  17578. switch (state.mode) {
  17579. case HEAD:
  17580. if (state.wrap === 0) {
  17581. state.mode = TYPEDO;
  17582. break;
  17583. }
  17584. //=== NEEDBITS(16);
  17585. while (bits < 16) {
  17586. if (have === 0) { break inf_leave; }
  17587. have--;
  17588. hold += input[next++] << bits;
  17589. bits += 8;
  17590. }
  17591. //===//
  17592. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17593. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17594. //=== CRC2(state.check, hold);
  17595. hbuf[0] = hold & 0xff;
  17596. hbuf[1] = (hold >>> 8) & 0xff;
  17597. state.check = crc32(state.check, hbuf, 2, 0);
  17598. //===//
  17599. //=== INITBITS();
  17600. hold = 0;
  17601. bits = 0;
  17602. //===//
  17603. state.mode = FLAGS;
  17604. break;
  17605. }
  17606. state.flags = 0; /* expect zlib header */
  17607. if (state.head) {
  17608. state.head.done = false;
  17609. }
  17610. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17611. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17612. strm.msg = 'incorrect header check';
  17613. state.mode = BAD;
  17614. break;
  17615. }
  17616. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17617. strm.msg = 'unknown compression method';
  17618. state.mode = BAD;
  17619. break;
  17620. }
  17621. //--- DROPBITS(4) ---//
  17622. hold >>>= 4;
  17623. bits -= 4;
  17624. //---//
  17625. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17626. if (state.wbits === 0) {
  17627. state.wbits = len;
  17628. }
  17629. else if (len > state.wbits) {
  17630. strm.msg = 'invalid window size';
  17631. state.mode = BAD;
  17632. break;
  17633. }
  17634. state.dmax = 1 << len;
  17635. //Tracev((stderr, "inflate: zlib header ok\n"));
  17636. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17637. state.mode = hold & 0x200 ? DICTID : TYPE;
  17638. //=== INITBITS();
  17639. hold = 0;
  17640. bits = 0;
  17641. //===//
  17642. break;
  17643. case FLAGS:
  17644. //=== NEEDBITS(16); */
  17645. while (bits < 16) {
  17646. if (have === 0) { break inf_leave; }
  17647. have--;
  17648. hold += input[next++] << bits;
  17649. bits += 8;
  17650. }
  17651. //===//
  17652. state.flags = hold;
  17653. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17654. strm.msg = 'unknown compression method';
  17655. state.mode = BAD;
  17656. break;
  17657. }
  17658. if (state.flags & 0xe000) {
  17659. strm.msg = 'unknown header flags set';
  17660. state.mode = BAD;
  17661. break;
  17662. }
  17663. if (state.head) {
  17664. state.head.text = ((hold >> 8) & 1);
  17665. }
  17666. if (state.flags & 0x0200) {
  17667. //=== CRC2(state.check, hold);
  17668. hbuf[0] = hold & 0xff;
  17669. hbuf[1] = (hold >>> 8) & 0xff;
  17670. state.check = crc32(state.check, hbuf, 2, 0);
  17671. //===//
  17672. }
  17673. //=== INITBITS();
  17674. hold = 0;
  17675. bits = 0;
  17676. //===//
  17677. state.mode = TIME;
  17678. /* falls through */
  17679. case TIME:
  17680. //=== NEEDBITS(32); */
  17681. while (bits < 32) {
  17682. if (have === 0) { break inf_leave; }
  17683. have--;
  17684. hold += input[next++] << bits;
  17685. bits += 8;
  17686. }
  17687. //===//
  17688. if (state.head) {
  17689. state.head.time = hold;
  17690. }
  17691. if (state.flags & 0x0200) {
  17692. //=== CRC4(state.check, hold)
  17693. hbuf[0] = hold & 0xff;
  17694. hbuf[1] = (hold >>> 8) & 0xff;
  17695. hbuf[2] = (hold >>> 16) & 0xff;
  17696. hbuf[3] = (hold >>> 24) & 0xff;
  17697. state.check = crc32(state.check, hbuf, 4, 0);
  17698. //===
  17699. }
  17700. //=== INITBITS();
  17701. hold = 0;
  17702. bits = 0;
  17703. //===//
  17704. state.mode = OS;
  17705. /* falls through */
  17706. case OS:
  17707. //=== NEEDBITS(16); */
  17708. while (bits < 16) {
  17709. if (have === 0) { break inf_leave; }
  17710. have--;
  17711. hold += input[next++] << bits;
  17712. bits += 8;
  17713. }
  17714. //===//
  17715. if (state.head) {
  17716. state.head.xflags = (hold & 0xff);
  17717. state.head.os = (hold >> 8);
  17718. }
  17719. if (state.flags & 0x0200) {
  17720. //=== CRC2(state.check, hold);
  17721. hbuf[0] = hold & 0xff;
  17722. hbuf[1] = (hold >>> 8) & 0xff;
  17723. state.check = crc32(state.check, hbuf, 2, 0);
  17724. //===//
  17725. }
  17726. //=== INITBITS();
  17727. hold = 0;
  17728. bits = 0;
  17729. //===//
  17730. state.mode = EXLEN;
  17731. /* falls through */
  17732. case EXLEN:
  17733. if (state.flags & 0x0400) {
  17734. //=== NEEDBITS(16); */
  17735. while (bits < 16) {
  17736. if (have === 0) { break inf_leave; }
  17737. have--;
  17738. hold += input[next++] << bits;
  17739. bits += 8;
  17740. }
  17741. //===//
  17742. state.length = hold;
  17743. if (state.head) {
  17744. state.head.extra_len = hold;
  17745. }
  17746. if (state.flags & 0x0200) {
  17747. //=== CRC2(state.check, hold);
  17748. hbuf[0] = hold & 0xff;
  17749. hbuf[1] = (hold >>> 8) & 0xff;
  17750. state.check = crc32(state.check, hbuf, 2, 0);
  17751. //===//
  17752. }
  17753. //=== INITBITS();
  17754. hold = 0;
  17755. bits = 0;
  17756. //===//
  17757. }
  17758. else if (state.head) {
  17759. state.head.extra = null/*Z_NULL*/;
  17760. }
  17761. state.mode = EXTRA;
  17762. /* falls through */
  17763. case EXTRA:
  17764. if (state.flags & 0x0400) {
  17765. copy = state.length;
  17766. if (copy > have) { copy = have; }
  17767. if (copy) {
  17768. if (state.head) {
  17769. len = state.head.extra_len - state.length;
  17770. if (!state.head.extra) {
  17771. // Use untyped array for more conveniend processing later
  17772. state.head.extra = new Array(state.head.extra_len);
  17773. }
  17774. utils.arraySet(
  17775. state.head.extra,
  17776. input,
  17777. next,
  17778. // extra field is limited to 65536 bytes
  17779. // - no need for additional size check
  17780. copy,
  17781. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17782. len
  17783. );
  17784. //zmemcpy(state.head.extra + len, next,
  17785. // len + copy > state.head.extra_max ?
  17786. // state.head.extra_max - len : copy);
  17787. }
  17788. if (state.flags & 0x0200) {
  17789. state.check = crc32(state.check, input, copy, next);
  17790. }
  17791. have -= copy;
  17792. next += copy;
  17793. state.length -= copy;
  17794. }
  17795. if (state.length) { break inf_leave; }
  17796. }
  17797. state.length = 0;
  17798. state.mode = NAME;
  17799. /* falls through */
  17800. case NAME:
  17801. if (state.flags & 0x0800) {
  17802. if (have === 0) { break inf_leave; }
  17803. copy = 0;
  17804. do {
  17805. // TODO: 2 or 1 bytes?
  17806. len = input[next + copy++];
  17807. /* use constant limit because in js we should not preallocate memory */
  17808. if (state.head && len &&
  17809. (state.length < 65536 /*state.head.name_max*/)) {
  17810. state.head.name += String.fromCharCode(len);
  17811. }
  17812. } while (len && copy < have);
  17813. if (state.flags & 0x0200) {
  17814. state.check = crc32(state.check, input, copy, next);
  17815. }
  17816. have -= copy;
  17817. next += copy;
  17818. if (len) { break inf_leave; }
  17819. }
  17820. else if (state.head) {
  17821. state.head.name = null;
  17822. }
  17823. state.length = 0;
  17824. state.mode = COMMENT;
  17825. /* falls through */
  17826. case COMMENT:
  17827. if (state.flags & 0x1000) {
  17828. if (have === 0) { break inf_leave; }
  17829. copy = 0;
  17830. do {
  17831. len = input[next + copy++];
  17832. /* use constant limit because in js we should not preallocate memory */
  17833. if (state.head && len &&
  17834. (state.length < 65536 /*state.head.comm_max*/)) {
  17835. state.head.comment += String.fromCharCode(len);
  17836. }
  17837. } while (len && copy < have);
  17838. if (state.flags & 0x0200) {
  17839. state.check = crc32(state.check, input, copy, next);
  17840. }
  17841. have -= copy;
  17842. next += copy;
  17843. if (len) { break inf_leave; }
  17844. }
  17845. else if (state.head) {
  17846. state.head.comment = null;
  17847. }
  17848. state.mode = HCRC;
  17849. /* falls through */
  17850. case HCRC:
  17851. if (state.flags & 0x0200) {
  17852. //=== NEEDBITS(16); */
  17853. while (bits < 16) {
  17854. if (have === 0) { break inf_leave; }
  17855. have--;
  17856. hold += input[next++] << bits;
  17857. bits += 8;
  17858. }
  17859. //===//
  17860. if (hold !== (state.check & 0xffff)) {
  17861. strm.msg = 'header crc mismatch';
  17862. state.mode = BAD;
  17863. break;
  17864. }
  17865. //=== INITBITS();
  17866. hold = 0;
  17867. bits = 0;
  17868. //===//
  17869. }
  17870. if (state.head) {
  17871. state.head.hcrc = ((state.flags >> 9) & 1);
  17872. state.head.done = true;
  17873. }
  17874. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  17875. state.mode = TYPE;
  17876. break;
  17877. case DICTID:
  17878. //=== NEEDBITS(32); */
  17879. while (bits < 32) {
  17880. if (have === 0) { break inf_leave; }
  17881. have--;
  17882. hold += input[next++] << bits;
  17883. bits += 8;
  17884. }
  17885. //===//
  17886. strm.adler = state.check = ZSWAP32(hold);
  17887. //=== INITBITS();
  17888. hold = 0;
  17889. bits = 0;
  17890. //===//
  17891. state.mode = DICT;
  17892. /* falls through */
  17893. case DICT:
  17894. if (state.havedict === 0) {
  17895. //--- RESTORE() ---
  17896. strm.next_out = put;
  17897. strm.avail_out = left;
  17898. strm.next_in = next;
  17899. strm.avail_in = have;
  17900. state.hold = hold;
  17901. state.bits = bits;
  17902. //---
  17903. return Z_NEED_DICT;
  17904. }
  17905. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17906. state.mode = TYPE;
  17907. /* falls through */
  17908. case TYPE:
  17909. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  17910. /* falls through */
  17911. case TYPEDO:
  17912. if (state.last) {
  17913. //--- BYTEBITS() ---//
  17914. hold >>>= bits & 7;
  17915. bits -= bits & 7;
  17916. //---//
  17917. state.mode = CHECK;
  17918. break;
  17919. }
  17920. //=== NEEDBITS(3); */
  17921. while (bits < 3) {
  17922. if (have === 0) { break inf_leave; }
  17923. have--;
  17924. hold += input[next++] << bits;
  17925. bits += 8;
  17926. }
  17927. //===//
  17928. state.last = (hold & 0x01)/*BITS(1)*/;
  17929. //--- DROPBITS(1) ---//
  17930. hold >>>= 1;
  17931. bits -= 1;
  17932. //---//
  17933. switch ((hold & 0x03)/*BITS(2)*/) {
  17934. case 0: /* stored block */
  17935. //Tracev((stderr, "inflate: stored block%s\n",
  17936. // state.last ? " (last)" : ""));
  17937. state.mode = STORED;
  17938. break;
  17939. case 1: /* fixed block */
  17940. fixedtables(state);
  17941. //Tracev((stderr, "inflate: fixed codes block%s\n",
  17942. // state.last ? " (last)" : ""));
  17943. state.mode = LEN_; /* decode codes */
  17944. if (flush === Z_TREES) {
  17945. //--- DROPBITS(2) ---//
  17946. hold >>>= 2;
  17947. bits -= 2;
  17948. //---//
  17949. break inf_leave;
  17950. }
  17951. break;
  17952. case 2: /* dynamic block */
  17953. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  17954. // state.last ? " (last)" : ""));
  17955. state.mode = TABLE;
  17956. break;
  17957. case 3:
  17958. strm.msg = 'invalid block type';
  17959. state.mode = BAD;
  17960. }
  17961. //--- DROPBITS(2) ---//
  17962. hold >>>= 2;
  17963. bits -= 2;
  17964. //---//
  17965. break;
  17966. case STORED:
  17967. //--- BYTEBITS() ---// /* go to byte boundary */
  17968. hold >>>= bits & 7;
  17969. bits -= bits & 7;
  17970. //---//
  17971. //=== NEEDBITS(32); */
  17972. while (bits < 32) {
  17973. if (have === 0) { break inf_leave; }
  17974. have--;
  17975. hold += input[next++] << bits;
  17976. bits += 8;
  17977. }
  17978. //===//
  17979. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  17980. strm.msg = 'invalid stored block lengths';
  17981. state.mode = BAD;
  17982. break;
  17983. }
  17984. state.length = hold & 0xffff;
  17985. //Tracev((stderr, "inflate: stored length %u\n",
  17986. // state.length));
  17987. //=== INITBITS();
  17988. hold = 0;
  17989. bits = 0;
  17990. //===//
  17991. state.mode = COPY_;
  17992. if (flush === Z_TREES) { break inf_leave; }
  17993. /* falls through */
  17994. case COPY_:
  17995. state.mode = COPY;
  17996. /* falls through */
  17997. case COPY:
  17998. copy = state.length;
  17999. if (copy) {
  18000. if (copy > have) { copy = have; }
  18001. if (copy > left) { copy = left; }
  18002. if (copy === 0) { break inf_leave; }
  18003. //--- zmemcpy(put, next, copy); ---
  18004. utils.arraySet(output, input, next, copy, put);
  18005. //---//
  18006. have -= copy;
  18007. next += copy;
  18008. left -= copy;
  18009. put += copy;
  18010. state.length -= copy;
  18011. break;
  18012. }
  18013. //Tracev((stderr, "inflate: stored end\n"));
  18014. state.mode = TYPE;
  18015. break;
  18016. case TABLE:
  18017. //=== NEEDBITS(14); */
  18018. while (bits < 14) {
  18019. if (have === 0) { break inf_leave; }
  18020. have--;
  18021. hold += input[next++] << bits;
  18022. bits += 8;
  18023. }
  18024. //===//
  18025. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18026. //--- DROPBITS(5) ---//
  18027. hold >>>= 5;
  18028. bits -= 5;
  18029. //---//
  18030. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18031. //--- DROPBITS(5) ---//
  18032. hold >>>= 5;
  18033. bits -= 5;
  18034. //---//
  18035. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18036. //--- DROPBITS(4) ---//
  18037. hold >>>= 4;
  18038. bits -= 4;
  18039. //---//
  18040. //#ifndef PKZIP_BUG_WORKAROUND
  18041. if (state.nlen > 286 || state.ndist > 30) {
  18042. strm.msg = 'too many length or distance symbols';
  18043. state.mode = BAD;
  18044. break;
  18045. }
  18046. //#endif
  18047. //Tracev((stderr, "inflate: table sizes ok\n"));
  18048. state.have = 0;
  18049. state.mode = LENLENS;
  18050. /* falls through */
  18051. case LENLENS:
  18052. while (state.have < state.ncode) {
  18053. //=== NEEDBITS(3);
  18054. while (bits < 3) {
  18055. if (have === 0) { break inf_leave; }
  18056. have--;
  18057. hold += input[next++] << bits;
  18058. bits += 8;
  18059. }
  18060. //===//
  18061. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18062. //--- DROPBITS(3) ---//
  18063. hold >>>= 3;
  18064. bits -= 3;
  18065. //---//
  18066. }
  18067. while (state.have < 19) {
  18068. state.lens[order[state.have++]] = 0;
  18069. }
  18070. // We have separate tables & no pointers. 2 commented lines below not needed.
  18071. //state.next = state.codes;
  18072. //state.lencode = state.next;
  18073. // Switch to use dynamic table
  18074. state.lencode = state.lendyn;
  18075. state.lenbits = 7;
  18076. opts = {bits: state.lenbits};
  18077. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18078. state.lenbits = opts.bits;
  18079. if (ret) {
  18080. strm.msg = 'invalid code lengths set';
  18081. state.mode = BAD;
  18082. break;
  18083. }
  18084. //Tracev((stderr, "inflate: code lengths ok\n"));
  18085. state.have = 0;
  18086. state.mode = CODELENS;
  18087. /* falls through */
  18088. case CODELENS:
  18089. while (state.have < state.nlen + state.ndist) {
  18090. for (;;) {
  18091. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18092. here_bits = here >>> 24;
  18093. here_op = (here >>> 16) & 0xff;
  18094. here_val = here & 0xffff;
  18095. if ((here_bits) <= bits) { break; }
  18096. //--- PULLBYTE() ---//
  18097. if (have === 0) { break inf_leave; }
  18098. have--;
  18099. hold += input[next++] << bits;
  18100. bits += 8;
  18101. //---//
  18102. }
  18103. if (here_val < 16) {
  18104. //--- DROPBITS(here.bits) ---//
  18105. hold >>>= here_bits;
  18106. bits -= here_bits;
  18107. //---//
  18108. state.lens[state.have++] = here_val;
  18109. }
  18110. else {
  18111. if (here_val === 16) {
  18112. //=== NEEDBITS(here.bits + 2);
  18113. n = here_bits + 2;
  18114. while (bits < n) {
  18115. if (have === 0) { break inf_leave; }
  18116. have--;
  18117. hold += input[next++] << bits;
  18118. bits += 8;
  18119. }
  18120. //===//
  18121. //--- DROPBITS(here.bits) ---//
  18122. hold >>>= here_bits;
  18123. bits -= here_bits;
  18124. //---//
  18125. if (state.have === 0) {
  18126. strm.msg = 'invalid bit length repeat';
  18127. state.mode = BAD;
  18128. break;
  18129. }
  18130. len = state.lens[state.have - 1];
  18131. copy = 3 + (hold & 0x03);//BITS(2);
  18132. //--- DROPBITS(2) ---//
  18133. hold >>>= 2;
  18134. bits -= 2;
  18135. //---//
  18136. }
  18137. else if (here_val === 17) {
  18138. //=== NEEDBITS(here.bits + 3);
  18139. n = here_bits + 3;
  18140. while (bits < n) {
  18141. if (have === 0) { break inf_leave; }
  18142. have--;
  18143. hold += input[next++] << bits;
  18144. bits += 8;
  18145. }
  18146. //===//
  18147. //--- DROPBITS(here.bits) ---//
  18148. hold >>>= here_bits;
  18149. bits -= here_bits;
  18150. //---//
  18151. len = 0;
  18152. copy = 3 + (hold & 0x07);//BITS(3);
  18153. //--- DROPBITS(3) ---//
  18154. hold >>>= 3;
  18155. bits -= 3;
  18156. //---//
  18157. }
  18158. else {
  18159. //=== NEEDBITS(here.bits + 7);
  18160. n = here_bits + 7;
  18161. while (bits < n) {
  18162. if (have === 0) { break inf_leave; }
  18163. have--;
  18164. hold += input[next++] << bits;
  18165. bits += 8;
  18166. }
  18167. //===//
  18168. //--- DROPBITS(here.bits) ---//
  18169. hold >>>= here_bits;
  18170. bits -= here_bits;
  18171. //---//
  18172. len = 0;
  18173. copy = 11 + (hold & 0x7f);//BITS(7);
  18174. //--- DROPBITS(7) ---//
  18175. hold >>>= 7;
  18176. bits -= 7;
  18177. //---//
  18178. }
  18179. if (state.have + copy > state.nlen + state.ndist) {
  18180. strm.msg = 'invalid bit length repeat';
  18181. state.mode = BAD;
  18182. break;
  18183. }
  18184. while (copy--) {
  18185. state.lens[state.have++] = len;
  18186. }
  18187. }
  18188. }
  18189. /* handle error breaks in while */
  18190. if (state.mode === BAD) { break; }
  18191. /* check for end-of-block code (better have one) */
  18192. if (state.lens[256] === 0) {
  18193. strm.msg = 'invalid code -- missing end-of-block';
  18194. state.mode = BAD;
  18195. break;
  18196. }
  18197. /* build code tables -- note: do not change the lenbits or distbits
  18198. values here (9 and 6) without reading the comments in inftrees.h
  18199. concerning the ENOUGH constants, which depend on those values */
  18200. state.lenbits = 9;
  18201. opts = {bits: state.lenbits};
  18202. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18203. // We have separate tables & no pointers. 2 commented lines below not needed.
  18204. // state.next_index = opts.table_index;
  18205. state.lenbits = opts.bits;
  18206. // state.lencode = state.next;
  18207. if (ret) {
  18208. strm.msg = 'invalid literal/lengths set';
  18209. state.mode = BAD;
  18210. break;
  18211. }
  18212. state.distbits = 6;
  18213. //state.distcode.copy(state.codes);
  18214. // Switch to use dynamic table
  18215. state.distcode = state.distdyn;
  18216. opts = {bits: state.distbits};
  18217. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18218. // We have separate tables & no pointers. 2 commented lines below not needed.
  18219. // state.next_index = opts.table_index;
  18220. state.distbits = opts.bits;
  18221. // state.distcode = state.next;
  18222. if (ret) {
  18223. strm.msg = 'invalid distances set';
  18224. state.mode = BAD;
  18225. break;
  18226. }
  18227. //Tracev((stderr, 'inflate: codes ok\n'));
  18228. state.mode = LEN_;
  18229. if (flush === Z_TREES) { break inf_leave; }
  18230. /* falls through */
  18231. case LEN_:
  18232. state.mode = LEN;
  18233. /* falls through */
  18234. case LEN:
  18235. if (have >= 6 && left >= 258) {
  18236. //--- RESTORE() ---
  18237. strm.next_out = put;
  18238. strm.avail_out = left;
  18239. strm.next_in = next;
  18240. strm.avail_in = have;
  18241. state.hold = hold;
  18242. state.bits = bits;
  18243. //---
  18244. inflate_fast(strm, _out);
  18245. //--- LOAD() ---
  18246. put = strm.next_out;
  18247. output = strm.output;
  18248. left = strm.avail_out;
  18249. next = strm.next_in;
  18250. input = strm.input;
  18251. have = strm.avail_in;
  18252. hold = state.hold;
  18253. bits = state.bits;
  18254. //---
  18255. if (state.mode === TYPE) {
  18256. state.back = -1;
  18257. }
  18258. break;
  18259. }
  18260. state.back = 0;
  18261. for (;;) {
  18262. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18263. here_bits = here >>> 24;
  18264. here_op = (here >>> 16) & 0xff;
  18265. here_val = here & 0xffff;
  18266. if (here_bits <= bits) { break; }
  18267. //--- PULLBYTE() ---//
  18268. if (have === 0) { break inf_leave; }
  18269. have--;
  18270. hold += input[next++] << bits;
  18271. bits += 8;
  18272. //---//
  18273. }
  18274. if (here_op && (here_op & 0xf0) === 0) {
  18275. last_bits = here_bits;
  18276. last_op = here_op;
  18277. last_val = here_val;
  18278. for (;;) {
  18279. here = state.lencode[last_val +
  18280. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18281. here_bits = here >>> 24;
  18282. here_op = (here >>> 16) & 0xff;
  18283. here_val = here & 0xffff;
  18284. if ((last_bits + here_bits) <= bits) { break; }
  18285. //--- PULLBYTE() ---//
  18286. if (have === 0) { break inf_leave; }
  18287. have--;
  18288. hold += input[next++] << bits;
  18289. bits += 8;
  18290. //---//
  18291. }
  18292. //--- DROPBITS(last.bits) ---//
  18293. hold >>>= last_bits;
  18294. bits -= last_bits;
  18295. //---//
  18296. state.back += last_bits;
  18297. }
  18298. //--- DROPBITS(here.bits) ---//
  18299. hold >>>= here_bits;
  18300. bits -= here_bits;
  18301. //---//
  18302. state.back += here_bits;
  18303. state.length = here_val;
  18304. if (here_op === 0) {
  18305. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18306. // "inflate: literal '%c'\n" :
  18307. // "inflate: literal 0x%02x\n", here.val));
  18308. state.mode = LIT;
  18309. break;
  18310. }
  18311. if (here_op & 32) {
  18312. //Tracevv((stderr, "inflate: end of block\n"));
  18313. state.back = -1;
  18314. state.mode = TYPE;
  18315. break;
  18316. }
  18317. if (here_op & 64) {
  18318. strm.msg = 'invalid literal/length code';
  18319. state.mode = BAD;
  18320. break;
  18321. }
  18322. state.extra = here_op & 15;
  18323. state.mode = LENEXT;
  18324. /* falls through */
  18325. case LENEXT:
  18326. if (state.extra) {
  18327. //=== NEEDBITS(state.extra);
  18328. n = state.extra;
  18329. while (bits < n) {
  18330. if (have === 0) { break inf_leave; }
  18331. have--;
  18332. hold += input[next++] << bits;
  18333. bits += 8;
  18334. }
  18335. //===//
  18336. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18337. //--- DROPBITS(state.extra) ---//
  18338. hold >>>= state.extra;
  18339. bits -= state.extra;
  18340. //---//
  18341. state.back += state.extra;
  18342. }
  18343. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18344. state.was = state.length;
  18345. state.mode = DIST;
  18346. /* falls through */
  18347. case DIST:
  18348. for (;;) {
  18349. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18350. here_bits = here >>> 24;
  18351. here_op = (here >>> 16) & 0xff;
  18352. here_val = here & 0xffff;
  18353. if ((here_bits) <= bits) { break; }
  18354. //--- PULLBYTE() ---//
  18355. if (have === 0) { break inf_leave; }
  18356. have--;
  18357. hold += input[next++] << bits;
  18358. bits += 8;
  18359. //---//
  18360. }
  18361. if ((here_op & 0xf0) === 0) {
  18362. last_bits = here_bits;
  18363. last_op = here_op;
  18364. last_val = here_val;
  18365. for (;;) {
  18366. here = state.distcode[last_val +
  18367. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18368. here_bits = here >>> 24;
  18369. here_op = (here >>> 16) & 0xff;
  18370. here_val = here & 0xffff;
  18371. if ((last_bits + here_bits) <= bits) { break; }
  18372. //--- PULLBYTE() ---//
  18373. if (have === 0) { break inf_leave; }
  18374. have--;
  18375. hold += input[next++] << bits;
  18376. bits += 8;
  18377. //---//
  18378. }
  18379. //--- DROPBITS(last.bits) ---//
  18380. hold >>>= last_bits;
  18381. bits -= last_bits;
  18382. //---//
  18383. state.back += last_bits;
  18384. }
  18385. //--- DROPBITS(here.bits) ---//
  18386. hold >>>= here_bits;
  18387. bits -= here_bits;
  18388. //---//
  18389. state.back += here_bits;
  18390. if (here_op & 64) {
  18391. strm.msg = 'invalid distance code';
  18392. state.mode = BAD;
  18393. break;
  18394. }
  18395. state.offset = here_val;
  18396. state.extra = (here_op) & 15;
  18397. state.mode = DISTEXT;
  18398. /* falls through */
  18399. case DISTEXT:
  18400. if (state.extra) {
  18401. //=== NEEDBITS(state.extra);
  18402. n = state.extra;
  18403. while (bits < n) {
  18404. if (have === 0) { break inf_leave; }
  18405. have--;
  18406. hold += input[next++] << bits;
  18407. bits += 8;
  18408. }
  18409. //===//
  18410. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18411. //--- DROPBITS(state.extra) ---//
  18412. hold >>>= state.extra;
  18413. bits -= state.extra;
  18414. //---//
  18415. state.back += state.extra;
  18416. }
  18417. //#ifdef INFLATE_STRICT
  18418. if (state.offset > state.dmax) {
  18419. strm.msg = 'invalid distance too far back';
  18420. state.mode = BAD;
  18421. break;
  18422. }
  18423. //#endif
  18424. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18425. state.mode = MATCH;
  18426. /* falls through */
  18427. case MATCH:
  18428. if (left === 0) { break inf_leave; }
  18429. copy = _out - left;
  18430. if (state.offset > copy) { /* copy from window */
  18431. copy = state.offset - copy;
  18432. if (copy > state.whave) {
  18433. if (state.sane) {
  18434. strm.msg = 'invalid distance too far back';
  18435. state.mode = BAD;
  18436. break;
  18437. }
  18438. // (!) This block is disabled in zlib defailts,
  18439. // don't enable it for binary compatibility
  18440. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18441. // Trace((stderr, "inflate.c too far\n"));
  18442. // copy -= state.whave;
  18443. // if (copy > state.length) { copy = state.length; }
  18444. // if (copy > left) { copy = left; }
  18445. // left -= copy;
  18446. // state.length -= copy;
  18447. // do {
  18448. // output[put++] = 0;
  18449. // } while (--copy);
  18450. // if (state.length === 0) { state.mode = LEN; }
  18451. // break;
  18452. //#endif
  18453. }
  18454. if (copy > state.wnext) {
  18455. copy -= state.wnext;
  18456. from = state.wsize - copy;
  18457. }
  18458. else {
  18459. from = state.wnext - copy;
  18460. }
  18461. if (copy > state.length) { copy = state.length; }
  18462. from_source = state.window;
  18463. }
  18464. else { /* copy from output */
  18465. from_source = output;
  18466. from = put - state.offset;
  18467. copy = state.length;
  18468. }
  18469. if (copy > left) { copy = left; }
  18470. left -= copy;
  18471. state.length -= copy;
  18472. do {
  18473. output[put++] = from_source[from++];
  18474. } while (--copy);
  18475. if (state.length === 0) { state.mode = LEN; }
  18476. break;
  18477. case LIT:
  18478. if (left === 0) { break inf_leave; }
  18479. output[put++] = state.length;
  18480. left--;
  18481. state.mode = LEN;
  18482. break;
  18483. case CHECK:
  18484. if (state.wrap) {
  18485. //=== NEEDBITS(32);
  18486. while (bits < 32) {
  18487. if (have === 0) { break inf_leave; }
  18488. have--;
  18489. // Use '|' insdead of '+' to make sure that result is signed
  18490. hold |= input[next++] << bits;
  18491. bits += 8;
  18492. }
  18493. //===//
  18494. _out -= left;
  18495. strm.total_out += _out;
  18496. state.total += _out;
  18497. if (_out) {
  18498. strm.adler = state.check =
  18499. /*UPDATE(state.check, put - _out, _out);*/
  18500. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18501. }
  18502. _out = left;
  18503. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18504. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18505. strm.msg = 'incorrect data check';
  18506. state.mode = BAD;
  18507. break;
  18508. }
  18509. //=== INITBITS();
  18510. hold = 0;
  18511. bits = 0;
  18512. //===//
  18513. //Tracev((stderr, "inflate: check matches trailer\n"));
  18514. }
  18515. state.mode = LENGTH;
  18516. /* falls through */
  18517. case LENGTH:
  18518. if (state.wrap && state.flags) {
  18519. //=== NEEDBITS(32);
  18520. while (bits < 32) {
  18521. if (have === 0) { break inf_leave; }
  18522. have--;
  18523. hold += input[next++] << bits;
  18524. bits += 8;
  18525. }
  18526. //===//
  18527. if (hold !== (state.total & 0xffffffff)) {
  18528. strm.msg = 'incorrect length check';
  18529. state.mode = BAD;
  18530. break;
  18531. }
  18532. //=== INITBITS();
  18533. hold = 0;
  18534. bits = 0;
  18535. //===//
  18536. //Tracev((stderr, "inflate: length matches trailer\n"));
  18537. }
  18538. state.mode = DONE;
  18539. /* falls through */
  18540. case DONE:
  18541. ret = Z_STREAM_END;
  18542. break inf_leave;
  18543. case BAD:
  18544. ret = Z_DATA_ERROR;
  18545. break inf_leave;
  18546. case MEM:
  18547. return Z_MEM_ERROR;
  18548. case SYNC:
  18549. /* falls through */
  18550. default:
  18551. return Z_STREAM_ERROR;
  18552. }
  18553. }
  18554. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18555. /*
  18556. Return from inflate(), updating the total counts and the check value.
  18557. If there was no progress during the inflate() call, return a buffer
  18558. error. Call updatewindow() to create and/or update the window state.
  18559. Note: a memory error from inflate() is non-recoverable.
  18560. */
  18561. //--- RESTORE() ---
  18562. strm.next_out = put;
  18563. strm.avail_out = left;
  18564. strm.next_in = next;
  18565. strm.avail_in = have;
  18566. state.hold = hold;
  18567. state.bits = bits;
  18568. //---
  18569. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18570. (state.mode < CHECK || flush !== Z_FINISH))) {
  18571. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18572. state.mode = MEM;
  18573. return Z_MEM_ERROR;
  18574. }
  18575. }
  18576. _in -= strm.avail_in;
  18577. _out -= strm.avail_out;
  18578. strm.total_in += _in;
  18579. strm.total_out += _out;
  18580. state.total += _out;
  18581. if (state.wrap && _out) {
  18582. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18583. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18584. }
  18585. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18586. (state.mode === TYPE ? 128 : 0) +
  18587. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18588. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18589. ret = Z_BUF_ERROR;
  18590. }
  18591. return ret;
  18592. }
  18593. function inflateEnd(strm) {
  18594. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18595. return Z_STREAM_ERROR;
  18596. }
  18597. var state = strm.state;
  18598. if (state.window) {
  18599. state.window = null;
  18600. }
  18601. strm.state = null;
  18602. return Z_OK;
  18603. }
  18604. function inflateGetHeader(strm, head) {
  18605. var state;
  18606. /* check state */
  18607. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18608. state = strm.state;
  18609. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18610. /* save header structure */
  18611. state.head = head;
  18612. head.done = false;
  18613. return Z_OK;
  18614. }
  18615. exports.inflateReset = inflateReset;
  18616. exports.inflateReset2 = inflateReset2;
  18617. exports.inflateResetKeep = inflateResetKeep;
  18618. exports.inflateInit = inflateInit;
  18619. exports.inflateInit2 = inflateInit2;
  18620. exports.inflate = inflate;
  18621. exports.inflateEnd = inflateEnd;
  18622. exports.inflateGetHeader = inflateGetHeader;
  18623. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18624. /* Not implemented
  18625. exports.inflateCopy = inflateCopy;
  18626. exports.inflateGetDictionary = inflateGetDictionary;
  18627. exports.inflateMark = inflateMark;
  18628. exports.inflatePrime = inflatePrime;
  18629. exports.inflateSetDictionary = inflateSetDictionary;
  18630. exports.inflateSync = inflateSync;
  18631. exports.inflateSyncPoint = inflateSyncPoint;
  18632. exports.inflateUndermine = inflateUndermine;
  18633. */
  18634. },{"../utils/common":54,"./adler32":56,"./crc32":58,"./inffast":61,"./inftrees":63}],63:[function(require,module,exports){
  18635. 'use strict';
  18636. var utils = require('../utils/common');
  18637. var MAXBITS = 15;
  18638. var ENOUGH_LENS = 852;
  18639. var ENOUGH_DISTS = 592;
  18640. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18641. var CODES = 0;
  18642. var LENS = 1;
  18643. var DISTS = 2;
  18644. var lbase = [ /* Length codes 257..285 base */
  18645. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18646. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18647. ];
  18648. var lext = [ /* Length codes 257..285 extra */
  18649. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18650. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18651. ];
  18652. var dbase = [ /* Distance codes 0..29 base */
  18653. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18654. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18655. 8193, 12289, 16385, 24577, 0, 0
  18656. ];
  18657. var dext = [ /* Distance codes 0..29 extra */
  18658. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18659. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18660. 28, 28, 29, 29, 64, 64
  18661. ];
  18662. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18663. {
  18664. var bits = opts.bits;
  18665. //here = opts.here; /* table entry for duplication */
  18666. var len = 0; /* a code's length in bits */
  18667. var sym = 0; /* index of code symbols */
  18668. var min = 0, max = 0; /* minimum and maximum code lengths */
  18669. var root = 0; /* number of index bits for root table */
  18670. var curr = 0; /* number of index bits for current table */
  18671. var drop = 0; /* code bits to drop for sub-table */
  18672. var left = 0; /* number of prefix codes available */
  18673. var used = 0; /* code entries in table used */
  18674. var huff = 0; /* Huffman code */
  18675. var incr; /* for incrementing code, index */
  18676. var fill; /* index for replicating entries */
  18677. var low; /* low bits for current root entry */
  18678. var mask; /* mask for low root bits */
  18679. var next; /* next available space in table */
  18680. var base = null; /* base value table to use */
  18681. var base_index = 0;
  18682. // var shoextra; /* extra bits table to use */
  18683. var end; /* use base and extra for symbol > end */
  18684. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18685. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18686. var extra = null;
  18687. var extra_index = 0;
  18688. var here_bits, here_op, here_val;
  18689. /*
  18690. Process a set of code lengths to create a canonical Huffman code. The
  18691. code lengths are lens[0..codes-1]. Each length corresponds to the
  18692. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18693. symbols by length from short to long, and retaining the symbol order
  18694. for codes with equal lengths. Then the code starts with all zero bits
  18695. for the first code of the shortest length, and the codes are integer
  18696. increments for the same length, and zeros are appended as the length
  18697. increases. For the deflate format, these bits are stored backwards
  18698. from their more natural integer increment ordering, and so when the
  18699. decoding tables are built in the large loop below, the integer codes
  18700. are incremented backwards.
  18701. This routine assumes, but does not check, that all of the entries in
  18702. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18703. 1..MAXBITS is interpreted as that code length. zero means that that
  18704. symbol does not occur in this code.
  18705. The codes are sorted by computing a count of codes for each length,
  18706. creating from that a table of starting indices for each length in the
  18707. sorted table, and then entering the symbols in order in the sorted
  18708. table. The sorted table is work[], with that space being provided by
  18709. the caller.
  18710. The length counts are used for other purposes as well, i.e. finding
  18711. the minimum and maximum length codes, determining if there are any
  18712. codes at all, checking for a valid set of lengths, and looking ahead
  18713. at length counts to determine sub-table sizes when building the
  18714. decoding tables.
  18715. */
  18716. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18717. for (len = 0; len <= MAXBITS; len++) {
  18718. count[len] = 0;
  18719. }
  18720. for (sym = 0; sym < codes; sym++) {
  18721. count[lens[lens_index + sym]]++;
  18722. }
  18723. /* bound code lengths, force root to be within code lengths */
  18724. root = bits;
  18725. for (max = MAXBITS; max >= 1; max--) {
  18726. if (count[max] !== 0) { break; }
  18727. }
  18728. if (root > max) {
  18729. root = max;
  18730. }
  18731. if (max === 0) { /* no symbols to code at all */
  18732. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18733. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18734. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18735. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18736. //table.op[opts.table_index] = 64;
  18737. //table.bits[opts.table_index] = 1;
  18738. //table.val[opts.table_index++] = 0;
  18739. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18740. opts.bits = 1;
  18741. return 0; /* no symbols, but wait for decoding to report error */
  18742. }
  18743. for (min = 1; min < max; min++) {
  18744. if (count[min] !== 0) { break; }
  18745. }
  18746. if (root < min) {
  18747. root = min;
  18748. }
  18749. /* check for an over-subscribed or incomplete set of lengths */
  18750. left = 1;
  18751. for (len = 1; len <= MAXBITS; len++) {
  18752. left <<= 1;
  18753. left -= count[len];
  18754. if (left < 0) {
  18755. return -1;
  18756. } /* over-subscribed */
  18757. }
  18758. if (left > 0 && (type === CODES || max !== 1)) {
  18759. return -1; /* incomplete set */
  18760. }
  18761. /* generate offsets into symbol table for each length for sorting */
  18762. offs[1] = 0;
  18763. for (len = 1; len < MAXBITS; len++) {
  18764. offs[len + 1] = offs[len] + count[len];
  18765. }
  18766. /* sort symbols by length, by symbol order within each length */
  18767. for (sym = 0; sym < codes; sym++) {
  18768. if (lens[lens_index + sym] !== 0) {
  18769. work[offs[lens[lens_index + sym]]++] = sym;
  18770. }
  18771. }
  18772. /*
  18773. Create and fill in decoding tables. In this loop, the table being
  18774. filled is at next and has curr index bits. The code being used is huff
  18775. with length len. That code is converted to an index by dropping drop
  18776. bits off of the bottom. For codes where len is less than drop + curr,
  18777. those top drop + curr - len bits are incremented through all values to
  18778. fill the table with replicated entries.
  18779. root is the number of index bits for the root table. When len exceeds
  18780. root, sub-tables are created pointed to by the root entry with an index
  18781. of the low root bits of huff. This is saved in low to check for when a
  18782. new sub-table should be started. drop is zero when the root table is
  18783. being filled, and drop is root when sub-tables are being filled.
  18784. When a new sub-table is needed, it is necessary to look ahead in the
  18785. code lengths to determine what size sub-table is needed. The length
  18786. counts are used for this, and so count[] is decremented as codes are
  18787. entered in the tables.
  18788. used keeps track of how many table entries have been allocated from the
  18789. provided *table space. It is checked for LENS and DIST tables against
  18790. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18791. the initial root table size constants. See the comments in inftrees.h
  18792. for more information.
  18793. sym increments through all symbols, and the loop terminates when
  18794. all codes of length max, i.e. all codes, have been processed. This
  18795. routine permits incomplete codes, so another loop after this one fills
  18796. in the rest of the decoding tables with invalid code markers.
  18797. */
  18798. /* set up for code type */
  18799. // poor man optimization - use if-else instead of switch,
  18800. // to avoid deopts in old v8
  18801. if (type === CODES) {
  18802. base = extra = work; /* dummy value--not used */
  18803. end = 19;
  18804. } else if (type === LENS) {
  18805. base = lbase;
  18806. base_index -= 257;
  18807. extra = lext;
  18808. extra_index -= 257;
  18809. end = 256;
  18810. } else { /* DISTS */
  18811. base = dbase;
  18812. extra = dext;
  18813. end = -1;
  18814. }
  18815. /* initialize opts for loop */
  18816. huff = 0; /* starting code */
  18817. sym = 0; /* starting code symbol */
  18818. len = min; /* starting code length */
  18819. next = table_index; /* current table to fill in */
  18820. curr = root; /* current table index bits */
  18821. drop = 0; /* current bits to drop from code for index */
  18822. low = -1; /* trigger new sub-table when len > root */
  18823. used = 1 << root; /* use root table entries */
  18824. mask = used - 1; /* mask for comparing low */
  18825. /* check available table space */
  18826. if ((type === LENS && used > ENOUGH_LENS) ||
  18827. (type === DISTS && used > ENOUGH_DISTS)) {
  18828. return 1;
  18829. }
  18830. var i=0;
  18831. /* process all codes and make table entries */
  18832. for (;;) {
  18833. i++;
  18834. /* create table entry */
  18835. here_bits = len - drop;
  18836. if (work[sym] < end) {
  18837. here_op = 0;
  18838. here_val = work[sym];
  18839. }
  18840. else if (work[sym] > end) {
  18841. here_op = extra[extra_index + work[sym]];
  18842. here_val = base[base_index + work[sym]];
  18843. }
  18844. else {
  18845. here_op = 32 + 64; /* end of block */
  18846. here_val = 0;
  18847. }
  18848. /* replicate for those indices with low len bits equal to huff */
  18849. incr = 1 << (len - drop);
  18850. fill = 1 << curr;
  18851. min = fill; /* save offset to next table */
  18852. do {
  18853. fill -= incr;
  18854. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  18855. } while (fill !== 0);
  18856. /* backwards increment the len-bit code huff */
  18857. incr = 1 << (len - 1);
  18858. while (huff & incr) {
  18859. incr >>= 1;
  18860. }
  18861. if (incr !== 0) {
  18862. huff &= incr - 1;
  18863. huff += incr;
  18864. } else {
  18865. huff = 0;
  18866. }
  18867. /* go to next symbol, update count, len */
  18868. sym++;
  18869. if (--count[len] === 0) {
  18870. if (len === max) { break; }
  18871. len = lens[lens_index + work[sym]];
  18872. }
  18873. /* create new sub-table if needed */
  18874. if (len > root && (huff & mask) !== low) {
  18875. /* if first time, transition to sub-tables */
  18876. if (drop === 0) {
  18877. drop = root;
  18878. }
  18879. /* increment past last table */
  18880. next += min; /* here min is 1 << curr */
  18881. /* determine length of next table */
  18882. curr = len - drop;
  18883. left = 1 << curr;
  18884. while (curr + drop < max) {
  18885. left -= count[curr + drop];
  18886. if (left <= 0) { break; }
  18887. curr++;
  18888. left <<= 1;
  18889. }
  18890. /* check for enough space */
  18891. used += 1 << curr;
  18892. if ((type === LENS && used > ENOUGH_LENS) ||
  18893. (type === DISTS && used > ENOUGH_DISTS)) {
  18894. return 1;
  18895. }
  18896. /* point entry in root table to sub-table */
  18897. low = huff & mask;
  18898. /*table.op[low] = curr;
  18899. table.bits[low] = root;
  18900. table.val[low] = next - opts.table_index;*/
  18901. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  18902. }
  18903. }
  18904. /* fill in remaining table entry if code is incomplete (guaranteed to have
  18905. at most one remaining entry, since if the code is incomplete, the
  18906. maximum code length that was allowed to get this far is one bit) */
  18907. if (huff !== 0) {
  18908. //table.op[next + huff] = 64; /* invalid code marker */
  18909. //table.bits[next + huff] = len - drop;
  18910. //table.val[next + huff] = 0;
  18911. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  18912. }
  18913. /* set return parameters */
  18914. //opts.table_index += used;
  18915. opts.bits = root;
  18916. return 0;
  18917. };
  18918. },{"../utils/common":54}],64:[function(require,module,exports){
  18919. 'use strict';
  18920. module.exports = {
  18921. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  18922. '1': 'stream end', /* Z_STREAM_END 1 */
  18923. '0': '', /* Z_OK 0 */
  18924. '-1': 'file error', /* Z_ERRNO (-1) */
  18925. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  18926. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  18927. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  18928. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  18929. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  18930. };
  18931. },{}],65:[function(require,module,exports){
  18932. 'use strict';
  18933. var utils = require('../utils/common');
  18934. /* Public constants ==========================================================*/
  18935. /* ===========================================================================*/
  18936. //var Z_FILTERED = 1;
  18937. //var Z_HUFFMAN_ONLY = 2;
  18938. //var Z_RLE = 3;
  18939. var Z_FIXED = 4;
  18940. //var Z_DEFAULT_STRATEGY = 0;
  18941. /* Possible values of the data_type field (though see inflate()) */
  18942. var Z_BINARY = 0;
  18943. var Z_TEXT = 1;
  18944. //var Z_ASCII = 1; // = Z_TEXT
  18945. var Z_UNKNOWN = 2;
  18946. /*============================================================================*/
  18947. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  18948. // From zutil.h
  18949. var STORED_BLOCK = 0;
  18950. var STATIC_TREES = 1;
  18951. var DYN_TREES = 2;
  18952. /* The three kinds of block type */
  18953. var MIN_MATCH = 3;
  18954. var MAX_MATCH = 258;
  18955. /* The minimum and maximum match lengths */
  18956. // From deflate.h
  18957. /* ===========================================================================
  18958. * Internal compression state.
  18959. */
  18960. var LENGTH_CODES = 29;
  18961. /* number of length codes, not counting the special END_BLOCK code */
  18962. var LITERALS = 256;
  18963. /* number of literal bytes 0..255 */
  18964. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  18965. /* number of Literal or Length codes, including the END_BLOCK code */
  18966. var D_CODES = 30;
  18967. /* number of distance codes */
  18968. var BL_CODES = 19;
  18969. /* number of codes used to transfer the bit lengths */
  18970. var HEAP_SIZE = 2*L_CODES + 1;
  18971. /* maximum heap size */
  18972. var MAX_BITS = 15;
  18973. /* All codes must not exceed MAX_BITS bits */
  18974. var Buf_size = 16;
  18975. /* size of bit buffer in bi_buf */
  18976. /* ===========================================================================
  18977. * Constants
  18978. */
  18979. var MAX_BL_BITS = 7;
  18980. /* Bit length codes must not exceed MAX_BL_BITS bits */
  18981. var END_BLOCK = 256;
  18982. /* end of block literal code */
  18983. var REP_3_6 = 16;
  18984. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  18985. var REPZ_3_10 = 17;
  18986. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  18987. var REPZ_11_138 = 18;
  18988. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  18989. var extra_lbits = /* extra bits for each length code */
  18990. [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];
  18991. var extra_dbits = /* extra bits for each distance code */
  18992. [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];
  18993. var extra_blbits = /* extra bits for each bit length code */
  18994. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  18995. var bl_order =
  18996. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  18997. /* The lengths of the bit length codes are sent in order of decreasing
  18998. * probability, to avoid transmitting the lengths for unused bit length codes.
  18999. */
  19000. /* ===========================================================================
  19001. * Local data. These are initialized only once.
  19002. */
  19003. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19004. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19005. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19006. var static_ltree = new Array((L_CODES+2) * 2);
  19007. zero(static_ltree);
  19008. /* The static literal tree. Since the bit lengths are imposed, there is no
  19009. * need for the L_CODES extra codes used during heap construction. However
  19010. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19011. * below).
  19012. */
  19013. var static_dtree = new Array(D_CODES * 2);
  19014. zero(static_dtree);
  19015. /* The static distance tree. (Actually a trivial tree since all codes use
  19016. * 5 bits.)
  19017. */
  19018. var _dist_code = new Array(DIST_CODE_LEN);
  19019. zero(_dist_code);
  19020. /* Distance codes. The first 256 values correspond to the distances
  19021. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19022. * the 15 bit distances.
  19023. */
  19024. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  19025. zero(_length_code);
  19026. /* length code for each normalized match length (0 == MIN_MATCH) */
  19027. var base_length = new Array(LENGTH_CODES);
  19028. zero(base_length);
  19029. /* First normalized length for each code (0 = MIN_MATCH) */
  19030. var base_dist = new Array(D_CODES);
  19031. zero(base_dist);
  19032. /* First normalized distance for each code (0 = distance of 1) */
  19033. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19034. this.static_tree = static_tree; /* static tree or NULL */
  19035. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19036. this.extra_base = extra_base; /* base index for extra_bits */
  19037. this.elems = elems; /* max number of elements in the tree */
  19038. this.max_length = max_length; /* max bit length for the codes */
  19039. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19040. this.has_stree = static_tree && static_tree.length;
  19041. };
  19042. var static_l_desc;
  19043. var static_d_desc;
  19044. var static_bl_desc;
  19045. var TreeDesc = function(dyn_tree, stat_desc) {
  19046. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19047. this.max_code = 0; /* largest code with non zero frequency */
  19048. this.stat_desc = stat_desc; /* the corresponding static tree */
  19049. };
  19050. function d_code(dist) {
  19051. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19052. }
  19053. /* ===========================================================================
  19054. * Output a short LSB first on the stream.
  19055. * IN assertion: there is enough room in pendingBuf.
  19056. */
  19057. function put_short (s, w) {
  19058. // put_byte(s, (uch)((w) & 0xff));
  19059. // put_byte(s, (uch)((ush)(w) >> 8));
  19060. s.pending_buf[s.pending++] = (w) & 0xff;
  19061. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19062. }
  19063. /* ===========================================================================
  19064. * Send a value on a given number of bits.
  19065. * IN assertion: length <= 16 and value fits in length bits.
  19066. */
  19067. function send_bits(s, value, length) {
  19068. if (s.bi_valid > (Buf_size - length)) {
  19069. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19070. put_short(s, s.bi_buf);
  19071. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19072. s.bi_valid += length - Buf_size;
  19073. } else {
  19074. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19075. s.bi_valid += length;
  19076. }
  19077. }
  19078. function send_code(s, c, tree) {
  19079. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19080. }
  19081. /* ===========================================================================
  19082. * Reverse the first len bits of a code, using straightforward code (a faster
  19083. * method would use a table)
  19084. * IN assertion: 1 <= len <= 15
  19085. */
  19086. function bi_reverse(code, len) {
  19087. var res = 0;
  19088. do {
  19089. res |= code & 1;
  19090. code >>>= 1;
  19091. res <<= 1;
  19092. } while (--len > 0);
  19093. return res >>> 1;
  19094. }
  19095. /* ===========================================================================
  19096. * Flush the bit buffer, keeping at most 7 bits in it.
  19097. */
  19098. function bi_flush(s) {
  19099. if (s.bi_valid === 16) {
  19100. put_short(s, s.bi_buf);
  19101. s.bi_buf = 0;
  19102. s.bi_valid = 0;
  19103. } else if (s.bi_valid >= 8) {
  19104. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19105. s.bi_buf >>= 8;
  19106. s.bi_valid -= 8;
  19107. }
  19108. }
  19109. /* ===========================================================================
  19110. * Compute the optimal bit lengths for a tree and update the total bit length
  19111. * for the current block.
  19112. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19113. * above are the tree nodes sorted by increasing frequency.
  19114. * OUT assertions: the field len is set to the optimal bit length, the
  19115. * array bl_count contains the frequencies for each bit length.
  19116. * The length opt_len is updated; static_len is also updated if stree is
  19117. * not null.
  19118. */
  19119. function gen_bitlen(s, desc)
  19120. // deflate_state *s;
  19121. // tree_desc *desc; /* the tree descriptor */
  19122. {
  19123. var tree = desc.dyn_tree;
  19124. var max_code = desc.max_code;
  19125. var stree = desc.stat_desc.static_tree;
  19126. var has_stree = desc.stat_desc.has_stree;
  19127. var extra = desc.stat_desc.extra_bits;
  19128. var base = desc.stat_desc.extra_base;
  19129. var max_length = desc.stat_desc.max_length;
  19130. var h; /* heap index */
  19131. var n, m; /* iterate over the tree elements */
  19132. var bits; /* bit length */
  19133. var xbits; /* extra bits */
  19134. var f; /* frequency */
  19135. var overflow = 0; /* number of elements with bit length too large */
  19136. for (bits = 0; bits <= MAX_BITS; bits++) {
  19137. s.bl_count[bits] = 0;
  19138. }
  19139. /* In a first pass, compute the optimal bit lengths (which may
  19140. * overflow in the case of the bit length tree).
  19141. */
  19142. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19143. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19144. n = s.heap[h];
  19145. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19146. if (bits > max_length) {
  19147. bits = max_length;
  19148. overflow++;
  19149. }
  19150. tree[n*2 + 1]/*.Len*/ = bits;
  19151. /* We overwrite tree[n].Dad which is no longer needed */
  19152. if (n > max_code) { continue; } /* not a leaf node */
  19153. s.bl_count[bits]++;
  19154. xbits = 0;
  19155. if (n >= base) {
  19156. xbits = extra[n-base];
  19157. }
  19158. f = tree[n * 2]/*.Freq*/;
  19159. s.opt_len += f * (bits + xbits);
  19160. if (has_stree) {
  19161. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19162. }
  19163. }
  19164. if (overflow === 0) { return; }
  19165. // Trace((stderr,"\nbit length overflow\n"));
  19166. /* This happens for example on obj2 and pic of the Calgary corpus */
  19167. /* Find the first bit length which could increase: */
  19168. do {
  19169. bits = max_length-1;
  19170. while (s.bl_count[bits] === 0) { bits--; }
  19171. s.bl_count[bits]--; /* move one leaf down the tree */
  19172. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19173. s.bl_count[max_length]--;
  19174. /* The brother of the overflow item also moves one step up,
  19175. * but this does not affect bl_count[max_length]
  19176. */
  19177. overflow -= 2;
  19178. } while (overflow > 0);
  19179. /* Now recompute all bit lengths, scanning in increasing frequency.
  19180. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19181. * lengths instead of fixing only the wrong ones. This idea is taken
  19182. * from 'ar' written by Haruhiko Okumura.)
  19183. */
  19184. for (bits = max_length; bits !== 0; bits--) {
  19185. n = s.bl_count[bits];
  19186. while (n !== 0) {
  19187. m = s.heap[--h];
  19188. if (m > max_code) { continue; }
  19189. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19190. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19191. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19192. tree[m*2 + 1]/*.Len*/ = bits;
  19193. }
  19194. n--;
  19195. }
  19196. }
  19197. }
  19198. /* ===========================================================================
  19199. * Generate the codes for a given tree and bit counts (which need not be
  19200. * optimal).
  19201. * IN assertion: the array bl_count contains the bit length statistics for
  19202. * the given tree and the field len is set for all tree elements.
  19203. * OUT assertion: the field code is set for all tree elements of non
  19204. * zero code length.
  19205. */
  19206. function gen_codes(tree, max_code, bl_count)
  19207. // ct_data *tree; /* the tree to decorate */
  19208. // int max_code; /* largest code with non zero frequency */
  19209. // ushf *bl_count; /* number of codes at each bit length */
  19210. {
  19211. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19212. var code = 0; /* running code value */
  19213. var bits; /* bit index */
  19214. var n; /* code index */
  19215. /* The distribution counts are first used to generate the code values
  19216. * without bit reversal.
  19217. */
  19218. for (bits = 1; bits <= MAX_BITS; bits++) {
  19219. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19220. }
  19221. /* Check that the bit counts in bl_count are consistent. The last code
  19222. * must be all ones.
  19223. */
  19224. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19225. // "inconsistent bit counts");
  19226. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19227. for (n = 0; n <= max_code; n++) {
  19228. var len = tree[n*2 + 1]/*.Len*/;
  19229. if (len === 0) { continue; }
  19230. /* Now reverse the bits */
  19231. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19232. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19233. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19234. }
  19235. }
  19236. /* ===========================================================================
  19237. * Initialize the various 'constant' tables.
  19238. */
  19239. function tr_static_init() {
  19240. var n; /* iterates over tree elements */
  19241. var bits; /* bit counter */
  19242. var length; /* length value */
  19243. var code; /* code value */
  19244. var dist; /* distance index */
  19245. var bl_count = new Array(MAX_BITS+1);
  19246. /* number of codes at each bit length for an optimal tree */
  19247. // do check in _tr_init()
  19248. //if (static_init_done) return;
  19249. /* For some embedded targets, global variables are not initialized: */
  19250. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19251. static_l_desc.static_tree = static_ltree;
  19252. static_l_desc.extra_bits = extra_lbits;
  19253. static_d_desc.static_tree = static_dtree;
  19254. static_d_desc.extra_bits = extra_dbits;
  19255. static_bl_desc.extra_bits = extra_blbits;
  19256. #endif*/
  19257. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19258. length = 0;
  19259. for (code = 0; code < LENGTH_CODES-1; code++) {
  19260. base_length[code] = length;
  19261. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19262. _length_code[length++] = code;
  19263. }
  19264. }
  19265. //Assert (length == 256, "tr_static_init: length != 256");
  19266. /* Note that the length 255 (match length 258) can be represented
  19267. * in two different ways: code 284 + 5 bits or code 285, so we
  19268. * overwrite length_code[255] to use the best encoding:
  19269. */
  19270. _length_code[length-1] = code;
  19271. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19272. dist = 0;
  19273. for (code = 0 ; code < 16; code++) {
  19274. base_dist[code] = dist;
  19275. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19276. _dist_code[dist++] = code;
  19277. }
  19278. }
  19279. //Assert (dist == 256, "tr_static_init: dist != 256");
  19280. dist >>= 7; /* from now on, all distances are divided by 128 */
  19281. for (; code < D_CODES; code++) {
  19282. base_dist[code] = dist << 7;
  19283. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19284. _dist_code[256 + dist++] = code;
  19285. }
  19286. }
  19287. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19288. /* Construct the codes of the static literal tree */
  19289. for (bits = 0; bits <= MAX_BITS; bits++) {
  19290. bl_count[bits] = 0;
  19291. }
  19292. n = 0;
  19293. while (n <= 143) {
  19294. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19295. n++;
  19296. bl_count[8]++;
  19297. }
  19298. while (n <= 255) {
  19299. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19300. n++;
  19301. bl_count[9]++;
  19302. }
  19303. while (n <= 279) {
  19304. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19305. n++;
  19306. bl_count[7]++;
  19307. }
  19308. while (n <= 287) {
  19309. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19310. n++;
  19311. bl_count[8]++;
  19312. }
  19313. /* Codes 286 and 287 do not exist, but we must include them in the
  19314. * tree construction to get a canonical Huffman tree (longest code
  19315. * all ones)
  19316. */
  19317. gen_codes(static_ltree, L_CODES+1, bl_count);
  19318. /* The static distance tree is trivial: */
  19319. for (n = 0; n < D_CODES; n++) {
  19320. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19321. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19322. }
  19323. // Now data ready and we can init static trees
  19324. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19325. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19326. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19327. //static_init_done = true;
  19328. }
  19329. /* ===========================================================================
  19330. * Initialize a new block.
  19331. */
  19332. function init_block(s) {
  19333. var n; /* iterates over tree elements */
  19334. /* Initialize the trees. */
  19335. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19336. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19337. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19338. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19339. s.opt_len = s.static_len = 0;
  19340. s.last_lit = s.matches = 0;
  19341. }
  19342. /* ===========================================================================
  19343. * Flush the bit buffer and align the output on a byte boundary
  19344. */
  19345. function bi_windup(s)
  19346. {
  19347. if (s.bi_valid > 8) {
  19348. put_short(s, s.bi_buf);
  19349. } else if (s.bi_valid > 0) {
  19350. //put_byte(s, (Byte)s->bi_buf);
  19351. s.pending_buf[s.pending++] = s.bi_buf;
  19352. }
  19353. s.bi_buf = 0;
  19354. s.bi_valid = 0;
  19355. }
  19356. /* ===========================================================================
  19357. * Copy a stored block, storing first the length and its
  19358. * one's complement if requested.
  19359. */
  19360. function copy_block(s, buf, len, header)
  19361. //DeflateState *s;
  19362. //charf *buf; /* the input data */
  19363. //unsigned len; /* its length */
  19364. //int header; /* true if block header must be written */
  19365. {
  19366. bi_windup(s); /* align on byte boundary */
  19367. if (header) {
  19368. put_short(s, len);
  19369. put_short(s, ~len);
  19370. }
  19371. // while (len--) {
  19372. // put_byte(s, *buf++);
  19373. // }
  19374. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19375. s.pending += len;
  19376. }
  19377. /* ===========================================================================
  19378. * Compares to subtrees, using the tree depth as tie breaker when
  19379. * the subtrees have equal frequency. This minimizes the worst case length.
  19380. */
  19381. function smaller(tree, n, m, depth) {
  19382. var _n2 = n*2;
  19383. var _m2 = m*2;
  19384. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19385. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19386. }
  19387. /* ===========================================================================
  19388. * Restore the heap property by moving down the tree starting at node k,
  19389. * exchanging a node with the smallest of its two sons if necessary, stopping
  19390. * when the heap property is re-established (each father smaller than its
  19391. * two sons).
  19392. */
  19393. function pqdownheap(s, tree, k)
  19394. // deflate_state *s;
  19395. // ct_data *tree; /* the tree to restore */
  19396. // int k; /* node to move down */
  19397. {
  19398. var v = s.heap[k];
  19399. var j = k << 1; /* left son of k */
  19400. while (j <= s.heap_len) {
  19401. /* Set j to the smallest of the two sons: */
  19402. if (j < s.heap_len &&
  19403. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19404. j++;
  19405. }
  19406. /* Exit if v is smaller than both sons */
  19407. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19408. /* Exchange v with the smallest son */
  19409. s.heap[k] = s.heap[j];
  19410. k = j;
  19411. /* And continue down the tree, setting j to the left son of k */
  19412. j <<= 1;
  19413. }
  19414. s.heap[k] = v;
  19415. }
  19416. // inlined manually
  19417. // var SMALLEST = 1;
  19418. /* ===========================================================================
  19419. * Send the block data compressed using the given Huffman trees
  19420. */
  19421. function compress_block(s, ltree, dtree)
  19422. // deflate_state *s;
  19423. // const ct_data *ltree; /* literal tree */
  19424. // const ct_data *dtree; /* distance tree */
  19425. {
  19426. var dist; /* distance of matched string */
  19427. var lc; /* match length or unmatched char (if dist == 0) */
  19428. var lx = 0; /* running index in l_buf */
  19429. var code; /* the code to send */
  19430. var extra; /* number of extra bits to send */
  19431. if (s.last_lit !== 0) {
  19432. do {
  19433. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19434. lc = s.pending_buf[s.l_buf + lx];
  19435. lx++;
  19436. if (dist === 0) {
  19437. send_code(s, lc, ltree); /* send a literal byte */
  19438. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19439. } else {
  19440. /* Here, lc is the match length - MIN_MATCH */
  19441. code = _length_code[lc];
  19442. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19443. extra = extra_lbits[code];
  19444. if (extra !== 0) {
  19445. lc -= base_length[code];
  19446. send_bits(s, lc, extra); /* send the extra length bits */
  19447. }
  19448. dist--; /* dist is now the match distance - 1 */
  19449. code = d_code(dist);
  19450. //Assert (code < D_CODES, "bad d_code");
  19451. send_code(s, code, dtree); /* send the distance code */
  19452. extra = extra_dbits[code];
  19453. if (extra !== 0) {
  19454. dist -= base_dist[code];
  19455. send_bits(s, dist, extra); /* send the extra distance bits */
  19456. }
  19457. } /* literal or match pair ? */
  19458. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19459. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19460. // "pendingBuf overflow");
  19461. } while (lx < s.last_lit);
  19462. }
  19463. send_code(s, END_BLOCK, ltree);
  19464. }
  19465. /* ===========================================================================
  19466. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19467. * Update the total bit length for the current block.
  19468. * IN assertion: the field freq is set for all tree elements.
  19469. * OUT assertions: the fields len and code are set to the optimal bit length
  19470. * and corresponding code. The length opt_len is updated; static_len is
  19471. * also updated if stree is not null. The field max_code is set.
  19472. */
  19473. function build_tree(s, desc)
  19474. // deflate_state *s;
  19475. // tree_desc *desc; /* the tree descriptor */
  19476. {
  19477. var tree = desc.dyn_tree;
  19478. var stree = desc.stat_desc.static_tree;
  19479. var has_stree = desc.stat_desc.has_stree;
  19480. var elems = desc.stat_desc.elems;
  19481. var n, m; /* iterate over heap elements */
  19482. var max_code = -1; /* largest code with non zero frequency */
  19483. var node; /* new node being created */
  19484. /* Construct the initial heap, with least frequent element in
  19485. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19486. * heap[0] is not used.
  19487. */
  19488. s.heap_len = 0;
  19489. s.heap_max = HEAP_SIZE;
  19490. for (n = 0; n < elems; n++) {
  19491. if (tree[n * 2]/*.Freq*/ !== 0) {
  19492. s.heap[++s.heap_len] = max_code = n;
  19493. s.depth[n] = 0;
  19494. } else {
  19495. tree[n*2 + 1]/*.Len*/ = 0;
  19496. }
  19497. }
  19498. /* The pkzip format requires that at least one distance code exists,
  19499. * and that at least one bit should be sent even if there is only one
  19500. * possible code. So to avoid special checks later on we force at least
  19501. * two codes of non zero frequency.
  19502. */
  19503. while (s.heap_len < 2) {
  19504. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19505. tree[node * 2]/*.Freq*/ = 1;
  19506. s.depth[node] = 0;
  19507. s.opt_len--;
  19508. if (has_stree) {
  19509. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19510. }
  19511. /* node is 0 or 1 so it does not have extra bits */
  19512. }
  19513. desc.max_code = max_code;
  19514. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19515. * establish sub-heaps of increasing lengths:
  19516. */
  19517. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19518. /* Construct the Huffman tree by repeatedly combining the least two
  19519. * frequent nodes.
  19520. */
  19521. node = elems; /* next internal node of the tree */
  19522. do {
  19523. //pqremove(s, tree, n); /* n = node of least frequency */
  19524. /*** pqremove ***/
  19525. n = s.heap[1/*SMALLEST*/];
  19526. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19527. pqdownheap(s, tree, 1/*SMALLEST*/);
  19528. /***/
  19529. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19530. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19531. s.heap[--s.heap_max] = m;
  19532. /* Create a new node father of n and m */
  19533. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19534. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19535. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19536. /* and insert the new node in the heap */
  19537. s.heap[1/*SMALLEST*/] = node++;
  19538. pqdownheap(s, tree, 1/*SMALLEST*/);
  19539. } while (s.heap_len >= 2);
  19540. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19541. /* At this point, the fields freq and dad are set. We can now
  19542. * generate the bit lengths.
  19543. */
  19544. gen_bitlen(s, desc);
  19545. /* The field len is now set, we can generate the bit codes */
  19546. gen_codes(tree, max_code, s.bl_count);
  19547. }
  19548. /* ===========================================================================
  19549. * Scan a literal or distance tree to determine the frequencies of the codes
  19550. * in the bit length tree.
  19551. */
  19552. function scan_tree(s, tree, max_code)
  19553. // deflate_state *s;
  19554. // ct_data *tree; /* the tree to be scanned */
  19555. // int max_code; /* and its largest code of non zero frequency */
  19556. {
  19557. var n; /* iterates over all tree elements */
  19558. var prevlen = -1; /* last emitted length */
  19559. var curlen; /* length of current code */
  19560. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19561. var count = 0; /* repeat count of the current code */
  19562. var max_count = 7; /* max repeat count */
  19563. var min_count = 4; /* min repeat count */
  19564. if (nextlen === 0) {
  19565. max_count = 138;
  19566. min_count = 3;
  19567. }
  19568. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19569. for (n = 0; n <= max_code; n++) {
  19570. curlen = nextlen;
  19571. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19572. if (++count < max_count && curlen === nextlen) {
  19573. continue;
  19574. } else if (count < min_count) {
  19575. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19576. } else if (curlen !== 0) {
  19577. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19578. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19579. } else if (count <= 10) {
  19580. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19581. } else {
  19582. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19583. }
  19584. count = 0;
  19585. prevlen = curlen;
  19586. if (nextlen === 0) {
  19587. max_count = 138;
  19588. min_count = 3;
  19589. } else if (curlen === nextlen) {
  19590. max_count = 6;
  19591. min_count = 3;
  19592. } else {
  19593. max_count = 7;
  19594. min_count = 4;
  19595. }
  19596. }
  19597. }
  19598. /* ===========================================================================
  19599. * Send a literal or distance tree in compressed form, using the codes in
  19600. * bl_tree.
  19601. */
  19602. function send_tree(s, tree, max_code)
  19603. // deflate_state *s;
  19604. // ct_data *tree; /* the tree to be scanned */
  19605. // int max_code; /* and its largest code of non zero frequency */
  19606. {
  19607. var n; /* iterates over all tree elements */
  19608. var prevlen = -1; /* last emitted length */
  19609. var curlen; /* length of current code */
  19610. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19611. var count = 0; /* repeat count of the current code */
  19612. var max_count = 7; /* max repeat count */
  19613. var min_count = 4; /* min repeat count */
  19614. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19615. if (nextlen === 0) {
  19616. max_count = 138;
  19617. min_count = 3;
  19618. }
  19619. for (n = 0; n <= max_code; n++) {
  19620. curlen = nextlen;
  19621. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19622. if (++count < max_count && curlen === nextlen) {
  19623. continue;
  19624. } else if (count < min_count) {
  19625. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19626. } else if (curlen !== 0) {
  19627. if (curlen !== prevlen) {
  19628. send_code(s, curlen, s.bl_tree);
  19629. count--;
  19630. }
  19631. //Assert(count >= 3 && count <= 6, " 3_6?");
  19632. send_code(s, REP_3_6, s.bl_tree);
  19633. send_bits(s, count-3, 2);
  19634. } else if (count <= 10) {
  19635. send_code(s, REPZ_3_10, s.bl_tree);
  19636. send_bits(s, count-3, 3);
  19637. } else {
  19638. send_code(s, REPZ_11_138, s.bl_tree);
  19639. send_bits(s, count-11, 7);
  19640. }
  19641. count = 0;
  19642. prevlen = curlen;
  19643. if (nextlen === 0) {
  19644. max_count = 138;
  19645. min_count = 3;
  19646. } else if (curlen === nextlen) {
  19647. max_count = 6;
  19648. min_count = 3;
  19649. } else {
  19650. max_count = 7;
  19651. min_count = 4;
  19652. }
  19653. }
  19654. }
  19655. /* ===========================================================================
  19656. * Construct the Huffman tree for the bit lengths and return the index in
  19657. * bl_order of the last bit length code to send.
  19658. */
  19659. function build_bl_tree(s) {
  19660. var max_blindex; /* index of last bit length code of non zero freq */
  19661. /* Determine the bit length frequencies for literal and distance trees */
  19662. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19663. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19664. /* Build the bit length tree: */
  19665. build_tree(s, s.bl_desc);
  19666. /* opt_len now includes the length of the tree representations, except
  19667. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19668. */
  19669. /* Determine the number of bit length codes to send. The pkzip format
  19670. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19671. * 3 but the actual value used is 4.)
  19672. */
  19673. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19674. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19675. break;
  19676. }
  19677. }
  19678. /* Update opt_len to include the bit length tree and counts */
  19679. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19680. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19681. // s->opt_len, s->static_len));
  19682. return max_blindex;
  19683. }
  19684. /* ===========================================================================
  19685. * Send the header for a block using dynamic Huffman trees: the counts, the
  19686. * lengths of the bit length codes, the literal tree and the distance tree.
  19687. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19688. */
  19689. function send_all_trees(s, lcodes, dcodes, blcodes)
  19690. // deflate_state *s;
  19691. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19692. {
  19693. var rank; /* index in bl_order */
  19694. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19695. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19696. // "too many codes");
  19697. //Tracev((stderr, "\nbl counts: "));
  19698. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19699. send_bits(s, dcodes-1, 5);
  19700. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19701. for (rank = 0; rank < blcodes; rank++) {
  19702. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19703. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19704. }
  19705. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19706. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19707. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19708. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19709. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19710. }
  19711. /* ===========================================================================
  19712. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19713. * - TEXT if the two conditions below are satisfied:
  19714. * a) There are no non-portable control characters belonging to the
  19715. * "black list" (0..6, 14..25, 28..31).
  19716. * b) There is at least one printable character belonging to the
  19717. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19718. * - BINARY otherwise.
  19719. * - The following partially-portable control characters form a
  19720. * "gray list" that is ignored in this detection algorithm:
  19721. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19722. * IN assertion: the fields Freq of dyn_ltree are set.
  19723. */
  19724. function detect_data_type(s) {
  19725. /* black_mask is the bit mask of black-listed bytes
  19726. * set bits 0..6, 14..25, and 28..31
  19727. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19728. */
  19729. var black_mask = 0xf3ffc07f;
  19730. var n;
  19731. /* Check for non-textual ("black-listed") bytes. */
  19732. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19733. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19734. return Z_BINARY;
  19735. }
  19736. }
  19737. /* Check for textual ("white-listed") bytes. */
  19738. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19739. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19740. return Z_TEXT;
  19741. }
  19742. for (n = 32; n < LITERALS; n++) {
  19743. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19744. return Z_TEXT;
  19745. }
  19746. }
  19747. /* There are no "black-listed" or "white-listed" bytes:
  19748. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19749. */
  19750. return Z_BINARY;
  19751. }
  19752. var static_init_done = false;
  19753. /* ===========================================================================
  19754. * Initialize the tree data structures for a new zlib stream.
  19755. */
  19756. function _tr_init(s)
  19757. {
  19758. if (!static_init_done) {
  19759. tr_static_init();
  19760. static_init_done = true;
  19761. }
  19762. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19763. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19764. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19765. s.bi_buf = 0;
  19766. s.bi_valid = 0;
  19767. /* Initialize the first block of the first file: */
  19768. init_block(s);
  19769. }
  19770. /* ===========================================================================
  19771. * Send a stored block
  19772. */
  19773. function _tr_stored_block(s, buf, stored_len, last)
  19774. //DeflateState *s;
  19775. //charf *buf; /* input block */
  19776. //ulg stored_len; /* length of input block */
  19777. //int last; /* one if this is the last block for a file */
  19778. {
  19779. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19780. copy_block(s, buf, stored_len, true); /* with header */
  19781. }
  19782. /* ===========================================================================
  19783. * Send one empty static block to give enough lookahead for inflate.
  19784. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19785. */
  19786. function _tr_align(s) {
  19787. send_bits(s, STATIC_TREES<<1, 3);
  19788. send_code(s, END_BLOCK, static_ltree);
  19789. bi_flush(s);
  19790. }
  19791. /* ===========================================================================
  19792. * Determine the best encoding for the current block: dynamic trees, static
  19793. * trees or store, and output the encoded block to the zip file.
  19794. */
  19795. function _tr_flush_block(s, buf, stored_len, last)
  19796. //DeflateState *s;
  19797. //charf *buf; /* input block, or NULL if too old */
  19798. //ulg stored_len; /* length of input block */
  19799. //int last; /* one if this is the last block for a file */
  19800. {
  19801. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19802. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19803. /* Build the Huffman trees unless a stored block is forced */
  19804. if (s.level > 0) {
  19805. /* Check if the file is binary or text */
  19806. if (s.strm.data_type === Z_UNKNOWN) {
  19807. s.strm.data_type = detect_data_type(s);
  19808. }
  19809. /* Construct the literal and distance trees */
  19810. build_tree(s, s.l_desc);
  19811. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19812. // s->static_len));
  19813. build_tree(s, s.d_desc);
  19814. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  19815. // s->static_len));
  19816. /* At this point, opt_len and static_len are the total bit lengths of
  19817. * the compressed block data, excluding the tree representations.
  19818. */
  19819. /* Build the bit length tree for the above two trees, and get the index
  19820. * in bl_order of the last bit length code to send.
  19821. */
  19822. max_blindex = build_bl_tree(s);
  19823. /* Determine the best encoding. Compute the block lengths in bytes. */
  19824. opt_lenb = (s.opt_len+3+7) >>> 3;
  19825. static_lenb = (s.static_len+3+7) >>> 3;
  19826. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  19827. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  19828. // s->last_lit));
  19829. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  19830. } else {
  19831. // Assert(buf != (char*)0, "lost buf");
  19832. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  19833. }
  19834. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  19835. /* 4: two words for the lengths */
  19836. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  19837. * Otherwise we can't have processed more than WSIZE input bytes since
  19838. * the last block flush, because compression would have been
  19839. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  19840. * transform a block into a stored block.
  19841. */
  19842. _tr_stored_block(s, buf, stored_len, last);
  19843. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  19844. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  19845. compress_block(s, static_ltree, static_dtree);
  19846. } else {
  19847. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  19848. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  19849. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  19850. }
  19851. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  19852. /* The above check is made mod 2^32, for files larger than 512 MB
  19853. * and uLong implemented on 32 bits.
  19854. */
  19855. init_block(s);
  19856. if (last) {
  19857. bi_windup(s);
  19858. }
  19859. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  19860. // s->compressed_len-7*last));
  19861. }
  19862. /* ===========================================================================
  19863. * Save the match info and tally the frequency counts. Return true if
  19864. * the current block must be flushed.
  19865. */
  19866. function _tr_tally(s, dist, lc)
  19867. // deflate_state *s;
  19868. // unsigned dist; /* distance of matched string */
  19869. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  19870. {
  19871. //var out_length, in_length, dcode;
  19872. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  19873. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  19874. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  19875. s.last_lit++;
  19876. if (dist === 0) {
  19877. /* lc is the unmatched char */
  19878. s.dyn_ltree[lc*2]/*.Freq*/++;
  19879. } else {
  19880. s.matches++;
  19881. /* Here, lc is the match length - MIN_MATCH */
  19882. dist--; /* dist = match distance - 1 */
  19883. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  19884. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  19885. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  19886. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  19887. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  19888. }
  19889. // (!) This block is disabled in zlib defailts,
  19890. // don't enable it for binary compatibility
  19891. //#ifdef TRUNCATE_BLOCK
  19892. // /* Try to guess if it is profitable to stop the current block here */
  19893. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  19894. // /* Compute an upper bound for the compressed length */
  19895. // out_length = s.last_lit*8;
  19896. // in_length = s.strstart - s.block_start;
  19897. //
  19898. // for (dcode = 0; dcode < D_CODES; dcode++) {
  19899. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  19900. // }
  19901. // out_length >>>= 3;
  19902. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  19903. // // s->last_lit, in_length, out_length,
  19904. // // 100L - out_length*100L/in_length));
  19905. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  19906. // return true;
  19907. // }
  19908. // }
  19909. //#endif
  19910. return (s.last_lit === s.lit_bufsize-1);
  19911. /* We avoid equality with lit_bufsize because of wraparound at 64K
  19912. * on 16 bit machines and because stored blocks are restricted to
  19913. * 64K-1 bytes.
  19914. */
  19915. }
  19916. exports._tr_init = _tr_init;
  19917. exports._tr_stored_block = _tr_stored_block;
  19918. exports._tr_flush_block = _tr_flush_block;
  19919. exports._tr_tally = _tr_tally;
  19920. exports._tr_align = _tr_align;
  19921. },{"../utils/common":54}],66:[function(require,module,exports){
  19922. 'use strict';
  19923. function ZStream() {
  19924. /* next input byte */
  19925. this.input = null; // JS specific, because we have no pointers
  19926. this.next_in = 0;
  19927. /* number of bytes available at input */
  19928. this.avail_in = 0;
  19929. /* total number of input bytes read so far */
  19930. this.total_in = 0;
  19931. /* next output byte should be put there */
  19932. this.output = null; // JS specific, because we have no pointers
  19933. this.next_out = 0;
  19934. /* remaining free space at output */
  19935. this.avail_out = 0;
  19936. /* total number of bytes output so far */
  19937. this.total_out = 0;
  19938. /* last error message, NULL if no error */
  19939. this.msg = ''/*Z_NULL*/;
  19940. /* not visible by applications */
  19941. this.state = null;
  19942. /* best guess about the data type: binary or text */
  19943. this.data_type = 2/*Z_UNKNOWN*/;
  19944. /* adler32 value of the uncompressed data */
  19945. this.adler = 0;
  19946. }
  19947. module.exports = ZStream;
  19948. },{}],67:[function(require,module,exports){
  19949. /* Copyright @ 2015 Atlassian Pty Ltd
  19950. *
  19951. * Licensed under the Apache License, Version 2.0 (the "License");
  19952. * you may not use this file except in compliance with the License.
  19953. * You may obtain a copy of the License at
  19954. *
  19955. * http://www.apache.org/licenses/LICENSE-2.0
  19956. *
  19957. * Unless required by applicable law or agreed to in writing, software
  19958. * distributed under the License is distributed on an "AS IS" BASIS,
  19959. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19960. * See the License for the specific language governing permissions and
  19961. * limitations under the License.
  19962. */
  19963. module.exports = function arrayEquals(array) {
  19964. // if the other array is a falsy value, return
  19965. if (!array)
  19966. return false;
  19967. // compare lengths - can save a lot of time
  19968. if (this.length != array.length)
  19969. return false;
  19970. for (var i = 0, l = this.length; i < l; i++) {
  19971. // Check if we have nested arrays
  19972. if (this[i] instanceof Array && array[i] instanceof Array) {
  19973. // recurse into the nested arrays
  19974. if (!arrayEquals.apply(this[i], [array[i]]))
  19975. return false;
  19976. } else if (this[i] != array[i]) {
  19977. // Warning - two different object instances will never be equal:
  19978. // {x:20} != {x:20}
  19979. return false;
  19980. }
  19981. }
  19982. return true;
  19983. };
  19984. },{}],68:[function(require,module,exports){
  19985. /* Copyright @ 2015 Atlassian Pty Ltd
  19986. *
  19987. * Licensed under the Apache License, Version 2.0 (the "License");
  19988. * you may not use this file except in compliance with the License.
  19989. * You may obtain a copy of the License at
  19990. *
  19991. * http://www.apache.org/licenses/LICENSE-2.0
  19992. *
  19993. * Unless required by applicable law or agreed to in writing, software
  19994. * distributed under the License is distributed on an "AS IS" BASIS,
  19995. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19996. * See the License for the specific language governing permissions and
  19997. * limitations under the License.
  19998. */
  19999. exports.Interop = require('./interop');
  20000. },{"./interop":69}],69:[function(require,module,exports){
  20001. /* Copyright @ 2015 Atlassian Pty Ltd
  20002. *
  20003. * Licensed under the Apache License, Version 2.0 (the "License");
  20004. * you may not use this file except in compliance with the License.
  20005. * You may obtain a copy of the License at
  20006. *
  20007. * http://www.apache.org/licenses/LICENSE-2.0
  20008. *
  20009. * Unless required by applicable law or agreed to in writing, software
  20010. * distributed under the License is distributed on an "AS IS" BASIS,
  20011. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20012. * See the License for the specific language governing permissions and
  20013. * limitations under the License.
  20014. */
  20015. /* global RTCSessionDescription */
  20016. /* jshint -W097 */
  20017. "use strict";
  20018. var transform = require('./transform');
  20019. var arrayEquals = require('./array-equals');
  20020. function Interop() {
  20021. /**
  20022. * This map holds the most recent Unified Plan offer/answer SDP that was
  20023. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  20024. * the SDP string as values.
  20025. *
  20026. * @type {{}}
  20027. */
  20028. this.cache = {};
  20029. }
  20030. module.exports = Interop;
  20031. /**
  20032. * Returns the index of the first m-line with the given media type and with a
  20033. * direction which allows sending, in the last Unified Plan description with
  20034. * type "answer" converted to Plan B. Returns {null} if there is no saved
  20035. * answer, or if none of its m-lines with the given type allow sending.
  20036. * @param type the media type ("audio" or "video").
  20037. * @returns {*}
  20038. */
  20039. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  20040. if (!this.cache.answer) {
  20041. return null;
  20042. }
  20043. var session = transform.parse(this.cache.answer);
  20044. if (session && session.media && Array.isArray(session.media)){
  20045. for (var i = 0; i < session.media.length; i++) {
  20046. if (session.media[i].type == type &&
  20047. (!session.media[i].direction /* default to sendrecv */ ||
  20048. session.media[i].direction === 'sendrecv' ||
  20049. session.media[i].direction === 'sendonly')){
  20050. return i;
  20051. }
  20052. }
  20053. }
  20054. return null;
  20055. };
  20056. /**
  20057. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  20058. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  20059. * application.
  20060. *
  20061. * @param desc
  20062. * @returns {*}
  20063. */
  20064. Interop.prototype.toPlanB = function(desc) {
  20065. var self = this;
  20066. //#region Preliminary input validation.
  20067. if (typeof desc !== 'object' || desc === null ||
  20068. typeof desc.sdp !== 'string') {
  20069. console.warn('An empty description was passed as an argument.');
  20070. return desc;
  20071. }
  20072. // Objectify the SDP for easier manipulation.
  20073. var session = transform.parse(desc.sdp);
  20074. // If the SDP contains no media, there's nothing to transform.
  20075. if (typeof session.media === 'undefined' ||
  20076. !Array.isArray(session.media) || session.media.length === 0) {
  20077. console.warn('The description has no media.');
  20078. return desc;
  20079. }
  20080. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  20081. // SDP has a video, an audio and a data "channel" at most.
  20082. if (session.media.length <= 3 && session.media.every(function(m) {
  20083. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20084. })) {
  20085. console.warn('This description does not look like Unified Plan.');
  20086. return desc;
  20087. }
  20088. //#endregion
  20089. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  20090. var sdp = desc.sdp;
  20091. var rewrite = false;
  20092. for (var i = 0; i < session.media.length; i++) {
  20093. var uLine = session.media[i];
  20094. uLine.rtp.forEach(function(rtp) {
  20095. if (rtp.codec === 'NULL')
  20096. {
  20097. rewrite = true;
  20098. var offer = transform.parse(self.cache['offer']);
  20099. rtp.codec = offer.media[i].rtp[0].codec;
  20100. }
  20101. });
  20102. };
  20103. if (rewrite) {
  20104. sdp = transform.write(session);
  20105. }
  20106. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  20107. // -> Unified Plan transformation.
  20108. this.cache[desc.type] = sdp;
  20109. //#region Convert from Unified Plan to Plan B.
  20110. // We rebuild the session.media array.
  20111. var media = session.media;
  20112. session.media = [];
  20113. // Associative array that maps channel types to channel objects for fast
  20114. // access to channel objects by their type, e.g. type2bl['audio']->channel
  20115. // obj.
  20116. var type2bl = {};
  20117. // Used to build the group:BUNDLE value after the channels construction
  20118. // loop.
  20119. var types = [];
  20120. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  20121. media.forEach(function(uLine) {
  20122. // rtcp-mux is required in the Plan B SDP.
  20123. if ((typeof uLine.rtcpMux !== 'string' ||
  20124. uLine.rtcpMux !== 'rtcp-mux') &&
  20125. uLine.direction !== 'inactive') {
  20126. throw new Error('Cannot convert to Plan B because m-lines ' +
  20127. 'without the rtcp-mux attribute were found.');
  20128. }
  20129. if (uLine.type === 'application') {
  20130. session.media.push(uLine);
  20131. types.push(uLine.mid);
  20132. return;
  20133. }
  20134. // If we don't have a channel for this uLine.type, then use this
  20135. // uLine as the channel basis.
  20136. if (typeof type2bl[uLine.type] === 'undefined') {
  20137. type2bl[uLine.type] = uLine;
  20138. }
  20139. // Add sources to the channel and handle a=msid.
  20140. if (typeof uLine.sources === 'object') {
  20141. Object.keys(uLine.sources).forEach(function(ssrc) {
  20142. if (typeof type2bl[uLine.type].sources !== 'object')
  20143. type2bl[uLine.type].sources = {};
  20144. // Assign the sources to the channel.
  20145. type2bl[uLine.type].sources[ssrc] =
  20146. uLine.sources[ssrc];
  20147. if (typeof uLine.msid !== 'undefined') {
  20148. // In Plan B the msid is an SSRC attribute. Also, we don't
  20149. // care about the obsolete label and mslabel attributes.
  20150. //
  20151. // Note that it is not guaranteed that the uLine will
  20152. // have an msid. recvonly channels in particular don't have
  20153. // one.
  20154. type2bl[uLine.type].sources[ssrc].msid =
  20155. uLine.msid;
  20156. }
  20157. // NOTE ssrcs in ssrc groups will share msids, as
  20158. // draft-uberti-rtcweb-plan-00 mandates.
  20159. });
  20160. }
  20161. // Add ssrc groups to the channel.
  20162. if (typeof uLine.ssrcGroups !== 'undefined' &&
  20163. Array.isArray(uLine.ssrcGroups)) {
  20164. // Create the ssrcGroups array, if it's not defined.
  20165. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  20166. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  20167. type2bl[uLine.type].ssrcGroups = [];
  20168. }
  20169. type2bl[uLine.type].ssrcGroups =
  20170. type2bl[uLine.type].ssrcGroups.concat(
  20171. uLine.ssrcGroups);
  20172. }
  20173. if (type2bl[uLine.type] === uLine) {
  20174. // Copy ICE related stuff from the principal media line.
  20175. uLine.candidates = media[0].candidates;
  20176. uLine.iceUfrag = media[0].iceUfrag;
  20177. uLine.icePwd = media[0].icePwd;
  20178. uLine.fingerprint = media[0].fingerprint;
  20179. // Plan B mids are in ['audio', 'video', 'data']
  20180. uLine.mid = uLine.type;
  20181. // Plan B doesn't support/need the bundle-only attribute.
  20182. delete uLine.bundleOnly;
  20183. // In Plan B the msid is an SSRC attribute.
  20184. delete uLine.msid;
  20185. // Used to build the group:BUNDLE value after this loop.
  20186. types.push(uLine.type);
  20187. // Add the channel to the new media array.
  20188. session.media.push(uLine);
  20189. }
  20190. });
  20191. // We regenerate the BUNDLE group with the new mids.
  20192. session.groups.some(function(group) {
  20193. if (group.type === 'BUNDLE') {
  20194. group.mids = types.join(' ');
  20195. return true;
  20196. }
  20197. });
  20198. // msid semantic
  20199. session.msidSemantic = {
  20200. semantic: 'WMS',
  20201. token: '*'
  20202. };
  20203. var resStr = transform.write(session);
  20204. return new RTCSessionDescription({
  20205. type: desc.type,
  20206. sdp: resStr
  20207. });
  20208. //#endregion
  20209. };
  20210. /**
  20211. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  20212. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  20213. * to FF.
  20214. *
  20215. * @param desc
  20216. * @returns {*}
  20217. */
  20218. Interop.prototype.toUnifiedPlan = function(desc) {
  20219. var self = this;
  20220. //#region Preliminary input validation.
  20221. if (typeof desc !== 'object' || desc === null ||
  20222. typeof desc.sdp !== 'string') {
  20223. console.warn('An empty description was passed as an argument.');
  20224. return desc;
  20225. }
  20226. var session = transform.parse(desc.sdp);
  20227. // If the SDP contains no media, there's nothing to transform.
  20228. if (typeof session.media === 'undefined' ||
  20229. !Array.isArray(session.media) || session.media.length === 0) {
  20230. console.warn('The description has no media.');
  20231. return desc;
  20232. }
  20233. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  20234. // a video, an audio and a data "channel" at most.
  20235. if (session.media.length > 3 || !session.media.every(function(m) {
  20236. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20237. })) {
  20238. console.warn('This description does not look like Plan B.');
  20239. return desc;
  20240. }
  20241. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  20242. var mids = [];
  20243. session.media.forEach(function(m) {
  20244. mids.push(m.mid);
  20245. });
  20246. var hasBundle = false;
  20247. if (typeof session.groups !== 'undefined' &&
  20248. Array.isArray(session.groups)) {
  20249. hasBundle = session.groups.every(function(g) {
  20250. return g.type !== 'BUNDLE' ||
  20251. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  20252. });
  20253. }
  20254. if (!hasBundle) {
  20255. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  20256. " are not bundled were found.");
  20257. }
  20258. //#endregion
  20259. //#region Convert from Plan B to Unified Plan.
  20260. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  20261. // rebuild an equivalent Unified Plan offer/answer.
  20262. //
  20263. // For example, if this is a local answer (in Unified Plan style) that we
  20264. // convert to Plan B prior to handing it over to the application (the
  20265. // PeerConnection wrapper called us, for instance, after a successful
  20266. // createAnswer), we want to remember the m-line at which we've seen the
  20267. // (local) SSRC. That's because when the application wants to do call the
  20268. // SLD method, forcing us to do the inverse transformation (from Plan B to
  20269. // Unified Plan), we need to know to which m-line to assign the (local)
  20270. // SSRC. We also need to know all the other m-lines that the original
  20271. // answer had and include them in the transformed answer as well.
  20272. //
  20273. // Another example is if this is a remote offer that we convert to Plan B
  20274. // prior to giving it to the application, we want to remember the mid at
  20275. // which we've seen the (remote) SSRC.
  20276. //
  20277. // In the iteration that follows, we use the cached Unified Plan (if it
  20278. // exists) to assign mids to ssrcs.
  20279. var cached;
  20280. if (typeof this.cache[desc.type] !== 'undefined') {
  20281. cached = transform.parse(this.cache[desc.type]);
  20282. }
  20283. var recvonlySsrcs = {
  20284. audio: {},
  20285. video: {}
  20286. };
  20287. // A helper map that sends mids to m-line objects. We use it later to
  20288. // rebuild the Unified Plan style session.media array.
  20289. var mid2ul = {};
  20290. session.media.forEach(function(bLine) {
  20291. if ((typeof bLine.rtcpMux !== 'string' ||
  20292. bLine.rtcpMux !== 'rtcp-mux') &&
  20293. bLine.direction !== 'inactive') {
  20294. throw new Error("Cannot convert to Unified Plan because m-lines " +
  20295. "without the rtcp-mux attribute were found.");
  20296. }
  20297. if (bLine.type === 'application') {
  20298. mid2ul[bLine.mid] = bLine;
  20299. return;
  20300. }
  20301. // With rtcp-mux and bundle all the channels should have the same ICE
  20302. // stuff.
  20303. var sources = bLine.sources;
  20304. var ssrcGroups = bLine.ssrcGroups;
  20305. var candidates = bLine.candidates;
  20306. var iceUfrag = bLine.iceUfrag;
  20307. var icePwd = bLine.icePwd;
  20308. var fingerprint = bLine.fingerprint;
  20309. var port = bLine.port;
  20310. // We'll use the "bLine" object as a prototype for each new "mLine"
  20311. // that we create, but first we need to clean it up a bit.
  20312. delete bLine.sources;
  20313. delete bLine.ssrcGroups;
  20314. delete bLine.candidates;
  20315. delete bLine.iceUfrag;
  20316. delete bLine.icePwd;
  20317. delete bLine.fingerprint;
  20318. delete bLine.port;
  20319. delete bLine.mid;
  20320. // inverted ssrc group map
  20321. var ssrc2group = {};
  20322. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  20323. ssrcGroups.forEach(function (ssrcGroup) {
  20324. // TODO(gp) find out how to receive simulcast with FF. For the
  20325. // time being, hide it.
  20326. if (ssrcGroup.semantics === 'SIM') {
  20327. return;
  20328. }
  20329. // XXX This might brake if an SSRC is in more than one group
  20330. // for some reason.
  20331. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20332. Array.isArray(ssrcGroup.ssrcs)) {
  20333. ssrcGroup.ssrcs.forEach(function (ssrc) {
  20334. if (typeof ssrc2group[ssrc] === 'undefined') {
  20335. ssrc2group[ssrc] = [];
  20336. }
  20337. ssrc2group[ssrc].push(ssrcGroup);
  20338. });
  20339. }
  20340. });
  20341. }
  20342. // ssrc to m-line index.
  20343. var ssrc2ml = {};
  20344. if (typeof sources === 'object') {
  20345. // Explode the Plan B channel sources with one m-line per source.
  20346. Object.keys(sources).forEach(function(ssrc) {
  20347. // The (unified) m-line for this SSRC. We either create it from
  20348. // scratch or, if it's a grouped SSRC, we re-use a related
  20349. // mline. In other words, if the source is grouped with another
  20350. // source, put the two together in the same m-line.
  20351. var uLine;
  20352. // We assume here that we are the answerer in the O/A, so any
  20353. // offers which we translate come from the remote side, while
  20354. // answers are local. So the check below is to make that we
  20355. // handle receive-only SSRCs in a special way only if they come
  20356. // from the remote side.
  20357. if (desc.type==='offer') {
  20358. // We want to detect SSRCs which are used by a remote peer
  20359. // in an m-line with direction=recvonly (i.e. they are
  20360. // being used for RTCP only).
  20361. // This information would have gotten lost if the remote
  20362. // peer used Unified Plan and their local description was
  20363. // translated to Plan B. So we use the lack of an MSID
  20364. // attribute to deduce a "receive only" SSRC.
  20365. if (!sources[ssrc].msid) {
  20366. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  20367. // Receive-only SSRCs must not create new m-lines. We
  20368. // will assign them to an existing m-line later.
  20369. return;
  20370. }
  20371. }
  20372. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  20373. Array.isArray(ssrc2group[ssrc])) {
  20374. ssrc2group[ssrc].some(function (ssrcGroup) {
  20375. // ssrcGroup.ssrcs *is* an Array, no need to check
  20376. // again here.
  20377. return ssrcGroup.ssrcs.some(function (related) {
  20378. if (typeof ssrc2ml[related] === 'object') {
  20379. uLine = ssrc2ml[related];
  20380. return true;
  20381. }
  20382. });
  20383. });
  20384. }
  20385. if (typeof uLine === 'object') {
  20386. // the m-line already exists. Just add the source.
  20387. uLine.sources[ssrc] = sources[ssrc];
  20388. delete sources[ssrc].msid;
  20389. } else {
  20390. // Use the "bLine" as a prototype for the "uLine".
  20391. uLine = Object.create(bLine);
  20392. ssrc2ml[ssrc] = uLine;
  20393. if (typeof sources[ssrc].msid !== 'undefined') {
  20394. // Assign the msid of the source to the m-line. Note
  20395. // that it is not guaranteed that the source will have
  20396. // msid. In particular "recvonly" sources don't have an
  20397. // msid. Note that "recvonly" is a term only defined
  20398. // for m-lines.
  20399. uLine.msid = sources[ssrc].msid;
  20400. uLine.direction = 'sendrecv';
  20401. delete sources[ssrc].msid;
  20402. }
  20403. // We assign one SSRC per media line.
  20404. uLine.sources = {};
  20405. uLine.sources[ssrc] = sources[ssrc];
  20406. uLine.ssrcGroups = ssrc2group[ssrc];
  20407. // Use the cached Unified Plan SDP (if it exists) to assign
  20408. // SSRCs to mids.
  20409. if (typeof cached !== 'undefined' &&
  20410. typeof cached.media !== 'undefined' &&
  20411. Array.isArray(cached.media)) {
  20412. cached.media.forEach(function (m) {
  20413. if (typeof m.sources === 'object') {
  20414. Object.keys(m.sources).forEach(function (s) {
  20415. if (s === ssrc) {
  20416. uLine.mid = m.mid;
  20417. }
  20418. });
  20419. }
  20420. });
  20421. }
  20422. if (typeof uLine.mid === 'undefined') {
  20423. // If this is an SSRC that we see for the first time
  20424. // assign it a new mid. This is typically the case when
  20425. // this method is called to transform a remote
  20426. // description for the first time or when there is a
  20427. // new SSRC in the remote description because a new
  20428. // peer has joined the conference. Local SSRCs should
  20429. // have already been added to the map in the toPlanB
  20430. // method.
  20431. //
  20432. // Because FF generates answers in Unified Plan style,
  20433. // we MUST already have a cached answer with all the
  20434. // local SSRCs mapped to some m-line/mid.
  20435. if (desc.type === 'answer') {
  20436. throw new Error("An unmapped SSRC was found.");
  20437. }
  20438. uLine.mid = [bLine.type, '-', ssrc].join('');
  20439. }
  20440. // Include the candidates in the 1st media line.
  20441. uLine.candidates = candidates;
  20442. uLine.iceUfrag = iceUfrag;
  20443. uLine.icePwd = icePwd;
  20444. uLine.fingerprint = fingerprint;
  20445. uLine.port = port;
  20446. mid2ul[uLine.mid] = uLine;
  20447. }
  20448. });
  20449. }
  20450. });
  20451. // Rebuild the media array in the right order and add the missing mLines
  20452. // (missing from the Plan B SDP).
  20453. session.media = [];
  20454. mids = []; // reuse
  20455. if (desc.type === 'answer') {
  20456. // The media lines in the answer must match the media lines in the
  20457. // offer. The order is important too. Here we assume that Firefox is
  20458. // the answerer, so we merely have to use the reconstructed (unified)
  20459. // answer to update the cached (unified) answer accordingly.
  20460. //
  20461. // In the general case, one would have to use the cached (unified)
  20462. // offer to find the m-lines that are missing from the reconstructed
  20463. // answer, potentially grabbing them from the cached (unified) answer.
  20464. // One has to be careful with this approach because inactive m-lines do
  20465. // not always have an mid, making it tricky (impossible?) to find where
  20466. // exactly and which m-lines are missing from the reconstructed answer.
  20467. for (var i = 0; i < cached.media.length; i++) {
  20468. var uLine = cached.media[i];
  20469. if (typeof mid2ul[uLine.mid] === 'undefined') {
  20470. // The mid isn't in the reconstructed (unified) answer.
  20471. // This is either a (unified) m-line containing a remote
  20472. // track only, or a (unified) m-line containing a remote
  20473. // track and a local track that has been removed.
  20474. // In either case, it MUST exist in the cached
  20475. // (unified) answer.
  20476. //
  20477. // In case this is a removed local track, clean-up
  20478. // the (unified) m-line and make sure it's 'recvonly' or
  20479. // 'inactive'.
  20480. delete uLine.msid;
  20481. delete uLine.sources;
  20482. delete uLine.ssrcGroups;
  20483. if (!uLine.direction
  20484. || uLine.direction === 'sendrecv')
  20485. uLine.direction = 'recvonly';
  20486. else if (uLine.direction === 'sendonly')
  20487. uLine.direction = 'inactive';
  20488. } else {
  20489. // This is an (unified) m-line/channel that contains a local
  20490. // track (sendrecv or sendonly channel) or it's a unified
  20491. // recvonly m-line/channel. In either case, since we're
  20492. // going from PlanB -> Unified Plan this m-line MUST
  20493. // exist in the cached answer.
  20494. }
  20495. session.media.push(uLine);
  20496. if (typeof uLine.mid === 'string') {
  20497. // inactive lines don't/may not have an mid.
  20498. mids.push(uLine.mid);
  20499. }
  20500. }
  20501. } else {
  20502. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  20503. // under any circumstances. If we are no longer interested in sending a
  20504. // track, we just remove the msid and ssrc attributes and set it to
  20505. // either a=recvonly (as the reofferer, we must use recvonly if the
  20506. // other side was previously sending on the m-section, but we can also
  20507. // leave the possibility open if it wasn't previously in use), or
  20508. // a=inactive.
  20509. if (typeof cached !== 'undefined' &&
  20510. typeof cached.media !== 'undefined' &&
  20511. Array.isArray(cached.media)) {
  20512. cached.media.forEach(function(uLine) {
  20513. mids.push(uLine.mid);
  20514. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  20515. session.media.push(mid2ul[uLine.mid]);
  20516. } else {
  20517. delete uLine.msid;
  20518. delete uLine.sources;
  20519. delete uLine.ssrcGroups;
  20520. if (!uLine.direction
  20521. || uLine.direction === 'sendrecv')
  20522. uLine.direction = 'recvonly';
  20523. if (!uLine.direction
  20524. || uLine.direction === 'sendonly')
  20525. uLine.direction = 'inactive';
  20526. session.media.push(uLine);
  20527. }
  20528. });
  20529. }
  20530. // Add all the remaining (new) m-lines of the transformed SDP.
  20531. Object.keys(mid2ul).forEach(function(mid) {
  20532. if (mids.indexOf(mid) === -1) {
  20533. mids.push(mid);
  20534. if (mid2ul[mid].direction === 'recvonly') {
  20535. // This is a remote recvonly channel. Add its SSRC to the
  20536. // appropriate sendrecv or sendonly channel.
  20537. // TODO(gp) what if we don't have sendrecv/sendonly
  20538. // channel?
  20539. session.media.some(function (uLine) {
  20540. if ((uLine.direction === 'sendrecv' ||
  20541. uLine.direction === 'sendonly') &&
  20542. uLine.type === mid2ul[mid].type) {
  20543. // mid2ul[mid] shouldn't have any ssrc-groups
  20544. Object.keys(mid2ul[mid].sources).forEach(
  20545. function (ssrc) {
  20546. uLine.sources[ssrc] =
  20547. mid2ul[mid].sources[ssrc];
  20548. });
  20549. return true;
  20550. }
  20551. });
  20552. } else {
  20553. session.media.push(mid2ul[mid]);
  20554. }
  20555. }
  20556. });
  20557. }
  20558. // After we have constructed the Plan Unified m-lines we can figure out
  20559. // where (in which m-line) to place the 'recvonly SSRCs'.
  20560. // Note: we assume here that we are the answerer in the O/A, so any offers
  20561. // which we translate come from the remote side, while answers are local
  20562. // (and so our last local description is cached as an 'answer').
  20563. ["audio", "video"].forEach(function (type) {
  20564. if (!session || !session.media || !Array.isArray(session.media))
  20565. return;
  20566. var idx = null;
  20567. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  20568. idx = self.getFirstSendingIndexFromAnswer(type);
  20569. if (idx === null){
  20570. // If this is the first offer we receive, we don't have a
  20571. // cached answer. Assume that we will be sending media using
  20572. // the first m-line for each media type.
  20573. for (var i = 0; i < session.media.length; i++) {
  20574. if (session.media[i].type === type) {
  20575. idx = i;
  20576. break;
  20577. }
  20578. }
  20579. }
  20580. }
  20581. if (idx && session.media.length > idx) {
  20582. var mLine = session.media[idx];
  20583. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  20584. if (mLine.sources && mLine.sources[ssrc]) {
  20585. console.warn("Replacing an existing SSRC.");
  20586. }
  20587. if (!mLine.sources) {
  20588. mLine.sources = {};
  20589. }
  20590. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  20591. });
  20592. }
  20593. });
  20594. // We regenerate the BUNDLE group (since we regenerated the mids)
  20595. session.groups.some(function(group) {
  20596. if (group.type === 'BUNDLE') {
  20597. group.mids = mids.join(' ');
  20598. return true;
  20599. }
  20600. });
  20601. // msid semantic
  20602. session.msidSemantic = {
  20603. semantic: 'WMS',
  20604. token: '*'
  20605. };
  20606. var resStr = transform.write(session);
  20607. // Cache the transformed SDP (Unified Plan) for later re-use in this
  20608. // function.
  20609. this.cache[desc.type] = resStr;
  20610. return new RTCSessionDescription({
  20611. type: desc.type,
  20612. sdp: resStr
  20613. });
  20614. //#endregion
  20615. };
  20616. },{"./array-equals":67,"./transform":70}],70:[function(require,module,exports){
  20617. /* Copyright @ 2015 Atlassian Pty Ltd
  20618. *
  20619. * Licensed under the Apache License, Version 2.0 (the "License");
  20620. * you may not use this file except in compliance with the License.
  20621. * You may obtain a copy of the License at
  20622. *
  20623. * http://www.apache.org/licenses/LICENSE-2.0
  20624. *
  20625. * Unless required by applicable law or agreed to in writing, software
  20626. * distributed under the License is distributed on an "AS IS" BASIS,
  20627. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20628. * See the License for the specific language governing permissions and
  20629. * limitations under the License.
  20630. */
  20631. var transform = require('sdp-transform');
  20632. exports.write = function(session, opts) {
  20633. if (typeof session !== 'undefined' &&
  20634. typeof session.media !== 'undefined' &&
  20635. Array.isArray(session.media)) {
  20636. session.media.forEach(function (mLine) {
  20637. // expand sources to ssrcs
  20638. if (typeof mLine.sources !== 'undefined' &&
  20639. Object.keys(mLine.sources).length !== 0) {
  20640. mLine.ssrcs = [];
  20641. Object.keys(mLine.sources).forEach(function (ssrc) {
  20642. var source = mLine.sources[ssrc];
  20643. Object.keys(source).forEach(function (attribute) {
  20644. mLine.ssrcs.push({
  20645. id: ssrc,
  20646. attribute: attribute,
  20647. value: source[attribute]
  20648. });
  20649. });
  20650. });
  20651. delete mLine.sources;
  20652. }
  20653. // join ssrcs in ssrc groups
  20654. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20655. Array.isArray(mLine.ssrcGroups)) {
  20656. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20657. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20658. Array.isArray(ssrcGroup.ssrcs)) {
  20659. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  20660. }
  20661. });
  20662. }
  20663. });
  20664. }
  20665. // join group mids
  20666. if (typeof session !== 'undefined' &&
  20667. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20668. session.groups.forEach(function (g) {
  20669. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  20670. g.mids = g.mids.join(' ');
  20671. }
  20672. });
  20673. }
  20674. return transform.write(session, opts);
  20675. };
  20676. exports.parse = function(sdp) {
  20677. var session = transform.parse(sdp);
  20678. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  20679. Array.isArray(session.media)) {
  20680. session.media.forEach(function (mLine) {
  20681. // group sources attributes by ssrc
  20682. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20683. mLine.sources = {};
  20684. mLine.ssrcs.forEach(function (ssrc) {
  20685. if (!mLine.sources[ssrc.id])
  20686. mLine.sources[ssrc.id] = {};
  20687. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20688. });
  20689. delete mLine.ssrcs;
  20690. }
  20691. // split ssrcs in ssrc groups
  20692. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20693. Array.isArray(mLine.ssrcGroups)) {
  20694. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20695. if (typeof ssrcGroup.ssrcs === 'string') {
  20696. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  20697. }
  20698. });
  20699. }
  20700. });
  20701. }
  20702. // split group mids
  20703. if (typeof session !== 'undefined' &&
  20704. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20705. session.groups.forEach(function (g) {
  20706. if (typeof g.mids === 'string') {
  20707. g.mids = g.mids.split(' ');
  20708. }
  20709. });
  20710. }
  20711. return session;
  20712. };
  20713. },{"sdp-transform":72}],71:[function(require,module,exports){
  20714. var grammar = module.exports = {
  20715. v: [{
  20716. name: 'version',
  20717. reg: /^(\d*)$/
  20718. }],
  20719. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20720. // NB: sessionId will be a String in most cases because it is huge
  20721. name: 'origin',
  20722. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20723. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20724. format: "%s %s %d %s IP%d %s"
  20725. }],
  20726. // default parsing of these only (though some of these feel outdated)
  20727. s: [{ name: 'name' }],
  20728. i: [{ name: 'description' }],
  20729. u: [{ name: 'uri' }],
  20730. e: [{ name: 'email' }],
  20731. p: [{ name: 'phone' }],
  20732. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20733. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20734. //k: [{}], // outdated thing ignored
  20735. t: [{ //t=0 0
  20736. name: 'timing',
  20737. reg: /^(\d*) (\d*)/,
  20738. names: ['start', 'stop'],
  20739. format: "%d %d"
  20740. }],
  20741. c: [{ //c=IN IP4 10.47.197.26
  20742. name: 'connection',
  20743. reg: /^IN IP(\d) (\S*)/,
  20744. names: ['version', 'ip'],
  20745. format: "IN IP%d %s"
  20746. }],
  20747. b: [{ //b=AS:4000
  20748. push: 'bandwidth',
  20749. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20750. names: ['type', 'limit'],
  20751. format: "%s:%s"
  20752. }],
  20753. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20754. // NB: special - pushes to session
  20755. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20756. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20757. names: ['type', 'port', 'protocol', 'payloads'],
  20758. format: "%s %d %s %s"
  20759. }],
  20760. a: [
  20761. { //a=rtpmap:110 opus/48000/2
  20762. push: 'rtp',
  20763. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  20764. names: ['payload', 'codec', 'rate', 'encoding'],
  20765. format: function (o) {
  20766. return (o.encoding) ?
  20767. "rtpmap:%d %s/%s/%s":
  20768. o.rate ?
  20769. "rtpmap:%d %s/%s":
  20770. "rtpmap:%d %s";
  20771. }
  20772. },
  20773. {
  20774. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20775. //a=fmtp:111 minptime=10; useinbandfec=1
  20776. push: 'fmtp',
  20777. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20778. names: ['payload', 'config'],
  20779. format: "fmtp:%d %s"
  20780. },
  20781. { //a=control:streamid=0
  20782. name: 'control',
  20783. reg: /^control:(.*)/,
  20784. format: "control:%s"
  20785. },
  20786. { //a=rtcp:65179 IN IP4 193.84.77.194
  20787. name: 'rtcp',
  20788. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20789. names: ['port', 'netType', 'ipVer', 'address'],
  20790. format: function (o) {
  20791. return (o.address != null) ?
  20792. "rtcp:%d %s IP%d %s":
  20793. "rtcp:%d";
  20794. }
  20795. },
  20796. { //a=rtcp-fb:98 trr-int 100
  20797. push: 'rtcpFbTrrInt',
  20798. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20799. names: ['payload', 'value'],
  20800. format: "rtcp-fb:%d trr-int %d"
  20801. },
  20802. { //a=rtcp-fb:98 nack rpsi
  20803. push: 'rtcpFb',
  20804. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20805. names: ['payload', 'type', 'subtype'],
  20806. format: function (o) {
  20807. return (o.subtype != null) ?
  20808. "rtcp-fb:%s %s %s":
  20809. "rtcp-fb:%s %s";
  20810. }
  20811. },
  20812. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20813. //a=extmap:1/recvonly URI-gps-string
  20814. push: 'ext',
  20815. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20816. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20817. format: function (o) {
  20818. return (o.config != null) ?
  20819. "extmap:%s %s %s":
  20820. "extmap:%s %s";
  20821. }
  20822. },
  20823. {
  20824. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20825. push: 'crypto',
  20826. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20827. names: ['id', 'suite', 'config', 'sessionConfig'],
  20828. format: function (o) {
  20829. return (o.sessionConfig != null) ?
  20830. "crypto:%d %s %s %s":
  20831. "crypto:%d %s %s";
  20832. }
  20833. },
  20834. { //a=setup:actpass
  20835. name: 'setup',
  20836. reg: /^setup:(\w*)/,
  20837. format: "setup:%s"
  20838. },
  20839. { //a=mid:1
  20840. name: 'mid',
  20841. reg: /^mid:([^\s]*)/,
  20842. format: "mid:%s"
  20843. },
  20844. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  20845. name: 'msid',
  20846. reg: /^msid:(.*)/,
  20847. format: "msid:%s"
  20848. },
  20849. { //a=ptime:20
  20850. name: 'ptime',
  20851. reg: /^ptime:(\d*)/,
  20852. format: "ptime:%d"
  20853. },
  20854. { //a=maxptime:60
  20855. name: 'maxptime',
  20856. reg: /^maxptime:(\d*)/,
  20857. format: "maxptime:%d"
  20858. },
  20859. { //a=sendrecv
  20860. name: 'direction',
  20861. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  20862. },
  20863. { //a=ice-lite
  20864. name: 'icelite',
  20865. reg: /^(ice-lite)/
  20866. },
  20867. { //a=ice-ufrag:F7gI
  20868. name: 'iceUfrag',
  20869. reg: /^ice-ufrag:(\S*)/,
  20870. format: "ice-ufrag:%s"
  20871. },
  20872. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  20873. name: 'icePwd',
  20874. reg: /^ice-pwd:(\S*)/,
  20875. format: "ice-pwd:%s"
  20876. },
  20877. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  20878. name: 'fingerprint',
  20879. reg: /^fingerprint:(\S*) (\S*)/,
  20880. names: ['type', 'hash'],
  20881. format: "fingerprint:%s %s"
  20882. },
  20883. {
  20884. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  20885. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  20886. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  20887. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  20888. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  20889. push:'candidates',
  20890. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  20891. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  20892. format: function (o) {
  20893. var str = "candidate:%s %d %s %d %s %d typ %s";
  20894. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  20895. // NB: candidate has three optional chunks, so %void middles one if it's missing
  20896. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  20897. if (o.generation != null) {
  20898. str += " generation %d";
  20899. }
  20900. return str;
  20901. }
  20902. },
  20903. { //a=end-of-candidates (keep after the candidates line for readability)
  20904. name: 'endOfCandidates',
  20905. reg: /^(end-of-candidates)/
  20906. },
  20907. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  20908. name: 'remoteCandidates',
  20909. reg: /^remote-candidates:(.*)/,
  20910. format: "remote-candidates:%s"
  20911. },
  20912. { //a=ice-options:google-ice
  20913. name: 'iceOptions',
  20914. reg: /^ice-options:(\S*)/,
  20915. format: "ice-options:%s"
  20916. },
  20917. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  20918. push: "ssrcs",
  20919. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  20920. names: ['id', 'attribute', 'value'],
  20921. format: "ssrc:%d %s:%s"
  20922. },
  20923. { //a=ssrc-group:FEC 1 2
  20924. push: "ssrcGroups",
  20925. reg: /^ssrc-group:(\w*) (.*)/,
  20926. names: ['semantics', 'ssrcs'],
  20927. format: "ssrc-group:%s %s"
  20928. },
  20929. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  20930. name: "msidSemantic",
  20931. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  20932. names: ['semantic', 'token'],
  20933. format: "msid-semantic: %s %s" // space after ":" is not accidental
  20934. },
  20935. { //a=group:BUNDLE audio video
  20936. push: 'groups',
  20937. reg: /^group:(\w*) (.*)/,
  20938. names: ['type', 'mids'],
  20939. format: "group:%s %s"
  20940. },
  20941. { //a=rtcp-mux
  20942. name: 'rtcpMux',
  20943. reg: /^(rtcp-mux)/
  20944. },
  20945. { //a=rtcp-rsize
  20946. name: 'rtcpRsize',
  20947. reg: /^(rtcp-rsize)/
  20948. },
  20949. { // any a= that we don't understand is kepts verbatim on media.invalid
  20950. push: 'invalid',
  20951. names: ["value"]
  20952. }
  20953. ]
  20954. };
  20955. // set sensible defaults to avoid polluting the grammar with boring details
  20956. Object.keys(grammar).forEach(function (key) {
  20957. var objs = grammar[key];
  20958. objs.forEach(function (obj) {
  20959. if (!obj.reg) {
  20960. obj.reg = /(.*)/;
  20961. }
  20962. if (!obj.format) {
  20963. obj.format = "%s";
  20964. }
  20965. });
  20966. });
  20967. },{}],72:[function(require,module,exports){
  20968. var parser = require('./parser');
  20969. var writer = require('./writer');
  20970. exports.write = writer;
  20971. exports.parse = parser.parse;
  20972. exports.parseFmtpConfig = parser.parseFmtpConfig;
  20973. exports.parsePayloads = parser.parsePayloads;
  20974. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  20975. },{"./parser":73,"./writer":74}],73:[function(require,module,exports){
  20976. var toIntIfInt = function (v) {
  20977. return String(Number(v)) === v ? Number(v) : v;
  20978. };
  20979. var attachProperties = function (match, location, names, rawName) {
  20980. if (rawName && !names) {
  20981. location[rawName] = toIntIfInt(match[1]);
  20982. }
  20983. else {
  20984. for (var i = 0; i < names.length; i += 1) {
  20985. if (match[i+1] != null) {
  20986. location[names[i]] = toIntIfInt(match[i+1]);
  20987. }
  20988. }
  20989. }
  20990. };
  20991. var parseReg = function (obj, location, content) {
  20992. var needsBlank = obj.name && obj.names;
  20993. if (obj.push && !location[obj.push]) {
  20994. location[obj.push] = [];
  20995. }
  20996. else if (needsBlank && !location[obj.name]) {
  20997. location[obj.name] = {};
  20998. }
  20999. var keyLocation = obj.push ?
  21000. {} : // blank object that will be pushed
  21001. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21002. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21003. if (obj.push) {
  21004. location[obj.push].push(keyLocation);
  21005. }
  21006. };
  21007. var grammar = require('./grammar');
  21008. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21009. exports.parse = function (sdp) {
  21010. var session = {}
  21011. , media = []
  21012. , location = session; // points at where properties go under (one of the above)
  21013. // parse lines we understand
  21014. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21015. var type = l[0];
  21016. var content = l.slice(2);
  21017. if (type === 'm') {
  21018. media.push({rtp: [], fmtp: []});
  21019. location = media[media.length-1]; // point at latest media line
  21020. }
  21021. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21022. var obj = grammar[type][j];
  21023. if (obj.reg.test(content)) {
  21024. return parseReg(obj, location, content);
  21025. }
  21026. }
  21027. });
  21028. session.media = media; // link it up
  21029. return session;
  21030. };
  21031. var fmtpReducer = function (acc, expr) {
  21032. var s = expr.split('=');
  21033. if (s.length === 2) {
  21034. acc[s[0]] = toIntIfInt(s[1]);
  21035. }
  21036. return acc;
  21037. };
  21038. exports.parseFmtpConfig = function (str) {
  21039. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21040. };
  21041. exports.parsePayloads = function (str) {
  21042. return str.split(' ').map(Number);
  21043. };
  21044. exports.parseRemoteCandidates = function (str) {
  21045. var candidates = [];
  21046. var parts = str.split(' ').map(toIntIfInt);
  21047. for (var i = 0; i < parts.length; i += 3) {
  21048. candidates.push({
  21049. component: parts[i],
  21050. ip: parts[i + 1],
  21051. port: parts[i + 2]
  21052. });
  21053. }
  21054. return candidates;
  21055. };
  21056. },{"./grammar":71}],74:[function(require,module,exports){
  21057. var grammar = require('./grammar');
  21058. // customized util.format - discards excess arguments and can void middle ones
  21059. var formatRegExp = /%[sdv%]/g;
  21060. var format = function (formatStr) {
  21061. var i = 1;
  21062. var args = arguments;
  21063. var len = args.length;
  21064. return formatStr.replace(formatRegExp, function (x) {
  21065. if (i >= len) {
  21066. return x; // missing argument
  21067. }
  21068. var arg = args[i];
  21069. i += 1;
  21070. switch (x) {
  21071. case '%%':
  21072. return '%';
  21073. case '%s':
  21074. return String(arg);
  21075. case '%d':
  21076. return Number(arg);
  21077. case '%v':
  21078. return '';
  21079. }
  21080. });
  21081. // NB: we discard excess arguments - they are typically undefined from makeLine
  21082. };
  21083. var makeLine = function (type, obj, location) {
  21084. var str = obj.format instanceof Function ?
  21085. (obj.format(obj.push ? location : location[obj.name])) :
  21086. obj.format;
  21087. var args = [type + '=' + str];
  21088. if (obj.names) {
  21089. for (var i = 0; i < obj.names.length; i += 1) {
  21090. var n = obj.names[i];
  21091. if (obj.name) {
  21092. args.push(location[obj.name][n]);
  21093. }
  21094. else { // for mLine and push attributes
  21095. args.push(location[obj.names[i]]);
  21096. }
  21097. }
  21098. }
  21099. else {
  21100. args.push(location[obj.name]);
  21101. }
  21102. return format.apply(null, args);
  21103. };
  21104. // RFC specified order
  21105. // TODO: extend this with all the rest
  21106. var defaultOuterOrder = [
  21107. 'v', 'o', 's', 'i',
  21108. 'u', 'e', 'p', 'c',
  21109. 'b', 't', 'r', 'z', 'a'
  21110. ];
  21111. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  21112. module.exports = function (session, opts) {
  21113. opts = opts || {};
  21114. // ensure certain properties exist
  21115. if (session.version == null) {
  21116. session.version = 0; // "v=0" must be there (only defined version atm)
  21117. }
  21118. if (session.name == null) {
  21119. session.name = " "; // "s= " must be there if no meaningful name set
  21120. }
  21121. session.media.forEach(function (mLine) {
  21122. if (mLine.payloads == null) {
  21123. mLine.payloads = "";
  21124. }
  21125. });
  21126. var outerOrder = opts.outerOrder || defaultOuterOrder;
  21127. var innerOrder = opts.innerOrder || defaultInnerOrder;
  21128. var sdp = [];
  21129. // loop through outerOrder for matching properties on session
  21130. outerOrder.forEach(function (type) {
  21131. grammar[type].forEach(function (obj) {
  21132. if (obj.name in session && session[obj.name] != null) {
  21133. sdp.push(makeLine(type, obj, session));
  21134. }
  21135. else if (obj.push in session && session[obj.push] != null) {
  21136. session[obj.push].forEach(function (el) {
  21137. sdp.push(makeLine(type, obj, el));
  21138. });
  21139. }
  21140. });
  21141. });
  21142. // then for each media line, follow the innerOrder
  21143. session.media.forEach(function (mLine) {
  21144. sdp.push(makeLine('m', grammar.m[0], mLine));
  21145. innerOrder.forEach(function (type) {
  21146. grammar[type].forEach(function (obj) {
  21147. if (obj.name in mLine && mLine[obj.name] != null) {
  21148. sdp.push(makeLine(type, obj, mLine));
  21149. }
  21150. else if (obj.push in mLine && mLine[obj.push] != null) {
  21151. mLine[obj.push].forEach(function (el) {
  21152. sdp.push(makeLine(type, obj, el));
  21153. });
  21154. }
  21155. });
  21156. });
  21157. });
  21158. return sdp.join('\r\n') + '\r\n';
  21159. };
  21160. },{"./grammar":71}],75:[function(require,module,exports){
  21161. /* Copyright @ 2015 Atlassian Pty Ltd
  21162. *
  21163. * Licensed under the Apache License, Version 2.0 (the "License");
  21164. * you may not use this file except in compliance with the License.
  21165. * You may obtain a copy of the License at
  21166. *
  21167. * http://www.apache.org/licenses/LICENSE-2.0
  21168. *
  21169. * Unless required by applicable law or agreed to in writing, software
  21170. * distributed under the License is distributed on an "AS IS" BASIS,
  21171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21172. * See the License for the specific language governing permissions and
  21173. * limitations under the License.
  21174. */
  21175. var transform = require('sdp-transform');
  21176. var transformUtils = require('./transform-utils');
  21177. var parseSsrcs = transformUtils.parseSsrcs;
  21178. var writeSsrcs = transformUtils.writeSsrcs;
  21179. //region Constants
  21180. var DEFAULT_NUM_OF_LAYERS = 3;
  21181. //endregion
  21182. //region Ctor
  21183. function Simulcast(options) {
  21184. this.options = options ? options : {};
  21185. if (!this.options.numOfLayers) {
  21186. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  21187. }
  21188. this.layers = [];
  21189. }
  21190. //endregion
  21191. //region Stateless private utility functions
  21192. /**
  21193. * Returns a random integer between min (included) and max (excluded)
  21194. * Using Math.round() gives a non-uniform distribution!
  21195. * @returns {number}
  21196. */
  21197. function generateSSRC() {
  21198. var min = 0, max = 0xffffffff;
  21199. return Math.floor(Math.random() * (max - min)) + min;
  21200. };
  21201. function processVideo(session, action) {
  21202. if (session == null || !Array.isArray(session.media)) {
  21203. return;
  21204. }
  21205. session.media.forEach(function (mLine) {
  21206. if (mLine.type === 'video') {
  21207. action(mLine);
  21208. }
  21209. });
  21210. }
  21211. function validateDescription(desc)
  21212. {
  21213. return desc && desc != null
  21214. && desc.type && desc.type != ''
  21215. && desc.sdp && desc.sdp != '';
  21216. }
  21217. function explodeRemoteSimulcast(mLine) {
  21218. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21219. return;
  21220. }
  21221. var sources = parseSsrcs(mLine);
  21222. var order = [];
  21223. // Find the SIM group and explode its sources.
  21224. var j = mLine.ssrcGroups.length;
  21225. while (j--) {
  21226. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  21227. continue;
  21228. }
  21229. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  21230. for (var i = 0; i < simulcastSsrcs.length; i++) {
  21231. var ssrc = simulcastSsrcs[i];
  21232. order.push(ssrc);
  21233. var parts = sources[ssrc].msid.split(' ');
  21234. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  21235. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  21236. // Remove all the groups that this SSRC participates in.
  21237. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21238. if (relatedGroup.semantics === 'SIM') {
  21239. return;
  21240. }
  21241. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21242. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21243. return;
  21244. }
  21245. // Nuke all the related SSRCs.
  21246. relatedSsrcs.forEach(function (relatedSSRC) {
  21247. sources[relatedSSRC].msid = sources[ssrc].msid;
  21248. sources[relatedSSRC].cname = sources[ssrc].cname;
  21249. if (relatedSSRC !== ssrc) {
  21250. order.push(relatedSSRC);
  21251. }
  21252. });
  21253. // Schedule the related group for nuking.
  21254. })
  21255. }
  21256. mLine.ssrcs = writeSsrcs(sources, order);
  21257. mLine.ssrcGroups.splice(j, 1);
  21258. };
  21259. }
  21260. function implodeRemoteSimulcast(mLine) {
  21261. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21262. console.info('Halt: There are no SSRC groups in the remote ' +
  21263. 'description.');
  21264. return;
  21265. }
  21266. var sources = parseSsrcs(mLine);
  21267. // Find the SIM group and nuke it.
  21268. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  21269. if (simulcastGroup.semantics !== 'SIM') {
  21270. return;
  21271. }
  21272. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  21273. // Schedule the SIM group for nuking.
  21274. simulcastGroup.nuke = true;
  21275. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  21276. // Nuke all the higher layer SSRCs.
  21277. for (var i = 1; i < simulcastSsrcs.length; i++) {
  21278. var ssrc = simulcastSsrcs[i];
  21279. delete sources[ssrc];
  21280. // Remove all the groups that this SSRC participates in.
  21281. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21282. if (relatedGroup.semantics === 'SIM') {
  21283. return;
  21284. }
  21285. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21286. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21287. return;
  21288. }
  21289. // Nuke all the related SSRCs.
  21290. relatedSsrcs.forEach(function (relatedSSRC) {
  21291. delete sources[relatedSSRC];
  21292. });
  21293. // Schedule the related group for nuking.
  21294. relatedGroup.nuke = true;
  21295. })
  21296. }
  21297. return;
  21298. });
  21299. mLine.ssrcs = writeSsrcs(sources);
  21300. // Nuke all the scheduled groups.
  21301. var i = mLine.ssrcGroups.length;
  21302. while (i--) {
  21303. if (mLine.ssrcGroups[i].nuke) {
  21304. mLine.ssrcGroups.splice(i, 1);
  21305. }
  21306. }
  21307. }
  21308. function removeGoogConference(mLine) {
  21309. if (!mLine || !Array.isArray(mLine.invalid)) {
  21310. return;
  21311. }
  21312. var i = mLine.invalid.length;
  21313. while (i--) {
  21314. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  21315. mLine.invalid.splice(i, 1);
  21316. }
  21317. }
  21318. }
  21319. function assertGoogConference(mLine) {
  21320. if (!mLine) {
  21321. return;
  21322. }
  21323. if (!Array.isArray(mLine.invalid)) {
  21324. mLine.invalid = [];
  21325. }
  21326. if (!mLine.invalid.some(
  21327. function (i) { return i.value === 'x-google-flag:conference' })) {
  21328. mLine.invalid.push({'value': 'x-google-flag:conference'});
  21329. }
  21330. }
  21331. //endregion
  21332. //region "Private" functions
  21333. /**
  21334. *
  21335. * @param mLine
  21336. * @private
  21337. */
  21338. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  21339. if (!mLine || mLine.type !== 'video') {
  21340. return;
  21341. }
  21342. var sources = parseSsrcs(mLine);
  21343. if (Object.keys(sources).length === 0) {
  21344. // no sources, disable simulcast.
  21345. if (this.layers.length !== 0) {
  21346. this.layers = [];
  21347. }
  21348. return;
  21349. }
  21350. // find the base layer (we'll reuse its msid and cname).
  21351. var baseLayerSSRC = Object.keys(sources)[0];
  21352. var baseLayer = sources[baseLayerSSRC];
  21353. // todo(gp) handle screen sharing.
  21354. // check if base CNAME has changed and reinitialise layers.
  21355. if (this.layers.length > 0
  21356. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  21357. this.layers = [];
  21358. }
  21359. // (re)initialise layers
  21360. if (this.layers.length < 1) {
  21361. // first push the base layer.
  21362. this.layers.push({
  21363. ssrc: baseLayerSSRC,
  21364. msid: baseLayer.msid,
  21365. cname: baseLayer.cname
  21366. });
  21367. var rtx = false; // RFC 4588
  21368. if (Array.isArray(mLine.rtp)) {
  21369. rtx = mLine.rtp.some(
  21370. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  21371. }
  21372. if (rtx) {
  21373. this.layers[0].rtx = generateSSRC();
  21374. }
  21375. // now push additional layers.
  21376. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  21377. var layer = { ssrc: generateSSRC() };
  21378. if (rtx) {
  21379. layer.rtx = generateSSRC();
  21380. }
  21381. this.layers.push(layer);
  21382. }
  21383. }
  21384. };
  21385. /**
  21386. *
  21387. * @param mLine
  21388. * @private
  21389. */
  21390. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  21391. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  21392. var sources = {};
  21393. var msid = this.layers[0].msid;
  21394. var cname = this.layers[0].cname;
  21395. var simulcastSsrcs = [];
  21396. var ssrcGroups = [];
  21397. for (var i = 0; i < this.layers.length; i++) {
  21398. var layer = this.layers[i];
  21399. sources[layer.ssrc] = { msid: msid, cname: cname };
  21400. simulcastSsrcs.push(layer.ssrc);
  21401. if (layer.rtx) {
  21402. sources[layer.rtx] = {
  21403. msid: msid,
  21404. cname: cname
  21405. }
  21406. ssrcGroups.push({
  21407. semantics: 'FID',
  21408. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  21409. });
  21410. }
  21411. }
  21412. ssrcGroups.push({
  21413. semantics: 'SIM',
  21414. ssrcs: simulcastSsrcs.join(' ')
  21415. });
  21416. mLine.ssrcGroups = ssrcGroups;
  21417. mLine.ssrcs = writeSsrcs(sources);
  21418. }
  21419. }
  21420. //endregion
  21421. //region "Public" functions
  21422. Simulcast.prototype.isSupported = function () {
  21423. return window.chrome;
  21424. // TODO this needs improvements. For example I doubt that Chrome in Android
  21425. // has simulcast support. Also, only recent versions of Chromium have native
  21426. // simulcast support.
  21427. }
  21428. /**
  21429. *
  21430. * @param desc
  21431. * @returns {RTCSessionDescription}
  21432. */
  21433. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  21434. if (!validateDescription(desc)) {
  21435. return desc;
  21436. }
  21437. var session = transform.parse(desc.sdp);
  21438. var self = this;
  21439. processVideo(session, function (mLine) {
  21440. // Handle simulcast reception.
  21441. if (self.options.explodeRemoteSimulcast) {
  21442. explodeRemoteSimulcast(mLine);
  21443. } else {
  21444. implodeRemoteSimulcast(mLine);
  21445. }
  21446. // If native simulcast is enabled, we must append the x-goog-conference
  21447. // attribute to the SDP.
  21448. if (self.layers.length < 1) {
  21449. removeGoogConference(mLine);
  21450. } else {
  21451. assertGoogConference(mLine);
  21452. }
  21453. });
  21454. return new RTCSessionDescription({
  21455. type: desc.type,
  21456. sdp: transform.write(session)
  21457. });
  21458. };
  21459. /**
  21460. *
  21461. * @param desc
  21462. * @returns {RTCSessionDescription}
  21463. */
  21464. Simulcast.prototype.mungeLocalDescription = function (desc) {
  21465. if (!validateDescription(desc) || !this.isSupported()) {
  21466. return desc;
  21467. }
  21468. var session = transform.parse(desc.sdp);
  21469. var self = this;
  21470. processVideo(session, function (mLine) {
  21471. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  21472. {
  21473. return;
  21474. }
  21475. // Initialize native simulcast layers, if not already done.
  21476. self._maybeInitializeLayers(mLine);
  21477. // Update the SDP with the simulcast layers.
  21478. self._restoreSimulcastView(mLine);
  21479. });
  21480. return new RTCSessionDescription({
  21481. type: desc.type,
  21482. sdp: transform.write(session)
  21483. });
  21484. };
  21485. //endregion
  21486. module.exports = Simulcast;
  21487. },{"./transform-utils":76,"sdp-transform":78}],76:[function(require,module,exports){
  21488. /* Copyright @ 2015 Atlassian Pty Ltd
  21489. *
  21490. * Licensed under the Apache License, Version 2.0 (the "License");
  21491. * you may not use this file except in compliance with the License.
  21492. * You may obtain a copy of the License at
  21493. *
  21494. * http://www.apache.org/licenses/LICENSE-2.0
  21495. *
  21496. * Unless required by applicable law or agreed to in writing, software
  21497. * distributed under the License is distributed on an "AS IS" BASIS,
  21498. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21499. * See the License for the specific language governing permissions and
  21500. * limitations under the License.
  21501. */
  21502. exports.writeSsrcs = function(sources, order) {
  21503. var ssrcs = [];
  21504. // expand sources to ssrcs
  21505. if (typeof sources !== 'undefined' &&
  21506. Object.keys(sources).length !== 0) {
  21507. if (Array.isArray(order)) {
  21508. for (var i = 0; i < order.length; i++) {
  21509. var ssrc = order[i];
  21510. var source = sources[ssrc];
  21511. Object.keys(source).forEach(function (attribute) {
  21512. ssrcs.push({
  21513. id: ssrc,
  21514. attribute: attribute,
  21515. value: source[attribute]
  21516. });
  21517. });
  21518. }
  21519. } else {
  21520. Object.keys(sources).forEach(function (ssrc) {
  21521. var source = sources[ssrc];
  21522. Object.keys(source).forEach(function (attribute) {
  21523. ssrcs.push({
  21524. id: ssrc,
  21525. attribute: attribute,
  21526. value: source[attribute]
  21527. });
  21528. });
  21529. });
  21530. }
  21531. }
  21532. return ssrcs;
  21533. };
  21534. exports.parseSsrcs = function (mLine) {
  21535. var sources = {};
  21536. // group sources attributes by ssrc.
  21537. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  21538. mLine.ssrcs.forEach(function (ssrc) {
  21539. if (!sources[ssrc.id])
  21540. sources[ssrc.id] = {};
  21541. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  21542. });
  21543. }
  21544. return sources;
  21545. };
  21546. },{}],77:[function(require,module,exports){
  21547. arguments[4][71][0].apply(exports,arguments)
  21548. },{"dup":71}],78:[function(require,module,exports){
  21549. arguments[4][72][0].apply(exports,arguments)
  21550. },{"./parser":79,"./writer":80,"dup":72}],79:[function(require,module,exports){
  21551. arguments[4][73][0].apply(exports,arguments)
  21552. },{"./grammar":77,"dup":73}],80:[function(require,module,exports){
  21553. arguments[4][74][0].apply(exports,arguments)
  21554. },{"./grammar":77,"dup":74}],81:[function(require,module,exports){
  21555. arguments[4][71][0].apply(exports,arguments)
  21556. },{"dup":71}],82:[function(require,module,exports){
  21557. arguments[4][72][0].apply(exports,arguments)
  21558. },{"./parser":83,"./writer":84,"dup":72}],83:[function(require,module,exports){
  21559. arguments[4][73][0].apply(exports,arguments)
  21560. },{"./grammar":81,"dup":73}],84:[function(require,module,exports){
  21561. arguments[4][74][0].apply(exports,arguments)
  21562. },{"./grammar":81,"dup":74}],85:[function(require,module,exports){
  21563. module.exports = require('./lib/');
  21564. },{"./lib/":86}],86:[function(require,module,exports){
  21565. /**
  21566. * Module dependencies.
  21567. */
  21568. var url = require('./url');
  21569. var parser = require('socket.io-parser');
  21570. var Manager = require('./manager');
  21571. var debug = require('debug')('socket.io-client');
  21572. /**
  21573. * Module exports.
  21574. */
  21575. module.exports = exports = lookup;
  21576. /**
  21577. * Managers cache.
  21578. */
  21579. var cache = exports.managers = {};
  21580. /**
  21581. * Looks up an existing `Manager` for multiplexing.
  21582. * If the user summons:
  21583. *
  21584. * `io('http://localhost/a');`
  21585. * `io('http://localhost/b');`
  21586. *
  21587. * We reuse the existing instance based on same scheme/port/host,
  21588. * and we initialize sockets for each namespace.
  21589. *
  21590. * @api public
  21591. */
  21592. function lookup(uri, opts) {
  21593. if (typeof uri == 'object') {
  21594. opts = uri;
  21595. uri = undefined;
  21596. }
  21597. opts = opts || {};
  21598. var parsed = url(uri);
  21599. var source = parsed.source;
  21600. var id = parsed.id;
  21601. var io;
  21602. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  21603. debug('ignoring socket cache for %s', source);
  21604. io = Manager(source, opts);
  21605. } else {
  21606. if (!cache[id]) {
  21607. debug('new io instance for %s', source);
  21608. cache[id] = Manager(source, opts);
  21609. }
  21610. io = cache[id];
  21611. }
  21612. return io.socket(parsed.path);
  21613. }
  21614. /**
  21615. * Protocol version.
  21616. *
  21617. * @api public
  21618. */
  21619. exports.protocol = parser.protocol;
  21620. /**
  21621. * `connect`.
  21622. *
  21623. * @param {String} uri
  21624. * @api public
  21625. */
  21626. exports.connect = lookup;
  21627. /**
  21628. * Expose constructors for standalone build.
  21629. *
  21630. * @api public
  21631. */
  21632. exports.Manager = require('./manager');
  21633. exports.Socket = require('./socket');
  21634. },{"./manager":87,"./socket":89,"./url":90,"debug":94,"socket.io-parser":130}],87:[function(require,module,exports){
  21635. /**
  21636. * Module dependencies.
  21637. */
  21638. var url = require('./url');
  21639. var eio = require('engine.io-client');
  21640. var Socket = require('./socket');
  21641. var Emitter = require('component-emitter');
  21642. var parser = require('socket.io-parser');
  21643. var on = require('./on');
  21644. var bind = require('component-bind');
  21645. var object = require('object-component');
  21646. var debug = require('debug')('socket.io-client:manager');
  21647. var indexOf = require('indexof');
  21648. var Backoff = require('backo2');
  21649. /**
  21650. * Module exports
  21651. */
  21652. module.exports = Manager;
  21653. /**
  21654. * `Manager` constructor.
  21655. *
  21656. * @param {String} engine instance or engine uri/opts
  21657. * @param {Object} options
  21658. * @api public
  21659. */
  21660. function Manager(uri, opts){
  21661. if (!(this instanceof Manager)) return new Manager(uri, opts);
  21662. if (uri && ('object' == typeof uri)) {
  21663. opts = uri;
  21664. uri = undefined;
  21665. }
  21666. opts = opts || {};
  21667. opts.path = opts.path || '/socket.io';
  21668. this.nsps = {};
  21669. this.subs = [];
  21670. this.opts = opts;
  21671. this.reconnection(opts.reconnection !== false);
  21672. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  21673. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  21674. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  21675. this.randomizationFactor(opts.randomizationFactor || 0.5);
  21676. this.backoff = new Backoff({
  21677. min: this.reconnectionDelay(),
  21678. max: this.reconnectionDelayMax(),
  21679. jitter: this.randomizationFactor()
  21680. });
  21681. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  21682. this.readyState = 'closed';
  21683. this.uri = uri;
  21684. this.connected = [];
  21685. this.encoding = false;
  21686. this.packetBuffer = [];
  21687. this.encoder = new parser.Encoder();
  21688. this.decoder = new parser.Decoder();
  21689. this.autoConnect = opts.autoConnect !== false;
  21690. if (this.autoConnect) this.open();
  21691. }
  21692. /**
  21693. * Propagate given event to sockets and emit on `this`
  21694. *
  21695. * @api private
  21696. */
  21697. Manager.prototype.emitAll = function() {
  21698. this.emit.apply(this, arguments);
  21699. for (var nsp in this.nsps) {
  21700. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  21701. }
  21702. };
  21703. /**
  21704. * Update `socket.id` of all sockets
  21705. *
  21706. * @api private
  21707. */
  21708. Manager.prototype.updateSocketIds = function(){
  21709. for (var nsp in this.nsps) {
  21710. this.nsps[nsp].id = this.engine.id;
  21711. }
  21712. };
  21713. /**
  21714. * Mix in `Emitter`.
  21715. */
  21716. Emitter(Manager.prototype);
  21717. /**
  21718. * Sets the `reconnection` config.
  21719. *
  21720. * @param {Boolean} true/false if it should automatically reconnect
  21721. * @return {Manager} self or value
  21722. * @api public
  21723. */
  21724. Manager.prototype.reconnection = function(v){
  21725. if (!arguments.length) return this._reconnection;
  21726. this._reconnection = !!v;
  21727. return this;
  21728. };
  21729. /**
  21730. * Sets the reconnection attempts config.
  21731. *
  21732. * @param {Number} max reconnection attempts before giving up
  21733. * @return {Manager} self or value
  21734. * @api public
  21735. */
  21736. Manager.prototype.reconnectionAttempts = function(v){
  21737. if (!arguments.length) return this._reconnectionAttempts;
  21738. this._reconnectionAttempts = v;
  21739. return this;
  21740. };
  21741. /**
  21742. * Sets the delay between reconnections.
  21743. *
  21744. * @param {Number} delay
  21745. * @return {Manager} self or value
  21746. * @api public
  21747. */
  21748. Manager.prototype.reconnectionDelay = function(v){
  21749. if (!arguments.length) return this._reconnectionDelay;
  21750. this._reconnectionDelay = v;
  21751. this.backoff && this.backoff.setMin(v);
  21752. return this;
  21753. };
  21754. Manager.prototype.randomizationFactor = function(v){
  21755. if (!arguments.length) return this._randomizationFactor;
  21756. this._randomizationFactor = v;
  21757. this.backoff && this.backoff.setJitter(v);
  21758. return this;
  21759. };
  21760. /**
  21761. * Sets the maximum delay between reconnections.
  21762. *
  21763. * @param {Number} delay
  21764. * @return {Manager} self or value
  21765. * @api public
  21766. */
  21767. Manager.prototype.reconnectionDelayMax = function(v){
  21768. if (!arguments.length) return this._reconnectionDelayMax;
  21769. this._reconnectionDelayMax = v;
  21770. this.backoff && this.backoff.setMax(v);
  21771. return this;
  21772. };
  21773. /**
  21774. * Sets the connection timeout. `false` to disable
  21775. *
  21776. * @return {Manager} self or value
  21777. * @api public
  21778. */
  21779. Manager.prototype.timeout = function(v){
  21780. if (!arguments.length) return this._timeout;
  21781. this._timeout = v;
  21782. return this;
  21783. };
  21784. /**
  21785. * Starts trying to reconnect if reconnection is enabled and we have not
  21786. * started reconnecting yet
  21787. *
  21788. * @api private
  21789. */
  21790. Manager.prototype.maybeReconnectOnOpen = function() {
  21791. // Only try to reconnect if it's the first time we're connecting
  21792. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  21793. // keeps reconnection from firing twice for the same reconnection loop
  21794. this.reconnect();
  21795. }
  21796. };
  21797. /**
  21798. * Sets the current transport `socket`.
  21799. *
  21800. * @param {Function} optional, callback
  21801. * @return {Manager} self
  21802. * @api public
  21803. */
  21804. Manager.prototype.open =
  21805. Manager.prototype.connect = function(fn){
  21806. debug('readyState %s', this.readyState);
  21807. if (~this.readyState.indexOf('open')) return this;
  21808. debug('opening %s', this.uri);
  21809. this.engine = eio(this.uri, this.opts);
  21810. var socket = this.engine;
  21811. var self = this;
  21812. this.readyState = 'opening';
  21813. this.skipReconnect = false;
  21814. // emit `open`
  21815. var openSub = on(socket, 'open', function() {
  21816. self.onopen();
  21817. fn && fn();
  21818. });
  21819. // emit `connect_error`
  21820. var errorSub = on(socket, 'error', function(data){
  21821. debug('connect_error');
  21822. self.cleanup();
  21823. self.readyState = 'closed';
  21824. self.emitAll('connect_error', data);
  21825. if (fn) {
  21826. var err = new Error('Connection error');
  21827. err.data = data;
  21828. fn(err);
  21829. } else {
  21830. // Only do this if there is no fn to handle the error
  21831. self.maybeReconnectOnOpen();
  21832. }
  21833. });
  21834. // emit `connect_timeout`
  21835. if (false !== this._timeout) {
  21836. var timeout = this._timeout;
  21837. debug('connect attempt will timeout after %d', timeout);
  21838. // set timer
  21839. var timer = setTimeout(function(){
  21840. debug('connect attempt timed out after %d', timeout);
  21841. openSub.destroy();
  21842. socket.close();
  21843. socket.emit('error', 'timeout');
  21844. self.emitAll('connect_timeout', timeout);
  21845. }, timeout);
  21846. this.subs.push({
  21847. destroy: function(){
  21848. clearTimeout(timer);
  21849. }
  21850. });
  21851. }
  21852. this.subs.push(openSub);
  21853. this.subs.push(errorSub);
  21854. return this;
  21855. };
  21856. /**
  21857. * Called upon transport open.
  21858. *
  21859. * @api private
  21860. */
  21861. Manager.prototype.onopen = function(){
  21862. debug('open');
  21863. // clear old subs
  21864. this.cleanup();
  21865. // mark as open
  21866. this.readyState = 'open';
  21867. this.emit('open');
  21868. // add new subs
  21869. var socket = this.engine;
  21870. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  21871. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  21872. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  21873. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  21874. };
  21875. /**
  21876. * Called with data.
  21877. *
  21878. * @api private
  21879. */
  21880. Manager.prototype.ondata = function(data){
  21881. this.decoder.add(data);
  21882. };
  21883. /**
  21884. * Called when parser fully decodes a packet.
  21885. *
  21886. * @api private
  21887. */
  21888. Manager.prototype.ondecoded = function(packet) {
  21889. this.emit('packet', packet);
  21890. };
  21891. /**
  21892. * Called upon socket error.
  21893. *
  21894. * @api private
  21895. */
  21896. Manager.prototype.onerror = function(err){
  21897. debug('error', err);
  21898. this.emitAll('error', err);
  21899. };
  21900. /**
  21901. * Creates a new socket for the given `nsp`.
  21902. *
  21903. * @return {Socket}
  21904. * @api public
  21905. */
  21906. Manager.prototype.socket = function(nsp){
  21907. var socket = this.nsps[nsp];
  21908. if (!socket) {
  21909. socket = new Socket(this, nsp);
  21910. this.nsps[nsp] = socket;
  21911. var self = this;
  21912. socket.on('connect', function(){
  21913. socket.id = self.engine.id;
  21914. if (!~indexOf(self.connected, socket)) {
  21915. self.connected.push(socket);
  21916. }
  21917. });
  21918. }
  21919. return socket;
  21920. };
  21921. /**
  21922. * Called upon a socket close.
  21923. *
  21924. * @param {Socket} socket
  21925. */
  21926. Manager.prototype.destroy = function(socket){
  21927. var index = indexOf(this.connected, socket);
  21928. if (~index) this.connected.splice(index, 1);
  21929. if (this.connected.length) return;
  21930. this.close();
  21931. };
  21932. /**
  21933. * Writes a packet.
  21934. *
  21935. * @param {Object} packet
  21936. * @api private
  21937. */
  21938. Manager.prototype.packet = function(packet){
  21939. debug('writing packet %j', packet);
  21940. var self = this;
  21941. if (!self.encoding) {
  21942. // encode, then write to engine with result
  21943. self.encoding = true;
  21944. this.encoder.encode(packet, function(encodedPackets) {
  21945. for (var i = 0; i < encodedPackets.length; i++) {
  21946. self.engine.write(encodedPackets[i]);
  21947. }
  21948. self.encoding = false;
  21949. self.processPacketQueue();
  21950. });
  21951. } else { // add packet to the queue
  21952. self.packetBuffer.push(packet);
  21953. }
  21954. };
  21955. /**
  21956. * If packet buffer is non-empty, begins encoding the
  21957. * next packet in line.
  21958. *
  21959. * @api private
  21960. */
  21961. Manager.prototype.processPacketQueue = function() {
  21962. if (this.packetBuffer.length > 0 && !this.encoding) {
  21963. var pack = this.packetBuffer.shift();
  21964. this.packet(pack);
  21965. }
  21966. };
  21967. /**
  21968. * Clean up transport subscriptions and packet buffer.
  21969. *
  21970. * @api private
  21971. */
  21972. Manager.prototype.cleanup = function(){
  21973. var sub;
  21974. while (sub = this.subs.shift()) sub.destroy();
  21975. this.packetBuffer = [];
  21976. this.encoding = false;
  21977. this.decoder.destroy();
  21978. };
  21979. /**
  21980. * Close the current socket.
  21981. *
  21982. * @api private
  21983. */
  21984. Manager.prototype.close =
  21985. Manager.prototype.disconnect = function(){
  21986. this.skipReconnect = true;
  21987. this.backoff.reset();
  21988. this.readyState = 'closed';
  21989. this.engine && this.engine.close();
  21990. };
  21991. /**
  21992. * Called upon engine close.
  21993. *
  21994. * @api private
  21995. */
  21996. Manager.prototype.onclose = function(reason){
  21997. debug('close');
  21998. this.cleanup();
  21999. this.backoff.reset();
  22000. this.readyState = 'closed';
  22001. this.emit('close', reason);
  22002. if (this._reconnection && !this.skipReconnect) {
  22003. this.reconnect();
  22004. }
  22005. };
  22006. /**
  22007. * Attempt a reconnection.
  22008. *
  22009. * @api private
  22010. */
  22011. Manager.prototype.reconnect = function(){
  22012. if (this.reconnecting || this.skipReconnect) return this;
  22013. var self = this;
  22014. if (this.backoff.attempts >= this._reconnectionAttempts) {
  22015. debug('reconnect failed');
  22016. this.backoff.reset();
  22017. this.emitAll('reconnect_failed');
  22018. this.reconnecting = false;
  22019. } else {
  22020. var delay = this.backoff.duration();
  22021. debug('will wait %dms before reconnect attempt', delay);
  22022. this.reconnecting = true;
  22023. var timer = setTimeout(function(){
  22024. if (self.skipReconnect) return;
  22025. debug('attempting reconnect');
  22026. self.emitAll('reconnect_attempt', self.backoff.attempts);
  22027. self.emitAll('reconnecting', self.backoff.attempts);
  22028. // check again for the case socket closed in above events
  22029. if (self.skipReconnect) return;
  22030. self.open(function(err){
  22031. if (err) {
  22032. debug('reconnect attempt error');
  22033. self.reconnecting = false;
  22034. self.reconnect();
  22035. self.emitAll('reconnect_error', err.data);
  22036. } else {
  22037. debug('reconnect success');
  22038. self.onreconnect();
  22039. }
  22040. });
  22041. }, delay);
  22042. this.subs.push({
  22043. destroy: function(){
  22044. clearTimeout(timer);
  22045. }
  22046. });
  22047. }
  22048. };
  22049. /**
  22050. * Called upon successful reconnect.
  22051. *
  22052. * @api private
  22053. */
  22054. Manager.prototype.onreconnect = function(){
  22055. var attempt = this.backoff.attempts;
  22056. this.reconnecting = false;
  22057. this.backoff.reset();
  22058. this.updateSocketIds();
  22059. this.emitAll('reconnect', attempt);
  22060. };
  22061. },{"./on":88,"./socket":89,"./url":90,"backo2":91,"component-bind":92,"component-emitter":93,"debug":94,"engine.io-client":95,"indexof":126,"object-component":127,"socket.io-parser":130}],88:[function(require,module,exports){
  22062. /**
  22063. * Module exports.
  22064. */
  22065. module.exports = on;
  22066. /**
  22067. * Helper for subscriptions.
  22068. *
  22069. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  22070. * @param {String} event name
  22071. * @param {Function} callback
  22072. * @api public
  22073. */
  22074. function on(obj, ev, fn) {
  22075. obj.on(ev, fn);
  22076. return {
  22077. destroy: function(){
  22078. obj.removeListener(ev, fn);
  22079. }
  22080. };
  22081. }
  22082. },{}],89:[function(require,module,exports){
  22083. /**
  22084. * Module dependencies.
  22085. */
  22086. var parser = require('socket.io-parser');
  22087. var Emitter = require('component-emitter');
  22088. var toArray = require('to-array');
  22089. var on = require('./on');
  22090. var bind = require('component-bind');
  22091. var debug = require('debug')('socket.io-client:socket');
  22092. var hasBin = require('has-binary');
  22093. /**
  22094. * Module exports.
  22095. */
  22096. module.exports = exports = Socket;
  22097. /**
  22098. * Internal events (blacklisted).
  22099. * These events can't be emitted by the user.
  22100. *
  22101. * @api private
  22102. */
  22103. var events = {
  22104. connect: 1,
  22105. connect_error: 1,
  22106. connect_timeout: 1,
  22107. disconnect: 1,
  22108. error: 1,
  22109. reconnect: 1,
  22110. reconnect_attempt: 1,
  22111. reconnect_failed: 1,
  22112. reconnect_error: 1,
  22113. reconnecting: 1
  22114. };
  22115. /**
  22116. * Shortcut to `Emitter#emit`.
  22117. */
  22118. var emit = Emitter.prototype.emit;
  22119. /**
  22120. * `Socket` constructor.
  22121. *
  22122. * @api public
  22123. */
  22124. function Socket(io, nsp){
  22125. this.io = io;
  22126. this.nsp = nsp;
  22127. this.json = this; // compat
  22128. this.ids = 0;
  22129. this.acks = {};
  22130. if (this.io.autoConnect) this.open();
  22131. this.receiveBuffer = [];
  22132. this.sendBuffer = [];
  22133. this.connected = false;
  22134. this.disconnected = true;
  22135. }
  22136. /**
  22137. * Mix in `Emitter`.
  22138. */
  22139. Emitter(Socket.prototype);
  22140. /**
  22141. * Subscribe to open, close and packet events
  22142. *
  22143. * @api private
  22144. */
  22145. Socket.prototype.subEvents = function() {
  22146. if (this.subs) return;
  22147. var io = this.io;
  22148. this.subs = [
  22149. on(io, 'open', bind(this, 'onopen')),
  22150. on(io, 'packet', bind(this, 'onpacket')),
  22151. on(io, 'close', bind(this, 'onclose'))
  22152. ];
  22153. };
  22154. /**
  22155. * "Opens" the socket.
  22156. *
  22157. * @api public
  22158. */
  22159. Socket.prototype.open =
  22160. Socket.prototype.connect = function(){
  22161. if (this.connected) return this;
  22162. this.subEvents();
  22163. this.io.open(); // ensure open
  22164. if ('open' == this.io.readyState) this.onopen();
  22165. return this;
  22166. };
  22167. /**
  22168. * Sends a `message` event.
  22169. *
  22170. * @return {Socket} self
  22171. * @api public
  22172. */
  22173. Socket.prototype.send = function(){
  22174. var args = toArray(arguments);
  22175. args.unshift('message');
  22176. this.emit.apply(this, args);
  22177. return this;
  22178. };
  22179. /**
  22180. * Override `emit`.
  22181. * If the event is in `events`, it's emitted normally.
  22182. *
  22183. * @param {String} event name
  22184. * @return {Socket} self
  22185. * @api public
  22186. */
  22187. Socket.prototype.emit = function(ev){
  22188. if (events.hasOwnProperty(ev)) {
  22189. emit.apply(this, arguments);
  22190. return this;
  22191. }
  22192. var args = toArray(arguments);
  22193. var parserType = parser.EVENT; // default
  22194. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  22195. var packet = { type: parserType, data: args };
  22196. // event ack callback
  22197. if ('function' == typeof args[args.length - 1]) {
  22198. debug('emitting packet with ack id %d', this.ids);
  22199. this.acks[this.ids] = args.pop();
  22200. packet.id = this.ids++;
  22201. }
  22202. if (this.connected) {
  22203. this.packet(packet);
  22204. } else {
  22205. this.sendBuffer.push(packet);
  22206. }
  22207. return this;
  22208. };
  22209. /**
  22210. * Sends a packet.
  22211. *
  22212. * @param {Object} packet
  22213. * @api private
  22214. */
  22215. Socket.prototype.packet = function(packet){
  22216. packet.nsp = this.nsp;
  22217. this.io.packet(packet);
  22218. };
  22219. /**
  22220. * Called upon engine `open`.
  22221. *
  22222. * @api private
  22223. */
  22224. Socket.prototype.onopen = function(){
  22225. debug('transport is open - connecting');
  22226. // write connect packet if necessary
  22227. if ('/' != this.nsp) {
  22228. this.packet({ type: parser.CONNECT });
  22229. }
  22230. };
  22231. /**
  22232. * Called upon engine `close`.
  22233. *
  22234. * @param {String} reason
  22235. * @api private
  22236. */
  22237. Socket.prototype.onclose = function(reason){
  22238. debug('close (%s)', reason);
  22239. this.connected = false;
  22240. this.disconnected = true;
  22241. delete this.id;
  22242. this.emit('disconnect', reason);
  22243. };
  22244. /**
  22245. * Called with socket packet.
  22246. *
  22247. * @param {Object} packet
  22248. * @api private
  22249. */
  22250. Socket.prototype.onpacket = function(packet){
  22251. if (packet.nsp != this.nsp) return;
  22252. switch (packet.type) {
  22253. case parser.CONNECT:
  22254. this.onconnect();
  22255. break;
  22256. case parser.EVENT:
  22257. this.onevent(packet);
  22258. break;
  22259. case parser.BINARY_EVENT:
  22260. this.onevent(packet);
  22261. break;
  22262. case parser.ACK:
  22263. this.onack(packet);
  22264. break;
  22265. case parser.BINARY_ACK:
  22266. this.onack(packet);
  22267. break;
  22268. case parser.DISCONNECT:
  22269. this.ondisconnect();
  22270. break;
  22271. case parser.ERROR:
  22272. this.emit('error', packet.data);
  22273. break;
  22274. }
  22275. };
  22276. /**
  22277. * Called upon a server event.
  22278. *
  22279. * @param {Object} packet
  22280. * @api private
  22281. */
  22282. Socket.prototype.onevent = function(packet){
  22283. var args = packet.data || [];
  22284. debug('emitting event %j', args);
  22285. if (null != packet.id) {
  22286. debug('attaching ack callback to event');
  22287. args.push(this.ack(packet.id));
  22288. }
  22289. if (this.connected) {
  22290. emit.apply(this, args);
  22291. } else {
  22292. this.receiveBuffer.push(args);
  22293. }
  22294. };
  22295. /**
  22296. * Produces an ack callback to emit with an event.
  22297. *
  22298. * @api private
  22299. */
  22300. Socket.prototype.ack = function(id){
  22301. var self = this;
  22302. var sent = false;
  22303. return function(){
  22304. // prevent double callbacks
  22305. if (sent) return;
  22306. sent = true;
  22307. var args = toArray(arguments);
  22308. debug('sending ack %j', args);
  22309. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  22310. self.packet({
  22311. type: type,
  22312. id: id,
  22313. data: args
  22314. });
  22315. };
  22316. };
  22317. /**
  22318. * Called upon a server acknowlegement.
  22319. *
  22320. * @param {Object} packet
  22321. * @api private
  22322. */
  22323. Socket.prototype.onack = function(packet){
  22324. debug('calling ack %s with %j', packet.id, packet.data);
  22325. var fn = this.acks[packet.id];
  22326. fn.apply(this, packet.data);
  22327. delete this.acks[packet.id];
  22328. };
  22329. /**
  22330. * Called upon server connect.
  22331. *
  22332. * @api private
  22333. */
  22334. Socket.prototype.onconnect = function(){
  22335. this.connected = true;
  22336. this.disconnected = false;
  22337. this.emit('connect');
  22338. this.emitBuffered();
  22339. };
  22340. /**
  22341. * Emit buffered events (received and emitted).
  22342. *
  22343. * @api private
  22344. */
  22345. Socket.prototype.emitBuffered = function(){
  22346. var i;
  22347. for (i = 0; i < this.receiveBuffer.length; i++) {
  22348. emit.apply(this, this.receiveBuffer[i]);
  22349. }
  22350. this.receiveBuffer = [];
  22351. for (i = 0; i < this.sendBuffer.length; i++) {
  22352. this.packet(this.sendBuffer[i]);
  22353. }
  22354. this.sendBuffer = [];
  22355. };
  22356. /**
  22357. * Called upon server disconnect.
  22358. *
  22359. * @api private
  22360. */
  22361. Socket.prototype.ondisconnect = function(){
  22362. debug('server disconnect (%s)', this.nsp);
  22363. this.destroy();
  22364. this.onclose('io server disconnect');
  22365. };
  22366. /**
  22367. * Called upon forced client/server side disconnections,
  22368. * this method ensures the manager stops tracking us and
  22369. * that reconnections don't get triggered for this.
  22370. *
  22371. * @api private.
  22372. */
  22373. Socket.prototype.destroy = function(){
  22374. if (this.subs) {
  22375. // clean subscriptions to avoid reconnections
  22376. for (var i = 0; i < this.subs.length; i++) {
  22377. this.subs[i].destroy();
  22378. }
  22379. this.subs = null;
  22380. }
  22381. this.io.destroy(this);
  22382. };
  22383. /**
  22384. * Disconnects the socket manually.
  22385. *
  22386. * @return {Socket} self
  22387. * @api public
  22388. */
  22389. Socket.prototype.close =
  22390. Socket.prototype.disconnect = function(){
  22391. if (this.connected) {
  22392. debug('performing disconnect (%s)', this.nsp);
  22393. this.packet({ type: parser.DISCONNECT });
  22394. }
  22395. // remove socket from pool
  22396. this.destroy();
  22397. if (this.connected) {
  22398. // fire events
  22399. this.onclose('io client disconnect');
  22400. }
  22401. return this;
  22402. };
  22403. },{"./on":88,"component-bind":92,"component-emitter":93,"debug":94,"has-binary":124,"socket.io-parser":130,"to-array":134}],90:[function(require,module,exports){
  22404. (function (global){
  22405. /**
  22406. * Module dependencies.
  22407. */
  22408. var parseuri = require('parseuri');
  22409. var debug = require('debug')('socket.io-client:url');
  22410. /**
  22411. * Module exports.
  22412. */
  22413. module.exports = url;
  22414. /**
  22415. * URL parser.
  22416. *
  22417. * @param {String} url
  22418. * @param {Object} An object meant to mimic window.location.
  22419. * Defaults to window.location.
  22420. * @api public
  22421. */
  22422. function url(uri, loc){
  22423. var obj = uri;
  22424. // default to window.location
  22425. var loc = loc || global.location;
  22426. if (null == uri) uri = loc.protocol + '//' + loc.host;
  22427. // relative path support
  22428. if ('string' == typeof uri) {
  22429. if ('/' == uri.charAt(0)) {
  22430. if ('/' == uri.charAt(1)) {
  22431. uri = loc.protocol + uri;
  22432. } else {
  22433. uri = loc.hostname + uri;
  22434. }
  22435. }
  22436. if (!/^(https?|wss?):\/\//.test(uri)) {
  22437. debug('protocol-less url %s', uri);
  22438. if ('undefined' != typeof loc) {
  22439. uri = loc.protocol + '//' + uri;
  22440. } else {
  22441. uri = 'https://' + uri;
  22442. }
  22443. }
  22444. // parse
  22445. debug('parse %s', uri);
  22446. obj = parseuri(uri);
  22447. }
  22448. // make sure we treat `localhost:80` and `localhost` equally
  22449. if (!obj.port) {
  22450. if (/^(http|ws)$/.test(obj.protocol)) {
  22451. obj.port = '80';
  22452. }
  22453. else if (/^(http|ws)s$/.test(obj.protocol)) {
  22454. obj.port = '443';
  22455. }
  22456. }
  22457. obj.path = obj.path || '/';
  22458. // define unique id
  22459. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  22460. // define href
  22461. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  22462. return obj;
  22463. }
  22464. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22465. },{"debug":94,"parseuri":128}],91:[function(require,module,exports){
  22466. /**
  22467. * Expose `Backoff`.
  22468. */
  22469. module.exports = Backoff;
  22470. /**
  22471. * Initialize backoff timer with `opts`.
  22472. *
  22473. * - `min` initial timeout in milliseconds [100]
  22474. * - `max` max timeout [10000]
  22475. * - `jitter` [0]
  22476. * - `factor` [2]
  22477. *
  22478. * @param {Object} opts
  22479. * @api public
  22480. */
  22481. function Backoff(opts) {
  22482. opts = opts || {};
  22483. this.ms = opts.min || 100;
  22484. this.max = opts.max || 10000;
  22485. this.factor = opts.factor || 2;
  22486. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  22487. this.attempts = 0;
  22488. }
  22489. /**
  22490. * Return the backoff duration.
  22491. *
  22492. * @return {Number}
  22493. * @api public
  22494. */
  22495. Backoff.prototype.duration = function(){
  22496. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  22497. if (this.jitter) {
  22498. var rand = Math.random();
  22499. var deviation = Math.floor(rand * this.jitter * ms);
  22500. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  22501. }
  22502. return Math.min(ms, this.max) | 0;
  22503. };
  22504. /**
  22505. * Reset the number of attempts.
  22506. *
  22507. * @api public
  22508. */
  22509. Backoff.prototype.reset = function(){
  22510. this.attempts = 0;
  22511. };
  22512. /**
  22513. * Set the minimum duration
  22514. *
  22515. * @api public
  22516. */
  22517. Backoff.prototype.setMin = function(min){
  22518. this.ms = min;
  22519. };
  22520. /**
  22521. * Set the maximum duration
  22522. *
  22523. * @api public
  22524. */
  22525. Backoff.prototype.setMax = function(max){
  22526. this.max = max;
  22527. };
  22528. /**
  22529. * Set the jitter
  22530. *
  22531. * @api public
  22532. */
  22533. Backoff.prototype.setJitter = function(jitter){
  22534. this.jitter = jitter;
  22535. };
  22536. },{}],92:[function(require,module,exports){
  22537. /**
  22538. * Slice reference.
  22539. */
  22540. var slice = [].slice;
  22541. /**
  22542. * Bind `obj` to `fn`.
  22543. *
  22544. * @param {Object} obj
  22545. * @param {Function|String} fn or string
  22546. * @return {Function}
  22547. * @api public
  22548. */
  22549. module.exports = function(obj, fn){
  22550. if ('string' == typeof fn) fn = obj[fn];
  22551. if ('function' != typeof fn) throw new Error('bind() requires a function');
  22552. var args = slice.call(arguments, 2);
  22553. return function(){
  22554. return fn.apply(obj, args.concat(slice.call(arguments)));
  22555. }
  22556. };
  22557. },{}],93:[function(require,module,exports){
  22558. /**
  22559. * Expose `Emitter`.
  22560. */
  22561. module.exports = Emitter;
  22562. /**
  22563. * Initialize a new `Emitter`.
  22564. *
  22565. * @api public
  22566. */
  22567. function Emitter(obj) {
  22568. if (obj) return mixin(obj);
  22569. };
  22570. /**
  22571. * Mixin the emitter properties.
  22572. *
  22573. * @param {Object} obj
  22574. * @return {Object}
  22575. * @api private
  22576. */
  22577. function mixin(obj) {
  22578. for (var key in Emitter.prototype) {
  22579. obj[key] = Emitter.prototype[key];
  22580. }
  22581. return obj;
  22582. }
  22583. /**
  22584. * Listen on the given `event` with `fn`.
  22585. *
  22586. * @param {String} event
  22587. * @param {Function} fn
  22588. * @return {Emitter}
  22589. * @api public
  22590. */
  22591. Emitter.prototype.on =
  22592. Emitter.prototype.addEventListener = function(event, fn){
  22593. this._callbacks = this._callbacks || {};
  22594. (this._callbacks[event] = this._callbacks[event] || [])
  22595. .push(fn);
  22596. return this;
  22597. };
  22598. /**
  22599. * Adds an `event` listener that will be invoked a single
  22600. * time then automatically removed.
  22601. *
  22602. * @param {String} event
  22603. * @param {Function} fn
  22604. * @return {Emitter}
  22605. * @api public
  22606. */
  22607. Emitter.prototype.once = function(event, fn){
  22608. var self = this;
  22609. this._callbacks = this._callbacks || {};
  22610. function on() {
  22611. self.off(event, on);
  22612. fn.apply(this, arguments);
  22613. }
  22614. on.fn = fn;
  22615. this.on(event, on);
  22616. return this;
  22617. };
  22618. /**
  22619. * Remove the given callback for `event` or all
  22620. * registered callbacks.
  22621. *
  22622. * @param {String} event
  22623. * @param {Function} fn
  22624. * @return {Emitter}
  22625. * @api public
  22626. */
  22627. Emitter.prototype.off =
  22628. Emitter.prototype.removeListener =
  22629. Emitter.prototype.removeAllListeners =
  22630. Emitter.prototype.removeEventListener = function(event, fn){
  22631. this._callbacks = this._callbacks || {};
  22632. // all
  22633. if (0 == arguments.length) {
  22634. this._callbacks = {};
  22635. return this;
  22636. }
  22637. // specific event
  22638. var callbacks = this._callbacks[event];
  22639. if (!callbacks) return this;
  22640. // remove all handlers
  22641. if (1 == arguments.length) {
  22642. delete this._callbacks[event];
  22643. return this;
  22644. }
  22645. // remove specific handler
  22646. var cb;
  22647. for (var i = 0; i < callbacks.length; i++) {
  22648. cb = callbacks[i];
  22649. if (cb === fn || cb.fn === fn) {
  22650. callbacks.splice(i, 1);
  22651. break;
  22652. }
  22653. }
  22654. return this;
  22655. };
  22656. /**
  22657. * Emit `event` with the given args.
  22658. *
  22659. * @param {String} event
  22660. * @param {Mixed} ...
  22661. * @return {Emitter}
  22662. */
  22663. Emitter.prototype.emit = function(event){
  22664. this._callbacks = this._callbacks || {};
  22665. var args = [].slice.call(arguments, 1)
  22666. , callbacks = this._callbacks[event];
  22667. if (callbacks) {
  22668. callbacks = callbacks.slice(0);
  22669. for (var i = 0, len = callbacks.length; i < len; ++i) {
  22670. callbacks[i].apply(this, args);
  22671. }
  22672. }
  22673. return this;
  22674. };
  22675. /**
  22676. * Return array of callbacks for `event`.
  22677. *
  22678. * @param {String} event
  22679. * @return {Array}
  22680. * @api public
  22681. */
  22682. Emitter.prototype.listeners = function(event){
  22683. this._callbacks = this._callbacks || {};
  22684. return this._callbacks[event] || [];
  22685. };
  22686. /**
  22687. * Check if this emitter has `event` handlers.
  22688. *
  22689. * @param {String} event
  22690. * @return {Boolean}
  22691. * @api public
  22692. */
  22693. Emitter.prototype.hasListeners = function(event){
  22694. return !! this.listeners(event).length;
  22695. };
  22696. },{}],94:[function(require,module,exports){
  22697. /**
  22698. * Expose `debug()` as the module.
  22699. */
  22700. module.exports = debug;
  22701. /**
  22702. * Create a debugger with the given `name`.
  22703. *
  22704. * @param {String} name
  22705. * @return {Type}
  22706. * @api public
  22707. */
  22708. function debug(name) {
  22709. if (!debug.enabled(name)) return function(){};
  22710. return function(fmt){
  22711. fmt = coerce(fmt);
  22712. var curr = new Date;
  22713. var ms = curr - (debug[name] || curr);
  22714. debug[name] = curr;
  22715. fmt = name
  22716. + ' '
  22717. + fmt
  22718. + ' +' + debug.humanize(ms);
  22719. // This hackery is required for IE8
  22720. // where `console.log` doesn't have 'apply'
  22721. window.console
  22722. && console.log
  22723. && Function.prototype.apply.call(console.log, console, arguments);
  22724. }
  22725. }
  22726. /**
  22727. * The currently active debug mode names.
  22728. */
  22729. debug.names = [];
  22730. debug.skips = [];
  22731. /**
  22732. * Enables a debug mode by name. This can include modes
  22733. * separated by a colon and wildcards.
  22734. *
  22735. * @param {String} name
  22736. * @api public
  22737. */
  22738. debug.enable = function(name) {
  22739. try {
  22740. localStorage.debug = name;
  22741. } catch(e){}
  22742. var split = (name || '').split(/[\s,]+/)
  22743. , len = split.length;
  22744. for (var i = 0; i < len; i++) {
  22745. name = split[i].replace('*', '.*?');
  22746. if (name[0] === '-') {
  22747. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  22748. }
  22749. else {
  22750. debug.names.push(new RegExp('^' + name + '$'));
  22751. }
  22752. }
  22753. };
  22754. /**
  22755. * Disable debug output.
  22756. *
  22757. * @api public
  22758. */
  22759. debug.disable = function(){
  22760. debug.enable('');
  22761. };
  22762. /**
  22763. * Humanize the given `ms`.
  22764. *
  22765. * @param {Number} m
  22766. * @return {String}
  22767. * @api private
  22768. */
  22769. debug.humanize = function(ms) {
  22770. var sec = 1000
  22771. , min = 60 * 1000
  22772. , hour = 60 * min;
  22773. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  22774. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  22775. if (ms >= sec) return (ms / sec | 0) + 's';
  22776. return ms + 'ms';
  22777. };
  22778. /**
  22779. * Returns true if the given mode name is enabled, false otherwise.
  22780. *
  22781. * @param {String} name
  22782. * @return {Boolean}
  22783. * @api public
  22784. */
  22785. debug.enabled = function(name) {
  22786. for (var i = 0, len = debug.skips.length; i < len; i++) {
  22787. if (debug.skips[i].test(name)) {
  22788. return false;
  22789. }
  22790. }
  22791. for (var i = 0, len = debug.names.length; i < len; i++) {
  22792. if (debug.names[i].test(name)) {
  22793. return true;
  22794. }
  22795. }
  22796. return false;
  22797. };
  22798. /**
  22799. * Coerce `val`.
  22800. */
  22801. function coerce(val) {
  22802. if (val instanceof Error) return val.stack || val.message;
  22803. return val;
  22804. }
  22805. // persist
  22806. try {
  22807. if (window.localStorage) debug.enable(localStorage.debug);
  22808. } catch(e){}
  22809. },{}],95:[function(require,module,exports){
  22810. module.exports = require('./lib/');
  22811. },{"./lib/":96}],96:[function(require,module,exports){
  22812. module.exports = require('./socket');
  22813. /**
  22814. * Exports parser
  22815. *
  22816. * @api public
  22817. *
  22818. */
  22819. module.exports.parser = require('engine.io-parser');
  22820. },{"./socket":97,"engine.io-parser":109}],97:[function(require,module,exports){
  22821. (function (global){
  22822. /**
  22823. * Module dependencies.
  22824. */
  22825. var transports = require('./transports');
  22826. var Emitter = require('component-emitter');
  22827. var debug = require('debug')('engine.io-client:socket');
  22828. var index = require('indexof');
  22829. var parser = require('engine.io-parser');
  22830. var parseuri = require('parseuri');
  22831. var parsejson = require('parsejson');
  22832. var parseqs = require('parseqs');
  22833. /**
  22834. * Module exports.
  22835. */
  22836. module.exports = Socket;
  22837. /**
  22838. * Noop function.
  22839. *
  22840. * @api private
  22841. */
  22842. function noop(){}
  22843. /**
  22844. * Socket constructor.
  22845. *
  22846. * @param {String|Object} uri or options
  22847. * @param {Object} options
  22848. * @api public
  22849. */
  22850. function Socket(uri, opts){
  22851. if (!(this instanceof Socket)) return new Socket(uri, opts);
  22852. opts = opts || {};
  22853. if (uri && 'object' == typeof uri) {
  22854. opts = uri;
  22855. uri = null;
  22856. }
  22857. if (uri) {
  22858. uri = parseuri(uri);
  22859. opts.host = uri.host;
  22860. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  22861. opts.port = uri.port;
  22862. if (uri.query) opts.query = uri.query;
  22863. }
  22864. this.secure = null != opts.secure ? opts.secure :
  22865. (global.location && 'https:' == location.protocol);
  22866. if (opts.host) {
  22867. var pieces = opts.host.split(':');
  22868. opts.hostname = pieces.shift();
  22869. if (pieces.length) {
  22870. opts.port = pieces.pop();
  22871. } else if (!opts.port) {
  22872. // if no port is specified manually, use the protocol default
  22873. opts.port = this.secure ? '443' : '80';
  22874. }
  22875. }
  22876. this.agent = opts.agent || false;
  22877. this.hostname = opts.hostname ||
  22878. (global.location ? location.hostname : 'localhost');
  22879. this.port = opts.port || (global.location && location.port ?
  22880. location.port :
  22881. (this.secure ? 443 : 80));
  22882. this.query = opts.query || {};
  22883. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  22884. this.upgrade = false !== opts.upgrade;
  22885. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  22886. this.forceJSONP = !!opts.forceJSONP;
  22887. this.jsonp = false !== opts.jsonp;
  22888. this.forceBase64 = !!opts.forceBase64;
  22889. this.enablesXDR = !!opts.enablesXDR;
  22890. this.timestampParam = opts.timestampParam || 't';
  22891. this.timestampRequests = opts.timestampRequests;
  22892. this.transports = opts.transports || ['polling', 'websocket'];
  22893. this.readyState = '';
  22894. this.writeBuffer = [];
  22895. this.callbackBuffer = [];
  22896. this.policyPort = opts.policyPort || 843;
  22897. this.rememberUpgrade = opts.rememberUpgrade || false;
  22898. this.binaryType = null;
  22899. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  22900. // SSL options for Node.js client
  22901. this.pfx = opts.pfx || null;
  22902. this.key = opts.key || null;
  22903. this.passphrase = opts.passphrase || null;
  22904. this.cert = opts.cert || null;
  22905. this.ca = opts.ca || null;
  22906. this.ciphers = opts.ciphers || null;
  22907. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  22908. this.open();
  22909. }
  22910. Socket.priorWebsocketSuccess = false;
  22911. /**
  22912. * Mix in `Emitter`.
  22913. */
  22914. Emitter(Socket.prototype);
  22915. /**
  22916. * Protocol version.
  22917. *
  22918. * @api public
  22919. */
  22920. Socket.protocol = parser.protocol; // this is an int
  22921. /**
  22922. * Expose deps for legacy compatibility
  22923. * and standalone browser access.
  22924. */
  22925. Socket.Socket = Socket;
  22926. Socket.Transport = require('./transport');
  22927. Socket.transports = require('./transports');
  22928. Socket.parser = require('engine.io-parser');
  22929. /**
  22930. * Creates transport of the given type.
  22931. *
  22932. * @param {String} transport name
  22933. * @return {Transport}
  22934. * @api private
  22935. */
  22936. Socket.prototype.createTransport = function (name) {
  22937. debug('creating transport "%s"', name);
  22938. var query = clone(this.query);
  22939. // append engine.io protocol identifier
  22940. query.EIO = parser.protocol;
  22941. // transport name
  22942. query.transport = name;
  22943. // session id if we already have one
  22944. if (this.id) query.sid = this.id;
  22945. var transport = new transports[name]({
  22946. agent: this.agent,
  22947. hostname: this.hostname,
  22948. port: this.port,
  22949. secure: this.secure,
  22950. path: this.path,
  22951. query: query,
  22952. forceJSONP: this.forceJSONP,
  22953. jsonp: this.jsonp,
  22954. forceBase64: this.forceBase64,
  22955. enablesXDR: this.enablesXDR,
  22956. timestampRequests: this.timestampRequests,
  22957. timestampParam: this.timestampParam,
  22958. policyPort: this.policyPort,
  22959. socket: this,
  22960. pfx: this.pfx,
  22961. key: this.key,
  22962. passphrase: this.passphrase,
  22963. cert: this.cert,
  22964. ca: this.ca,
  22965. ciphers: this.ciphers,
  22966. rejectUnauthorized: this.rejectUnauthorized
  22967. });
  22968. return transport;
  22969. };
  22970. function clone (obj) {
  22971. var o = {};
  22972. for (var i in obj) {
  22973. if (obj.hasOwnProperty(i)) {
  22974. o[i] = obj[i];
  22975. }
  22976. }
  22977. return o;
  22978. }
  22979. /**
  22980. * Initializes transport to use and starts probe.
  22981. *
  22982. * @api private
  22983. */
  22984. Socket.prototype.open = function () {
  22985. var transport;
  22986. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  22987. transport = 'websocket';
  22988. } else if (0 == this.transports.length) {
  22989. // Emit error on next tick so it can be listened to
  22990. var self = this;
  22991. setTimeout(function() {
  22992. self.emit('error', 'No transports available');
  22993. }, 0);
  22994. return;
  22995. } else {
  22996. transport = this.transports[0];
  22997. }
  22998. this.readyState = 'opening';
  22999. // Retry with the next transport if the transport is disabled (jsonp: false)
  23000. var transport;
  23001. try {
  23002. transport = this.createTransport(transport);
  23003. } catch (e) {
  23004. this.transports.shift();
  23005. this.open();
  23006. return;
  23007. }
  23008. transport.open();
  23009. this.setTransport(transport);
  23010. };
  23011. /**
  23012. * Sets the current transport. Disables the existing one (if any).
  23013. *
  23014. * @api private
  23015. */
  23016. Socket.prototype.setTransport = function(transport){
  23017. debug('setting transport %s', transport.name);
  23018. var self = this;
  23019. if (this.transport) {
  23020. debug('clearing existing transport %s', this.transport.name);
  23021. this.transport.removeAllListeners();
  23022. }
  23023. // set up transport
  23024. this.transport = transport;
  23025. // set up transport listeners
  23026. transport
  23027. .on('drain', function(){
  23028. self.onDrain();
  23029. })
  23030. .on('packet', function(packet){
  23031. self.onPacket(packet);
  23032. })
  23033. .on('error', function(e){
  23034. self.onError(e);
  23035. })
  23036. .on('close', function(){
  23037. self.onClose('transport close');
  23038. });
  23039. };
  23040. /**
  23041. * Probes a transport.
  23042. *
  23043. * @param {String} transport name
  23044. * @api private
  23045. */
  23046. Socket.prototype.probe = function (name) {
  23047. debug('probing transport "%s"', name);
  23048. var transport = this.createTransport(name, { probe: 1 })
  23049. , failed = false
  23050. , self = this;
  23051. Socket.priorWebsocketSuccess = false;
  23052. function onTransportOpen(){
  23053. if (self.onlyBinaryUpgrades) {
  23054. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  23055. failed = failed || upgradeLosesBinary;
  23056. }
  23057. if (failed) return;
  23058. debug('probe transport "%s" opened', name);
  23059. transport.send([{ type: 'ping', data: 'probe' }]);
  23060. transport.once('packet', function (msg) {
  23061. if (failed) return;
  23062. if ('pong' == msg.type && 'probe' == msg.data) {
  23063. debug('probe transport "%s" pong', name);
  23064. self.upgrading = true;
  23065. self.emit('upgrading', transport);
  23066. if (!transport) return;
  23067. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  23068. debug('pausing current transport "%s"', self.transport.name);
  23069. self.transport.pause(function () {
  23070. if (failed) return;
  23071. if ('closed' == self.readyState) return;
  23072. debug('changing transport and sending upgrade packet');
  23073. cleanup();
  23074. self.setTransport(transport);
  23075. transport.send([{ type: 'upgrade' }]);
  23076. self.emit('upgrade', transport);
  23077. transport = null;
  23078. self.upgrading = false;
  23079. self.flush();
  23080. });
  23081. } else {
  23082. debug('probe transport "%s" failed', name);
  23083. var err = new Error('probe error');
  23084. err.transport = transport.name;
  23085. self.emit('upgradeError', err);
  23086. }
  23087. });
  23088. }
  23089. function freezeTransport() {
  23090. if (failed) return;
  23091. // Any callback called by transport should be ignored since now
  23092. failed = true;
  23093. cleanup();
  23094. transport.close();
  23095. transport = null;
  23096. }
  23097. //Handle any error that happens while probing
  23098. function onerror(err) {
  23099. var error = new Error('probe error: ' + err);
  23100. error.transport = transport.name;
  23101. freezeTransport();
  23102. debug('probe transport "%s" failed because of error: %s', name, err);
  23103. self.emit('upgradeError', error);
  23104. }
  23105. function onTransportClose(){
  23106. onerror("transport closed");
  23107. }
  23108. //When the socket is closed while we're probing
  23109. function onclose(){
  23110. onerror("socket closed");
  23111. }
  23112. //When the socket is upgraded while we're probing
  23113. function onupgrade(to){
  23114. if (transport && to.name != transport.name) {
  23115. debug('"%s" works - aborting "%s"', to.name, transport.name);
  23116. freezeTransport();
  23117. }
  23118. }
  23119. //Remove all listeners on the transport and on self
  23120. function cleanup(){
  23121. transport.removeListener('open', onTransportOpen);
  23122. transport.removeListener('error', onerror);
  23123. transport.removeListener('close', onTransportClose);
  23124. self.removeListener('close', onclose);
  23125. self.removeListener('upgrading', onupgrade);
  23126. }
  23127. transport.once('open', onTransportOpen);
  23128. transport.once('error', onerror);
  23129. transport.once('close', onTransportClose);
  23130. this.once('close', onclose);
  23131. this.once('upgrading', onupgrade);
  23132. transport.open();
  23133. };
  23134. /**
  23135. * Called when connection is deemed open.
  23136. *
  23137. * @api public
  23138. */
  23139. Socket.prototype.onOpen = function () {
  23140. debug('socket open');
  23141. this.readyState = 'open';
  23142. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  23143. this.emit('open');
  23144. this.flush();
  23145. // we check for `readyState` in case an `open`
  23146. // listener already closed the socket
  23147. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  23148. debug('starting upgrade probes');
  23149. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  23150. this.probe(this.upgrades[i]);
  23151. }
  23152. }
  23153. };
  23154. /**
  23155. * Handles a packet.
  23156. *
  23157. * @api private
  23158. */
  23159. Socket.prototype.onPacket = function (packet) {
  23160. if ('opening' == this.readyState || 'open' == this.readyState) {
  23161. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  23162. this.emit('packet', packet);
  23163. // Socket is live - any packet counts
  23164. this.emit('heartbeat');
  23165. switch (packet.type) {
  23166. case 'open':
  23167. this.onHandshake(parsejson(packet.data));
  23168. break;
  23169. case 'pong':
  23170. this.setPing();
  23171. break;
  23172. case 'error':
  23173. var err = new Error('server error');
  23174. err.code = packet.data;
  23175. this.emit('error', err);
  23176. break;
  23177. case 'message':
  23178. this.emit('data', packet.data);
  23179. this.emit('message', packet.data);
  23180. break;
  23181. }
  23182. } else {
  23183. debug('packet received with socket readyState "%s"', this.readyState);
  23184. }
  23185. };
  23186. /**
  23187. * Called upon handshake completion.
  23188. *
  23189. * @param {Object} handshake obj
  23190. * @api private
  23191. */
  23192. Socket.prototype.onHandshake = function (data) {
  23193. this.emit('handshake', data);
  23194. this.id = data.sid;
  23195. this.transport.query.sid = data.sid;
  23196. this.upgrades = this.filterUpgrades(data.upgrades);
  23197. this.pingInterval = data.pingInterval;
  23198. this.pingTimeout = data.pingTimeout;
  23199. this.onOpen();
  23200. // In case open handler closes socket
  23201. if ('closed' == this.readyState) return;
  23202. this.setPing();
  23203. // Prolong liveness of socket on heartbeat
  23204. this.removeListener('heartbeat', this.onHeartbeat);
  23205. this.on('heartbeat', this.onHeartbeat);
  23206. };
  23207. /**
  23208. * Resets ping timeout.
  23209. *
  23210. * @api private
  23211. */
  23212. Socket.prototype.onHeartbeat = function (timeout) {
  23213. clearTimeout(this.pingTimeoutTimer);
  23214. var self = this;
  23215. self.pingTimeoutTimer = setTimeout(function () {
  23216. if ('closed' == self.readyState) return;
  23217. self.onClose('ping timeout');
  23218. }, timeout || (self.pingInterval + self.pingTimeout));
  23219. };
  23220. /**
  23221. * Pings server every `this.pingInterval` and expects response
  23222. * within `this.pingTimeout` or closes connection.
  23223. *
  23224. * @api private
  23225. */
  23226. Socket.prototype.setPing = function () {
  23227. var self = this;
  23228. clearTimeout(self.pingIntervalTimer);
  23229. self.pingIntervalTimer = setTimeout(function () {
  23230. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  23231. self.ping();
  23232. self.onHeartbeat(self.pingTimeout);
  23233. }, self.pingInterval);
  23234. };
  23235. /**
  23236. * Sends a ping packet.
  23237. *
  23238. * @api public
  23239. */
  23240. Socket.prototype.ping = function () {
  23241. this.sendPacket('ping');
  23242. };
  23243. /**
  23244. * Called on `drain` event
  23245. *
  23246. * @api private
  23247. */
  23248. Socket.prototype.onDrain = function() {
  23249. for (var i = 0; i < this.prevBufferLen; i++) {
  23250. if (this.callbackBuffer[i]) {
  23251. this.callbackBuffer[i]();
  23252. }
  23253. }
  23254. this.writeBuffer.splice(0, this.prevBufferLen);
  23255. this.callbackBuffer.splice(0, this.prevBufferLen);
  23256. // setting prevBufferLen = 0 is very important
  23257. // for example, when upgrading, upgrade packet is sent over,
  23258. // and a nonzero prevBufferLen could cause problems on `drain`
  23259. this.prevBufferLen = 0;
  23260. if (this.writeBuffer.length == 0) {
  23261. this.emit('drain');
  23262. } else {
  23263. this.flush();
  23264. }
  23265. };
  23266. /**
  23267. * Flush write buffers.
  23268. *
  23269. * @api private
  23270. */
  23271. Socket.prototype.flush = function () {
  23272. if ('closed' != this.readyState && this.transport.writable &&
  23273. !this.upgrading && this.writeBuffer.length) {
  23274. debug('flushing %d packets in socket', this.writeBuffer.length);
  23275. this.transport.send(this.writeBuffer);
  23276. // keep track of current length of writeBuffer
  23277. // splice writeBuffer and callbackBuffer on `drain`
  23278. this.prevBufferLen = this.writeBuffer.length;
  23279. this.emit('flush');
  23280. }
  23281. };
  23282. /**
  23283. * Sends a message.
  23284. *
  23285. * @param {String} message.
  23286. * @param {Function} callback function.
  23287. * @return {Socket} for chaining.
  23288. * @api public
  23289. */
  23290. Socket.prototype.write =
  23291. Socket.prototype.send = function (msg, fn) {
  23292. this.sendPacket('message', msg, fn);
  23293. return this;
  23294. };
  23295. /**
  23296. * Sends a packet.
  23297. *
  23298. * @param {String} packet type.
  23299. * @param {String} data.
  23300. * @param {Function} callback function.
  23301. * @api private
  23302. */
  23303. Socket.prototype.sendPacket = function (type, data, fn) {
  23304. if ('closing' == this.readyState || 'closed' == this.readyState) {
  23305. return;
  23306. }
  23307. var packet = { type: type, data: data };
  23308. this.emit('packetCreate', packet);
  23309. this.writeBuffer.push(packet);
  23310. this.callbackBuffer.push(fn);
  23311. this.flush();
  23312. };
  23313. /**
  23314. * Closes the connection.
  23315. *
  23316. * @api private
  23317. */
  23318. Socket.prototype.close = function () {
  23319. if ('opening' == this.readyState || 'open' == this.readyState) {
  23320. this.readyState = 'closing';
  23321. var self = this;
  23322. function close() {
  23323. self.onClose('forced close');
  23324. debug('socket closing - telling transport to close');
  23325. self.transport.close();
  23326. }
  23327. function cleanupAndClose() {
  23328. self.removeListener('upgrade', cleanupAndClose);
  23329. self.removeListener('upgradeError', cleanupAndClose);
  23330. close();
  23331. }
  23332. function waitForUpgrade() {
  23333. // wait for upgrade to finish since we can't send packets while pausing a transport
  23334. self.once('upgrade', cleanupAndClose);
  23335. self.once('upgradeError', cleanupAndClose);
  23336. }
  23337. if (this.writeBuffer.length) {
  23338. this.once('drain', function() {
  23339. if (this.upgrading) {
  23340. waitForUpgrade();
  23341. } else {
  23342. close();
  23343. }
  23344. });
  23345. } else if (this.upgrading) {
  23346. waitForUpgrade();
  23347. } else {
  23348. close();
  23349. }
  23350. }
  23351. return this;
  23352. };
  23353. /**
  23354. * Called upon transport error
  23355. *
  23356. * @api private
  23357. */
  23358. Socket.prototype.onError = function (err) {
  23359. debug('socket error %j', err);
  23360. Socket.priorWebsocketSuccess = false;
  23361. this.emit('error', err);
  23362. this.onClose('transport error', err);
  23363. };
  23364. /**
  23365. * Called upon transport close.
  23366. *
  23367. * @api private
  23368. */
  23369. Socket.prototype.onClose = function (reason, desc) {
  23370. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  23371. debug('socket close with reason: "%s"', reason);
  23372. var self = this;
  23373. // clear timers
  23374. clearTimeout(this.pingIntervalTimer);
  23375. clearTimeout(this.pingTimeoutTimer);
  23376. // clean buffers in next tick, so developers can still
  23377. // grab the buffers on `close` event
  23378. setTimeout(function() {
  23379. self.writeBuffer = [];
  23380. self.callbackBuffer = [];
  23381. self.prevBufferLen = 0;
  23382. }, 0);
  23383. // stop event from firing again for transport
  23384. this.transport.removeAllListeners('close');
  23385. // ensure transport won't stay open
  23386. this.transport.close();
  23387. // ignore further transport communication
  23388. this.transport.removeAllListeners();
  23389. // set ready state
  23390. this.readyState = 'closed';
  23391. // clear session id
  23392. this.id = null;
  23393. // emit close event
  23394. this.emit('close', reason, desc);
  23395. }
  23396. };
  23397. /**
  23398. * Filters upgrades, returning only those matching client transports.
  23399. *
  23400. * @param {Array} server upgrades
  23401. * @api private
  23402. *
  23403. */
  23404. Socket.prototype.filterUpgrades = function (upgrades) {
  23405. var filteredUpgrades = [];
  23406. for (var i = 0, j = upgrades.length; i<j; i++) {
  23407. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  23408. }
  23409. return filteredUpgrades;
  23410. };
  23411. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23412. },{"./transport":98,"./transports":99,"component-emitter":93,"debug":106,"engine.io-parser":109,"indexof":126,"parsejson":120,"parseqs":121,"parseuri":122}],98:[function(require,module,exports){
  23413. /**
  23414. * Module dependencies.
  23415. */
  23416. var parser = require('engine.io-parser');
  23417. var Emitter = require('component-emitter');
  23418. /**
  23419. * Module exports.
  23420. */
  23421. module.exports = Transport;
  23422. /**
  23423. * Transport abstract constructor.
  23424. *
  23425. * @param {Object} options.
  23426. * @api private
  23427. */
  23428. function Transport (opts) {
  23429. this.path = opts.path;
  23430. this.hostname = opts.hostname;
  23431. this.port = opts.port;
  23432. this.secure = opts.secure;
  23433. this.query = opts.query;
  23434. this.timestampParam = opts.timestampParam;
  23435. this.timestampRequests = opts.timestampRequests;
  23436. this.readyState = '';
  23437. this.agent = opts.agent || false;
  23438. this.socket = opts.socket;
  23439. this.enablesXDR = opts.enablesXDR;
  23440. // SSL options for Node.js client
  23441. this.pfx = opts.pfx;
  23442. this.key = opts.key;
  23443. this.passphrase = opts.passphrase;
  23444. this.cert = opts.cert;
  23445. this.ca = opts.ca;
  23446. this.ciphers = opts.ciphers;
  23447. this.rejectUnauthorized = opts.rejectUnauthorized;
  23448. }
  23449. /**
  23450. * Mix in `Emitter`.
  23451. */
  23452. Emitter(Transport.prototype);
  23453. /**
  23454. * A counter used to prevent collisions in the timestamps used
  23455. * for cache busting.
  23456. */
  23457. Transport.timestamps = 0;
  23458. /**
  23459. * Emits an error.
  23460. *
  23461. * @param {String} str
  23462. * @return {Transport} for chaining
  23463. * @api public
  23464. */
  23465. Transport.prototype.onError = function (msg, desc) {
  23466. var err = new Error(msg);
  23467. err.type = 'TransportError';
  23468. err.description = desc;
  23469. this.emit('error', err);
  23470. return this;
  23471. };
  23472. /**
  23473. * Opens the transport.
  23474. *
  23475. * @api public
  23476. */
  23477. Transport.prototype.open = function () {
  23478. if ('closed' == this.readyState || '' == this.readyState) {
  23479. this.readyState = 'opening';
  23480. this.doOpen();
  23481. }
  23482. return this;
  23483. };
  23484. /**
  23485. * Closes the transport.
  23486. *
  23487. * @api private
  23488. */
  23489. Transport.prototype.close = function () {
  23490. if ('opening' == this.readyState || 'open' == this.readyState) {
  23491. this.doClose();
  23492. this.onClose();
  23493. }
  23494. return this;
  23495. };
  23496. /**
  23497. * Sends multiple packets.
  23498. *
  23499. * @param {Array} packets
  23500. * @api private
  23501. */
  23502. Transport.prototype.send = function(packets){
  23503. if ('open' == this.readyState) {
  23504. this.write(packets);
  23505. } else {
  23506. throw new Error('Transport not open');
  23507. }
  23508. };
  23509. /**
  23510. * Called upon open
  23511. *
  23512. * @api private
  23513. */
  23514. Transport.prototype.onOpen = function () {
  23515. this.readyState = 'open';
  23516. this.writable = true;
  23517. this.emit('open');
  23518. };
  23519. /**
  23520. * Called with data.
  23521. *
  23522. * @param {String} data
  23523. * @api private
  23524. */
  23525. Transport.prototype.onData = function(data){
  23526. var packet = parser.decodePacket(data, this.socket.binaryType);
  23527. this.onPacket(packet);
  23528. };
  23529. /**
  23530. * Called with a decoded packet.
  23531. */
  23532. Transport.prototype.onPacket = function (packet) {
  23533. this.emit('packet', packet);
  23534. };
  23535. /**
  23536. * Called upon close.
  23537. *
  23538. * @api private
  23539. */
  23540. Transport.prototype.onClose = function () {
  23541. this.readyState = 'closed';
  23542. this.emit('close');
  23543. };
  23544. },{"component-emitter":93,"engine.io-parser":109}],99:[function(require,module,exports){
  23545. (function (global){
  23546. /**
  23547. * Module dependencies
  23548. */
  23549. var XMLHttpRequest = require('xmlhttprequest');
  23550. var XHR = require('./polling-xhr');
  23551. var JSONP = require('./polling-jsonp');
  23552. var websocket = require('./websocket');
  23553. /**
  23554. * Export transports.
  23555. */
  23556. exports.polling = polling;
  23557. exports.websocket = websocket;
  23558. /**
  23559. * Polling transport polymorphic constructor.
  23560. * Decides on xhr vs jsonp based on feature detection.
  23561. *
  23562. * @api private
  23563. */
  23564. function polling(opts){
  23565. var xhr;
  23566. var xd = false;
  23567. var xs = false;
  23568. var jsonp = false !== opts.jsonp;
  23569. if (global.location) {
  23570. var isSSL = 'https:' == location.protocol;
  23571. var port = location.port;
  23572. // some user agents have empty `location.port`
  23573. if (!port) {
  23574. port = isSSL ? 443 : 80;
  23575. }
  23576. xd = opts.hostname != location.hostname || port != opts.port;
  23577. xs = opts.secure != isSSL;
  23578. }
  23579. opts.xdomain = xd;
  23580. opts.xscheme = xs;
  23581. xhr = new XMLHttpRequest(opts);
  23582. if ('open' in xhr && !opts.forceJSONP) {
  23583. return new XHR(opts);
  23584. } else {
  23585. if (!jsonp) throw new Error('JSONP disabled');
  23586. return new JSONP(opts);
  23587. }
  23588. }
  23589. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23590. },{"./polling-jsonp":100,"./polling-xhr":101,"./websocket":103,"xmlhttprequest":104}],100:[function(require,module,exports){
  23591. (function (global){
  23592. /**
  23593. * Module requirements.
  23594. */
  23595. var Polling = require('./polling');
  23596. var inherit = require('component-inherit');
  23597. /**
  23598. * Module exports.
  23599. */
  23600. module.exports = JSONPPolling;
  23601. /**
  23602. * Cached regular expressions.
  23603. */
  23604. var rNewline = /\n/g;
  23605. var rEscapedNewline = /\\n/g;
  23606. /**
  23607. * Global JSONP callbacks.
  23608. */
  23609. var callbacks;
  23610. /**
  23611. * Callbacks count.
  23612. */
  23613. var index = 0;
  23614. /**
  23615. * Noop.
  23616. */
  23617. function empty () { }
  23618. /**
  23619. * JSONP Polling constructor.
  23620. *
  23621. * @param {Object} opts.
  23622. * @api public
  23623. */
  23624. function JSONPPolling (opts) {
  23625. Polling.call(this, opts);
  23626. this.query = this.query || {};
  23627. // define global callbacks array if not present
  23628. // we do this here (lazily) to avoid unneeded global pollution
  23629. if (!callbacks) {
  23630. // we need to consider multiple engines in the same page
  23631. if (!global.___eio) global.___eio = [];
  23632. callbacks = global.___eio;
  23633. }
  23634. // callback identifier
  23635. this.index = callbacks.length;
  23636. // add callback to jsonp global
  23637. var self = this;
  23638. callbacks.push(function (msg) {
  23639. self.onData(msg);
  23640. });
  23641. // append to query string
  23642. this.query.j = this.index;
  23643. // prevent spurious errors from being emitted when the window is unloaded
  23644. if (global.document && global.addEventListener) {
  23645. global.addEventListener('beforeunload', function () {
  23646. if (self.script) self.script.onerror = empty;
  23647. }, false);
  23648. }
  23649. }
  23650. /**
  23651. * Inherits from Polling.
  23652. */
  23653. inherit(JSONPPolling, Polling);
  23654. /*
  23655. * JSONP only supports binary as base64 encoded strings
  23656. */
  23657. JSONPPolling.prototype.supportsBinary = false;
  23658. /**
  23659. * Closes the socket.
  23660. *
  23661. * @api private
  23662. */
  23663. JSONPPolling.prototype.doClose = function () {
  23664. if (this.script) {
  23665. this.script.parentNode.removeChild(this.script);
  23666. this.script = null;
  23667. }
  23668. if (this.form) {
  23669. this.form.parentNode.removeChild(this.form);
  23670. this.form = null;
  23671. this.iframe = null;
  23672. }
  23673. Polling.prototype.doClose.call(this);
  23674. };
  23675. /**
  23676. * Starts a poll cycle.
  23677. *
  23678. * @api private
  23679. */
  23680. JSONPPolling.prototype.doPoll = function () {
  23681. var self = this;
  23682. var script = document.createElement('script');
  23683. if (this.script) {
  23684. this.script.parentNode.removeChild(this.script);
  23685. this.script = null;
  23686. }
  23687. script.async = true;
  23688. script.src = this.uri();
  23689. script.onerror = function(e){
  23690. self.onError('jsonp poll error',e);
  23691. };
  23692. var insertAt = document.getElementsByTagName('script')[0];
  23693. insertAt.parentNode.insertBefore(script, insertAt);
  23694. this.script = script;
  23695. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  23696. if (isUAgecko) {
  23697. setTimeout(function () {
  23698. var iframe = document.createElement('iframe');
  23699. document.body.appendChild(iframe);
  23700. document.body.removeChild(iframe);
  23701. }, 100);
  23702. }
  23703. };
  23704. /**
  23705. * Writes with a hidden iframe.
  23706. *
  23707. * @param {String} data to send
  23708. * @param {Function} called upon flush.
  23709. * @api private
  23710. */
  23711. JSONPPolling.prototype.doWrite = function (data, fn) {
  23712. var self = this;
  23713. if (!this.form) {
  23714. var form = document.createElement('form');
  23715. var area = document.createElement('textarea');
  23716. var id = this.iframeId = 'eio_iframe_' + this.index;
  23717. var iframe;
  23718. form.className = 'socketio';
  23719. form.style.position = 'absolute';
  23720. form.style.top = '-1000px';
  23721. form.style.left = '-1000px';
  23722. form.target = id;
  23723. form.method = 'POST';
  23724. form.setAttribute('accept-charset', 'utf-8');
  23725. area.name = 'd';
  23726. form.appendChild(area);
  23727. document.body.appendChild(form);
  23728. this.form = form;
  23729. this.area = area;
  23730. }
  23731. this.form.action = this.uri();
  23732. function complete () {
  23733. initIframe();
  23734. fn();
  23735. }
  23736. function initIframe () {
  23737. if (self.iframe) {
  23738. try {
  23739. self.form.removeChild(self.iframe);
  23740. } catch (e) {
  23741. self.onError('jsonp polling iframe removal error', e);
  23742. }
  23743. }
  23744. try {
  23745. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  23746. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  23747. iframe = document.createElement(html);
  23748. } catch (e) {
  23749. iframe = document.createElement('iframe');
  23750. iframe.name = self.iframeId;
  23751. iframe.src = 'javascript:0';
  23752. }
  23753. iframe.id = self.iframeId;
  23754. self.form.appendChild(iframe);
  23755. self.iframe = iframe;
  23756. }
  23757. initIframe();
  23758. // escape \n to prevent it from being converted into \r\n by some UAs
  23759. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  23760. data = data.replace(rEscapedNewline, '\\\n');
  23761. this.area.value = data.replace(rNewline, '\\n');
  23762. try {
  23763. this.form.submit();
  23764. } catch(e) {}
  23765. if (this.iframe.attachEvent) {
  23766. this.iframe.onreadystatechange = function(){
  23767. if (self.iframe.readyState == 'complete') {
  23768. complete();
  23769. }
  23770. };
  23771. } else {
  23772. this.iframe.onload = complete;
  23773. }
  23774. };
  23775. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23776. },{"./polling":102,"component-inherit":105}],101:[function(require,module,exports){
  23777. (function (global){
  23778. /**
  23779. * Module requirements.
  23780. */
  23781. var XMLHttpRequest = require('xmlhttprequest');
  23782. var Polling = require('./polling');
  23783. var Emitter = require('component-emitter');
  23784. var inherit = require('component-inherit');
  23785. var debug = require('debug')('engine.io-client:polling-xhr');
  23786. /**
  23787. * Module exports.
  23788. */
  23789. module.exports = XHR;
  23790. module.exports.Request = Request;
  23791. /**
  23792. * Empty function
  23793. */
  23794. function empty(){}
  23795. /**
  23796. * XHR Polling constructor.
  23797. *
  23798. * @param {Object} opts
  23799. * @api public
  23800. */
  23801. function XHR(opts){
  23802. Polling.call(this, opts);
  23803. if (global.location) {
  23804. var isSSL = 'https:' == location.protocol;
  23805. var port = location.port;
  23806. // some user agents have empty `location.port`
  23807. if (!port) {
  23808. port = isSSL ? 443 : 80;
  23809. }
  23810. this.xd = opts.hostname != global.location.hostname ||
  23811. port != opts.port;
  23812. this.xs = opts.secure != isSSL;
  23813. }
  23814. }
  23815. /**
  23816. * Inherits from Polling.
  23817. */
  23818. inherit(XHR, Polling);
  23819. /**
  23820. * XHR supports binary
  23821. */
  23822. XHR.prototype.supportsBinary = true;
  23823. /**
  23824. * Creates a request.
  23825. *
  23826. * @param {String} method
  23827. * @api private
  23828. */
  23829. XHR.prototype.request = function(opts){
  23830. opts = opts || {};
  23831. opts.uri = this.uri();
  23832. opts.xd = this.xd;
  23833. opts.xs = this.xs;
  23834. opts.agent = this.agent || false;
  23835. opts.supportsBinary = this.supportsBinary;
  23836. opts.enablesXDR = this.enablesXDR;
  23837. // SSL options for Node.js client
  23838. opts.pfx = this.pfx;
  23839. opts.key = this.key;
  23840. opts.passphrase = this.passphrase;
  23841. opts.cert = this.cert;
  23842. opts.ca = this.ca;
  23843. opts.ciphers = this.ciphers;
  23844. opts.rejectUnauthorized = this.rejectUnauthorized;
  23845. return new Request(opts);
  23846. };
  23847. /**
  23848. * Sends data.
  23849. *
  23850. * @param {String} data to send.
  23851. * @param {Function} called upon flush.
  23852. * @api private
  23853. */
  23854. XHR.prototype.doWrite = function(data, fn){
  23855. var isBinary = typeof data !== 'string' && data !== undefined;
  23856. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  23857. var self = this;
  23858. req.on('success', fn);
  23859. req.on('error', function(err){
  23860. self.onError('xhr post error', err);
  23861. });
  23862. this.sendXhr = req;
  23863. };
  23864. /**
  23865. * Starts a poll cycle.
  23866. *
  23867. * @api private
  23868. */
  23869. XHR.prototype.doPoll = function(){
  23870. debug('xhr poll');
  23871. var req = this.request();
  23872. var self = this;
  23873. req.on('data', function(data){
  23874. self.onData(data);
  23875. });
  23876. req.on('error', function(err){
  23877. self.onError('xhr poll error', err);
  23878. });
  23879. this.pollXhr = req;
  23880. };
  23881. /**
  23882. * Request constructor
  23883. *
  23884. * @param {Object} options
  23885. * @api public
  23886. */
  23887. function Request(opts){
  23888. this.method = opts.method || 'GET';
  23889. this.uri = opts.uri;
  23890. this.xd = !!opts.xd;
  23891. this.xs = !!opts.xs;
  23892. this.async = false !== opts.async;
  23893. this.data = undefined != opts.data ? opts.data : null;
  23894. this.agent = opts.agent;
  23895. this.isBinary = opts.isBinary;
  23896. this.supportsBinary = opts.supportsBinary;
  23897. this.enablesXDR = opts.enablesXDR;
  23898. // SSL options for Node.js client
  23899. this.pfx = opts.pfx;
  23900. this.key = opts.key;
  23901. this.passphrase = opts.passphrase;
  23902. this.cert = opts.cert;
  23903. this.ca = opts.ca;
  23904. this.ciphers = opts.ciphers;
  23905. this.rejectUnauthorized = opts.rejectUnauthorized;
  23906. this.create();
  23907. }
  23908. /**
  23909. * Mix in `Emitter`.
  23910. */
  23911. Emitter(Request.prototype);
  23912. /**
  23913. * Creates the XHR object and sends the request.
  23914. *
  23915. * @api private
  23916. */
  23917. Request.prototype.create = function(){
  23918. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  23919. // SSL options for Node.js client
  23920. opts.pfx = this.pfx;
  23921. opts.key = this.key;
  23922. opts.passphrase = this.passphrase;
  23923. opts.cert = this.cert;
  23924. opts.ca = this.ca;
  23925. opts.ciphers = this.ciphers;
  23926. opts.rejectUnauthorized = this.rejectUnauthorized;
  23927. var xhr = this.xhr = new XMLHttpRequest(opts);
  23928. var self = this;
  23929. try {
  23930. debug('xhr open %s: %s', this.method, this.uri);
  23931. xhr.open(this.method, this.uri, this.async);
  23932. if (this.supportsBinary) {
  23933. // This has to be done after open because Firefox is stupid
  23934. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  23935. xhr.responseType = 'arraybuffer';
  23936. }
  23937. if ('POST' == this.method) {
  23938. try {
  23939. if (this.isBinary) {
  23940. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  23941. } else {
  23942. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  23943. }
  23944. } catch (e) {}
  23945. }
  23946. // ie6 check
  23947. if ('withCredentials' in xhr) {
  23948. xhr.withCredentials = true;
  23949. }
  23950. if (this.hasXDR()) {
  23951. xhr.onload = function(){
  23952. self.onLoad();
  23953. };
  23954. xhr.onerror = function(){
  23955. self.onError(xhr.responseText);
  23956. };
  23957. } else {
  23958. xhr.onreadystatechange = function(){
  23959. if (4 != xhr.readyState) return;
  23960. if (200 == xhr.status || 1223 == xhr.status) {
  23961. self.onLoad();
  23962. } else {
  23963. // make sure the `error` event handler that's user-set
  23964. // does not throw in the same tick and gets caught here
  23965. setTimeout(function(){
  23966. self.onError(xhr.status);
  23967. }, 0);
  23968. }
  23969. };
  23970. }
  23971. debug('xhr data %s', this.data);
  23972. xhr.send(this.data);
  23973. } catch (e) {
  23974. // Need to defer since .create() is called directly fhrom the constructor
  23975. // and thus the 'error' event can only be only bound *after* this exception
  23976. // occurs. Therefore, also, we cannot throw here at all.
  23977. setTimeout(function() {
  23978. self.onError(e);
  23979. }, 0);
  23980. return;
  23981. }
  23982. if (global.document) {
  23983. this.index = Request.requestsCount++;
  23984. Request.requests[this.index] = this;
  23985. }
  23986. };
  23987. /**
  23988. * Called upon successful response.
  23989. *
  23990. * @api private
  23991. */
  23992. Request.prototype.onSuccess = function(){
  23993. this.emit('success');
  23994. this.cleanup();
  23995. };
  23996. /**
  23997. * Called if we have data.
  23998. *
  23999. * @api private
  24000. */
  24001. Request.prototype.onData = function(data){
  24002. this.emit('data', data);
  24003. this.onSuccess();
  24004. };
  24005. /**
  24006. * Called upon error.
  24007. *
  24008. * @api private
  24009. */
  24010. Request.prototype.onError = function(err){
  24011. this.emit('error', err);
  24012. this.cleanup(true);
  24013. };
  24014. /**
  24015. * Cleans up house.
  24016. *
  24017. * @api private
  24018. */
  24019. Request.prototype.cleanup = function(fromError){
  24020. if ('undefined' == typeof this.xhr || null === this.xhr) {
  24021. return;
  24022. }
  24023. // xmlhttprequest
  24024. if (this.hasXDR()) {
  24025. this.xhr.onload = this.xhr.onerror = empty;
  24026. } else {
  24027. this.xhr.onreadystatechange = empty;
  24028. }
  24029. if (fromError) {
  24030. try {
  24031. this.xhr.abort();
  24032. } catch(e) {}
  24033. }
  24034. if (global.document) {
  24035. delete Request.requests[this.index];
  24036. }
  24037. this.xhr = null;
  24038. };
  24039. /**
  24040. * Called upon load.
  24041. *
  24042. * @api private
  24043. */
  24044. Request.prototype.onLoad = function(){
  24045. var data;
  24046. try {
  24047. var contentType;
  24048. try {
  24049. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  24050. } catch (e) {}
  24051. if (contentType === 'application/octet-stream') {
  24052. data = this.xhr.response;
  24053. } else {
  24054. if (!this.supportsBinary) {
  24055. data = this.xhr.responseText;
  24056. } else {
  24057. data = 'ok';
  24058. }
  24059. }
  24060. } catch (e) {
  24061. this.onError(e);
  24062. }
  24063. if (null != data) {
  24064. this.onData(data);
  24065. }
  24066. };
  24067. /**
  24068. * Check if it has XDomainRequest.
  24069. *
  24070. * @api private
  24071. */
  24072. Request.prototype.hasXDR = function(){
  24073. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  24074. };
  24075. /**
  24076. * Aborts the request.
  24077. *
  24078. * @api public
  24079. */
  24080. Request.prototype.abort = function(){
  24081. this.cleanup();
  24082. };
  24083. /**
  24084. * Aborts pending requests when unloading the window. This is needed to prevent
  24085. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  24086. * emitted.
  24087. */
  24088. if (global.document) {
  24089. Request.requestsCount = 0;
  24090. Request.requests = {};
  24091. if (global.attachEvent) {
  24092. global.attachEvent('onunload', unloadHandler);
  24093. } else if (global.addEventListener) {
  24094. global.addEventListener('beforeunload', unloadHandler, false);
  24095. }
  24096. }
  24097. function unloadHandler() {
  24098. for (var i in Request.requests) {
  24099. if (Request.requests.hasOwnProperty(i)) {
  24100. Request.requests[i].abort();
  24101. }
  24102. }
  24103. }
  24104. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24105. },{"./polling":102,"component-emitter":93,"component-inherit":105,"debug":106,"xmlhttprequest":104}],102:[function(require,module,exports){
  24106. /**
  24107. * Module dependencies.
  24108. */
  24109. var Transport = require('../transport');
  24110. var parseqs = require('parseqs');
  24111. var parser = require('engine.io-parser');
  24112. var inherit = require('component-inherit');
  24113. var debug = require('debug')('engine.io-client:polling');
  24114. /**
  24115. * Module exports.
  24116. */
  24117. module.exports = Polling;
  24118. /**
  24119. * Is XHR2 supported?
  24120. */
  24121. var hasXHR2 = (function() {
  24122. var XMLHttpRequest = require('xmlhttprequest');
  24123. var xhr = new XMLHttpRequest({ xdomain: false });
  24124. return null != xhr.responseType;
  24125. })();
  24126. /**
  24127. * Polling interface.
  24128. *
  24129. * @param {Object} opts
  24130. * @api private
  24131. */
  24132. function Polling(opts){
  24133. var forceBase64 = (opts && opts.forceBase64);
  24134. if (!hasXHR2 || forceBase64) {
  24135. this.supportsBinary = false;
  24136. }
  24137. Transport.call(this, opts);
  24138. }
  24139. /**
  24140. * Inherits from Transport.
  24141. */
  24142. inherit(Polling, Transport);
  24143. /**
  24144. * Transport name.
  24145. */
  24146. Polling.prototype.name = 'polling';
  24147. /**
  24148. * Opens the socket (triggers polling). We write a PING message to determine
  24149. * when the transport is open.
  24150. *
  24151. * @api private
  24152. */
  24153. Polling.prototype.doOpen = function(){
  24154. this.poll();
  24155. };
  24156. /**
  24157. * Pauses polling.
  24158. *
  24159. * @param {Function} callback upon buffers are flushed and transport is paused
  24160. * @api private
  24161. */
  24162. Polling.prototype.pause = function(onPause){
  24163. var pending = 0;
  24164. var self = this;
  24165. this.readyState = 'pausing';
  24166. function pause(){
  24167. debug('paused');
  24168. self.readyState = 'paused';
  24169. onPause();
  24170. }
  24171. if (this.polling || !this.writable) {
  24172. var total = 0;
  24173. if (this.polling) {
  24174. debug('we are currently polling - waiting to pause');
  24175. total++;
  24176. this.once('pollComplete', function(){
  24177. debug('pre-pause polling complete');
  24178. --total || pause();
  24179. });
  24180. }
  24181. if (!this.writable) {
  24182. debug('we are currently writing - waiting to pause');
  24183. total++;
  24184. this.once('drain', function(){
  24185. debug('pre-pause writing complete');
  24186. --total || pause();
  24187. });
  24188. }
  24189. } else {
  24190. pause();
  24191. }
  24192. };
  24193. /**
  24194. * Starts polling cycle.
  24195. *
  24196. * @api public
  24197. */
  24198. Polling.prototype.poll = function(){
  24199. debug('polling');
  24200. this.polling = true;
  24201. this.doPoll();
  24202. this.emit('poll');
  24203. };
  24204. /**
  24205. * Overloads onData to detect payloads.
  24206. *
  24207. * @api private
  24208. */
  24209. Polling.prototype.onData = function(data){
  24210. var self = this;
  24211. debug('polling got data %s', data);
  24212. var callback = function(packet, index, total) {
  24213. // if its the first message we consider the transport open
  24214. if ('opening' == self.readyState) {
  24215. self.onOpen();
  24216. }
  24217. // if its a close packet, we close the ongoing requests
  24218. if ('close' == packet.type) {
  24219. self.onClose();
  24220. return false;
  24221. }
  24222. // otherwise bypass onData and handle the message
  24223. self.onPacket(packet);
  24224. };
  24225. // decode payload
  24226. parser.decodePayload(data, this.socket.binaryType, callback);
  24227. // if an event did not trigger closing
  24228. if ('closed' != this.readyState) {
  24229. // if we got data we're not polling
  24230. this.polling = false;
  24231. this.emit('pollComplete');
  24232. if ('open' == this.readyState) {
  24233. this.poll();
  24234. } else {
  24235. debug('ignoring poll - transport state "%s"', this.readyState);
  24236. }
  24237. }
  24238. };
  24239. /**
  24240. * For polling, send a close packet.
  24241. *
  24242. * @api private
  24243. */
  24244. Polling.prototype.doClose = function(){
  24245. var self = this;
  24246. function close(){
  24247. debug('writing close packet');
  24248. self.write([{ type: 'close' }]);
  24249. }
  24250. if ('open' == this.readyState) {
  24251. debug('transport open - closing');
  24252. close();
  24253. } else {
  24254. // in case we're trying to close while
  24255. // handshaking is in progress (GH-164)
  24256. debug('transport not open - deferring close');
  24257. this.once('open', close);
  24258. }
  24259. };
  24260. /**
  24261. * Writes a packets payload.
  24262. *
  24263. * @param {Array} data packets
  24264. * @param {Function} drain callback
  24265. * @api private
  24266. */
  24267. Polling.prototype.write = function(packets){
  24268. var self = this;
  24269. this.writable = false;
  24270. var callbackfn = function() {
  24271. self.writable = true;
  24272. self.emit('drain');
  24273. };
  24274. var self = this;
  24275. parser.encodePayload(packets, this.supportsBinary, function(data) {
  24276. self.doWrite(data, callbackfn);
  24277. });
  24278. };
  24279. /**
  24280. * Generates uri for connection.
  24281. *
  24282. * @api private
  24283. */
  24284. Polling.prototype.uri = function(){
  24285. var query = this.query || {};
  24286. var schema = this.secure ? 'https' : 'http';
  24287. var port = '';
  24288. // cache busting is forced
  24289. if (false !== this.timestampRequests) {
  24290. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  24291. }
  24292. if (!this.supportsBinary && !query.sid) {
  24293. query.b64 = 1;
  24294. }
  24295. query = parseqs.encode(query);
  24296. // avoid port if default for schema
  24297. if (this.port && (('https' == schema && this.port != 443) ||
  24298. ('http' == schema && this.port != 80))) {
  24299. port = ':' + this.port;
  24300. }
  24301. // prepend ? to query
  24302. if (query.length) {
  24303. query = '?' + query;
  24304. }
  24305. return schema + '://' + this.hostname + port + this.path + query;
  24306. };
  24307. },{"../transport":98,"component-inherit":105,"debug":106,"engine.io-parser":109,"parseqs":121,"xmlhttprequest":104}],103:[function(require,module,exports){
  24308. /**
  24309. * Module dependencies.
  24310. */
  24311. var Transport = require('../transport');
  24312. var parser = require('engine.io-parser');
  24313. var parseqs = require('parseqs');
  24314. var inherit = require('component-inherit');
  24315. var debug = require('debug')('engine.io-client:websocket');
  24316. /**
  24317. * `ws` exposes a WebSocket-compatible interface in
  24318. * Node, or the `WebSocket` or `MozWebSocket` globals
  24319. * in the browser.
  24320. */
  24321. var WebSocket = require('ws');
  24322. /**
  24323. * Module exports.
  24324. */
  24325. module.exports = WS;
  24326. /**
  24327. * WebSocket transport constructor.
  24328. *
  24329. * @api {Object} connection options
  24330. * @api public
  24331. */
  24332. function WS(opts){
  24333. var forceBase64 = (opts && opts.forceBase64);
  24334. if (forceBase64) {
  24335. this.supportsBinary = false;
  24336. }
  24337. Transport.call(this, opts);
  24338. }
  24339. /**
  24340. * Inherits from Transport.
  24341. */
  24342. inherit(WS, Transport);
  24343. /**
  24344. * Transport name.
  24345. *
  24346. * @api public
  24347. */
  24348. WS.prototype.name = 'websocket';
  24349. /*
  24350. * WebSockets support binary
  24351. */
  24352. WS.prototype.supportsBinary = true;
  24353. /**
  24354. * Opens socket.
  24355. *
  24356. * @api private
  24357. */
  24358. WS.prototype.doOpen = function(){
  24359. if (!this.check()) {
  24360. // let probe timeout
  24361. return;
  24362. }
  24363. var self = this;
  24364. var uri = this.uri();
  24365. var protocols = void(0);
  24366. var opts = { agent: this.agent };
  24367. // SSL options for Node.js client
  24368. opts.pfx = this.pfx;
  24369. opts.key = this.key;
  24370. opts.passphrase = this.passphrase;
  24371. opts.cert = this.cert;
  24372. opts.ca = this.ca;
  24373. opts.ciphers = this.ciphers;
  24374. opts.rejectUnauthorized = this.rejectUnauthorized;
  24375. this.ws = new WebSocket(uri, protocols, opts);
  24376. if (this.ws.binaryType === undefined) {
  24377. this.supportsBinary = false;
  24378. }
  24379. this.ws.binaryType = 'arraybuffer';
  24380. this.addEventListeners();
  24381. };
  24382. /**
  24383. * Adds event listeners to the socket
  24384. *
  24385. * @api private
  24386. */
  24387. WS.prototype.addEventListeners = function(){
  24388. var self = this;
  24389. this.ws.onopen = function(){
  24390. self.onOpen();
  24391. };
  24392. this.ws.onclose = function(){
  24393. self.onClose();
  24394. };
  24395. this.ws.onmessage = function(ev){
  24396. self.onData(ev.data);
  24397. };
  24398. this.ws.onerror = function(e){
  24399. self.onError('websocket error', e);
  24400. };
  24401. };
  24402. /**
  24403. * Override `onData` to use a timer on iOS.
  24404. * See: https://gist.github.com/mloughran/2052006
  24405. *
  24406. * @api private
  24407. */
  24408. if ('undefined' != typeof navigator
  24409. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  24410. WS.prototype.onData = function(data){
  24411. var self = this;
  24412. setTimeout(function(){
  24413. Transport.prototype.onData.call(self, data);
  24414. }, 0);
  24415. };
  24416. }
  24417. /**
  24418. * Writes data to socket.
  24419. *
  24420. * @param {Array} array of packets.
  24421. * @api private
  24422. */
  24423. WS.prototype.write = function(packets){
  24424. var self = this;
  24425. this.writable = false;
  24426. // encodePacket efficient as it uses WS framing
  24427. // no need for encodePayload
  24428. for (var i = 0, l = packets.length; i < l; i++) {
  24429. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  24430. //Sometimes the websocket has already been closed but the browser didn't
  24431. //have a chance of informing us about it yet, in that case send will
  24432. //throw an error
  24433. try {
  24434. self.ws.send(data);
  24435. } catch (e){
  24436. debug('websocket closed before onclose event');
  24437. }
  24438. });
  24439. }
  24440. function ondrain() {
  24441. self.writable = true;
  24442. self.emit('drain');
  24443. }
  24444. // fake drain
  24445. // defer to next tick to allow Socket to clear writeBuffer
  24446. setTimeout(ondrain, 0);
  24447. };
  24448. /**
  24449. * Called upon close
  24450. *
  24451. * @api private
  24452. */
  24453. WS.prototype.onClose = function(){
  24454. Transport.prototype.onClose.call(this);
  24455. };
  24456. /**
  24457. * Closes socket.
  24458. *
  24459. * @api private
  24460. */
  24461. WS.prototype.doClose = function(){
  24462. if (typeof this.ws !== 'undefined') {
  24463. this.ws.close();
  24464. }
  24465. };
  24466. /**
  24467. * Generates uri for connection.
  24468. *
  24469. * @api private
  24470. */
  24471. WS.prototype.uri = function(){
  24472. var query = this.query || {};
  24473. var schema = this.secure ? 'wss' : 'ws';
  24474. var port = '';
  24475. // avoid port if default for schema
  24476. if (this.port && (('wss' == schema && this.port != 443)
  24477. || ('ws' == schema && this.port != 80))) {
  24478. port = ':' + this.port;
  24479. }
  24480. // append timestamp to URI
  24481. if (this.timestampRequests) {
  24482. query[this.timestampParam] = +new Date;
  24483. }
  24484. // communicate binary support capabilities
  24485. if (!this.supportsBinary) {
  24486. query.b64 = 1;
  24487. }
  24488. query = parseqs.encode(query);
  24489. // prepend ? to query
  24490. if (query.length) {
  24491. query = '?' + query;
  24492. }
  24493. return schema + '://' + this.hostname + port + this.path + query;
  24494. };
  24495. /**
  24496. * Feature detection for WebSocket.
  24497. *
  24498. * @return {Boolean} whether this transport is available.
  24499. * @api public
  24500. */
  24501. WS.prototype.check = function(){
  24502. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  24503. };
  24504. },{"../transport":98,"component-inherit":105,"debug":106,"engine.io-parser":109,"parseqs":121,"ws":123}],104:[function(require,module,exports){
  24505. // browser shim for xmlhttprequest module
  24506. var hasCORS = require('has-cors');
  24507. module.exports = function(opts) {
  24508. var xdomain = opts.xdomain;
  24509. // scheme must be same when usign XDomainRequest
  24510. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  24511. var xscheme = opts.xscheme;
  24512. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  24513. // https://github.com/Automattic/engine.io-client/pull/217
  24514. var enablesXDR = opts.enablesXDR;
  24515. // XMLHttpRequest can be disabled on IE
  24516. try {
  24517. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  24518. return new XMLHttpRequest();
  24519. }
  24520. } catch (e) { }
  24521. // Use XDomainRequest for IE8 if enablesXDR is true
  24522. // because loading bar keeps flashing when using jsonp-polling
  24523. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  24524. try {
  24525. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  24526. return new XDomainRequest();
  24527. }
  24528. } catch (e) { }
  24529. if (!xdomain) {
  24530. try {
  24531. return new ActiveXObject('Microsoft.XMLHTTP');
  24532. } catch(e) { }
  24533. }
  24534. }
  24535. },{"has-cors":118}],105:[function(require,module,exports){
  24536. module.exports = function(a, b){
  24537. var fn = function(){};
  24538. fn.prototype = b.prototype;
  24539. a.prototype = new fn;
  24540. a.prototype.constructor = a;
  24541. };
  24542. },{}],106:[function(require,module,exports){
  24543. /**
  24544. * This is the web browser implementation of `debug()`.
  24545. *
  24546. * Expose `debug()` as the module.
  24547. */
  24548. exports = module.exports = require('./debug');
  24549. exports.log = log;
  24550. exports.formatArgs = formatArgs;
  24551. exports.save = save;
  24552. exports.load = load;
  24553. exports.useColors = useColors;
  24554. /**
  24555. * Colors.
  24556. */
  24557. exports.colors = [
  24558. 'lightseagreen',
  24559. 'forestgreen',
  24560. 'goldenrod',
  24561. 'dodgerblue',
  24562. 'darkorchid',
  24563. 'crimson'
  24564. ];
  24565. /**
  24566. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  24567. * and the Firebug extension (any Firefox version) are known
  24568. * to support "%c" CSS customizations.
  24569. *
  24570. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  24571. */
  24572. function useColors() {
  24573. // is webkit? http://stackoverflow.com/a/16459606/376773
  24574. return ('WebkitAppearance' in document.documentElement.style) ||
  24575. // is firebug? http://stackoverflow.com/a/398120/376773
  24576. (window.console && (console.firebug || (console.exception && console.table))) ||
  24577. // is firefox >= v31?
  24578. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  24579. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  24580. }
  24581. /**
  24582. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  24583. */
  24584. exports.formatters.j = function(v) {
  24585. return JSON.stringify(v);
  24586. };
  24587. /**
  24588. * Colorize log arguments if enabled.
  24589. *
  24590. * @api public
  24591. */
  24592. function formatArgs() {
  24593. var args = arguments;
  24594. var useColors = this.useColors;
  24595. args[0] = (useColors ? '%c' : '')
  24596. + this.namespace
  24597. + (useColors ? ' %c' : ' ')
  24598. + args[0]
  24599. + (useColors ? '%c ' : ' ')
  24600. + '+' + exports.humanize(this.diff);
  24601. if (!useColors) return args;
  24602. var c = 'color: ' + this.color;
  24603. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  24604. // the final "%c" is somewhat tricky, because there could be other
  24605. // arguments passed either before or after the %c, so we need to
  24606. // figure out the correct index to insert the CSS into
  24607. var index = 0;
  24608. var lastC = 0;
  24609. args[0].replace(/%[a-z%]/g, function(match) {
  24610. if ('%%' === match) return;
  24611. index++;
  24612. if ('%c' === match) {
  24613. // we only are interested in the *last* %c
  24614. // (the user may have provided their own)
  24615. lastC = index;
  24616. }
  24617. });
  24618. args.splice(lastC, 0, c);
  24619. return args;
  24620. }
  24621. /**
  24622. * Invokes `console.log()` when available.
  24623. * No-op when `console.log` is not a "function".
  24624. *
  24625. * @api public
  24626. */
  24627. function log() {
  24628. // This hackery is required for IE8,
  24629. // where the `console.log` function doesn't have 'apply'
  24630. return 'object' == typeof console
  24631. && 'function' == typeof console.log
  24632. && Function.prototype.apply.call(console.log, console, arguments);
  24633. }
  24634. /**
  24635. * Save `namespaces`.
  24636. *
  24637. * @param {String} namespaces
  24638. * @api private
  24639. */
  24640. function save(namespaces) {
  24641. try {
  24642. if (null == namespaces) {
  24643. localStorage.removeItem('debug');
  24644. } else {
  24645. localStorage.debug = namespaces;
  24646. }
  24647. } catch(e) {}
  24648. }
  24649. /**
  24650. * Load `namespaces`.
  24651. *
  24652. * @return {String} returns the previously persisted debug modes
  24653. * @api private
  24654. */
  24655. function load() {
  24656. var r;
  24657. try {
  24658. r = localStorage.debug;
  24659. } catch(e) {}
  24660. return r;
  24661. }
  24662. /**
  24663. * Enable namespaces listed in `localStorage.debug` initially.
  24664. */
  24665. exports.enable(load());
  24666. },{"./debug":107}],107:[function(require,module,exports){
  24667. /**
  24668. * This is the common logic for both the Node.js and web browser
  24669. * implementations of `debug()`.
  24670. *
  24671. * Expose `debug()` as the module.
  24672. */
  24673. exports = module.exports = debug;
  24674. exports.coerce = coerce;
  24675. exports.disable = disable;
  24676. exports.enable = enable;
  24677. exports.enabled = enabled;
  24678. exports.humanize = require('ms');
  24679. /**
  24680. * The currently active debug mode names, and names to skip.
  24681. */
  24682. exports.names = [];
  24683. exports.skips = [];
  24684. /**
  24685. * Map of special "%n" handling functions, for the debug "format" argument.
  24686. *
  24687. * Valid key names are a single, lowercased letter, i.e. "n".
  24688. */
  24689. exports.formatters = {};
  24690. /**
  24691. * Previously assigned color.
  24692. */
  24693. var prevColor = 0;
  24694. /**
  24695. * Previous log timestamp.
  24696. */
  24697. var prevTime;
  24698. /**
  24699. * Select a color.
  24700. *
  24701. * @return {Number}
  24702. * @api private
  24703. */
  24704. function selectColor() {
  24705. return exports.colors[prevColor++ % exports.colors.length];
  24706. }
  24707. /**
  24708. * Create a debugger with the given `namespace`.
  24709. *
  24710. * @param {String} namespace
  24711. * @return {Function}
  24712. * @api public
  24713. */
  24714. function debug(namespace) {
  24715. // define the `disabled` version
  24716. function disabled() {
  24717. }
  24718. disabled.enabled = false;
  24719. // define the `enabled` version
  24720. function enabled() {
  24721. var self = enabled;
  24722. // set `diff` timestamp
  24723. var curr = +new Date();
  24724. var ms = curr - (prevTime || curr);
  24725. self.diff = ms;
  24726. self.prev = prevTime;
  24727. self.curr = curr;
  24728. prevTime = curr;
  24729. // add the `color` if not set
  24730. if (null == self.useColors) self.useColors = exports.useColors();
  24731. if (null == self.color && self.useColors) self.color = selectColor();
  24732. var args = Array.prototype.slice.call(arguments);
  24733. args[0] = exports.coerce(args[0]);
  24734. if ('string' !== typeof args[0]) {
  24735. // anything else let's inspect with %o
  24736. args = ['%o'].concat(args);
  24737. }
  24738. // apply any `formatters` transformations
  24739. var index = 0;
  24740. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  24741. // if we encounter an escaped % then don't increase the array index
  24742. if (match === '%%') return match;
  24743. index++;
  24744. var formatter = exports.formatters[format];
  24745. if ('function' === typeof formatter) {
  24746. var val = args[index];
  24747. match = formatter.call(self, val);
  24748. // now we need to remove `args[index]` since it's inlined in the `format`
  24749. args.splice(index, 1);
  24750. index--;
  24751. }
  24752. return match;
  24753. });
  24754. if ('function' === typeof exports.formatArgs) {
  24755. args = exports.formatArgs.apply(self, args);
  24756. }
  24757. var logFn = enabled.log || exports.log || console.log.bind(console);
  24758. logFn.apply(self, args);
  24759. }
  24760. enabled.enabled = true;
  24761. var fn = exports.enabled(namespace) ? enabled : disabled;
  24762. fn.namespace = namespace;
  24763. return fn;
  24764. }
  24765. /**
  24766. * Enables a debug mode by namespaces. This can include modes
  24767. * separated by a colon and wildcards.
  24768. *
  24769. * @param {String} namespaces
  24770. * @api public
  24771. */
  24772. function enable(namespaces) {
  24773. exports.save(namespaces);
  24774. var split = (namespaces || '').split(/[\s,]+/);
  24775. var len = split.length;
  24776. for (var i = 0; i < len; i++) {
  24777. if (!split[i]) continue; // ignore empty strings
  24778. namespaces = split[i].replace(/\*/g, '.*?');
  24779. if (namespaces[0] === '-') {
  24780. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  24781. } else {
  24782. exports.names.push(new RegExp('^' + namespaces + '$'));
  24783. }
  24784. }
  24785. }
  24786. /**
  24787. * Disable debug output.
  24788. *
  24789. * @api public
  24790. */
  24791. function disable() {
  24792. exports.enable('');
  24793. }
  24794. /**
  24795. * Returns true if the given mode name is enabled, false otherwise.
  24796. *
  24797. * @param {String} name
  24798. * @return {Boolean}
  24799. * @api public
  24800. */
  24801. function enabled(name) {
  24802. var i, len;
  24803. for (i = 0, len = exports.skips.length; i < len; i++) {
  24804. if (exports.skips[i].test(name)) {
  24805. return false;
  24806. }
  24807. }
  24808. for (i = 0, len = exports.names.length; i < len; i++) {
  24809. if (exports.names[i].test(name)) {
  24810. return true;
  24811. }
  24812. }
  24813. return false;
  24814. }
  24815. /**
  24816. * Coerce `val`.
  24817. *
  24818. * @param {Mixed} val
  24819. * @return {Mixed}
  24820. * @api private
  24821. */
  24822. function coerce(val) {
  24823. if (val instanceof Error) return val.stack || val.message;
  24824. return val;
  24825. }
  24826. },{"ms":108}],108:[function(require,module,exports){
  24827. /**
  24828. * Helpers.
  24829. */
  24830. var s = 1000;
  24831. var m = s * 60;
  24832. var h = m * 60;
  24833. var d = h * 24;
  24834. var y = d * 365.25;
  24835. /**
  24836. * Parse or format the given `val`.
  24837. *
  24838. * Options:
  24839. *
  24840. * - `long` verbose formatting [false]
  24841. *
  24842. * @param {String|Number} val
  24843. * @param {Object} options
  24844. * @return {String|Number}
  24845. * @api public
  24846. */
  24847. module.exports = function(val, options){
  24848. options = options || {};
  24849. if ('string' == typeof val) return parse(val);
  24850. return options.long
  24851. ? long(val)
  24852. : short(val);
  24853. };
  24854. /**
  24855. * Parse the given `str` and return milliseconds.
  24856. *
  24857. * @param {String} str
  24858. * @return {Number}
  24859. * @api private
  24860. */
  24861. function parse(str) {
  24862. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  24863. if (!match) return;
  24864. var n = parseFloat(match[1]);
  24865. var type = (match[2] || 'ms').toLowerCase();
  24866. switch (type) {
  24867. case 'years':
  24868. case 'year':
  24869. case 'y':
  24870. return n * y;
  24871. case 'days':
  24872. case 'day':
  24873. case 'd':
  24874. return n * d;
  24875. case 'hours':
  24876. case 'hour':
  24877. case 'h':
  24878. return n * h;
  24879. case 'minutes':
  24880. case 'minute':
  24881. case 'm':
  24882. return n * m;
  24883. case 'seconds':
  24884. case 'second':
  24885. case 's':
  24886. return n * s;
  24887. case 'ms':
  24888. return n;
  24889. }
  24890. }
  24891. /**
  24892. * Short format for `ms`.
  24893. *
  24894. * @param {Number} ms
  24895. * @return {String}
  24896. * @api private
  24897. */
  24898. function short(ms) {
  24899. if (ms >= d) return Math.round(ms / d) + 'd';
  24900. if (ms >= h) return Math.round(ms / h) + 'h';
  24901. if (ms >= m) return Math.round(ms / m) + 'm';
  24902. if (ms >= s) return Math.round(ms / s) + 's';
  24903. return ms + 'ms';
  24904. }
  24905. /**
  24906. * Long format for `ms`.
  24907. *
  24908. * @param {Number} ms
  24909. * @return {String}
  24910. * @api private
  24911. */
  24912. function long(ms) {
  24913. return plural(ms, d, 'day')
  24914. || plural(ms, h, 'hour')
  24915. || plural(ms, m, 'minute')
  24916. || plural(ms, s, 'second')
  24917. || ms + ' ms';
  24918. }
  24919. /**
  24920. * Pluralization helper.
  24921. */
  24922. function plural(ms, n, name) {
  24923. if (ms < n) return;
  24924. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  24925. return Math.ceil(ms / n) + ' ' + name + 's';
  24926. }
  24927. },{}],109:[function(require,module,exports){
  24928. (function (global){
  24929. /**
  24930. * Module dependencies.
  24931. */
  24932. var keys = require('./keys');
  24933. var hasBinary = require('has-binary');
  24934. var sliceBuffer = require('arraybuffer.slice');
  24935. var base64encoder = require('base64-arraybuffer');
  24936. var after = require('after');
  24937. var utf8 = require('utf8');
  24938. /**
  24939. * Check if we are running an android browser. That requires us to use
  24940. * ArrayBuffer with polling transports...
  24941. *
  24942. * http://ghinda.net/jpeg-blob-ajax-android/
  24943. */
  24944. var isAndroid = navigator.userAgent.match(/Android/i);
  24945. /**
  24946. * Check if we are running in PhantomJS.
  24947. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  24948. * https://github.com/ariya/phantomjs/issues/11395
  24949. * @type boolean
  24950. */
  24951. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  24952. /**
  24953. * When true, avoids using Blobs to encode payloads.
  24954. * @type boolean
  24955. */
  24956. var dontSendBlobs = isAndroid || isPhantomJS;
  24957. /**
  24958. * Current protocol version.
  24959. */
  24960. exports.protocol = 3;
  24961. /**
  24962. * Packet types.
  24963. */
  24964. var packets = exports.packets = {
  24965. open: 0 // non-ws
  24966. , close: 1 // non-ws
  24967. , ping: 2
  24968. , pong: 3
  24969. , message: 4
  24970. , upgrade: 5
  24971. , noop: 6
  24972. };
  24973. var packetslist = keys(packets);
  24974. /**
  24975. * Premade error packet.
  24976. */
  24977. var err = { type: 'error', data: 'parser error' };
  24978. /**
  24979. * Create a blob api even for blob builder when vendor prefixes exist
  24980. */
  24981. var Blob = require('blob');
  24982. /**
  24983. * Encodes a packet.
  24984. *
  24985. * <packet type id> [ <data> ]
  24986. *
  24987. * Example:
  24988. *
  24989. * 5hello world
  24990. * 3
  24991. * 4
  24992. *
  24993. * Binary is encoded in an identical principle
  24994. *
  24995. * @api private
  24996. */
  24997. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  24998. if ('function' == typeof supportsBinary) {
  24999. callback = supportsBinary;
  25000. supportsBinary = false;
  25001. }
  25002. if ('function' == typeof utf8encode) {
  25003. callback = utf8encode;
  25004. utf8encode = null;
  25005. }
  25006. var data = (packet.data === undefined)
  25007. ? undefined
  25008. : packet.data.buffer || packet.data;
  25009. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  25010. return encodeArrayBuffer(packet, supportsBinary, callback);
  25011. } else if (Blob && data instanceof global.Blob) {
  25012. return encodeBlob(packet, supportsBinary, callback);
  25013. }
  25014. // might be an object with { base64: true, data: dataAsBase64String }
  25015. if (data && data.base64) {
  25016. return encodeBase64Object(packet, callback);
  25017. }
  25018. // Sending data as a utf-8 string
  25019. var encoded = packets[packet.type];
  25020. // data fragment is optional
  25021. if (undefined !== packet.data) {
  25022. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  25023. }
  25024. return callback('' + encoded);
  25025. };
  25026. function encodeBase64Object(packet, callback) {
  25027. // packet data is an object { base64: true, data: dataAsBase64String }
  25028. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  25029. return callback(message);
  25030. }
  25031. /**
  25032. * Encode packet helpers for binary types
  25033. */
  25034. function encodeArrayBuffer(packet, supportsBinary, callback) {
  25035. if (!supportsBinary) {
  25036. return exports.encodeBase64Packet(packet, callback);
  25037. }
  25038. var data = packet.data;
  25039. var contentArray = new Uint8Array(data);
  25040. var resultBuffer = new Uint8Array(1 + data.byteLength);
  25041. resultBuffer[0] = packets[packet.type];
  25042. for (var i = 0; i < contentArray.length; i++) {
  25043. resultBuffer[i+1] = contentArray[i];
  25044. }
  25045. return callback(resultBuffer.buffer);
  25046. }
  25047. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  25048. if (!supportsBinary) {
  25049. return exports.encodeBase64Packet(packet, callback);
  25050. }
  25051. var fr = new FileReader();
  25052. fr.onload = function() {
  25053. packet.data = fr.result;
  25054. exports.encodePacket(packet, supportsBinary, true, callback);
  25055. };
  25056. return fr.readAsArrayBuffer(packet.data);
  25057. }
  25058. function encodeBlob(packet, supportsBinary, callback) {
  25059. if (!supportsBinary) {
  25060. return exports.encodeBase64Packet(packet, callback);
  25061. }
  25062. if (dontSendBlobs) {
  25063. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  25064. }
  25065. var length = new Uint8Array(1);
  25066. length[0] = packets[packet.type];
  25067. var blob = new Blob([length.buffer, packet.data]);
  25068. return callback(blob);
  25069. }
  25070. /**
  25071. * Encodes a packet with binary data in a base64 string
  25072. *
  25073. * @param {Object} packet, has `type` and `data`
  25074. * @return {String} base64 encoded message
  25075. */
  25076. exports.encodeBase64Packet = function(packet, callback) {
  25077. var message = 'b' + exports.packets[packet.type];
  25078. if (Blob && packet.data instanceof Blob) {
  25079. var fr = new FileReader();
  25080. fr.onload = function() {
  25081. var b64 = fr.result.split(',')[1];
  25082. callback(message + b64);
  25083. };
  25084. return fr.readAsDataURL(packet.data);
  25085. }
  25086. var b64data;
  25087. try {
  25088. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  25089. } catch (e) {
  25090. // iPhone Safari doesn't let you apply with typed arrays
  25091. var typed = new Uint8Array(packet.data);
  25092. var basic = new Array(typed.length);
  25093. for (var i = 0; i < typed.length; i++) {
  25094. basic[i] = typed[i];
  25095. }
  25096. b64data = String.fromCharCode.apply(null, basic);
  25097. }
  25098. message += global.btoa(b64data);
  25099. return callback(message);
  25100. };
  25101. /**
  25102. * Decodes a packet. Changes format to Blob if requested.
  25103. *
  25104. * @return {Object} with `type` and `data` (if any)
  25105. * @api private
  25106. */
  25107. exports.decodePacket = function (data, binaryType, utf8decode) {
  25108. // String data
  25109. if (typeof data == 'string' || data === undefined) {
  25110. if (data.charAt(0) == 'b') {
  25111. return exports.decodeBase64Packet(data.substr(1), binaryType);
  25112. }
  25113. if (utf8decode) {
  25114. try {
  25115. data = utf8.decode(data);
  25116. } catch (e) {
  25117. return err;
  25118. }
  25119. }
  25120. var type = data.charAt(0);
  25121. if (Number(type) != type || !packetslist[type]) {
  25122. return err;
  25123. }
  25124. if (data.length > 1) {
  25125. return { type: packetslist[type], data: data.substring(1) };
  25126. } else {
  25127. return { type: packetslist[type] };
  25128. }
  25129. }
  25130. var asArray = new Uint8Array(data);
  25131. var type = asArray[0];
  25132. var rest = sliceBuffer(data, 1);
  25133. if (Blob && binaryType === 'blob') {
  25134. rest = new Blob([rest]);
  25135. }
  25136. return { type: packetslist[type], data: rest };
  25137. };
  25138. /**
  25139. * Decodes a packet encoded in a base64 string
  25140. *
  25141. * @param {String} base64 encoded message
  25142. * @return {Object} with `type` and `data` (if any)
  25143. */
  25144. exports.decodeBase64Packet = function(msg, binaryType) {
  25145. var type = packetslist[msg.charAt(0)];
  25146. if (!global.ArrayBuffer) {
  25147. return { type: type, data: { base64: true, data: msg.substr(1) } };
  25148. }
  25149. var data = base64encoder.decode(msg.substr(1));
  25150. if (binaryType === 'blob' && Blob) {
  25151. data = new Blob([data]);
  25152. }
  25153. return { type: type, data: data };
  25154. };
  25155. /**
  25156. * Encodes multiple messages (payload).
  25157. *
  25158. * <length>:data
  25159. *
  25160. * Example:
  25161. *
  25162. * 11:hello world2:hi
  25163. *
  25164. * If any contents are binary, they will be encoded as base64 strings. Base64
  25165. * encoded strings are marked with a b before the length specifier
  25166. *
  25167. * @param {Array} packets
  25168. * @api private
  25169. */
  25170. exports.encodePayload = function (packets, supportsBinary, callback) {
  25171. if (typeof supportsBinary == 'function') {
  25172. callback = supportsBinary;
  25173. supportsBinary = null;
  25174. }
  25175. var isBinary = hasBinary(packets);
  25176. if (supportsBinary && isBinary) {
  25177. if (Blob && !dontSendBlobs) {
  25178. return exports.encodePayloadAsBlob(packets, callback);
  25179. }
  25180. return exports.encodePayloadAsArrayBuffer(packets, callback);
  25181. }
  25182. if (!packets.length) {
  25183. return callback('0:');
  25184. }
  25185. function setLengthHeader(message) {
  25186. return message.length + ':' + message;
  25187. }
  25188. function encodeOne(packet, doneCallback) {
  25189. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  25190. doneCallback(null, setLengthHeader(message));
  25191. });
  25192. }
  25193. map(packets, encodeOne, function(err, results) {
  25194. return callback(results.join(''));
  25195. });
  25196. };
  25197. /**
  25198. * Async array map using after
  25199. */
  25200. function map(ary, each, done) {
  25201. var result = new Array(ary.length);
  25202. var next = after(ary.length, done);
  25203. var eachWithIndex = function(i, el, cb) {
  25204. each(el, function(error, msg) {
  25205. result[i] = msg;
  25206. cb(error, result);
  25207. });
  25208. };
  25209. for (var i = 0; i < ary.length; i++) {
  25210. eachWithIndex(i, ary[i], next);
  25211. }
  25212. }
  25213. /*
  25214. * Decodes data when a payload is maybe expected. Possible binary contents are
  25215. * decoded from their base64 representation
  25216. *
  25217. * @param {String} data, callback method
  25218. * @api public
  25219. */
  25220. exports.decodePayload = function (data, binaryType, callback) {
  25221. if (typeof data != 'string') {
  25222. return exports.decodePayloadAsBinary(data, binaryType, callback);
  25223. }
  25224. if (typeof binaryType === 'function') {
  25225. callback = binaryType;
  25226. binaryType = null;
  25227. }
  25228. var packet;
  25229. if (data == '') {
  25230. // parser error - ignoring payload
  25231. return callback(err, 0, 1);
  25232. }
  25233. var length = ''
  25234. , n, msg;
  25235. for (var i = 0, l = data.length; i < l; i++) {
  25236. var chr = data.charAt(i);
  25237. if (':' != chr) {
  25238. length += chr;
  25239. } else {
  25240. if ('' == length || (length != (n = Number(length)))) {
  25241. // parser error - ignoring payload
  25242. return callback(err, 0, 1);
  25243. }
  25244. msg = data.substr(i + 1, n);
  25245. if (length != msg.length) {
  25246. // parser error - ignoring payload
  25247. return callback(err, 0, 1);
  25248. }
  25249. if (msg.length) {
  25250. packet = exports.decodePacket(msg, binaryType, true);
  25251. if (err.type == packet.type && err.data == packet.data) {
  25252. // parser error in individual packet - ignoring payload
  25253. return callback(err, 0, 1);
  25254. }
  25255. var ret = callback(packet, i + n, l);
  25256. if (false === ret) return;
  25257. }
  25258. // advance cursor
  25259. i += n;
  25260. length = '';
  25261. }
  25262. }
  25263. if (length != '') {
  25264. // parser error - ignoring payload
  25265. return callback(err, 0, 1);
  25266. }
  25267. };
  25268. /**
  25269. * Encodes multiple messages (payload) as binary.
  25270. *
  25271. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  25272. * 255><data>
  25273. *
  25274. * Example:
  25275. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  25276. *
  25277. * @param {Array} packets
  25278. * @return {ArrayBuffer} encoded payload
  25279. * @api private
  25280. */
  25281. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  25282. if (!packets.length) {
  25283. return callback(new ArrayBuffer(0));
  25284. }
  25285. function encodeOne(packet, doneCallback) {
  25286. exports.encodePacket(packet, true, true, function(data) {
  25287. return doneCallback(null, data);
  25288. });
  25289. }
  25290. map(packets, encodeOne, function(err, encodedPackets) {
  25291. var totalLength = encodedPackets.reduce(function(acc, p) {
  25292. var len;
  25293. if (typeof p === 'string'){
  25294. len = p.length;
  25295. } else {
  25296. len = p.byteLength;
  25297. }
  25298. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  25299. }, 0);
  25300. var resultArray = new Uint8Array(totalLength);
  25301. var bufferIndex = 0;
  25302. encodedPackets.forEach(function(p) {
  25303. var isString = typeof p === 'string';
  25304. var ab = p;
  25305. if (isString) {
  25306. var view = new Uint8Array(p.length);
  25307. for (var i = 0; i < p.length; i++) {
  25308. view[i] = p.charCodeAt(i);
  25309. }
  25310. ab = view.buffer;
  25311. }
  25312. if (isString) { // not true binary
  25313. resultArray[bufferIndex++] = 0;
  25314. } else { // true binary
  25315. resultArray[bufferIndex++] = 1;
  25316. }
  25317. var lenStr = ab.byteLength.toString();
  25318. for (var i = 0; i < lenStr.length; i++) {
  25319. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  25320. }
  25321. resultArray[bufferIndex++] = 255;
  25322. var view = new Uint8Array(ab);
  25323. for (var i = 0; i < view.length; i++) {
  25324. resultArray[bufferIndex++] = view[i];
  25325. }
  25326. });
  25327. return callback(resultArray.buffer);
  25328. });
  25329. };
  25330. /**
  25331. * Encode as Blob
  25332. */
  25333. exports.encodePayloadAsBlob = function(packets, callback) {
  25334. function encodeOne(packet, doneCallback) {
  25335. exports.encodePacket(packet, true, true, function(encoded) {
  25336. var binaryIdentifier = new Uint8Array(1);
  25337. binaryIdentifier[0] = 1;
  25338. if (typeof encoded === 'string') {
  25339. var view = new Uint8Array(encoded.length);
  25340. for (var i = 0; i < encoded.length; i++) {
  25341. view[i] = encoded.charCodeAt(i);
  25342. }
  25343. encoded = view.buffer;
  25344. binaryIdentifier[0] = 0;
  25345. }
  25346. var len = (encoded instanceof ArrayBuffer)
  25347. ? encoded.byteLength
  25348. : encoded.size;
  25349. var lenStr = len.toString();
  25350. var lengthAry = new Uint8Array(lenStr.length + 1);
  25351. for (var i = 0; i < lenStr.length; i++) {
  25352. lengthAry[i] = parseInt(lenStr[i]);
  25353. }
  25354. lengthAry[lenStr.length] = 255;
  25355. if (Blob) {
  25356. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  25357. doneCallback(null, blob);
  25358. }
  25359. });
  25360. }
  25361. map(packets, encodeOne, function(err, results) {
  25362. return callback(new Blob(results));
  25363. });
  25364. };
  25365. /*
  25366. * Decodes data when a payload is maybe expected. Strings are decoded by
  25367. * interpreting each byte as a key code for entries marked to start with 0. See
  25368. * description of encodePayloadAsBinary
  25369. *
  25370. * @param {ArrayBuffer} data, callback method
  25371. * @api public
  25372. */
  25373. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  25374. if (typeof binaryType === 'function') {
  25375. callback = binaryType;
  25376. binaryType = null;
  25377. }
  25378. var bufferTail = data;
  25379. var buffers = [];
  25380. var numberTooLong = false;
  25381. while (bufferTail.byteLength > 0) {
  25382. var tailArray = new Uint8Array(bufferTail);
  25383. var isString = tailArray[0] === 0;
  25384. var msgLength = '';
  25385. for (var i = 1; ; i++) {
  25386. if (tailArray[i] == 255) break;
  25387. if (msgLength.length > 310) {
  25388. numberTooLong = true;
  25389. break;
  25390. }
  25391. msgLength += tailArray[i];
  25392. }
  25393. if(numberTooLong) return callback(err, 0, 1);
  25394. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  25395. msgLength = parseInt(msgLength);
  25396. var msg = sliceBuffer(bufferTail, 0, msgLength);
  25397. if (isString) {
  25398. try {
  25399. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  25400. } catch (e) {
  25401. // iPhone Safari doesn't let you apply to typed arrays
  25402. var typed = new Uint8Array(msg);
  25403. msg = '';
  25404. for (var i = 0; i < typed.length; i++) {
  25405. msg += String.fromCharCode(typed[i]);
  25406. }
  25407. }
  25408. }
  25409. buffers.push(msg);
  25410. bufferTail = sliceBuffer(bufferTail, msgLength);
  25411. }
  25412. var total = buffers.length;
  25413. buffers.forEach(function(buffer, i) {
  25414. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  25415. });
  25416. };
  25417. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25418. },{"./keys":110,"after":111,"arraybuffer.slice":112,"base64-arraybuffer":113,"blob":114,"has-binary":115,"utf8":117}],110:[function(require,module,exports){
  25419. /**
  25420. * Gets the keys for an object.
  25421. *
  25422. * @return {Array} keys
  25423. * @api private
  25424. */
  25425. module.exports = Object.keys || function keys (obj){
  25426. var arr = [];
  25427. var has = Object.prototype.hasOwnProperty;
  25428. for (var i in obj) {
  25429. if (has.call(obj, i)) {
  25430. arr.push(i);
  25431. }
  25432. }
  25433. return arr;
  25434. };
  25435. },{}],111:[function(require,module,exports){
  25436. module.exports = after
  25437. function after(count, callback, err_cb) {
  25438. var bail = false
  25439. err_cb = err_cb || noop
  25440. proxy.count = count
  25441. return (count === 0) ? callback() : proxy
  25442. function proxy(err, result) {
  25443. if (proxy.count <= 0) {
  25444. throw new Error('after called too many times')
  25445. }
  25446. --proxy.count
  25447. // after first error, rest are passed to err_cb
  25448. if (err) {
  25449. bail = true
  25450. callback(err)
  25451. // future error callbacks will go to error handler
  25452. callback = err_cb
  25453. } else if (proxy.count === 0 && !bail) {
  25454. callback(null, result)
  25455. }
  25456. }
  25457. }
  25458. function noop() {}
  25459. },{}],112:[function(require,module,exports){
  25460. /**
  25461. * An abstraction for slicing an arraybuffer even when
  25462. * ArrayBuffer.prototype.slice is not supported
  25463. *
  25464. * @api public
  25465. */
  25466. module.exports = function(arraybuffer, start, end) {
  25467. var bytes = arraybuffer.byteLength;
  25468. start = start || 0;
  25469. end = end || bytes;
  25470. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  25471. if (start < 0) { start += bytes; }
  25472. if (end < 0) { end += bytes; }
  25473. if (end > bytes) { end = bytes; }
  25474. if (start >= bytes || start >= end || bytes === 0) {
  25475. return new ArrayBuffer(0);
  25476. }
  25477. var abv = new Uint8Array(arraybuffer);
  25478. var result = new Uint8Array(end - start);
  25479. for (var i = start, ii = 0; i < end; i++, ii++) {
  25480. result[ii] = abv[i];
  25481. }
  25482. return result.buffer;
  25483. };
  25484. },{}],113:[function(require,module,exports){
  25485. /*
  25486. * base64-arraybuffer
  25487. * https://github.com/niklasvh/base64-arraybuffer
  25488. *
  25489. * Copyright (c) 2012 Niklas von Hertzen
  25490. * Licensed under the MIT license.
  25491. */
  25492. (function(chars){
  25493. "use strict";
  25494. exports.encode = function(arraybuffer) {
  25495. var bytes = new Uint8Array(arraybuffer),
  25496. i, len = bytes.length, base64 = "";
  25497. for (i = 0; i < len; i+=3) {
  25498. base64 += chars[bytes[i] >> 2];
  25499. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  25500. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  25501. base64 += chars[bytes[i + 2] & 63];
  25502. }
  25503. if ((len % 3) === 2) {
  25504. base64 = base64.substring(0, base64.length - 1) + "=";
  25505. } else if (len % 3 === 1) {
  25506. base64 = base64.substring(0, base64.length - 2) + "==";
  25507. }
  25508. return base64;
  25509. };
  25510. exports.decode = function(base64) {
  25511. var bufferLength = base64.length * 0.75,
  25512. len = base64.length, i, p = 0,
  25513. encoded1, encoded2, encoded3, encoded4;
  25514. if (base64[base64.length - 1] === "=") {
  25515. bufferLength--;
  25516. if (base64[base64.length - 2] === "=") {
  25517. bufferLength--;
  25518. }
  25519. }
  25520. var arraybuffer = new ArrayBuffer(bufferLength),
  25521. bytes = new Uint8Array(arraybuffer);
  25522. for (i = 0; i < len; i+=4) {
  25523. encoded1 = chars.indexOf(base64[i]);
  25524. encoded2 = chars.indexOf(base64[i+1]);
  25525. encoded3 = chars.indexOf(base64[i+2]);
  25526. encoded4 = chars.indexOf(base64[i+3]);
  25527. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  25528. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  25529. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  25530. }
  25531. return arraybuffer;
  25532. };
  25533. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  25534. },{}],114:[function(require,module,exports){
  25535. (function (global){
  25536. /**
  25537. * Create a blob builder even when vendor prefixes exist
  25538. */
  25539. var BlobBuilder = global.BlobBuilder
  25540. || global.WebKitBlobBuilder
  25541. || global.MSBlobBuilder
  25542. || global.MozBlobBuilder;
  25543. /**
  25544. * Check if Blob constructor is supported
  25545. */
  25546. var blobSupported = (function() {
  25547. try {
  25548. var b = new Blob(['hi']);
  25549. return b.size == 2;
  25550. } catch(e) {
  25551. return false;
  25552. }
  25553. })();
  25554. /**
  25555. * Check if BlobBuilder is supported
  25556. */
  25557. var blobBuilderSupported = BlobBuilder
  25558. && BlobBuilder.prototype.append
  25559. && BlobBuilder.prototype.getBlob;
  25560. function BlobBuilderConstructor(ary, options) {
  25561. options = options || {};
  25562. var bb = new BlobBuilder();
  25563. for (var i = 0; i < ary.length; i++) {
  25564. bb.append(ary[i]);
  25565. }
  25566. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  25567. };
  25568. module.exports = (function() {
  25569. if (blobSupported) {
  25570. return global.Blob;
  25571. } else if (blobBuilderSupported) {
  25572. return BlobBuilderConstructor;
  25573. } else {
  25574. return undefined;
  25575. }
  25576. })();
  25577. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25578. },{}],115:[function(require,module,exports){
  25579. (function (global){
  25580. /*
  25581. * Module requirements.
  25582. */
  25583. var isArray = require('isarray');
  25584. /**
  25585. * Module exports.
  25586. */
  25587. module.exports = hasBinary;
  25588. /**
  25589. * Checks for binary data.
  25590. *
  25591. * Right now only Buffer and ArrayBuffer are supported..
  25592. *
  25593. * @param {Object} anything
  25594. * @api public
  25595. */
  25596. function hasBinary(data) {
  25597. function _hasBinary(obj) {
  25598. if (!obj) return false;
  25599. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  25600. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  25601. (global.Blob && obj instanceof Blob) ||
  25602. (global.File && obj instanceof File)
  25603. ) {
  25604. return true;
  25605. }
  25606. if (isArray(obj)) {
  25607. for (var i = 0; i < obj.length; i++) {
  25608. if (_hasBinary(obj[i])) {
  25609. return true;
  25610. }
  25611. }
  25612. } else if (obj && 'object' == typeof obj) {
  25613. if (obj.toJSON) {
  25614. obj = obj.toJSON();
  25615. }
  25616. for (var key in obj) {
  25617. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  25618. return true;
  25619. }
  25620. }
  25621. }
  25622. return false;
  25623. }
  25624. return _hasBinary(data);
  25625. }
  25626. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25627. },{"isarray":116}],116:[function(require,module,exports){
  25628. module.exports = Array.isArray || function (arr) {
  25629. return Object.prototype.toString.call(arr) == '[object Array]';
  25630. };
  25631. },{}],117:[function(require,module,exports){
  25632. (function (global){
  25633. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  25634. ;(function(root) {
  25635. // Detect free variables `exports`
  25636. var freeExports = typeof exports == 'object' && exports;
  25637. // Detect free variable `module`
  25638. var freeModule = typeof module == 'object' && module &&
  25639. module.exports == freeExports && module;
  25640. // Detect free variable `global`, from Node.js or Browserified code,
  25641. // and use it as `root`
  25642. var freeGlobal = typeof global == 'object' && global;
  25643. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  25644. root = freeGlobal;
  25645. }
  25646. /*--------------------------------------------------------------------------*/
  25647. var stringFromCharCode = String.fromCharCode;
  25648. // Taken from http://mths.be/punycode
  25649. function ucs2decode(string) {
  25650. var output = [];
  25651. var counter = 0;
  25652. var length = string.length;
  25653. var value;
  25654. var extra;
  25655. while (counter < length) {
  25656. value = string.charCodeAt(counter++);
  25657. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  25658. // high surrogate, and there is a next character
  25659. extra = string.charCodeAt(counter++);
  25660. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  25661. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  25662. } else {
  25663. // unmatched surrogate; only append this code unit, in case the next
  25664. // code unit is the high surrogate of a surrogate pair
  25665. output.push(value);
  25666. counter--;
  25667. }
  25668. } else {
  25669. output.push(value);
  25670. }
  25671. }
  25672. return output;
  25673. }
  25674. // Taken from http://mths.be/punycode
  25675. function ucs2encode(array) {
  25676. var length = array.length;
  25677. var index = -1;
  25678. var value;
  25679. var output = '';
  25680. while (++index < length) {
  25681. value = array[index];
  25682. if (value > 0xFFFF) {
  25683. value -= 0x10000;
  25684. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  25685. value = 0xDC00 | value & 0x3FF;
  25686. }
  25687. output += stringFromCharCode(value);
  25688. }
  25689. return output;
  25690. }
  25691. /*--------------------------------------------------------------------------*/
  25692. function createByte(codePoint, shift) {
  25693. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  25694. }
  25695. function encodeCodePoint(codePoint) {
  25696. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  25697. return stringFromCharCode(codePoint);
  25698. }
  25699. var symbol = '';
  25700. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  25701. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  25702. }
  25703. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  25704. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  25705. symbol += createByte(codePoint, 6);
  25706. }
  25707. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  25708. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  25709. symbol += createByte(codePoint, 12);
  25710. symbol += createByte(codePoint, 6);
  25711. }
  25712. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  25713. return symbol;
  25714. }
  25715. function utf8encode(string) {
  25716. var codePoints = ucs2decode(string);
  25717. // console.log(JSON.stringify(codePoints.map(function(x) {
  25718. // return 'U+' + x.toString(16).toUpperCase();
  25719. // })));
  25720. var length = codePoints.length;
  25721. var index = -1;
  25722. var codePoint;
  25723. var byteString = '';
  25724. while (++index < length) {
  25725. codePoint = codePoints[index];
  25726. byteString += encodeCodePoint(codePoint);
  25727. }
  25728. return byteString;
  25729. }
  25730. /*--------------------------------------------------------------------------*/
  25731. function readContinuationByte() {
  25732. if (byteIndex >= byteCount) {
  25733. throw Error('Invalid byte index');
  25734. }
  25735. var continuationByte = byteArray[byteIndex] & 0xFF;
  25736. byteIndex++;
  25737. if ((continuationByte & 0xC0) == 0x80) {
  25738. return continuationByte & 0x3F;
  25739. }
  25740. // If we end up here, it’s not a continuation byte
  25741. throw Error('Invalid continuation byte');
  25742. }
  25743. function decodeSymbol() {
  25744. var byte1;
  25745. var byte2;
  25746. var byte3;
  25747. var byte4;
  25748. var codePoint;
  25749. if (byteIndex > byteCount) {
  25750. throw Error('Invalid byte index');
  25751. }
  25752. if (byteIndex == byteCount) {
  25753. return false;
  25754. }
  25755. // Read first byte
  25756. byte1 = byteArray[byteIndex] & 0xFF;
  25757. byteIndex++;
  25758. // 1-byte sequence (no continuation bytes)
  25759. if ((byte1 & 0x80) == 0) {
  25760. return byte1;
  25761. }
  25762. // 2-byte sequence
  25763. if ((byte1 & 0xE0) == 0xC0) {
  25764. var byte2 = readContinuationByte();
  25765. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  25766. if (codePoint >= 0x80) {
  25767. return codePoint;
  25768. } else {
  25769. throw Error('Invalid continuation byte');
  25770. }
  25771. }
  25772. // 3-byte sequence (may include unpaired surrogates)
  25773. if ((byte1 & 0xF0) == 0xE0) {
  25774. byte2 = readContinuationByte();
  25775. byte3 = readContinuationByte();
  25776. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  25777. if (codePoint >= 0x0800) {
  25778. return codePoint;
  25779. } else {
  25780. throw Error('Invalid continuation byte');
  25781. }
  25782. }
  25783. // 4-byte sequence
  25784. if ((byte1 & 0xF8) == 0xF0) {
  25785. byte2 = readContinuationByte();
  25786. byte3 = readContinuationByte();
  25787. byte4 = readContinuationByte();
  25788. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  25789. (byte3 << 0x06) | byte4;
  25790. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  25791. return codePoint;
  25792. }
  25793. }
  25794. throw Error('Invalid UTF-8 detected');
  25795. }
  25796. var byteArray;
  25797. var byteCount;
  25798. var byteIndex;
  25799. function utf8decode(byteString) {
  25800. byteArray = ucs2decode(byteString);
  25801. byteCount = byteArray.length;
  25802. byteIndex = 0;
  25803. var codePoints = [];
  25804. var tmp;
  25805. while ((tmp = decodeSymbol()) !== false) {
  25806. codePoints.push(tmp);
  25807. }
  25808. return ucs2encode(codePoints);
  25809. }
  25810. /*--------------------------------------------------------------------------*/
  25811. var utf8 = {
  25812. 'version': '2.0.0',
  25813. 'encode': utf8encode,
  25814. 'decode': utf8decode
  25815. };
  25816. // Some AMD build optimizers, like r.js, check for specific condition patterns
  25817. // like the following:
  25818. if (
  25819. typeof define == 'function' &&
  25820. typeof define.amd == 'object' &&
  25821. define.amd
  25822. ) {
  25823. define(function() {
  25824. return utf8;
  25825. });
  25826. } else if (freeExports && !freeExports.nodeType) {
  25827. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  25828. freeModule.exports = utf8;
  25829. } else { // in Narwhal or RingoJS v0.7.0-
  25830. var object = {};
  25831. var hasOwnProperty = object.hasOwnProperty;
  25832. for (var key in utf8) {
  25833. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  25834. }
  25835. }
  25836. } else { // in Rhino or a web browser
  25837. root.utf8 = utf8;
  25838. }
  25839. }(this));
  25840. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25841. },{}],118:[function(require,module,exports){
  25842. /**
  25843. * Module dependencies.
  25844. */
  25845. var global = require('global');
  25846. /**
  25847. * Module exports.
  25848. *
  25849. * Logic borrowed from Modernizr:
  25850. *
  25851. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  25852. */
  25853. try {
  25854. module.exports = 'XMLHttpRequest' in global &&
  25855. 'withCredentials' in new global.XMLHttpRequest();
  25856. } catch (err) {
  25857. // if XMLHttp support is disabled in IE then it will throw
  25858. // when trying to create
  25859. module.exports = false;
  25860. }
  25861. },{"global":119}],119:[function(require,module,exports){
  25862. /**
  25863. * Returns `this`. Execute this without a "context" (i.e. without it being
  25864. * attached to an object of the left-hand side), and `this` points to the
  25865. * "global" scope of the current JS execution.
  25866. */
  25867. module.exports = (function () { return this; })();
  25868. },{}],120:[function(require,module,exports){
  25869. (function (global){
  25870. /**
  25871. * JSON parse.
  25872. *
  25873. * @see Based on jQuery#parseJSON (MIT) and JSON2
  25874. * @api private
  25875. */
  25876. var rvalidchars = /^[\],:{}\s]*$/;
  25877. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  25878. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  25879. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  25880. var rtrimLeft = /^\s+/;
  25881. var rtrimRight = /\s+$/;
  25882. module.exports = function parsejson(data) {
  25883. if ('string' != typeof data || !data) {
  25884. return null;
  25885. }
  25886. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  25887. // Attempt to parse using the native JSON parser first
  25888. if (global.JSON && JSON.parse) {
  25889. return JSON.parse(data);
  25890. }
  25891. if (rvalidchars.test(data.replace(rvalidescape, '@')
  25892. .replace(rvalidtokens, ']')
  25893. .replace(rvalidbraces, ''))) {
  25894. return (new Function('return ' + data))();
  25895. }
  25896. };
  25897. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25898. },{}],121:[function(require,module,exports){
  25899. /**
  25900. * Compiles a querystring
  25901. * Returns string representation of the object
  25902. *
  25903. * @param {Object}
  25904. * @api private
  25905. */
  25906. exports.encode = function (obj) {
  25907. var str = '';
  25908. for (var i in obj) {
  25909. if (obj.hasOwnProperty(i)) {
  25910. if (str.length) str += '&';
  25911. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  25912. }
  25913. }
  25914. return str;
  25915. };
  25916. /**
  25917. * Parses a simple querystring into an object
  25918. *
  25919. * @param {String} qs
  25920. * @api private
  25921. */
  25922. exports.decode = function(qs){
  25923. var qry = {};
  25924. var pairs = qs.split('&');
  25925. for (var i = 0, l = pairs.length; i < l; i++) {
  25926. var pair = pairs[i].split('=');
  25927. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  25928. }
  25929. return qry;
  25930. };
  25931. },{}],122:[function(require,module,exports){
  25932. /**
  25933. * Parses an URI
  25934. *
  25935. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  25936. * @api private
  25937. */
  25938. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  25939. var parts = [
  25940. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  25941. ];
  25942. module.exports = function parseuri(str) {
  25943. var src = str,
  25944. b = str.indexOf('['),
  25945. e = str.indexOf(']');
  25946. if (b != -1 && e != -1) {
  25947. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  25948. }
  25949. var m = re.exec(str || ''),
  25950. uri = {},
  25951. i = 14;
  25952. while (i--) {
  25953. uri[parts[i]] = m[i] || '';
  25954. }
  25955. if (b != -1 && e != -1) {
  25956. uri.source = src;
  25957. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  25958. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  25959. uri.ipv6uri = true;
  25960. }
  25961. return uri;
  25962. };
  25963. },{}],123:[function(require,module,exports){
  25964. /**
  25965. * Module dependencies.
  25966. */
  25967. var global = (function() { return this; })();
  25968. /**
  25969. * WebSocket constructor.
  25970. */
  25971. var WebSocket = global.WebSocket || global.MozWebSocket;
  25972. /**
  25973. * Module exports.
  25974. */
  25975. module.exports = WebSocket ? ws : null;
  25976. /**
  25977. * WebSocket constructor.
  25978. *
  25979. * The third `opts` options object gets ignored in web browsers, since it's
  25980. * non-standard, and throws a TypeError if passed to the constructor.
  25981. * See: https://github.com/einaros/ws/issues/227
  25982. *
  25983. * @param {String} uri
  25984. * @param {Array} protocols (optional)
  25985. * @param {Object) opts (optional)
  25986. * @api public
  25987. */
  25988. function ws(uri, protocols, opts) {
  25989. var instance;
  25990. if (protocols) {
  25991. instance = new WebSocket(uri, protocols);
  25992. } else {
  25993. instance = new WebSocket(uri);
  25994. }
  25995. return instance;
  25996. }
  25997. if (WebSocket) ws.prototype = WebSocket.prototype;
  25998. },{}],124:[function(require,module,exports){
  25999. (function (global){
  26000. /*
  26001. * Module requirements.
  26002. */
  26003. var isArray = require('isarray');
  26004. /**
  26005. * Module exports.
  26006. */
  26007. module.exports = hasBinary;
  26008. /**
  26009. * Checks for binary data.
  26010. *
  26011. * Right now only Buffer and ArrayBuffer are supported..
  26012. *
  26013. * @param {Object} anything
  26014. * @api public
  26015. */
  26016. function hasBinary(data) {
  26017. function _hasBinary(obj) {
  26018. if (!obj) return false;
  26019. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26020. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  26021. (global.Blob && obj instanceof Blob) ||
  26022. (global.File && obj instanceof File)
  26023. ) {
  26024. return true;
  26025. }
  26026. if (isArray(obj)) {
  26027. for (var i = 0; i < obj.length; i++) {
  26028. if (_hasBinary(obj[i])) {
  26029. return true;
  26030. }
  26031. }
  26032. } else if (obj && 'object' == typeof obj) {
  26033. if (obj.toJSON) {
  26034. obj = obj.toJSON();
  26035. }
  26036. for (var key in obj) {
  26037. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26038. return true;
  26039. }
  26040. }
  26041. }
  26042. return false;
  26043. }
  26044. return _hasBinary(data);
  26045. }
  26046. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26047. },{"isarray":125}],125:[function(require,module,exports){
  26048. arguments[4][116][0].apply(exports,arguments)
  26049. },{"dup":116}],126:[function(require,module,exports){
  26050. var indexOf = [].indexOf;
  26051. module.exports = function(arr, obj){
  26052. if (indexOf) return arr.indexOf(obj);
  26053. for (var i = 0; i < arr.length; ++i) {
  26054. if (arr[i] === obj) return i;
  26055. }
  26056. return -1;
  26057. };
  26058. },{}],127:[function(require,module,exports){
  26059. /**
  26060. * HOP ref.
  26061. */
  26062. var has = Object.prototype.hasOwnProperty;
  26063. /**
  26064. * Return own keys in `obj`.
  26065. *
  26066. * @param {Object} obj
  26067. * @return {Array}
  26068. * @api public
  26069. */
  26070. exports.keys = Object.keys || function(obj){
  26071. var keys = [];
  26072. for (var key in obj) {
  26073. if (has.call(obj, key)) {
  26074. keys.push(key);
  26075. }
  26076. }
  26077. return keys;
  26078. };
  26079. /**
  26080. * Return own values in `obj`.
  26081. *
  26082. * @param {Object} obj
  26083. * @return {Array}
  26084. * @api public
  26085. */
  26086. exports.values = function(obj){
  26087. var vals = [];
  26088. for (var key in obj) {
  26089. if (has.call(obj, key)) {
  26090. vals.push(obj[key]);
  26091. }
  26092. }
  26093. return vals;
  26094. };
  26095. /**
  26096. * Merge `b` into `a`.
  26097. *
  26098. * @param {Object} a
  26099. * @param {Object} b
  26100. * @return {Object} a
  26101. * @api public
  26102. */
  26103. exports.merge = function(a, b){
  26104. for (var key in b) {
  26105. if (has.call(b, key)) {
  26106. a[key] = b[key];
  26107. }
  26108. }
  26109. return a;
  26110. };
  26111. /**
  26112. * Return length of `obj`.
  26113. *
  26114. * @param {Object} obj
  26115. * @return {Number}
  26116. * @api public
  26117. */
  26118. exports.length = function(obj){
  26119. return exports.keys(obj).length;
  26120. };
  26121. /**
  26122. * Check if `obj` is empty.
  26123. *
  26124. * @param {Object} obj
  26125. * @return {Boolean}
  26126. * @api public
  26127. */
  26128. exports.isEmpty = function(obj){
  26129. return 0 == exports.length(obj);
  26130. };
  26131. },{}],128:[function(require,module,exports){
  26132. /**
  26133. * Parses an URI
  26134. *
  26135. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26136. * @api private
  26137. */
  26138. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26139. var parts = [
  26140. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  26141. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26142. ];
  26143. module.exports = function parseuri(str) {
  26144. var m = re.exec(str || '')
  26145. , uri = {}
  26146. , i = 14;
  26147. while (i--) {
  26148. uri[parts[i]] = m[i] || '';
  26149. }
  26150. return uri;
  26151. };
  26152. },{}],129:[function(require,module,exports){
  26153. (function (global){
  26154. /*global Blob,File*/
  26155. /**
  26156. * Module requirements
  26157. */
  26158. var isArray = require('isarray');
  26159. var isBuf = require('./is-buffer');
  26160. /**
  26161. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26162. * Anything with blobs or files should be fed through removeBlobs before coming
  26163. * here.
  26164. *
  26165. * @param {Object} packet - socket.io event packet
  26166. * @return {Object} with deconstructed packet and list of buffers
  26167. * @api public
  26168. */
  26169. exports.deconstructPacket = function(packet){
  26170. var buffers = [];
  26171. var packetData = packet.data;
  26172. function _deconstructPacket(data) {
  26173. if (!data) return data;
  26174. if (isBuf(data)) {
  26175. var placeholder = { _placeholder: true, num: buffers.length };
  26176. buffers.push(data);
  26177. return placeholder;
  26178. } else if (isArray(data)) {
  26179. var newData = new Array(data.length);
  26180. for (var i = 0; i < data.length; i++) {
  26181. newData[i] = _deconstructPacket(data[i]);
  26182. }
  26183. return newData;
  26184. } else if ('object' == typeof data && !(data instanceof Date)) {
  26185. var newData = {};
  26186. for (var key in data) {
  26187. newData[key] = _deconstructPacket(data[key]);
  26188. }
  26189. return newData;
  26190. }
  26191. return data;
  26192. }
  26193. var pack = packet;
  26194. pack.data = _deconstructPacket(packetData);
  26195. pack.attachments = buffers.length; // number of binary 'attachments'
  26196. return {packet: pack, buffers: buffers};
  26197. };
  26198. /**
  26199. * Reconstructs a binary packet from its placeholder packet and buffers
  26200. *
  26201. * @param {Object} packet - event packet with placeholders
  26202. * @param {Array} buffers - binary buffers to put in placeholder positions
  26203. * @return {Object} reconstructed packet
  26204. * @api public
  26205. */
  26206. exports.reconstructPacket = function(packet, buffers) {
  26207. var curPlaceHolder = 0;
  26208. function _reconstructPacket(data) {
  26209. if (data && data._placeholder) {
  26210. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26211. return buf;
  26212. } else if (isArray(data)) {
  26213. for (var i = 0; i < data.length; i++) {
  26214. data[i] = _reconstructPacket(data[i]);
  26215. }
  26216. return data;
  26217. } else if (data && 'object' == typeof data) {
  26218. for (var key in data) {
  26219. data[key] = _reconstructPacket(data[key]);
  26220. }
  26221. return data;
  26222. }
  26223. return data;
  26224. }
  26225. packet.data = _reconstructPacket(packet.data);
  26226. packet.attachments = undefined; // no longer useful
  26227. return packet;
  26228. };
  26229. /**
  26230. * Asynchronously removes Blobs or Files from data via
  26231. * FileReader's readAsArrayBuffer method. Used before encoding
  26232. * data as msgpack. Calls callback with the blobless data.
  26233. *
  26234. * @param {Object} data
  26235. * @param {Function} callback
  26236. * @api private
  26237. */
  26238. exports.removeBlobs = function(data, callback) {
  26239. function _removeBlobs(obj, curKey, containingObject) {
  26240. if (!obj) return obj;
  26241. // convert any blob
  26242. if ((global.Blob && obj instanceof Blob) ||
  26243. (global.File && obj instanceof File)) {
  26244. pendingBlobs++;
  26245. // async filereader
  26246. var fileReader = new FileReader();
  26247. fileReader.onload = function() { // this.result == arraybuffer
  26248. if (containingObject) {
  26249. containingObject[curKey] = this.result;
  26250. }
  26251. else {
  26252. bloblessData = this.result;
  26253. }
  26254. // if nothing pending its callback time
  26255. if(! --pendingBlobs) {
  26256. callback(bloblessData);
  26257. }
  26258. };
  26259. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26260. } else if (isArray(obj)) { // handle array
  26261. for (var i = 0; i < obj.length; i++) {
  26262. _removeBlobs(obj[i], i, obj);
  26263. }
  26264. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26265. for (var key in obj) {
  26266. _removeBlobs(obj[key], key, obj);
  26267. }
  26268. }
  26269. }
  26270. var pendingBlobs = 0;
  26271. var bloblessData = data;
  26272. _removeBlobs(bloblessData);
  26273. if (!pendingBlobs) {
  26274. callback(bloblessData);
  26275. }
  26276. };
  26277. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26278. },{"./is-buffer":131,"isarray":132}],130:[function(require,module,exports){
  26279. /**
  26280. * Module dependencies.
  26281. */
  26282. var debug = require('debug')('socket.io-parser');
  26283. var json = require('json3');
  26284. var isArray = require('isarray');
  26285. var Emitter = require('component-emitter');
  26286. var binary = require('./binary');
  26287. var isBuf = require('./is-buffer');
  26288. /**
  26289. * Protocol version.
  26290. *
  26291. * @api public
  26292. */
  26293. exports.protocol = 4;
  26294. /**
  26295. * Packet types.
  26296. *
  26297. * @api public
  26298. */
  26299. exports.types = [
  26300. 'CONNECT',
  26301. 'DISCONNECT',
  26302. 'EVENT',
  26303. 'BINARY_EVENT',
  26304. 'ACK',
  26305. 'BINARY_ACK',
  26306. 'ERROR'
  26307. ];
  26308. /**
  26309. * Packet type `connect`.
  26310. *
  26311. * @api public
  26312. */
  26313. exports.CONNECT = 0;
  26314. /**
  26315. * Packet type `disconnect`.
  26316. *
  26317. * @api public
  26318. */
  26319. exports.DISCONNECT = 1;
  26320. /**
  26321. * Packet type `event`.
  26322. *
  26323. * @api public
  26324. */
  26325. exports.EVENT = 2;
  26326. /**
  26327. * Packet type `ack`.
  26328. *
  26329. * @api public
  26330. */
  26331. exports.ACK = 3;
  26332. /**
  26333. * Packet type `error`.
  26334. *
  26335. * @api public
  26336. */
  26337. exports.ERROR = 4;
  26338. /**
  26339. * Packet type 'binary event'
  26340. *
  26341. * @api public
  26342. */
  26343. exports.BINARY_EVENT = 5;
  26344. /**
  26345. * Packet type `binary ack`. For acks with binary arguments.
  26346. *
  26347. * @api public
  26348. */
  26349. exports.BINARY_ACK = 6;
  26350. /**
  26351. * Encoder constructor.
  26352. *
  26353. * @api public
  26354. */
  26355. exports.Encoder = Encoder;
  26356. /**
  26357. * Decoder constructor.
  26358. *
  26359. * @api public
  26360. */
  26361. exports.Decoder = Decoder;
  26362. /**
  26363. * A socket.io Encoder instance
  26364. *
  26365. * @api public
  26366. */
  26367. function Encoder() {}
  26368. /**
  26369. * Encode a packet as a single string if non-binary, or as a
  26370. * buffer sequence, depending on packet type.
  26371. *
  26372. * @param {Object} obj - packet object
  26373. * @param {Function} callback - function to handle encodings (likely engine.write)
  26374. * @return Calls callback with Array of encodings
  26375. * @api public
  26376. */
  26377. Encoder.prototype.encode = function(obj, callback){
  26378. debug('encoding packet %j', obj);
  26379. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26380. encodeAsBinary(obj, callback);
  26381. }
  26382. else {
  26383. var encoding = encodeAsString(obj);
  26384. callback([encoding]);
  26385. }
  26386. };
  26387. /**
  26388. * Encode packet as string.
  26389. *
  26390. * @param {Object} packet
  26391. * @return {String} encoded
  26392. * @api private
  26393. */
  26394. function encodeAsString(obj) {
  26395. var str = '';
  26396. var nsp = false;
  26397. // first is type
  26398. str += obj.type;
  26399. // attachments if we have them
  26400. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26401. str += obj.attachments;
  26402. str += '-';
  26403. }
  26404. // if we have a namespace other than `/`
  26405. // we append it followed by a comma `,`
  26406. if (obj.nsp && '/' != obj.nsp) {
  26407. nsp = true;
  26408. str += obj.nsp;
  26409. }
  26410. // immediately followed by the id
  26411. if (null != obj.id) {
  26412. if (nsp) {
  26413. str += ',';
  26414. nsp = false;
  26415. }
  26416. str += obj.id;
  26417. }
  26418. // json data
  26419. if (null != obj.data) {
  26420. if (nsp) str += ',';
  26421. str += json.stringify(obj.data);
  26422. }
  26423. debug('encoded %j as %s', obj, str);
  26424. return str;
  26425. }
  26426. /**
  26427. * Encode packet as 'buffer sequence' by removing blobs, and
  26428. * deconstructing packet into object with placeholders and
  26429. * a list of buffers.
  26430. *
  26431. * @param {Object} packet
  26432. * @return {Buffer} encoded
  26433. * @api private
  26434. */
  26435. function encodeAsBinary(obj, callback) {
  26436. function writeEncoding(bloblessData) {
  26437. var deconstruction = binary.deconstructPacket(bloblessData);
  26438. var pack = encodeAsString(deconstruction.packet);
  26439. var buffers = deconstruction.buffers;
  26440. buffers.unshift(pack); // add packet info to beginning of data list
  26441. callback(buffers); // write all the buffers
  26442. }
  26443. binary.removeBlobs(obj, writeEncoding);
  26444. }
  26445. /**
  26446. * A socket.io Decoder instance
  26447. *
  26448. * @return {Object} decoder
  26449. * @api public
  26450. */
  26451. function Decoder() {
  26452. this.reconstructor = null;
  26453. }
  26454. /**
  26455. * Mix in `Emitter` with Decoder.
  26456. */
  26457. Emitter(Decoder.prototype);
  26458. /**
  26459. * Decodes an ecoded packet string into packet JSON.
  26460. *
  26461. * @param {String} obj - encoded packet
  26462. * @return {Object} packet
  26463. * @api public
  26464. */
  26465. Decoder.prototype.add = function(obj) {
  26466. var packet;
  26467. if ('string' == typeof obj) {
  26468. packet = decodeString(obj);
  26469. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  26470. this.reconstructor = new BinaryReconstructor(packet);
  26471. // no attachments, labeled binary but no binary data to follow
  26472. if (this.reconstructor.reconPack.attachments === 0) {
  26473. this.emit('decoded', packet);
  26474. }
  26475. } else { // non-binary full packet
  26476. this.emit('decoded', packet);
  26477. }
  26478. }
  26479. else if (isBuf(obj) || obj.base64) { // raw binary data
  26480. if (!this.reconstructor) {
  26481. throw new Error('got binary data when not reconstructing a packet');
  26482. } else {
  26483. packet = this.reconstructor.takeBinaryData(obj);
  26484. if (packet) { // received final buffer
  26485. this.reconstructor = null;
  26486. this.emit('decoded', packet);
  26487. }
  26488. }
  26489. }
  26490. else {
  26491. throw new Error('Unknown type: ' + obj);
  26492. }
  26493. };
  26494. /**
  26495. * Decode a packet String (JSON data)
  26496. *
  26497. * @param {String} str
  26498. * @return {Object} packet
  26499. * @api private
  26500. */
  26501. function decodeString(str) {
  26502. var p = {};
  26503. var i = 0;
  26504. // look up type
  26505. p.type = Number(str.charAt(0));
  26506. if (null == exports.types[p.type]) return error();
  26507. // look up attachments if type binary
  26508. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  26509. var buf = '';
  26510. while (str.charAt(++i) != '-') {
  26511. buf += str.charAt(i);
  26512. if (i == str.length) break;
  26513. }
  26514. if (buf != Number(buf) || str.charAt(i) != '-') {
  26515. throw new Error('Illegal attachments');
  26516. }
  26517. p.attachments = Number(buf);
  26518. }
  26519. // look up namespace (if any)
  26520. if ('/' == str.charAt(i + 1)) {
  26521. p.nsp = '';
  26522. while (++i) {
  26523. var c = str.charAt(i);
  26524. if (',' == c) break;
  26525. p.nsp += c;
  26526. if (i == str.length) break;
  26527. }
  26528. } else {
  26529. p.nsp = '/';
  26530. }
  26531. // look up id
  26532. var next = str.charAt(i + 1);
  26533. if ('' !== next && Number(next) == next) {
  26534. p.id = '';
  26535. while (++i) {
  26536. var c = str.charAt(i);
  26537. if (null == c || Number(c) != c) {
  26538. --i;
  26539. break;
  26540. }
  26541. p.id += str.charAt(i);
  26542. if (i == str.length) break;
  26543. }
  26544. p.id = Number(p.id);
  26545. }
  26546. // look up json data
  26547. if (str.charAt(++i)) {
  26548. try {
  26549. p.data = json.parse(str.substr(i));
  26550. } catch(e){
  26551. return error();
  26552. }
  26553. }
  26554. debug('decoded %s as %j', str, p);
  26555. return p;
  26556. }
  26557. /**
  26558. * Deallocates a parser's resources
  26559. *
  26560. * @api public
  26561. */
  26562. Decoder.prototype.destroy = function() {
  26563. if (this.reconstructor) {
  26564. this.reconstructor.finishedReconstruction();
  26565. }
  26566. };
  26567. /**
  26568. * A manager of a binary event's 'buffer sequence'. Should
  26569. * be constructed whenever a packet of type BINARY_EVENT is
  26570. * decoded.
  26571. *
  26572. * @param {Object} packet
  26573. * @return {BinaryReconstructor} initialized reconstructor
  26574. * @api private
  26575. */
  26576. function BinaryReconstructor(packet) {
  26577. this.reconPack = packet;
  26578. this.buffers = [];
  26579. }
  26580. /**
  26581. * Method to be called when binary data received from connection
  26582. * after a BINARY_EVENT packet.
  26583. *
  26584. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  26585. * @return {null | Object} returns null if more binary data is expected or
  26586. * a reconstructed packet object if all buffers have been received.
  26587. * @api private
  26588. */
  26589. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  26590. this.buffers.push(binData);
  26591. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  26592. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  26593. this.finishedReconstruction();
  26594. return packet;
  26595. }
  26596. return null;
  26597. };
  26598. /**
  26599. * Cleans up binary packet reconstruction variables.
  26600. *
  26601. * @api private
  26602. */
  26603. BinaryReconstructor.prototype.finishedReconstruction = function() {
  26604. this.reconPack = null;
  26605. this.buffers = [];
  26606. };
  26607. function error(data){
  26608. return {
  26609. type: exports.ERROR,
  26610. data: 'parser error'
  26611. };
  26612. }
  26613. },{"./binary":129,"./is-buffer":131,"component-emitter":93,"debug":94,"isarray":132,"json3":133}],131:[function(require,module,exports){
  26614. (function (global){
  26615. module.exports = isBuf;
  26616. /**
  26617. * Returns true if obj is a buffer or an arraybuffer.
  26618. *
  26619. * @api private
  26620. */
  26621. function isBuf(obj) {
  26622. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26623. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  26624. }
  26625. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26626. },{}],132:[function(require,module,exports){
  26627. arguments[4][116][0].apply(exports,arguments)
  26628. },{"dup":116}],133:[function(require,module,exports){
  26629. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  26630. ;(function (window) {
  26631. // Convenience aliases.
  26632. var getClass = {}.toString, isProperty, forEach, undef;
  26633. // Detect the `define` function exposed by asynchronous module loaders. The
  26634. // strict `define` check is necessary for compatibility with `r.js`.
  26635. var isLoader = typeof define === "function" && define.amd;
  26636. // Detect native implementations.
  26637. var nativeJSON = typeof JSON == "object" && JSON;
  26638. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  26639. // available.
  26640. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  26641. if (JSON3 && nativeJSON) {
  26642. // Explicitly delegate to the native `stringify` and `parse`
  26643. // implementations in CommonJS environments.
  26644. JSON3.stringify = nativeJSON.stringify;
  26645. JSON3.parse = nativeJSON.parse;
  26646. } else {
  26647. // Export for web browsers, JavaScript engines, and asynchronous module
  26648. // loaders, using the global `JSON` object if available.
  26649. JSON3 = window.JSON = nativeJSON || {};
  26650. }
  26651. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  26652. var isExtended = new Date(-3509827334573292);
  26653. try {
  26654. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  26655. // results for certain dates in Opera >= 10.53.
  26656. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  26657. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  26658. // but clips the values returned by the date methods to the range of
  26659. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  26660. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  26661. } catch (exception) {}
  26662. // Internal: Determines whether the native `JSON.stringify` and `parse`
  26663. // implementations are spec-compliant. Based on work by Ken Snyder.
  26664. function has(name) {
  26665. if (has[name] !== undef) {
  26666. // Return cached feature test result.
  26667. return has[name];
  26668. }
  26669. var isSupported;
  26670. if (name == "bug-string-char-index") {
  26671. // IE <= 7 doesn't support accessing string characters using square
  26672. // bracket notation. IE 8 only supports this for primitives.
  26673. isSupported = "a"[0] != "a";
  26674. } else if (name == "json") {
  26675. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  26676. // supported.
  26677. isSupported = has("json-stringify") && has("json-parse");
  26678. } else {
  26679. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  26680. // Test `JSON.stringify`.
  26681. if (name == "json-stringify") {
  26682. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  26683. if (stringifySupported) {
  26684. // A test function object with a custom `toJSON` method.
  26685. (value = function () {
  26686. return 1;
  26687. }).toJSON = value;
  26688. try {
  26689. stringifySupported =
  26690. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  26691. // primitives as object literals.
  26692. stringify(0) === "0" &&
  26693. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  26694. // literals.
  26695. stringify(new Number()) === "0" &&
  26696. stringify(new String()) == '""' &&
  26697. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  26698. // does not define a canonical JSON representation (this applies to
  26699. // objects with `toJSON` properties as well, *unless* they are nested
  26700. // within an object or array).
  26701. stringify(getClass) === undef &&
  26702. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  26703. // FF 3.1b3 pass this test.
  26704. stringify(undef) === undef &&
  26705. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  26706. // respectively, if the value is omitted entirely.
  26707. stringify() === undef &&
  26708. // FF 3.1b1, 2 throw an error if the given value is not a number,
  26709. // string, array, object, Boolean, or `null` literal. This applies to
  26710. // objects with custom `toJSON` methods as well, unless they are nested
  26711. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  26712. // methods entirely.
  26713. stringify(value) === "1" &&
  26714. stringify([value]) == "[1]" &&
  26715. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  26716. // `"[null]"`.
  26717. stringify([undef]) == "[null]" &&
  26718. // YUI 3.0.0b1 fails to serialize `null` literals.
  26719. stringify(null) == "null" &&
  26720. // FF 3.1b1, 2 halts serialization if an array contains a function:
  26721. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  26722. // elides non-JSON values from objects and arrays, unless they
  26723. // define custom `toJSON` methods.
  26724. stringify([undef, getClass, null]) == "[null,null,null]" &&
  26725. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  26726. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  26727. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  26728. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  26729. stringify(null, value) === "1" &&
  26730. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  26731. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  26732. // serialize extended years.
  26733. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  26734. // The milliseconds are optional in ES 5, but required in 5.1.
  26735. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  26736. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  26737. // four-digit years instead of six-digit years. Credits: @Yaffle.
  26738. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  26739. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  26740. // values less than 1000. Credits: @Yaffle.
  26741. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  26742. } catch (exception) {
  26743. stringifySupported = false;
  26744. }
  26745. }
  26746. isSupported = stringifySupported;
  26747. }
  26748. // Test `JSON.parse`.
  26749. if (name == "json-parse") {
  26750. var parse = JSON3.parse;
  26751. if (typeof parse == "function") {
  26752. try {
  26753. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  26754. // Conforming implementations should also coerce the initial argument to
  26755. // a string prior to parsing.
  26756. if (parse("0") === 0 && !parse(false)) {
  26757. // Simple parsing test.
  26758. value = parse(serialized);
  26759. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  26760. if (parseSupported) {
  26761. try {
  26762. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  26763. parseSupported = !parse('"\t"');
  26764. } catch (exception) {}
  26765. if (parseSupported) {
  26766. try {
  26767. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  26768. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  26769. // certain octal literals.
  26770. parseSupported = parse("01") !== 1;
  26771. } catch (exception) {}
  26772. }
  26773. if (parseSupported) {
  26774. try {
  26775. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  26776. // points. These environments, along with FF 3.1b1 and 2,
  26777. // also allow trailing commas in JSON objects and arrays.
  26778. parseSupported = parse("1.") !== 1;
  26779. } catch (exception) {}
  26780. }
  26781. }
  26782. }
  26783. } catch (exception) {
  26784. parseSupported = false;
  26785. }
  26786. }
  26787. isSupported = parseSupported;
  26788. }
  26789. }
  26790. return has[name] = !!isSupported;
  26791. }
  26792. if (!has("json")) {
  26793. // Common `[[Class]]` name aliases.
  26794. var functionClass = "[object Function]";
  26795. var dateClass = "[object Date]";
  26796. var numberClass = "[object Number]";
  26797. var stringClass = "[object String]";
  26798. var arrayClass = "[object Array]";
  26799. var booleanClass = "[object Boolean]";
  26800. // Detect incomplete support for accessing string characters by index.
  26801. var charIndexBuggy = has("bug-string-char-index");
  26802. // Define additional utility methods if the `Date` methods are buggy.
  26803. if (!isExtended) {
  26804. var floor = Math.floor;
  26805. // A mapping between the months of the year and the number of days between
  26806. // January 1st and the first of the respective month.
  26807. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  26808. // Internal: Calculates the number of days between the Unix epoch and the
  26809. // first day of the given month.
  26810. var getDay = function (year, month) {
  26811. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  26812. };
  26813. }
  26814. // Internal: Determines if a property is a direct property of the given
  26815. // object. Delegates to the native `Object#hasOwnProperty` method.
  26816. if (!(isProperty = {}.hasOwnProperty)) {
  26817. isProperty = function (property) {
  26818. var members = {}, constructor;
  26819. if ((members.__proto__ = null, members.__proto__ = {
  26820. // The *proto* property cannot be set multiple times in recent
  26821. // versions of Firefox and SeaMonkey.
  26822. "toString": 1
  26823. }, members).toString != getClass) {
  26824. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  26825. // supports the mutable *proto* property.
  26826. isProperty = function (property) {
  26827. // Capture and break the object's prototype chain (see section 8.6.2
  26828. // of the ES 5.1 spec). The parenthesized expression prevents an
  26829. // unsafe transformation by the Closure Compiler.
  26830. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  26831. // Restore the original prototype chain.
  26832. this.__proto__ = original;
  26833. return result;
  26834. };
  26835. } else {
  26836. // Capture a reference to the top-level `Object` constructor.
  26837. constructor = members.constructor;
  26838. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  26839. // other environments.
  26840. isProperty = function (property) {
  26841. var parent = (this.constructor || constructor).prototype;
  26842. return property in this && !(property in parent && this[property] === parent[property]);
  26843. };
  26844. }
  26845. members = null;
  26846. return isProperty.call(this, property);
  26847. };
  26848. }
  26849. // Internal: A set of primitive types used by `isHostType`.
  26850. var PrimitiveTypes = {
  26851. 'boolean': 1,
  26852. 'number': 1,
  26853. 'string': 1,
  26854. 'undefined': 1
  26855. };
  26856. // Internal: Determines if the given object `property` value is a
  26857. // non-primitive.
  26858. var isHostType = function (object, property) {
  26859. var type = typeof object[property];
  26860. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  26861. };
  26862. // Internal: Normalizes the `for...in` iteration algorithm across
  26863. // environments. Each enumerated key is yielded to a `callback` function.
  26864. forEach = function (object, callback) {
  26865. var size = 0, Properties, members, property;
  26866. // Tests for bugs in the current environment's `for...in` algorithm. The
  26867. // `valueOf` property inherits the non-enumerable flag from
  26868. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  26869. (Properties = function () {
  26870. this.valueOf = 0;
  26871. }).prototype.valueOf = 0;
  26872. // Iterate over a new instance of the `Properties` class.
  26873. members = new Properties();
  26874. for (property in members) {
  26875. // Ignore all properties inherited from `Object.prototype`.
  26876. if (isProperty.call(members, property)) {
  26877. size++;
  26878. }
  26879. }
  26880. Properties = members = null;
  26881. // Normalize the iteration algorithm.
  26882. if (!size) {
  26883. // A list of non-enumerable properties inherited from `Object.prototype`.
  26884. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  26885. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  26886. // properties.
  26887. forEach = function (object, callback) {
  26888. var isFunction = getClass.call(object) == functionClass, property, length;
  26889. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  26890. for (property in object) {
  26891. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  26892. // certain conditions; IE does not.
  26893. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  26894. callback(property);
  26895. }
  26896. }
  26897. // Manually invoke the callback for each non-enumerable property.
  26898. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  26899. };
  26900. } else if (size == 2) {
  26901. // Safari <= 2.0.4 enumerates shadowed properties twice.
  26902. forEach = function (object, callback) {
  26903. // Create a set of iterated properties.
  26904. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  26905. for (property in object) {
  26906. // Store each property name to prevent double enumeration. The
  26907. // `prototype` property of functions is not enumerated due to cross-
  26908. // environment inconsistencies.
  26909. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  26910. callback(property);
  26911. }
  26912. }
  26913. };
  26914. } else {
  26915. // No bugs detected; use the standard `for...in` algorithm.
  26916. forEach = function (object, callback) {
  26917. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  26918. for (property in object) {
  26919. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  26920. callback(property);
  26921. }
  26922. }
  26923. // Manually invoke the callback for the `constructor` property due to
  26924. // cross-environment inconsistencies.
  26925. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  26926. callback(property);
  26927. }
  26928. };
  26929. }
  26930. return forEach(object, callback);
  26931. };
  26932. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  26933. // `filter` argument may specify either a function that alters how object and
  26934. // array members are serialized, or an array of strings and numbers that
  26935. // indicates which properties should be serialized. The optional `width`
  26936. // argument may be either a string or number that specifies the indentation
  26937. // level of the output.
  26938. if (!has("json-stringify")) {
  26939. // Internal: A map of control characters and their escaped equivalents.
  26940. var Escapes = {
  26941. 92: "\\\\",
  26942. 34: '\\"',
  26943. 8: "\\b",
  26944. 12: "\\f",
  26945. 10: "\\n",
  26946. 13: "\\r",
  26947. 9: "\\t"
  26948. };
  26949. // Internal: Converts `value` into a zero-padded string such that its
  26950. // length is at least equal to `width`. The `width` must be <= 6.
  26951. var leadingZeroes = "000000";
  26952. var toPaddedString = function (width, value) {
  26953. // The `|| 0` expression is necessary to work around a bug in
  26954. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  26955. return (leadingZeroes + (value || 0)).slice(-width);
  26956. };
  26957. // Internal: Double-quotes a string `value`, replacing all ASCII control
  26958. // characters (characters with code unit values between 0 and 31) with
  26959. // their escaped equivalents. This is an implementation of the
  26960. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  26961. var unicodePrefix = "\\u00";
  26962. var quote = function (value) {
  26963. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  26964. if (isLarge) {
  26965. symbols = value.split("");
  26966. }
  26967. for (; index < length; index++) {
  26968. var charCode = value.charCodeAt(index);
  26969. // If the character is a control character, append its Unicode or
  26970. // shorthand escape sequence; otherwise, append the character as-is.
  26971. switch (charCode) {
  26972. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  26973. result += Escapes[charCode];
  26974. break;
  26975. default:
  26976. if (charCode < 32) {
  26977. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  26978. break;
  26979. }
  26980. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  26981. }
  26982. }
  26983. return result + '"';
  26984. };
  26985. // Internal: Recursively serializes an object. Implements the
  26986. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  26987. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  26988. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  26989. try {
  26990. // Necessary for host object support.
  26991. value = object[property];
  26992. } catch (exception) {}
  26993. if (typeof value == "object" && value) {
  26994. className = getClass.call(value);
  26995. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  26996. if (value > -1 / 0 && value < 1 / 0) {
  26997. // Dates are serialized according to the `Date#toJSON` method
  26998. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  26999. // for the ISO 8601 date time string format.
  27000. if (getDay) {
  27001. // Manually compute the year, month, date, hours, minutes,
  27002. // seconds, and milliseconds if the `getUTC*` methods are
  27003. // buggy. Adapted from @Yaffle's `date-shim` project.
  27004. date = floor(value / 864e5);
  27005. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  27006. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  27007. date = 1 + date - getDay(year, month);
  27008. // The `time` value specifies the time within the day (see ES
  27009. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  27010. // to compute `A modulo B`, as the `%` operator does not
  27011. // correspond to the `modulo` operation for negative numbers.
  27012. time = (value % 864e5 + 864e5) % 864e5;
  27013. // The hours, minutes, seconds, and milliseconds are obtained by
  27014. // decomposing the time within the day. See section 15.9.1.10.
  27015. hours = floor(time / 36e5) % 24;
  27016. minutes = floor(time / 6e4) % 60;
  27017. seconds = floor(time / 1e3) % 60;
  27018. milliseconds = time % 1e3;
  27019. } else {
  27020. year = value.getUTCFullYear();
  27021. month = value.getUTCMonth();
  27022. date = value.getUTCDate();
  27023. hours = value.getUTCHours();
  27024. minutes = value.getUTCMinutes();
  27025. seconds = value.getUTCSeconds();
  27026. milliseconds = value.getUTCMilliseconds();
  27027. }
  27028. // Serialize extended years correctly.
  27029. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  27030. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  27031. // Months, dates, hours, minutes, and seconds should have two
  27032. // digits; milliseconds should have three.
  27033. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  27034. // Milliseconds are optional in ES 5.0, but required in 5.1.
  27035. "." + toPaddedString(3, milliseconds) + "Z";
  27036. } else {
  27037. value = null;
  27038. }
  27039. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  27040. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  27041. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  27042. // ignores all `toJSON` methods on these objects unless they are
  27043. // defined directly on an instance.
  27044. value = value.toJSON(property);
  27045. }
  27046. }
  27047. if (callback) {
  27048. // If a replacement function was provided, call it to obtain the value
  27049. // for serialization.
  27050. value = callback.call(object, property, value);
  27051. }
  27052. if (value === null) {
  27053. return "null";
  27054. }
  27055. className = getClass.call(value);
  27056. if (className == booleanClass) {
  27057. // Booleans are represented literally.
  27058. return "" + value;
  27059. } else if (className == numberClass) {
  27060. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  27061. // `"null"`.
  27062. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  27063. } else if (className == stringClass) {
  27064. // Strings are double-quoted and escaped.
  27065. return quote("" + value);
  27066. }
  27067. // Recursively serialize objects and arrays.
  27068. if (typeof value == "object") {
  27069. // Check for cyclic structures. This is a linear search; performance
  27070. // is inversely proportional to the number of unique nested objects.
  27071. for (length = stack.length; length--;) {
  27072. if (stack[length] === value) {
  27073. // Cyclic structures cannot be serialized by `JSON.stringify`.
  27074. throw TypeError();
  27075. }
  27076. }
  27077. // Add the object to the stack of traversed objects.
  27078. stack.push(value);
  27079. results = [];
  27080. // Save the current indentation level and indent one additional level.
  27081. prefix = indentation;
  27082. indentation += whitespace;
  27083. if (className == arrayClass) {
  27084. // Recursively serialize array elements.
  27085. for (index = 0, length = value.length; index < length; index++) {
  27086. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  27087. results.push(element === undef ? "null" : element);
  27088. }
  27089. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  27090. } else {
  27091. // Recursively serialize object members. Members are selected from
  27092. // either a user-specified list of property names, or the object
  27093. // itself.
  27094. forEach(properties || value, function (property) {
  27095. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  27096. if (element !== undef) {
  27097. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  27098. // is not the empty string, let `member` {quote(property) + ":"}
  27099. // be the concatenation of `member` and the `space` character."
  27100. // The "`space` character" refers to the literal space
  27101. // character, not the `space` {width} argument provided to
  27102. // `JSON.stringify`.
  27103. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  27104. }
  27105. });
  27106. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  27107. }
  27108. // Remove the object from the traversed object stack.
  27109. stack.pop();
  27110. return result;
  27111. }
  27112. };
  27113. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  27114. JSON3.stringify = function (source, filter, width) {
  27115. var whitespace, callback, properties, className;
  27116. if (typeof filter == "function" || typeof filter == "object" && filter) {
  27117. if ((className = getClass.call(filter)) == functionClass) {
  27118. callback = filter;
  27119. } else if (className == arrayClass) {
  27120. // Convert the property names array into a makeshift set.
  27121. properties = {};
  27122. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  27123. }
  27124. }
  27125. if (width) {
  27126. if ((className = getClass.call(width)) == numberClass) {
  27127. // Convert the `width` to an integer and create a string containing
  27128. // `width` number of space characters.
  27129. if ((width -= width % 1) > 0) {
  27130. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  27131. }
  27132. } else if (className == stringClass) {
  27133. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  27134. }
  27135. }
  27136. // Opera <= 7.54u2 discards the values associated with empty string keys
  27137. // (`""`) only if they are used directly within an object member list
  27138. // (e.g., `!("" in { "": 1})`).
  27139. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  27140. };
  27141. }
  27142. // Public: Parses a JSON source string.
  27143. if (!has("json-parse")) {
  27144. var fromCharCode = String.fromCharCode;
  27145. // Internal: A map of escaped control characters and their unescaped
  27146. // equivalents.
  27147. var Unescapes = {
  27148. 92: "\\",
  27149. 34: '"',
  27150. 47: "/",
  27151. 98: "\b",
  27152. 116: "\t",
  27153. 110: "\n",
  27154. 102: "\f",
  27155. 114: "\r"
  27156. };
  27157. // Internal: Stores the parser state.
  27158. var Index, Source;
  27159. // Internal: Resets the parser state and throws a `SyntaxError`.
  27160. var abort = function() {
  27161. Index = Source = null;
  27162. throw SyntaxError();
  27163. };
  27164. // Internal: Returns the next token, or `"$"` if the parser has reached
  27165. // the end of the source string. A token may be a string, number, `null`
  27166. // literal, or Boolean literal.
  27167. var lex = function () {
  27168. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  27169. while (Index < length) {
  27170. charCode = source.charCodeAt(Index);
  27171. switch (charCode) {
  27172. case 9: case 10: case 13: case 32:
  27173. // Skip whitespace tokens, including tabs, carriage returns, line
  27174. // feeds, and space characters.
  27175. Index++;
  27176. break;
  27177. case 123: case 125: case 91: case 93: case 58: case 44:
  27178. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  27179. // the current position.
  27180. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  27181. Index++;
  27182. return value;
  27183. case 34:
  27184. // `"` delimits a JSON string; advance to the next character and
  27185. // begin parsing the string. String tokens are prefixed with the
  27186. // sentinel `@` character to distinguish them from punctuators and
  27187. // end-of-string tokens.
  27188. for (value = "@", Index++; Index < length;) {
  27189. charCode = source.charCodeAt(Index);
  27190. if (charCode < 32) {
  27191. // Unescaped ASCII control characters (those with a code unit
  27192. // less than the space character) are not permitted.
  27193. abort();
  27194. } else if (charCode == 92) {
  27195. // A reverse solidus (`\`) marks the beginning of an escaped
  27196. // control character (including `"`, `\`, and `/`) or Unicode
  27197. // escape sequence.
  27198. charCode = source.charCodeAt(++Index);
  27199. switch (charCode) {
  27200. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  27201. // Revive escaped control characters.
  27202. value += Unescapes[charCode];
  27203. Index++;
  27204. break;
  27205. case 117:
  27206. // `\u` marks the beginning of a Unicode escape sequence.
  27207. // Advance to the first character and validate the
  27208. // four-digit code point.
  27209. begin = ++Index;
  27210. for (position = Index + 4; Index < position; Index++) {
  27211. charCode = source.charCodeAt(Index);
  27212. // A valid sequence comprises four hexdigits (case-
  27213. // insensitive) that form a single hexadecimal value.
  27214. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  27215. // Invalid Unicode escape sequence.
  27216. abort();
  27217. }
  27218. }
  27219. // Revive the escaped character.
  27220. value += fromCharCode("0x" + source.slice(begin, Index));
  27221. break;
  27222. default:
  27223. // Invalid escape sequence.
  27224. abort();
  27225. }
  27226. } else {
  27227. if (charCode == 34) {
  27228. // An unescaped double-quote character marks the end of the
  27229. // string.
  27230. break;
  27231. }
  27232. charCode = source.charCodeAt(Index);
  27233. begin = Index;
  27234. // Optimize for the common case where a string is valid.
  27235. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  27236. charCode = source.charCodeAt(++Index);
  27237. }
  27238. // Append the string as-is.
  27239. value += source.slice(begin, Index);
  27240. }
  27241. }
  27242. if (source.charCodeAt(Index) == 34) {
  27243. // Advance to the next character and return the revived string.
  27244. Index++;
  27245. return value;
  27246. }
  27247. // Unterminated string.
  27248. abort();
  27249. default:
  27250. // Parse numbers and literals.
  27251. begin = Index;
  27252. // Advance past the negative sign, if one is specified.
  27253. if (charCode == 45) {
  27254. isSigned = true;
  27255. charCode = source.charCodeAt(++Index);
  27256. }
  27257. // Parse an integer or floating-point value.
  27258. if (charCode >= 48 && charCode <= 57) {
  27259. // Leading zeroes are interpreted as octal literals.
  27260. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  27261. // Illegal octal literal.
  27262. abort();
  27263. }
  27264. isSigned = false;
  27265. // Parse the integer component.
  27266. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  27267. // Floats cannot contain a leading decimal point; however, this
  27268. // case is already accounted for by the parser.
  27269. if (source.charCodeAt(Index) == 46) {
  27270. position = ++Index;
  27271. // Parse the decimal component.
  27272. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27273. if (position == Index) {
  27274. // Illegal trailing decimal.
  27275. abort();
  27276. }
  27277. Index = position;
  27278. }
  27279. // Parse exponents. The `e` denoting the exponent is
  27280. // case-insensitive.
  27281. charCode = source.charCodeAt(Index);
  27282. if (charCode == 101 || charCode == 69) {
  27283. charCode = source.charCodeAt(++Index);
  27284. // Skip past the sign following the exponent, if one is
  27285. // specified.
  27286. if (charCode == 43 || charCode == 45) {
  27287. Index++;
  27288. }
  27289. // Parse the exponential component.
  27290. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27291. if (position == Index) {
  27292. // Illegal empty exponent.
  27293. abort();
  27294. }
  27295. Index = position;
  27296. }
  27297. // Coerce the parsed value to a JavaScript number.
  27298. return +source.slice(begin, Index);
  27299. }
  27300. // A negative sign may only precede numbers.
  27301. if (isSigned) {
  27302. abort();
  27303. }
  27304. // `true`, `false`, and `null` literals.
  27305. if (source.slice(Index, Index + 4) == "true") {
  27306. Index += 4;
  27307. return true;
  27308. } else if (source.slice(Index, Index + 5) == "false") {
  27309. Index += 5;
  27310. return false;
  27311. } else if (source.slice(Index, Index + 4) == "null") {
  27312. Index += 4;
  27313. return null;
  27314. }
  27315. // Unrecognized token.
  27316. abort();
  27317. }
  27318. }
  27319. // Return the sentinel `$` character if the parser has reached the end
  27320. // of the source string.
  27321. return "$";
  27322. };
  27323. // Internal: Parses a JSON `value` token.
  27324. var get = function (value) {
  27325. var results, hasMembers;
  27326. if (value == "$") {
  27327. // Unexpected end of input.
  27328. abort();
  27329. }
  27330. if (typeof value == "string") {
  27331. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  27332. // Remove the sentinel `@` character.
  27333. return value.slice(1);
  27334. }
  27335. // Parse object and array literals.
  27336. if (value == "[") {
  27337. // Parses a JSON array, returning a new JavaScript array.
  27338. results = [];
  27339. for (;; hasMembers || (hasMembers = true)) {
  27340. value = lex();
  27341. // A closing square bracket marks the end of the array literal.
  27342. if (value == "]") {
  27343. break;
  27344. }
  27345. // If the array literal contains elements, the current token
  27346. // should be a comma separating the previous element from the
  27347. // next.
  27348. if (hasMembers) {
  27349. if (value == ",") {
  27350. value = lex();
  27351. if (value == "]") {
  27352. // Unexpected trailing `,` in array literal.
  27353. abort();
  27354. }
  27355. } else {
  27356. // A `,` must separate each array element.
  27357. abort();
  27358. }
  27359. }
  27360. // Elisions and leading commas are not permitted.
  27361. if (value == ",") {
  27362. abort();
  27363. }
  27364. results.push(get(value));
  27365. }
  27366. return results;
  27367. } else if (value == "{") {
  27368. // Parses a JSON object, returning a new JavaScript object.
  27369. results = {};
  27370. for (;; hasMembers || (hasMembers = true)) {
  27371. value = lex();
  27372. // A closing curly brace marks the end of the object literal.
  27373. if (value == "}") {
  27374. break;
  27375. }
  27376. // If the object literal contains members, the current token
  27377. // should be a comma separator.
  27378. if (hasMembers) {
  27379. if (value == ",") {
  27380. value = lex();
  27381. if (value == "}") {
  27382. // Unexpected trailing `,` in object literal.
  27383. abort();
  27384. }
  27385. } else {
  27386. // A `,` must separate each object member.
  27387. abort();
  27388. }
  27389. }
  27390. // Leading commas are not permitted, object property names must be
  27391. // double-quoted strings, and a `:` must separate each property
  27392. // name and value.
  27393. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  27394. abort();
  27395. }
  27396. results[value.slice(1)] = get(lex());
  27397. }
  27398. return results;
  27399. }
  27400. // Unexpected token encountered.
  27401. abort();
  27402. }
  27403. return value;
  27404. };
  27405. // Internal: Updates a traversed object member.
  27406. var update = function(source, property, callback) {
  27407. var element = walk(source, property, callback);
  27408. if (element === undef) {
  27409. delete source[property];
  27410. } else {
  27411. source[property] = element;
  27412. }
  27413. };
  27414. // Internal: Recursively traverses a parsed JSON object, invoking the
  27415. // `callback` function for each value. This is an implementation of the
  27416. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  27417. var walk = function (source, property, callback) {
  27418. var value = source[property], length;
  27419. if (typeof value == "object" && value) {
  27420. // `forEach` can't be used to traverse an array in Opera <= 8.54
  27421. // because its `Object#hasOwnProperty` implementation returns `false`
  27422. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  27423. if (getClass.call(value) == arrayClass) {
  27424. for (length = value.length; length--;) {
  27425. update(value, length, callback);
  27426. }
  27427. } else {
  27428. forEach(value, function (property) {
  27429. update(value, property, callback);
  27430. });
  27431. }
  27432. }
  27433. return callback.call(source, property, value);
  27434. };
  27435. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  27436. JSON3.parse = function (source, callback) {
  27437. var result, value;
  27438. Index = 0;
  27439. Source = "" + source;
  27440. result = get(lex());
  27441. // If a JSON string contains multiple tokens, it is invalid.
  27442. if (lex() != "$") {
  27443. abort();
  27444. }
  27445. // Reset the parser state.
  27446. Index = Source = null;
  27447. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  27448. };
  27449. }
  27450. }
  27451. // Export for asynchronous module loaders.
  27452. if (isLoader) {
  27453. define(function () {
  27454. return JSON3;
  27455. });
  27456. }
  27457. }(this));
  27458. },{}],134:[function(require,module,exports){
  27459. module.exports = toArray
  27460. function toArray(list, index) {
  27461. var array = []
  27462. index = index || 0
  27463. for (var i = index || 0; i < list.length; i++) {
  27464. array[i - index] = list[i]
  27465. }
  27466. return array
  27467. }
  27468. },{}],135:[function(require,module,exports){
  27469. var MediaStreamType = {
  27470. VIDEO_TYPE: "Video",
  27471. AUDIO_TYPE: "Audio"
  27472. };
  27473. module.exports = MediaStreamType;
  27474. },{}],136:[function(require,module,exports){
  27475. var RTCEvents = {
  27476. RTC_READY: "rtc.ready",
  27477. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27478. LASTN_CHANGED: "rtc.lastn_changed",
  27479. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27480. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27481. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27482. FAKE_VIDEO_TRACK_CREATED: "rtc.fake_video_track_created"
  27483. };
  27484. module.exports = RTCEvents;
  27485. },{}],137:[function(require,module,exports){
  27486. var Resolutions = {
  27487. "1080": {
  27488. width: 1920,
  27489. height: 1080,
  27490. order: 7
  27491. },
  27492. "fullhd": {
  27493. width: 1920,
  27494. height: 1080,
  27495. order: 7
  27496. },
  27497. "720": {
  27498. width: 1280,
  27499. height: 720,
  27500. order: 6
  27501. },
  27502. "hd": {
  27503. width: 1280,
  27504. height: 720,
  27505. order: 6
  27506. },
  27507. "960": {
  27508. width: 960,
  27509. height: 720,
  27510. order: 5
  27511. },
  27512. "640": {
  27513. width: 640,
  27514. height: 480,
  27515. order: 4
  27516. },
  27517. "vga": {
  27518. width: 640,
  27519. height: 480,
  27520. order: 4
  27521. },
  27522. "360": {
  27523. width: 640,
  27524. height: 360,
  27525. order: 3
  27526. },
  27527. "320": {
  27528. width: 320,
  27529. height: 240,
  27530. order: 2
  27531. },
  27532. "180": {
  27533. width: 320,
  27534. height: 180,
  27535. order: 1
  27536. }
  27537. };
  27538. module.exports = Resolutions;
  27539. },{}],138:[function(require,module,exports){
  27540. var AuthenticationEvents = {
  27541. /**
  27542. * Event callback arguments:
  27543. * function(authenticationEnabled, userIdentity)
  27544. * authenticationEnabled - indicates whether authentication has been enabled
  27545. * in this session
  27546. * userIdentity - if user has been logged in then it contains user name. If
  27547. * contains 'null' or 'undefined' then user is not logged in.
  27548. */
  27549. IDENTITY_UPDATED: "authentication.identity_updated"
  27550. };
  27551. module.exports = AuthenticationEvents;
  27552. },{}],139:[function(require,module,exports){
  27553. var DesktopSharingEventTypes = {
  27554. /**
  27555. * An event which indicates that the jidesha extension for Firefox is
  27556. * needed to proceed with screen sharing, and that it is not installed.
  27557. */
  27558. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27559. };
  27560. module.exports = DesktopSharingEventTypes;
  27561. },{}],140:[function(require,module,exports){
  27562. module.exports = {
  27563. /**
  27564. * An event carrying connection statistics.
  27565. */
  27566. CONNECTION_STATS: "statistics.connectionstats",
  27567. /**
  27568. * FIXME: needs documentation.
  27569. */
  27570. AUDIO_LEVEL: "statistics.audioLevel",
  27571. /**
  27572. * FIXME: needs documentation.
  27573. */
  27574. STOP: "statistics.stop"
  27575. };
  27576. },{}],141:[function(require,module,exports){
  27577. var Constants = {
  27578. LOCAL_JID: 'local'
  27579. };
  27580. module.exports = Constants;
  27581. },{}],142:[function(require,module,exports){
  27582. var XMPPEvents = {
  27583. // Designates an event indicating that the connection to the XMPP server
  27584. // failed.
  27585. CONNECTION_FAILED: "xmpp.connection.failed",
  27586. // Designates an event indicating that the media (ICE) connection was
  27587. // interrupted. This should go to the RTC module.
  27588. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27589. // Designates an event indicating that the media (ICE) connection was
  27590. // restored. This should go to the RTC module.
  27591. CONNECTION_RESTORED: "xmpp.connection.restored",
  27592. // Designates an event indicating that an offer (e.g. Jingle
  27593. // session-initiate) was received.
  27594. CALL_INCOMING: "xmpp.callincoming.jingle",
  27595. // Designates an event indicating that we were kicked from the XMPP MUC.
  27596. KICKED: "xmpp.kicked",
  27597. // Designates an event indicating that the userID for a specific JID has
  27598. // changed.
  27599. // Note: currently this event fires every time we receive presence from
  27600. // someone (regardless of whether or not the "userID" changed).
  27601. USER_ID_CHANGED: "xmpp.user_id_changed",
  27602. // Designates an event indicating that we have joined the XMPP MUC.
  27603. MUC_JOINED: "xmpp.muc_joined",
  27604. // Designates an event indicating that a participant joined the XMPP MUC.
  27605. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27606. // Designates an event indicating that a participant left the XMPP MUC.
  27607. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27608. // Designates an event indicating that the MUC role of a participant has
  27609. // changed.
  27610. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27611. // Designates an event indicating that the XMPP MUC was destroyed.
  27612. MUC_DESTROYED: "xmpp.muc_destroyed",
  27613. // Designates an event indicating that the display name of a participant
  27614. // has changed.
  27615. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27616. // Designates an event indicating that we received statistics from a
  27617. // participant in the MUC.
  27618. REMOTE_STATS: "xmpp.remote_stats",
  27619. // Designates an event indicating that our role in the XMPP MUC has changed.
  27620. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27621. // Designates an event indicating that the subject of the XMPP MUC has
  27622. // changed.
  27623. SUBJECT_CHANGED: "xmpp.subject_changed",
  27624. // Designates an event indicating that an XMPP message in the MUC was
  27625. // received.
  27626. MESSAGE_RECEIVED: "xmpp.message_received",
  27627. // Designates an event indicating that we sent an XMPP message to the MUC.
  27628. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27629. // Designates an event indicating that the video type (e.g. 'camera' or
  27630. // 'screen') for a participant has changed.
  27631. // Note: currently this event fires every time we receive presence from
  27632. // someone (regardless of whether or not the "video type" changed).
  27633. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  27634. // Designates an event indicating that a participant in the XMPP MUC has
  27635. // advertised that they have audio muted (or unmuted).
  27636. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  27637. // Designates an event indicating that a participant in the XMPP MUC has
  27638. // advertised that they have video muted (or unmuted).
  27639. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  27640. // Designates an event indicating that the focus has asked us to mute our
  27641. // audio.
  27642. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27643. // Designates an event indicating that we should join the conference with
  27644. // audio and/or video muted.
  27645. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27646. // Designates an event indicating that a remote participant's available
  27647. // devices (whether he supports a audio and/or video) changed.
  27648. // Note: currently this event fires every time we receive presence from
  27649. // someone (regardless of whether or not the devices changed).
  27650. DEVICE_AVAILABLE: "xmpp.device_available",
  27651. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27652. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27653. PASSWORD_REQUIRED: "xmpp.password_required",
  27654. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27655. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27656. ETHERPAD: "xmpp.etherpad",
  27657. BRIDGE_DOWN: "xmpp.bridge_down",
  27658. PRESENCE_STATUS: "xmpp.presence_status",
  27659. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27660. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27661. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27662. // TODO: only used in a hack, should probably be removed.
  27663. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27664. // TODO: only used in a hack, should probably be removed.
  27665. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27666. // TODO: only used in a hack, should probably be removed.
  27667. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27668. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27669. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27670. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27671. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27672. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27673. // xmpp is connected and obtained user media
  27674. READY_TO_JOIN: 'xmpp.ready_to_join',
  27675. FOCUS_LEFT: "xmpp.focus_left",
  27676. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  27677. /**
  27678. * Indicates that recording state changed.
  27679. */
  27680. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  27681. /**
  27682. * Indicates that phone number changed.
  27683. */
  27684. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  27685. /**
  27686. * Indicates error while create offer call.
  27687. */
  27688. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  27689. /**
  27690. * Indicates error while create answer call.
  27691. */
  27692. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  27693. /**
  27694. * Indicates error while set local description.
  27695. */
  27696. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  27697. /**
  27698. * Indicates error while set remote description.
  27699. */
  27700. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  27701. /**
  27702. * Indicates error while adding ice candidate.
  27703. */
  27704. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  27705. };
  27706. module.exports = XMPPEvents;
  27707. },{}]},{},[7])(7)
  27708. });