Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

lib-jitsi-meet.js 1004KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. var Settings = require("./modules/settings/Settings");
  18. /**
  19. * Creates a JitsiConference object with the given name and properties.
  20. * Note: this constructor is not a part of the public API (objects should be
  21. * created using JitsiConnection.createConference).
  22. * @param options.config properties / settings related to the conference that will be created.
  23. * @param options.name the name of the conference
  24. * @param options.connection the JitsiConnection object for this JitsiConference.
  25. * @constructor
  26. */
  27. function JitsiConference(options) {
  28. if(!options.name || options.name.toLowerCase() !== options.name) {
  29. logger.error("Invalid conference name (no conference name passed or it"
  30. + "contains invalid characters like capital letters)!");
  31. return;
  32. }
  33. this.options = options;
  34. this.connection = this.options.connection;
  35. this.xmpp = this.connection.xmpp;
  36. this.eventEmitter = new EventEmitter();
  37. var confID = this.options.name + '@' + this.xmpp.options.hosts.muc;
  38. this.settings = new Settings(confID);
  39. this.room = this.xmpp.createRoom(this.options.name, this.options.config,
  40. this.settings);
  41. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  42. this.rtc = new RTC(this.room, options);
  43. this.statistics = new Statistics({
  44. callStatsID: this.options.config.callStatsID,
  45. callStatsSecret: this.options.config.callStatsSecret,
  46. disableThirdPartyRequests: this.options.config.disableThirdPartyRequests
  47. });
  48. setupListeners(this);
  49. JitsiMeetJS._gumFailedHandler.push(function(error) {
  50. this.statistics.sendGetUserMediaFailed(error);
  51. }.bind(this));
  52. this.participants = {};
  53. this.lastDominantSpeaker = null;
  54. this.dtmfManager = null;
  55. this.somebodySupportsDTMF = false;
  56. this.authEnabled = false;
  57. this.authIdentity;
  58. this.startAudioMuted = false;
  59. this.startVideoMuted = false;
  60. this.startMutedPolicy = {audio: false, video: false};
  61. this.availableDevices = {
  62. audio: undefined,
  63. video: undefined
  64. };
  65. }
  66. /**
  67. * Joins the conference.
  68. * @param password {string} the password
  69. */
  70. JitsiConference.prototype.join = function (password) {
  71. if(this.room)
  72. this.room.join(password);
  73. };
  74. /**
  75. * Check if joined to the conference.
  76. */
  77. JitsiConference.prototype.isJoined = function () {
  78. return this.room && this.room.joined;
  79. };
  80. /**
  81. * Leaves the conference.
  82. */
  83. JitsiConference.prototype.leave = function () {
  84. if(this.xmpp && this.room)
  85. this.xmpp.leaveRoom(this.room.roomjid);
  86. this.room = null;
  87. };
  88. /**
  89. * Returns name of this conference.
  90. */
  91. JitsiConference.prototype.getName = function () {
  92. return this.options.name;
  93. };
  94. /**
  95. * Check if authentication is enabled for this conference.
  96. */
  97. JitsiConference.prototype.isAuthEnabled = function () {
  98. return this.authEnabled;
  99. };
  100. /**
  101. * Check if user is logged in.
  102. */
  103. JitsiConference.prototype.isLoggedIn = function () {
  104. return !!this.authIdentity;
  105. };
  106. /**
  107. * Get authorized login.
  108. */
  109. JitsiConference.prototype.getAuthLogin = function () {
  110. return this.authIdentity;
  111. };
  112. /**
  113. * Check if external authentication is enabled for this conference.
  114. */
  115. JitsiConference.prototype.isExternalAuthEnabled = function () {
  116. return this.room && this.room.moderator.isExternalAuthEnabled();
  117. };
  118. /**
  119. * Get url for external authentication.
  120. * @param {boolean} [urlForPopup] if true then return url for login popup,
  121. * else url of login page.
  122. * @returns {Promise}
  123. */
  124. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  125. return new Promise(function (resolve, reject) {
  126. if (!this.isExternalAuthEnabled()) {
  127. reject();
  128. return;
  129. }
  130. if (urlForPopup) {
  131. this.room.moderator.getPopupLoginUrl(resolve, reject);
  132. } else {
  133. this.room.moderator.getLoginUrl(resolve, reject);
  134. }
  135. }.bind(this));
  136. };
  137. /**
  138. * Returns the local tracks.
  139. */
  140. JitsiConference.prototype.getLocalTracks = function () {
  141. if (this.rtc) {
  142. return this.rtc.localStreams;
  143. } else {
  144. return [];
  145. }
  146. };
  147. /**
  148. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  149. * in JitsiConferenceEvents.
  150. * @param eventId the event ID.
  151. * @param handler handler for the event.
  152. *
  153. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  154. */
  155. JitsiConference.prototype.on = function (eventId, handler) {
  156. if(this.eventEmitter)
  157. this.eventEmitter.on(eventId, handler);
  158. };
  159. /**
  160. * Removes event listener
  161. * @param eventId the event ID.
  162. * @param [handler] optional, the specific handler to unbind
  163. *
  164. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  165. */
  166. JitsiConference.prototype.off = function (eventId, handler) {
  167. if(this.eventEmitter)
  168. this.eventEmitter.removeListener(eventId, handler);
  169. };
  170. // Common aliases for event emitter
  171. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  172. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  173. /**
  174. * Receives notifications from another participants for commands / custom events
  175. * (send by sendPresenceCommand method).
  176. * @param command {String} the name of the command
  177. * @param handler {Function} handler for the command
  178. */
  179. JitsiConference.prototype.addCommandListener = function (command, handler) {
  180. if(this.room)
  181. this.room.addPresenceListener(command, handler);
  182. };
  183. /**
  184. * Removes command listener
  185. * @param command {String} the name of the command
  186. */
  187. JitsiConference.prototype.removeCommandListener = function (command) {
  188. if(this.room)
  189. this.room.removePresenceListener(command);
  190. };
  191. /**
  192. * Sends text message to the other participants in the conference
  193. * @param message the text message.
  194. */
  195. JitsiConference.prototype.sendTextMessage = function (message) {
  196. if(this.room)
  197. this.room.sendMessage(message);
  198. };
  199. /**
  200. * Send presence command.
  201. * @param name the name of the command.
  202. * @param values Object with keys and values that will be send.
  203. **/
  204. JitsiConference.prototype.sendCommand = function (name, values) {
  205. if(this.room) {
  206. this.room.addToPresence(name, values);
  207. this.room.sendPresence();
  208. }
  209. };
  210. /**
  211. * Send presence command one time.
  212. * @param name the name of the command.
  213. * @param values Object with keys and values that will be send.
  214. **/
  215. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  216. this.sendCommand(name, values);
  217. this.removeCommand(name);
  218. };
  219. /**
  220. * Send presence command.
  221. * @param name the name of the command.
  222. * @param values Object with keys and values that will be send.
  223. * @param persistent if false the command will be sent only one time
  224. **/
  225. JitsiConference.prototype.removeCommand = function (name) {
  226. if(this.room)
  227. this.room.removeFromPresence(name);
  228. };
  229. /**
  230. * Sets the display name for this conference.
  231. * @param name the display name to set
  232. */
  233. JitsiConference.prototype.setDisplayName = function(name) {
  234. if(this.room){
  235. // remove previously set nickname
  236. this.room.removeFromPresence("nick");
  237. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  238. this.room.sendPresence();
  239. }
  240. };
  241. /**
  242. * Set new subject for this conference. (available only for moderator)
  243. * @param {string} subject new subject
  244. */
  245. JitsiConference.prototype.setSubject = function (subject) {
  246. if (this.room && this.isModerator()) {
  247. this.room.setSubject(subject);
  248. }
  249. };
  250. /**
  251. * Adds JitsiLocalTrack object to the conference.
  252. * @param track the JitsiLocalTrack object.
  253. */
  254. JitsiConference.prototype.addTrack = function (track) {
  255. this.room.addStream(track.getOriginalStream(), function () {
  256. this.rtc.addLocalStream(track);
  257. if (track.startMuted) {
  258. track.mute();
  259. }
  260. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  261. track.stopHandler = this.removeTrack.bind(this, track);
  262. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  263. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  264. track.muteHandler);
  265. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
  266. track.stopHandler);
  267. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  268. track.audioLevelHandler);
  269. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  270. }.bind(this));
  271. };
  272. /**
  273. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  274. * @param audioLevel the audio level
  275. */
  276. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  277. this.eventEmitter.emit(
  278. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  279. this.myUserId(), audioLevel);
  280. };
  281. /**
  282. * Fires TRACK_MUTE_CHANGED change conference event.
  283. * @param track the JitsiTrack object related to the event.
  284. */
  285. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  286. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  287. };
  288. /**
  289. * Removes JitsiLocalTrack object to the conference.
  290. * @param track the JitsiLocalTrack object.
  291. */
  292. JitsiConference.prototype.removeTrack = function (track) {
  293. if(!this.room){
  294. if(this.rtc)
  295. this.rtc.removeLocalStream(track);
  296. return;
  297. }
  298. this.room.removeStream(track.getOriginalStream(), function(){
  299. this.rtc.removeLocalStream(track);
  300. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  301. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  302. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  303. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  304. }.bind(this));
  305. };
  306. /**
  307. * Get role of the local user.
  308. * @returns {string} user role: 'moderator' or 'none'
  309. */
  310. JitsiConference.prototype.getRole = function () {
  311. return this.room.role;
  312. };
  313. /**
  314. * Check if local user is moderator.
  315. * @returns {boolean} true if local user is moderator, false otherwise.
  316. */
  317. JitsiConference.prototype.isModerator = function () {
  318. return this.room.isModerator();
  319. };
  320. /**
  321. * Set password for the room.
  322. * @param {string} password new password for the room.
  323. * @returns {Promise}
  324. */
  325. JitsiConference.prototype.lock = function (password) {
  326. if (!this.isModerator()) {
  327. return Promise.reject();
  328. }
  329. var conference = this;
  330. return new Promise(function (resolve, reject) {
  331. conference.room.lockRoom(password || "", function () {
  332. resolve();
  333. }, function (err) {
  334. reject(err);
  335. }, function () {
  336. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  337. });
  338. });
  339. };
  340. /**
  341. * Remove password from the room.
  342. * @returns {Promise}
  343. */
  344. JitsiConference.prototype.unlock = function () {
  345. return this.lock();
  346. };
  347. /**
  348. * Elects the participant with the given id to be the selected participant or the speaker.
  349. * @param id the identifier of the participant
  350. */
  351. JitsiConference.prototype.selectParticipant = function(participantId) {
  352. if (this.rtc) {
  353. this.rtc.selectedEndpoint(participantId);
  354. }
  355. };
  356. /**
  357. *
  358. * @param id the identifier of the participant
  359. */
  360. JitsiConference.prototype.pinParticipant = function(participantId) {
  361. if (this.rtc) {
  362. this.rtc.pinEndpoint(participantId);
  363. }
  364. };
  365. /**
  366. * Returns the list of participants for this conference.
  367. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  368. */
  369. JitsiConference.prototype.getParticipants = function() {
  370. return Object.keys(this.participants).map(function (key) {
  371. return this.participants[key];
  372. }, this);
  373. };
  374. /**
  375. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  376. * undefined if there isn't one).
  377. * @param id the id of the participant.
  378. */
  379. JitsiConference.prototype.getParticipantById = function(id) {
  380. return this.participants[id];
  381. };
  382. /**
  383. * Kick participant from this conference.
  384. * @param {string} id id of the participant to kick
  385. */
  386. JitsiConference.prototype.kickParticipant = function (id) {
  387. var participant = this.getParticipantById(id);
  388. if (!participant) {
  389. return;
  390. }
  391. this.room.kick(participant.getJid());
  392. };
  393. /**
  394. * Kick participant from this conference.
  395. * @param {string} id id of the participant to kick
  396. */
  397. JitsiConference.prototype.muteParticipant = function (id) {
  398. var participant = this.getParticipantById(id);
  399. if (!participant) {
  400. return;
  401. }
  402. this.room.muteParticipant(participant.getJid(), true);
  403. };
  404. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  405. var id = Strophe.getResourceFromJid(jid);
  406. if (id === 'focus' || this.myUserId() === id) {
  407. return;
  408. }
  409. var participant = new JitsiParticipant(jid, this, nick);
  410. participant._role = role;
  411. this.participants[id] = participant;
  412. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  413. this.xmpp.connection.disco.info(
  414. jid, "node", function(iq) {
  415. participant._supportsDTMF = $(iq).find(
  416. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  417. this.updateDTMFSupport();
  418. }.bind(this)
  419. );
  420. };
  421. JitsiConference.prototype.onMemberLeft = function (jid) {
  422. var id = Strophe.getResourceFromJid(jid);
  423. if (id === 'focus' || this.myUserId() === id) {
  424. return;
  425. }
  426. var participant = this.participants[id];
  427. delete this.participants[id];
  428. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  429. };
  430. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  431. var id = Strophe.getResourceFromJid(jid);
  432. var participant = this.getParticipantById(id);
  433. if (!participant) {
  434. return;
  435. }
  436. participant._role = role;
  437. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  438. };
  439. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  440. var id = Strophe.getResourceFromJid(jid);
  441. var participant = this.getParticipantById(id);
  442. if (!participant) {
  443. return;
  444. }
  445. participant._displayName = displayName;
  446. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  447. };
  448. JitsiConference.prototype.onTrackAdded = function (track) {
  449. var id = track.getParticipantId();
  450. var participant = this.getParticipantById(id);
  451. if (!participant) {
  452. return;
  453. }
  454. // add track to JitsiParticipant
  455. participant._tracks.push(track);
  456. var emitter = this.eventEmitter;
  457. track.addEventListener(
  458. JitsiTrackEvents.TRACK_STOPPED,
  459. function () {
  460. // remove track from JitsiParticipant
  461. var pos = participant._tracks.indexOf(track);
  462. if (pos > -1) {
  463. participant._tracks.splice(pos, 1);
  464. }
  465. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  466. }
  467. );
  468. track.addEventListener(
  469. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  470. function () {
  471. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  472. }
  473. );
  474. track.addEventListener(
  475. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  476. function (audioLevel) {
  477. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  478. }
  479. );
  480. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  481. };
  482. JitsiConference.prototype.updateDTMFSupport = function () {
  483. var somebodySupportsDTMF = false;
  484. var participants = this.getParticipants();
  485. // check if at least 1 participant supports DTMF
  486. for (var i = 0; i < participants.length; i += 1) {
  487. if (participants[i].supportsDTMF()) {
  488. somebodySupportsDTMF = true;
  489. break;
  490. }
  491. }
  492. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  493. this.somebodySupportsDTMF = somebodySupportsDTMF;
  494. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  495. }
  496. };
  497. /**
  498. * Allows to check if there is at least one user in the conference
  499. * that supports DTMF.
  500. * @returns {boolean} true if somebody supports DTMF, false otherwise
  501. */
  502. JitsiConference.prototype.isDTMFSupported = function () {
  503. return this.somebodySupportsDTMF;
  504. };
  505. /**
  506. * Returns the local user's ID
  507. * @return {string} local user's ID
  508. */
  509. JitsiConference.prototype.myUserId = function () {
  510. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  511. };
  512. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  513. if (!this.dtmfManager) {
  514. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  515. if (!connection) {
  516. logger.warn("cannot sendTones: no conneciton");
  517. return;
  518. }
  519. var tracks = this.getLocalTracks().filter(function (track) {
  520. return track.isAudioTrack();
  521. });
  522. if (!tracks.length) {
  523. logger.warn("cannot sendTones: no local audio stream");
  524. return;
  525. }
  526. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  527. }
  528. this.dtmfManager.sendTones(tones, duration, pause);
  529. };
  530. /**
  531. * Returns true if the recording is supproted and false if not.
  532. */
  533. JitsiConference.prototype.isRecordingSupported = function () {
  534. if(this.room)
  535. return this.room.isRecordingSupported();
  536. return false;
  537. };
  538. /**
  539. * Returns null if the recording is not supported, "on" if the recording started
  540. * and "off" if the recording is not started.
  541. */
  542. JitsiConference.prototype.getRecordingState = function () {
  543. if(this.room)
  544. return this.room.getRecordingState();
  545. return "off";
  546. }
  547. /**
  548. * Returns the url of the recorded video.
  549. */
  550. JitsiConference.prototype.getRecordingURL = function () {
  551. if(this.room)
  552. return this.room.getRecordingURL();
  553. return null;
  554. }
  555. /**
  556. * Starts/stops the recording
  557. */
  558. JitsiConference.prototype.toggleRecording = function (options) {
  559. if(this.room)
  560. return this.room.toggleRecording(options, function (status, error) {
  561. this.eventEmitter.emit(
  562. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  563. }.bind(this));
  564. this.eventEmitter.emit(
  565. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  566. new Error("The conference is not created yet!"));
  567. }
  568. /**
  569. * Returns true if the SIP calls are supported and false otherwise
  570. */
  571. JitsiConference.prototype.isSIPCallingSupported = function () {
  572. if(this.room)
  573. return this.room.isSIPCallingSupported();
  574. return false;
  575. }
  576. /**
  577. * Dials a number.
  578. * @param number the number
  579. */
  580. JitsiConference.prototype.dial = function (number) {
  581. if(this.room)
  582. return this.room.dial(number);
  583. return new Promise(function(resolve, reject){
  584. reject(new Error("The conference is not created yet!"))});
  585. }
  586. /**
  587. * Hangup an existing call
  588. */
  589. JitsiConference.prototype.hangup = function () {
  590. if(this.room)
  591. return this.room.hangup();
  592. return new Promise(function(resolve, reject){
  593. reject(new Error("The conference is not created yet!"))});
  594. }
  595. /**
  596. * Returns the phone number for joining the conference.
  597. */
  598. JitsiConference.prototype.getPhoneNumber = function () {
  599. if(this.room)
  600. return this.room.getPhoneNumber();
  601. return null;
  602. }
  603. /**
  604. * Returns the pin for joining the conference with phone.
  605. */
  606. JitsiConference.prototype.getPhonePin = function () {
  607. if(this.room)
  608. return this.room.getPhonePin();
  609. return null;
  610. }
  611. /**
  612. * Returns the connection state for the current room. Its ice connection state
  613. * for its session.
  614. */
  615. JitsiConference.prototype.getConnectionState = function () {
  616. if(this.room)
  617. return this.room.getConnectionState();
  618. return null;
  619. }
  620. /**
  621. * Make all new participants mute their audio/video on join.
  622. * @param policy {Object} object with 2 boolean properties for video and audio:
  623. * @param {boolean} audio if audio should be muted.
  624. * @param {boolean} video if video should be muted.
  625. */
  626. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  627. if (!this.isModerator()) {
  628. return;
  629. }
  630. this.startMutedPolicy = policy;
  631. this.room.removeFromPresence("startmuted");
  632. this.room.addToPresence("startmuted", {
  633. attributes: {
  634. audio: policy.audio,
  635. video: policy.video,
  636. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  637. }
  638. });
  639. this.room.sendPresence();
  640. };
  641. /**
  642. * Returns current start muted policy
  643. * @returns {Object} with 2 proprties - audio and video.
  644. */
  645. JitsiConference.prototype.getStartMutedPolicy = function () {
  646. return this.startMutedPolicy;
  647. };
  648. /**
  649. * Check if audio is muted on join.
  650. */
  651. JitsiConference.prototype.isStartAudioMuted = function () {
  652. return this.startAudioMuted;
  653. };
  654. /**
  655. * Check if video is muted on join.
  656. */
  657. JitsiConference.prototype.isStartVideoMuted = function () {
  658. return this.startVideoMuted;
  659. };
  660. /**
  661. * Get object with internal logs.
  662. */
  663. JitsiConference.prototype.getLogs = function () {
  664. var data = this.xmpp.getJingleLog();
  665. var metadata = {};
  666. metadata.time = new Date();
  667. metadata.url = window.location.href;
  668. metadata.ua = navigator.userAgent;
  669. var log = this.xmpp.getXmppLog();
  670. if (log) {
  671. metadata.xmpp = log;
  672. }
  673. data.metadata = metadata;
  674. return data;
  675. };
  676. /**
  677. * Sends the given feedback through CallStats if enabled.
  678. *
  679. * @param overallFeedback an integer between 1 and 5 indicating the
  680. * user feedback
  681. * @param detailedFeedback detailed feedback from the user. Not yet used
  682. */
  683. JitsiConference.prototype.sendFeedback =
  684. function(overallFeedback, detailedFeedback){
  685. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  686. }
  687. /**
  688. * Returns true if the callstats integration is enabled, otherwise returns
  689. * false.
  690. *
  691. * @returns true if the callstats integration is enabled, otherwise returns
  692. * false.
  693. */
  694. JitsiConference.prototype.isCallstatsEnabled = function () {
  695. return this.statistics.isCallstatsEnabled();
  696. }
  697. /**
  698. * Setups the listeners needed for the conference.
  699. * @param conference the conference
  700. */
  701. function setupListeners(conference) {
  702. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  703. conference.rtc.onIncommingCall(event);
  704. conference.statistics.startRemoteStats(event.peerconnection);
  705. });
  706. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  707. function (data, sid, thessrc) {
  708. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  709. if (track) {
  710. conference.onTrackAdded(track);
  711. }
  712. }
  713. );
  714. conference.rtc.addListener(RTCEvents.FAKE_VIDEO_TRACK_CREATED,
  715. function (track) {
  716. conference.onTrackAdded(track);
  717. }
  718. );
  719. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  720. function (value) {
  721. conference.rtc.setAudioMute(value);
  722. }
  723. );
  724. conference.room.addListener(XMPPEvents.SUBJECT_CHANGED, function (subject) {
  725. conference.eventEmitter.emit(JitsiConferenceEvents.SUBJECT_CHANGED, subject);
  726. });
  727. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  728. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  729. });
  730. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  731. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  732. });
  733. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  734. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  735. });
  736. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  737. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  738. });
  739. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  740. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  741. });
  742. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  743. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  744. });
  745. conference.room.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  746. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.RESERVATION_ERROR, code, msg);
  747. });
  748. conference.room.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  749. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.GRACEFUL_SHUTDOWN);
  750. });
  751. conference.room.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function () {
  752. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.JINGLE_FATAL_ERROR);
  753. });
  754. conference.room.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  755. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_DESTROYED, reason);
  756. });
  757. conference.room.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, function (err, msg) {
  758. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_ERROR, JitsiConferenceErrors.CHAT_ERROR, err, msg);
  759. });
  760. conference.room.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focus, retrySec) {
  761. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.FOCUS_DISCONNECTED, focus, retrySec);
  762. });
  763. // FIXME
  764. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  765. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  766. // });
  767. conference.room.addListener(XMPPEvents.KICKED, function () {
  768. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  769. });
  770. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  771. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  772. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  773. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  774. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  775. });
  776. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  777. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  778. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  779. });
  780. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  781. function () {
  782. conference.eventEmitter.emit(
  783. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  784. });
  785. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  786. conference.eventEmitter.emit(
  787. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  788. });
  789. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  790. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  791. });
  792. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  793. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  794. });
  795. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  796. conference.authEnabled = authEnabled;
  797. conference.authIdentity = authIdentity;
  798. });
  799. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  800. var id = Strophe.getResourceFromJid(jid);
  801. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  802. });
  803. conference.room.addListener(XMPPEvents.PRESENCE_STATUS, function (jid, status) {
  804. var id = Strophe.getResourceFromJid(jid);
  805. var participant = conference.getParticipantById(id);
  806. if (!participant || participant._status === status) {
  807. return;
  808. }
  809. participant._status = status;
  810. conference.eventEmitter.emit(JitsiConferenceEvents.USER_STATUS_CHANGED, id, status);
  811. });
  812. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  813. if(conference.lastDominantSpeaker !== id && conference.room) {
  814. conference.lastDominantSpeaker = id;
  815. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  816. }
  817. });
  818. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  819. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  820. });
  821. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  822. function (lastNEndpoints, endpointsEnteringLastN) {
  823. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  824. lastNEndpoints, endpointsEnteringLastN);
  825. });
  826. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  827. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  828. });
  829. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  830. function (audioMuted, videoMuted) {
  831. conference.startAudioMuted = audioMuted;
  832. conference.startVideoMuted = videoMuted;
  833. // mute existing local tracks because this is initial mute from
  834. // Jicofo
  835. conference.getLocalTracks().forEach(function (track) {
  836. if (conference.startAudioMuted && track.isAudioTrack()) {
  837. track.mute();
  838. }
  839. if (conference.startVideoMuted && track.isVideoTrack()) {
  840. track.mute();
  841. }
  842. });
  843. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  844. });
  845. conference.room.addPresenceListener("startmuted", function (data, from) {
  846. var isModerator = false;
  847. if (conference.myUserId() === from && conference.isModerator()) {
  848. isModerator = true;
  849. } else {
  850. var participant = conference.getParticipantById(from);
  851. if (participant && participant.isModerator()) {
  852. isModerator = true;
  853. }
  854. }
  855. if (!isModerator) {
  856. return;
  857. }
  858. var startAudioMuted = data.attributes.audio === 'true';
  859. var startVideoMuted = data.attributes.video === 'true';
  860. var updated = false;
  861. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  862. conference.startMutedPolicy.audio = startAudioMuted;
  863. updated = true;
  864. }
  865. if (startVideoMuted !== conference.startMutedPolicy.video) {
  866. conference.startMutedPolicy.video = startVideoMuted;
  867. updated = true;
  868. }
  869. if (updated) {
  870. conference.eventEmitter.emit(
  871. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  872. conference.startMutedPolicy
  873. );
  874. }
  875. });
  876. conference.rtc.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  877. conference.room.updateDeviceAvailability(devices);
  878. });
  879. conference.room.addPresenceListener("devices", function (data, from) {
  880. var isAudioAvailable = false;
  881. var isVideoAvailable = false;
  882. data.children.forEach(function (config) {
  883. if (config.tagName === 'audio') {
  884. isAudioAvailable = config.value === 'true';
  885. }
  886. if (config.tagName === 'video') {
  887. isVideoAvailable = config.value === 'true';
  888. }
  889. });
  890. var availableDevices;
  891. if (conference.myUserId() === from) {
  892. availableDevices = conference.availableDevices;
  893. } else {
  894. var participant = conference.getParticipantById(from);
  895. if (!participant) {
  896. return;
  897. }
  898. availableDevices = participant._availableDevices;
  899. }
  900. var updated = false;
  901. if (availableDevices.audio !== isAudioAvailable) {
  902. updated = true;
  903. availableDevices.audio = isAudioAvailable;
  904. }
  905. if (availableDevices.video !== isVideoAvailable) {
  906. updated = true;
  907. availableDevices.video = isVideoAvailable;
  908. }
  909. if (updated) {
  910. conference.eventEmitter.emit(JitsiConferenceEvents.AVAILABLE_DEVICES_CHANGED, from, availableDevices);
  911. }
  912. });
  913. if(conference.statistics) {
  914. //FIXME: Maybe remove event should not be associated with the conference.
  915. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  916. var userId = null;
  917. var jid = conference.room.getJidBySSRC(ssrc);
  918. if (!jid)
  919. return;
  920. conference.rtc.setAudioLevel(jid, level);
  921. });
  922. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  923. function () {
  924. conference.statistics.dispose();
  925. });
  926. conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
  927. function (session) {
  928. conference.statistics.startCallStats(
  929. session, conference.settings);
  930. });
  931. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
  932. function () {
  933. conference.statistics.sendSetupFailedEvent();
  934. });
  935. conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  936. function (track) {
  937. if(!track.isLocal())
  938. return;
  939. var type = (track.getType() === "audio")? "audio" : "video";
  940. conference.statistics.sendMuteEvent(track.isMuted(), type);
  941. });
  942. conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
  943. conference.statistics.sendCreateOfferFailed(e, pc);
  944. });
  945. conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
  946. conference.statistics.sendCreateAnswerFailed(e, pc);
  947. });
  948. conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  949. function (e, pc) {
  950. conference.statistics.sendSetLocalDescFailed(e, pc);
  951. }
  952. );
  953. conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  954. function (e, pc) {
  955. conference.statistics.sendSetRemoteDescFailed(e, pc);
  956. }
  957. );
  958. conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  959. function (e, pc) {
  960. conference.statistics.sendAddIceCandidateFailed(e, pc);
  961. }
  962. );
  963. }
  964. }
  965. module.exports = JitsiConference;
  966. }).call(this,"/JitsiConference.js")
  967. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":137,"./service/authentication/AuthenticationEvents":139,"./service/xmpp/XMPPEvents":143,"events":46,"jitsi-meet-logger":50}],2:[function(require,module,exports){
  968. /**
  969. * Enumeration with the errors for the conference.
  970. * @type {{string: string}}
  971. */
  972. var JitsiConferenceErrors = {
  973. /**
  974. * Indicates that a password is required in order to join the conference.
  975. */
  976. PASSWORD_REQUIRED: "conference.passwordRequired",
  977. /**
  978. * Indicates that client must be authenticated to create the conference.
  979. */
  980. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  981. /**
  982. * Indicates that password cannot be set for this conference.
  983. */
  984. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  985. /**
  986. * Indicates that a connection error occurred when trying to join a
  987. * conference.
  988. */
  989. CONNECTION_ERROR: "conference.connectionError",
  990. /**
  991. * Indicates that the conference setup failed.
  992. */
  993. SETUP_FAILED: "conference.setup_failed",
  994. /**
  995. * Indicates that there is no available videobridge.
  996. */
  997. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable",
  998. /**
  999. * Indicates that reservation system returned error.
  1000. */
  1001. RESERVATION_ERROR: "conference.reservationError",
  1002. /**
  1003. * Indicates that graceful shutdown happened.
  1004. */
  1005. GRACEFUL_SHUTDOWN: "conference.gracefulShutdown",
  1006. /**
  1007. * Indicates that jingle fatal error happened.
  1008. */
  1009. JINGLE_FATAL_ERROR: "conference.jingleFatalError",
  1010. /**
  1011. * Indicates that conference has been destroyed.
  1012. */
  1013. CONFERENCE_DESTROYED: "conference.destroyed",
  1014. /**
  1015. * Indicates that chat error occurred.
  1016. */
  1017. CHAT_ERROR: "conference.chatError",
  1018. /**
  1019. * Indicates that focus error happened.
  1020. */
  1021. FOCUS_DISCONNECTED: "conference.focusDisconnected"
  1022. /**
  1023. * Many more errors TBD here.
  1024. */
  1025. };
  1026. module.exports = JitsiConferenceErrors;
  1027. },{}],3:[function(require,module,exports){
  1028. /**
  1029. * Enumeration with the events for the conference.
  1030. * @type {{string: string}}
  1031. */
  1032. var JitsiConferenceEvents = {
  1033. /**
  1034. * A new media track was added to the conference.
  1035. */
  1036. TRACK_ADDED: "conference.trackAdded",
  1037. /**
  1038. * The media track was removed from the conference.
  1039. */
  1040. TRACK_REMOVED: "conference.trackRemoved",
  1041. /**
  1042. * The dominant speaker was changed.
  1043. */
  1044. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  1045. /**
  1046. * A new user joinned the conference.
  1047. */
  1048. USER_JOINED: "conference.userJoined",
  1049. /**
  1050. * A user has left the conference.
  1051. */
  1052. USER_LEFT: "conference.userLeft",
  1053. /**
  1054. * User role changed.
  1055. */
  1056. USER_ROLE_CHANGED: "conference.roleChanged",
  1057. /**
  1058. * User status changed.
  1059. */
  1060. USER_STATUS_CHANGED: "conference.statusChanged",
  1061. /**
  1062. * New text message was received.
  1063. */
  1064. MESSAGE_RECEIVED: "conference.messageReceived",
  1065. /**
  1066. * A user has changed it display name
  1067. */
  1068. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  1069. /**
  1070. * Indicates that subject of the conference has changed.
  1071. */
  1072. SUBJECT_CHANGED: "conference.subjectChanged",
  1073. /**
  1074. * A participant avatar has changed.
  1075. */
  1076. AVATAR_CHANGED: "conference.avatarChanged",
  1077. /**
  1078. * New connection statistics are received.
  1079. */
  1080. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  1081. /**
  1082. * The Last N set is changed.
  1083. */
  1084. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  1085. /**
  1086. * You are included / excluded in somebody's last N set
  1087. */
  1088. IN_LAST_N_CHANGED: "conference.inLastNChanged",
  1089. /**
  1090. * A media track ( attached to the conference) mute status was changed.
  1091. */
  1092. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  1093. /**
  1094. * Audio levels of a media track ( attached to the conference) was changed.
  1095. */
  1096. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  1097. /**
  1098. * Indicates that the connection to the conference has been interrupted
  1099. * for some reason.
  1100. */
  1101. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  1102. /**
  1103. * Indicates that the connection to the conference has been restored.
  1104. */
  1105. CONNECTION_RESTORED: "conference.connectionRestored",
  1106. /**
  1107. * Indicates that conference failed.
  1108. */
  1109. CONFERENCE_FAILED: "conference.failed",
  1110. /**
  1111. * Indicates that an error occured.
  1112. */
  1113. CONFERENCE_ERROR: "conference.error",
  1114. /**
  1115. * Indicates that conference has been joined.
  1116. */
  1117. CONFERENCE_JOINED: "conference.joined",
  1118. /**
  1119. * Indicates that conference has been left.
  1120. */
  1121. CONFERENCE_LEFT: "conference.left",
  1122. /**
  1123. * You are kicked from the conference.
  1124. */
  1125. KICKED: "conferenece.kicked",
  1126. /**
  1127. * Indicates that start muted settings changed.
  1128. */
  1129. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  1130. /**
  1131. * Indicates that the local user has started muted.
  1132. */
  1133. STARTED_MUTED: "conference.started_muted",
  1134. /**
  1135. * Indicates that DTMF support changed.
  1136. */
  1137. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  1138. /**
  1139. * Indicates that recording state changed.
  1140. */
  1141. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  1142. /**
  1143. * Indicates that phone number changed.
  1144. */
  1145. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  1146. /**
  1147. * Indicates that available devices changed.
  1148. */
  1149. AVAILABLE_DEVICES_CHANGED: "conference.availableDevicesChanged"
  1150. };
  1151. module.exports = JitsiConferenceEvents;
  1152. },{}],4:[function(require,module,exports){
  1153. var JitsiConference = require("./JitsiConference");
  1154. var XMPP = require("./modules/xmpp/xmpp");
  1155. /**
  1156. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  1157. * JitsiConference interface.
  1158. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  1159. * @param token the JWT token used to authenticate with the server(optional)
  1160. * @param options Object with properties / settings related to connection with the server.
  1161. * @constructor
  1162. */
  1163. function JitsiConnection(appID, token, options) {
  1164. this.appID = appID;
  1165. this.token = token;
  1166. this.options = options;
  1167. this.xmpp = new XMPP(options);
  1168. this.conferences = {};
  1169. }
  1170. /**
  1171. * Connect the client with the server.
  1172. * @param options {object} connecting options (for example authentications parameters).
  1173. */
  1174. JitsiConnection.prototype.connect = function (options) {
  1175. if(!options)
  1176. options = {};
  1177. this.xmpp.connect(options.id, options.password);
  1178. }
  1179. /**
  1180. * Disconnect the client from the server.
  1181. */
  1182. JitsiConnection.prototype.disconnect = function () {
  1183. // XXX Forward any arguments passed to JitsiConnection.disconnect to
  1184. // XMPP.disconnect. For example, the caller of JitsiConnection.disconnect
  1185. // may optionally pass the event which triggered the disconnect in order to
  1186. // provide the implementation with finer-grained context.
  1187. var x = this.xmpp;
  1188. x.disconnect.apply(x, arguments);
  1189. }
  1190. /**
  1191. * This method allows renewal of the tokens if they are expiring.
  1192. * @param token the new token.
  1193. */
  1194. JitsiConnection.prototype.setToken = function (token) {
  1195. this.token = token;
  1196. }
  1197. /**
  1198. * Creates and joins new conference.
  1199. * @param name the name of the conference; if null - a generated name will be
  1200. * provided from the api
  1201. * @param options Object with properties / settings related to the conference
  1202. * that will be created.
  1203. * @returns {JitsiConference} returns the new conference object.
  1204. */
  1205. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1206. this.conferences[name] = new JitsiConference({name: name, config: options,
  1207. connection: this});
  1208. return this.conferences[name];
  1209. }
  1210. /**
  1211. * Subscribes the passed listener to the event.
  1212. * @param event {JitsiConnectionEvents} the connection event.
  1213. * @param listener {Function} the function that will receive the event
  1214. */
  1215. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1216. this.xmpp.addListener(event, listener);
  1217. }
  1218. /**
  1219. * Unsubscribes the passed handler.
  1220. * @param event {JitsiConnectionEvents} the connection event.
  1221. * @param listener {Function} the function that will receive the event
  1222. */
  1223. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1224. this.xmpp.removeListener(event, listener);
  1225. }
  1226. module.exports = JitsiConnection;
  1227. },{"./JitsiConference":1,"./modules/xmpp/xmpp":44}],5:[function(require,module,exports){
  1228. /**
  1229. * Enumeration with the errors for the connection.
  1230. * @type {{string: string}}
  1231. */
  1232. var JitsiConnectionErrors = {
  1233. /**
  1234. * Indicates that a password is required in order to join the conference.
  1235. */
  1236. PASSWORD_REQUIRED: "connection.passwordRequired",
  1237. /**
  1238. * Indicates that a connection error occurred when trying to join a
  1239. * conference.
  1240. */
  1241. CONNECTION_ERROR: "connection.connectionError",
  1242. /**
  1243. * Not specified errors.
  1244. */
  1245. OTHER_ERROR: "connection.otherError"
  1246. };
  1247. module.exports = JitsiConnectionErrors;
  1248. },{}],6:[function(require,module,exports){
  1249. /**
  1250. * Enumeration with the events for the connection.
  1251. * @type {{string: string}}
  1252. */
  1253. var JitsiConnnectionEvents = {
  1254. /**
  1255. * Indicates that the connection has been failed for some reason.
  1256. */
  1257. CONNECTION_FAILED: "connection.connectionFailed",
  1258. /**
  1259. * Indicates that the connection has been established.
  1260. */
  1261. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1262. /**
  1263. * Indicates that the connection has been disconnected.
  1264. */
  1265. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1266. /**
  1267. * Indicates that the perfomed action cannot be executed because the
  1268. * connection is not in the correct state(connected, disconnected, etc.)
  1269. */
  1270. WRONG_STATE: "connection.wrongState"
  1271. };
  1272. module.exports = JitsiConnnectionEvents;
  1273. },{}],7:[function(require,module,exports){
  1274. var JitsiConnection = require("./JitsiConnection");
  1275. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1276. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1277. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1278. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1279. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1280. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1281. var Logger = require("jitsi-meet-logger");
  1282. var RTC = require("./modules/RTC/RTC");
  1283. var Statistics = require("./modules/statistics/statistics");
  1284. var Resolutions = require("./service/RTC/Resolutions");
  1285. var ScriptUtil = require("./modules/util/ScriptUtil");
  1286. function getLowerResolution(resolution) {
  1287. if(!Resolutions[resolution])
  1288. return null;
  1289. var order = Resolutions[resolution].order;
  1290. var res = null;
  1291. var resName = null;
  1292. for(var i in Resolutions) {
  1293. var tmp = Resolutions[i];
  1294. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1295. resName = i;
  1296. res = tmp;
  1297. }
  1298. }
  1299. return resName;
  1300. }
  1301. /**
  1302. * Namespace for the interface of Jitsi Meet Library.
  1303. */
  1304. var LibJitsiMeet = {
  1305. JitsiConnection: JitsiConnection,
  1306. events: {
  1307. conference: JitsiConferenceEvents,
  1308. connection: JitsiConnectionEvents,
  1309. track: JitsiTrackEvents
  1310. },
  1311. errors: {
  1312. conference: JitsiConferenceErrors,
  1313. connection: JitsiConnectionErrors,
  1314. track: JitsiTrackErrors
  1315. },
  1316. logLevels: Logger.levels,
  1317. /**
  1318. * Array of functions that will receive the GUM error.
  1319. */
  1320. _gumFailedHandler: [],
  1321. init: function (options) {
  1322. Statistics.audioLevelsEnabled = !options.disableAudioLevels || true;
  1323. return RTC.init(options || {});
  1324. },
  1325. /**
  1326. * Returns whether the desktop sharing is enabled or not.
  1327. * @returns {boolean}
  1328. */
  1329. isDesktopSharingEnabled: function () {
  1330. return RTC.isDesktopSharingEnabled();
  1331. },
  1332. setLogLevel: function (level) {
  1333. Logger.setLogLevel(level);
  1334. },
  1335. /**
  1336. * Creates the media tracks and returns them trough the callback.
  1337. * @param options Object with properties / settings specifying the tracks which should be created.
  1338. * should be created or some additional configurations about resolution for example.
  1339. * @param {Array} options.devices the devices that will be requested
  1340. * @param {string} options.resolution resolution constraints
  1341. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1342. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1343. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1344. * @param {string} options.cameraDeviceId
  1345. * @param {string} options.micDeviceId
  1346. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1347. * A promise that returns an array of created JitsiTracks if resolved,
  1348. * or a JitsiConferenceError if rejected.
  1349. */
  1350. createLocalTracks: function (options) {
  1351. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1352. function(tracks) {
  1353. if(!RTC.options.disableAudioLevels)
  1354. for(var i = 0; i < tracks.length; i++) {
  1355. var track = tracks[i];
  1356. var mStream = track.getOriginalStream();
  1357. if(track.getType() === "audio"){
  1358. Statistics.startLocalStats(mStream,
  1359. track.setAudioLevel.bind(track));
  1360. track.addEventListener(
  1361. JitsiTrackEvents.TRACK_STOPPED,
  1362. function(){
  1363. Statistics.stopLocalStats(mStream);
  1364. });
  1365. }
  1366. }
  1367. return tracks;
  1368. }).catch(function (error) {
  1369. this._gumFailedHandler.forEach(function (handler) {
  1370. handler(error);
  1371. });
  1372. if(!this._gumFailedHandler.length)
  1373. Statistics.sendGetUserMediaFailed(error);
  1374. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1375. var oldResolution = options.resolution || '360';
  1376. var newResolution = getLowerResolution(oldResolution);
  1377. if(newResolution === null)
  1378. return Promise.reject(error);
  1379. options.resolution = newResolution;
  1380. return LibJitsiMeet.createLocalTracks(options);
  1381. }
  1382. return Promise.reject(error);
  1383. }.bind(this));
  1384. },
  1385. /**
  1386. * Checks if its possible to enumerate available cameras/micropones.
  1387. * @returns {boolean} true if available, false otherwise.
  1388. */
  1389. isDeviceListAvailable: function () {
  1390. return RTC.isDeviceListAvailable();
  1391. },
  1392. /**
  1393. * Returns true if changing the camera / microphone device is supported and
  1394. * false if not.
  1395. * @returns {boolean} true if available, false otherwise.
  1396. */
  1397. isDeviceChangeAvailable: function () {
  1398. return RTC.isDeviceChangeAvailable();
  1399. },
  1400. enumerateDevices: function (callback) {
  1401. RTC.enumerateDevices(callback);
  1402. },
  1403. /**
  1404. * Represents a hub/namespace for utility functionality which may be of
  1405. * interest to LibJitsiMeet clients.
  1406. */
  1407. util: {
  1408. ScriptUtil: ScriptUtil,
  1409. },
  1410. };
  1411. //Setups the promise object.
  1412. window.Promise = window.Promise || require("es6-promise").Promise;
  1413. module.exports = LibJitsiMeet;
  1414. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./modules/util/ScriptUtil":27,"./service/RTC/Resolutions":138,"es6-promise":48,"jitsi-meet-logger":50}],8:[function(require,module,exports){
  1415. /* global Strophe */
  1416. /**
  1417. * Represents a participant in (a member of) a conference.
  1418. */
  1419. function JitsiParticipant(jid, conference, displayName){
  1420. this._jid = jid;
  1421. this._id = Strophe.getResourceFromJid(jid);
  1422. this._conference = conference;
  1423. this._displayName = displayName;
  1424. this._supportsDTMF = false;
  1425. this._tracks = [];
  1426. this._role = 'none';
  1427. this._status = null;
  1428. this._availableDevices = {
  1429. audio: undefined,
  1430. video: undefined
  1431. };
  1432. }
  1433. /**
  1434. * @returns {JitsiConference} The conference that this participant belongs to.
  1435. */
  1436. JitsiParticipant.prototype.getConference = function() {
  1437. return this._conference;
  1438. };
  1439. /**
  1440. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1441. */
  1442. JitsiParticipant.prototype.getTracks = function() {
  1443. return this._tracks;
  1444. };
  1445. /**
  1446. * @returns {String} The ID of this participant.
  1447. */
  1448. JitsiParticipant.prototype.getId = function() {
  1449. return this._id;
  1450. };
  1451. /**
  1452. * @returns {String} The JID of this participant.
  1453. */
  1454. JitsiParticipant.prototype.getJid = function() {
  1455. return this._jid;
  1456. };
  1457. /**
  1458. * @returns {String} The human-readable display name of this participant.
  1459. */
  1460. JitsiParticipant.prototype.getDisplayName = function() {
  1461. return this._displayName;
  1462. };
  1463. /**
  1464. * @returns {String} The status of the participant.
  1465. */
  1466. JitsiParticipant.prototype.getStatus = function () {
  1467. return this._status;
  1468. };
  1469. /**
  1470. * @returns {Boolean} Whether this participant is a moderator or not.
  1471. */
  1472. JitsiParticipant.prototype.isModerator = function() {
  1473. return this._role === 'moderator';
  1474. };
  1475. // Gets a link to an etherpad instance advertised by the participant?
  1476. //JitsiParticipant.prototype.getEtherpad = function() {
  1477. //
  1478. //}
  1479. /*
  1480. * @returns {Boolean} Whether this participant has muted their audio.
  1481. */
  1482. JitsiParticipant.prototype.isAudioMuted = function() {
  1483. return this.getTracks().reduce(function (track, isAudioMuted) {
  1484. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1485. }, true);
  1486. };
  1487. /*
  1488. * @returns {Boolean} Whether this participant has muted their video.
  1489. */
  1490. JitsiParticipant.prototype.isVideoMuted = function() {
  1491. return this.getTracks().reduce(function (track, isVideoMuted) {
  1492. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1493. }, true);
  1494. };
  1495. /*
  1496. * @returns {???} The latest statistics reported by this participant
  1497. * (i.e. info used to populate the GSM bars)
  1498. * TODO: do we expose this or handle it internally?
  1499. */
  1500. JitsiParticipant.prototype.getLatestStats = function() {
  1501. };
  1502. /**
  1503. * @returns {String} The role of this participant.
  1504. */
  1505. JitsiParticipant.prototype.getRole = function() {
  1506. return this._role;
  1507. };
  1508. /*
  1509. * @returns {Boolean} Whether this participant is
  1510. * the conference focus (i.e. jicofo).
  1511. */
  1512. JitsiParticipant.prototype.isFocus = function() {
  1513. };
  1514. /*
  1515. * @returns {Boolean} Whether this participant is
  1516. * a conference recorder (i.e. jirecon).
  1517. */
  1518. JitsiParticipant.prototype.isRecorder = function() {
  1519. };
  1520. /*
  1521. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1522. */
  1523. JitsiParticipant.prototype.isSipGateway = function() {
  1524. };
  1525. /**
  1526. * @returns {Boolean} Whether this participant
  1527. * is currently sharing their screen.
  1528. */
  1529. JitsiParticipant.prototype.isScreenSharing = function() {
  1530. };
  1531. /**
  1532. * @returns {String} The user agent of this participant
  1533. * (i.e. browser userAgent string).
  1534. */
  1535. JitsiParticipant.prototype.getUserAgent = function() {
  1536. };
  1537. /**
  1538. * Kicks the participant from the conference (requires certain privileges).
  1539. */
  1540. JitsiParticipant.prototype.kick = function() {
  1541. };
  1542. /**
  1543. * Asks this participant to mute themselves.
  1544. */
  1545. JitsiParticipant.prototype.askToMute = function() {
  1546. };
  1547. JitsiParticipant.prototype.supportsDTMF = function () {
  1548. return this._supportsDTMF;
  1549. };
  1550. module.exports = JitsiParticipant;
  1551. },{}],9:[function(require,module,exports){
  1552. module.exports = {
  1553. /**
  1554. * Returns JitsiTrackErrors based on the error object passed by GUM
  1555. * @param error the error
  1556. * @param {Array} devices Array with the requested devices
  1557. */
  1558. parseError: function (error, devices) {
  1559. devices = devices || [];
  1560. if (typeof error == "object" && error.constraintName && error.name
  1561. && (error.name == "ConstraintNotSatisfiedError" ||
  1562. error.name == "OverconstrainedError") &&
  1563. (error.constraintName == "minWidth" ||
  1564. error.constraintName == "maxWidth" ||
  1565. error.constraintName == "minHeight" ||
  1566. error.constraintName == "maxHeight") &&
  1567. devices.indexOf("video") !== -1) {
  1568. return this.UNSUPPORTED_RESOLUTION;
  1569. } else if(typeof error === "object" && error.type === "jitsiError") {
  1570. return error.errorObject;
  1571. } else {
  1572. return this.GENERAL;
  1573. }
  1574. },
  1575. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1576. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1577. GENERAL: "gum.general"
  1578. };
  1579. },{}],10:[function(require,module,exports){
  1580. var JitsiTrackEvents = {
  1581. /**
  1582. * A media track mute status was changed.
  1583. */
  1584. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1585. /**
  1586. * Audio levels of a this track was changed.
  1587. */
  1588. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1589. /**
  1590. * The media track was removed to the conference.
  1591. */
  1592. TRACK_STOPPED: "track.stopped"
  1593. };
  1594. module.exports = JitsiTrackEvents;
  1595. },{}],11:[function(require,module,exports){
  1596. (function (__filename){
  1597. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1598. function JitsiDTMFManager (localAudio, peerConnection) {
  1599. var tracks = localAudio._getTracks();
  1600. if (!tracks.length) {
  1601. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1602. }
  1603. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1604. logger.debug("Initialized DTMFSender");
  1605. }
  1606. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1607. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1608. };
  1609. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1610. },{"jitsi-meet-logger":50}],12:[function(require,module,exports){
  1611. (function (__filename){
  1612. /* global config, APP, Strophe */
  1613. // cache datachannels to avoid garbage collection
  1614. // https://code.google.com/p/chromium/issues/detail?id=405545
  1615. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1616. var RTCEvents = require("../../service/RTC/RTCEvents");
  1617. /**
  1618. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1619. * @param peerConnection WebRTC peer connection instance.
  1620. */
  1621. function DataChannels(peerConnection, emitter) {
  1622. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1623. this.eventEmitter = emitter;
  1624. this._dataChannels = [];
  1625. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1626. // Although it's not a requirement to open separate channels from both bridge
  1627. // and peer as single channel can be used for sending and receiving data.
  1628. // So either channel opened by the bridge or the one opened here is enough
  1629. // for communication with the bridge.
  1630. /*var dataChannelOptions =
  1631. {
  1632. reliable: true
  1633. };
  1634. var dataChannel
  1635. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1636. // Can be used only when is in open state
  1637. dataChannel.onopen = function ()
  1638. {
  1639. dataChannel.send("My channel !!!");
  1640. };
  1641. dataChannel.onmessage = function (event)
  1642. {
  1643. var msgData = event.data;
  1644. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1645. };*/
  1646. };
  1647. /**
  1648. * Callback triggered by PeerConnection when new data channel is opened
  1649. * on the bridge.
  1650. * @param event the event info object.
  1651. */
  1652. DataChannels.prototype.onDataChannel = function (event) {
  1653. var dataChannel = event.channel;
  1654. var self = this;
  1655. var lastSelectedEndpoint = null;
  1656. dataChannel.onopen = function () {
  1657. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1658. // Code sample for sending string and/or binary data
  1659. // Sends String message to the bridge
  1660. //dataChannel.send("Hello bridge!");
  1661. // Sends 12 bytes binary message to the bridge
  1662. //dataChannel.send(new ArrayBuffer(12));
  1663. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1664. // when the data channel becomes available, tell the bridge about video
  1665. // selections so that it can do adaptive simulcast,
  1666. // we want the notification to trigger even if userJid is undefined,
  1667. // or null.
  1668. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1669. };
  1670. dataChannel.onerror = function (error) {
  1671. logger.error("Data Channel Error:", error, dataChannel);
  1672. };
  1673. dataChannel.onmessage = function (event) {
  1674. var data = event.data;
  1675. // JSON
  1676. var obj;
  1677. try {
  1678. obj = JSON.parse(data);
  1679. }
  1680. catch (e) {
  1681. logger.error(
  1682. "Failed to parse data channel message as JSON: ",
  1683. data,
  1684. dataChannel);
  1685. }
  1686. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1687. var colibriClass = obj.colibriClass;
  1688. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1689. // Endpoint ID from the Videobridge.
  1690. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1691. logger.info(
  1692. "Data channel new dominant speaker event: ",
  1693. dominantSpeakerEndpoint);
  1694. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1695. }
  1696. else if ("InLastNChangeEvent" === colibriClass) {
  1697. var oldValue = obj.oldValue;
  1698. var newValue = obj.newValue;
  1699. // Make sure that oldValue and newValue are of type boolean.
  1700. var type;
  1701. if ((type = typeof oldValue) !== 'boolean') {
  1702. if (type === 'string') {
  1703. oldValue = (oldValue == "true");
  1704. } else {
  1705. oldValue = new Boolean(oldValue).valueOf();
  1706. }
  1707. }
  1708. if ((type = typeof newValue) !== 'boolean') {
  1709. if (type === 'string') {
  1710. newValue = (newValue == "true");
  1711. } else {
  1712. newValue = new Boolean(newValue).valueOf();
  1713. }
  1714. }
  1715. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1716. }
  1717. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1718. // The new/latest list of last-n endpoint IDs.
  1719. var lastNEndpoints = obj.lastNEndpoints;
  1720. // The list of endpoint IDs which are entering the list of
  1721. // last-n at this time i.e. were not in the old list of last-n
  1722. // endpoint IDs.
  1723. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1724. logger.info(
  1725. "Data channel new last-n event: ",
  1726. lastNEndpoints, endpointsEnteringLastN, obj);
  1727. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1728. lastNEndpoints, endpointsEnteringLastN, obj);
  1729. }
  1730. else {
  1731. logger.debug("Data channel JSON-formatted message: ", obj);
  1732. // The received message appears to be appropriately formatted
  1733. // (i.e. is a JSON object which assigns a value to the mandatory
  1734. // property colibriClass) so don't just swallow it, expose it to
  1735. // public consumption.
  1736. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1737. }
  1738. }
  1739. };
  1740. dataChannel.onclose = function () {
  1741. logger.info("The Data Channel closed", dataChannel);
  1742. var idx = self._dataChannels.indexOf(dataChannel);
  1743. if (idx > -1)
  1744. self._dataChannels = self._dataChannels.splice(idx, 1);
  1745. };
  1746. this._dataChannels.push(dataChannel);
  1747. };
  1748. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1749. this.lastSelectedEndpoint = userResource;
  1750. this._onXXXEndpointChanged("selected", userResource);
  1751. }
  1752. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1753. this._onXXXEndpointChanged("pinnned", userResource);
  1754. }
  1755. /**
  1756. * Notifies Videobridge about a change in the value of a specific
  1757. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1758. *
  1759. * @param xxx the name of the endpoint-related property whose value changed
  1760. * @param userResource the new value of the endpoint-related property after the
  1761. * change
  1762. */
  1763. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1764. // Derive the correct words from xxx such as selected and Selected, pinned
  1765. // and Pinned.
  1766. var head = xxx.charAt(0);
  1767. var tail = xxx.substring(1);
  1768. var lower = head.toLowerCase() + tail;
  1769. var upper = head.toUpperCase() + tail;
  1770. // Notify Videobridge about the specified endpoint change.
  1771. console.log(lower + ' endpoint changed: ', userResource);
  1772. this._some(function (dataChannel) {
  1773. if (dataChannel.readyState == 'open') {
  1774. console.log(
  1775. 'sending ' + lower
  1776. + ' endpoint changed notification to the bridge: ',
  1777. userResource);
  1778. var jsonObject = {};
  1779. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1780. jsonObject[lower + "Endpoint"]
  1781. = (userResource ? userResource : null);
  1782. dataChannel.send(JSON.stringify(jsonObject));
  1783. return true;
  1784. }
  1785. });
  1786. }
  1787. DataChannels.prototype._some = function (callback, thisArg) {
  1788. var dataChannels = this._dataChannels;
  1789. if (dataChannels && dataChannels.length !== 0) {
  1790. if (thisArg)
  1791. return dataChannels.some(callback, thisArg);
  1792. else
  1793. return dataChannels.some(callback);
  1794. } else {
  1795. return false;
  1796. }
  1797. }
  1798. module.exports = DataChannels;
  1799. }).call(this,"/modules/RTC/DataChannels.js")
  1800. },{"../../service/RTC/RTCEvents":137,"jitsi-meet-logger":50}],13:[function(require,module,exports){
  1801. var JitsiTrack = require("./JitsiTrack");
  1802. var RTCBrowserType = require("./RTCBrowserType");
  1803. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1804. var RTCUtils = require("./RTCUtils");
  1805. /**
  1806. * Represents a single media track (either audio or video).
  1807. * @constructor
  1808. */
  1809. function JitsiLocalTrack(stream, videoType,
  1810. resolution, deviceId)
  1811. {
  1812. this.videoType = videoType;
  1813. this.dontFireRemoveEvent = false;
  1814. this.resolution = resolution;
  1815. this.deviceId = deviceId;
  1816. this.startMuted = false;
  1817. var self = this;
  1818. JitsiTrack.call(this, null, stream,
  1819. function () {
  1820. if(!this.dontFireRemoveEvent)
  1821. this.eventEmitter.emit(
  1822. JitsiTrackEvents.TRACK_STOPPED);
  1823. this.dontFireRemoveEvent = false;
  1824. }.bind(this));
  1825. }
  1826. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1827. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1828. /**
  1829. * Mutes / unmutes the track.
  1830. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1831. */
  1832. JitsiLocalTrack.prototype._setMute = function (mute) {
  1833. if (this.isMuted() === mute) {
  1834. return;
  1835. }
  1836. if(!this.rtc) {
  1837. this.startMuted = mute;
  1838. return;
  1839. }
  1840. var isAudio = this.type === JitsiTrack.AUDIO;
  1841. this.dontFireRemoveEvent = false;
  1842. if ((window.location.protocol != "https:") ||
  1843. (isAudio) || this.videoType === "desktop" ||
  1844. // FIXME FF does not support 'removeStream' method used to mute
  1845. RTCBrowserType.isFirefox()) {
  1846. var tracks = this._getTracks();
  1847. for (var idx = 0; idx < tracks.length; idx++) {
  1848. tracks[idx].enabled = !mute;
  1849. }
  1850. if(isAudio)
  1851. this.rtc.room.setAudioMute(mute);
  1852. else
  1853. this.rtc.room.setVideoMute(mute);
  1854. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1855. } else {
  1856. if (mute) {
  1857. this.dontFireRemoveEvent = true;
  1858. this.rtc.room.removeStream(this.stream, function () {});
  1859. RTCUtils.stopMediaStream(this.stream);
  1860. if(isAudio)
  1861. this.rtc.room.setAudioMute(mute);
  1862. else
  1863. this.rtc.room.setVideoMute(mute);
  1864. this.stream = null;
  1865. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1866. //FIXME: Maybe here we should set the SRC for the containers to something
  1867. } else {
  1868. var self = this;
  1869. var streamOptions = {
  1870. devices: (isAudio ? ["audio"] : ["video"]),
  1871. resolution: self.resolution
  1872. };
  1873. if (isAudio) {
  1874. streamOptions['micDeviceId'] = self.deviceId;
  1875. } else if(self.videoType === 'camera') {
  1876. streamOptions['cameraDeviceId'] = self.deviceId;
  1877. }
  1878. RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  1879. .then(function (streams) {
  1880. var stream = null;
  1881. for(var i = 0; i < streams.length; i++) {
  1882. stream = streams[i];
  1883. if(stream.type === self.type) {
  1884. self.stream = stream.stream;
  1885. self.videoType = stream.videoType;
  1886. break;
  1887. }
  1888. }
  1889. if(!stream)
  1890. return;
  1891. for(var i = 0; i < self.containers.length; i++)
  1892. {
  1893. RTCUtils.attachMediaStream(
  1894. self.containers[i], self.stream);
  1895. }
  1896. self.rtc.room.addStream(stream.stream,
  1897. function () {
  1898. if(isAudio)
  1899. self.rtc.room.setAudioMute(mute);
  1900. else
  1901. self.rtc.room.setVideoMute(mute);
  1902. self.eventEmitter.emit(
  1903. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1904. });
  1905. });
  1906. }
  1907. }
  1908. }
  1909. /**
  1910. * Stops sending the media track. And removes it from the HTML.
  1911. * NOTE: Works for local tracks only.
  1912. */
  1913. JitsiLocalTrack.prototype.stop = function () {
  1914. if(!this.stream)
  1915. return;
  1916. if(this.rtc)
  1917. this.rtc.room.removeStream(this.stream, function () {});
  1918. RTCUtils.stopMediaStream(this.stream);
  1919. this.detach();
  1920. }
  1921. /**
  1922. * Returns <tt>true</tt> - if the stream is muted
  1923. * and <tt>false</tt> otherwise.
  1924. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1925. * and <tt>false</tt> otherwise.
  1926. */
  1927. JitsiLocalTrack.prototype.isMuted = function () {
  1928. if (!this.stream)
  1929. return true;
  1930. var tracks = [];
  1931. var isAudio = this.type === JitsiTrack.AUDIO;
  1932. if (isAudio) {
  1933. tracks = this.stream.getAudioTracks();
  1934. } else {
  1935. if (!this.isActive())
  1936. return true;
  1937. tracks = this.stream.getVideoTracks();
  1938. }
  1939. for (var idx = 0; idx < tracks.length; idx++) {
  1940. if(tracks[idx].enabled)
  1941. return false;
  1942. }
  1943. return true;
  1944. };
  1945. /**
  1946. * Private method. Updates rtc property of the track.
  1947. * @param rtc the rtc instance.
  1948. */
  1949. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1950. this.rtc = rtc;
  1951. };
  1952. /**
  1953. * Return true;
  1954. */
  1955. JitsiLocalTrack.prototype.isLocal = function () {
  1956. return true;
  1957. }
  1958. module.exports = JitsiLocalTrack;
  1959. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1960. var JitsiTrack = require("./JitsiTrack");
  1961. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1962. /**
  1963. * Represents a single media track (either audio or video).
  1964. * @param RTC the rtc instance.
  1965. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1966. * @param sid sid for the Media Stream
  1967. * @param ssrc ssrc for the Media Stream
  1968. * @param eventEmitter the event emitter
  1969. * @constructor
  1970. */
  1971. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1972. JitsiTrack.call(this, RTC, data.stream,
  1973. function () {
  1974. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1975. }.bind(this), data.jitsiTrackType);
  1976. this.rtc = RTC;
  1977. this.sid = sid;
  1978. this.stream = data.stream;
  1979. this.peerjid = data.peerjid;
  1980. this.videoType = data.videoType;
  1981. this.ssrc = ssrc;
  1982. this.muted = false;
  1983. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1984. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1985. this.muted = true;
  1986. }
  1987. }
  1988. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1989. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1990. /**
  1991. * Sets current muted status and fires an events for the change.
  1992. * @param value the muted status.
  1993. */
  1994. JitsiRemoteTrack.prototype.setMute = function (value) {
  1995. if(this.muted === value)
  1996. return;
  1997. // we can have a fake video stream
  1998. if(this.stream)
  1999. this.stream.muted = value;
  2000. this.muted = value;
  2001. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  2002. };
  2003. /**
  2004. * Returns the current muted status of the track.
  2005. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  2006. */
  2007. JitsiRemoteTrack.prototype.isMuted = function () {
  2008. return this.muted;
  2009. };
  2010. /**
  2011. * Returns the participant id which owns the track.
  2012. * @returns {string} the id of the participants.
  2013. */
  2014. JitsiRemoteTrack.prototype.getParticipantId = function() {
  2015. return Strophe.getResourceFromJid(this.peerjid);
  2016. };
  2017. /**
  2018. * Return false;
  2019. */
  2020. JitsiRemoteTrack.prototype.isLocal = function () {
  2021. return false;
  2022. };
  2023. delete JitsiRemoteTrack.prototype.stop;
  2024. module.exports = JitsiRemoteTrack;
  2025. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  2026. var RTCBrowserType = require("./RTCBrowserType");
  2027. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  2028. var EventEmitter = require("events");
  2029. var RTC = require("./RTCUtils");
  2030. /**
  2031. * This implements 'onended' callback normally fired by WebRTC after the stream
  2032. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  2033. * @param jitsiTrack our track object holding the original WebRTC stream object
  2034. * to which 'onended' handling will be added.
  2035. */
  2036. function implementOnEndedHandling(jitsiTrack) {
  2037. var stream = jitsiTrack.getOriginalStream();
  2038. if(!stream)
  2039. return;
  2040. var originalStop = stream.stop;
  2041. stream.stop = function () {
  2042. originalStop.apply(stream);
  2043. if (jitsiTrack.isActive()) {
  2044. stream.onended();
  2045. }
  2046. };
  2047. }
  2048. /**
  2049. * Adds onended/oninactive handler to a MediaStream.
  2050. * @param mediaStream a MediaStream to attach onended/oninactive handler
  2051. * @param handler the handler
  2052. */
  2053. function addMediaStreamInactiveHandler(mediaStream, handler) {
  2054. if(RTCBrowserType.isTemasysPluginUsed()) {
  2055. // themasys
  2056. //FIXME: Seems that not working properly.
  2057. if(mediaStream.onended) {
  2058. mediaStream.onended = handler;
  2059. } else if(mediaStream.addEventListener) {
  2060. mediaStream.addEventListener('ended', function () {
  2061. handler(mediaStream);
  2062. });
  2063. } else if(mediaStream.attachEvent) {
  2064. mediaStream.attachEvent('ended', function () {
  2065. handler(mediaStream);
  2066. });
  2067. }
  2068. }
  2069. else {
  2070. if(typeof mediaStream.active !== "undefined")
  2071. mediaStream.oninactive = handler;
  2072. else
  2073. mediaStream.onended = handler;
  2074. }
  2075. }
  2076. /**
  2077. * Represents a single media track (either audio or video).
  2078. * @constructor
  2079. * @param rtc the rtc instance
  2080. * @param stream the stream
  2081. * @param streamInactiveHandler the function that will handle
  2082. * onended/oninactive events of the stream.
  2083. * @param jitsiTrackType optionally a type can be specified.
  2084. * This is the case where we are creating a dummy track with no stream
  2085. * Currently this happens when a remote side is starting with video muted
  2086. */
  2087. function JitsiTrack(rtc, stream, streamInactiveHandler, jitsiTrackType)
  2088. {
  2089. /**
  2090. * Array with the HTML elements that are displaying the streams.
  2091. * @type {Array}
  2092. */
  2093. this.containers = [];
  2094. this.rtc = rtc;
  2095. this.stream = stream;
  2096. this.eventEmitter = new EventEmitter();
  2097. this.audioLevel = -1;
  2098. this.type = jitsiTrackType || (this.stream.getVideoTracks().length > 0)?
  2099. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  2100. if(this.type == JitsiTrack.AUDIO) {
  2101. this._getTracks = function () {
  2102. return this.stream.getAudioTracks();
  2103. }.bind(this);
  2104. } else {
  2105. this._getTracks = function () {
  2106. return this.stream.getVideoTracks();
  2107. }.bind(this);
  2108. }
  2109. if (RTCBrowserType.isFirefox() && this.stream) {
  2110. implementOnEndedHandling(this);
  2111. }
  2112. if(stream)
  2113. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  2114. }
  2115. /**
  2116. * JitsiTrack video type.
  2117. * @type {string}
  2118. */
  2119. JitsiTrack.VIDEO = "video";
  2120. /**
  2121. * JitsiTrack audio type.
  2122. * @type {string}
  2123. */
  2124. JitsiTrack.AUDIO = "audio";
  2125. /**
  2126. * Returns the type (audio or video) of this track.
  2127. */
  2128. JitsiTrack.prototype.getType = function() {
  2129. return this.type;
  2130. };
  2131. /**
  2132. * Check if this is audiotrack.
  2133. */
  2134. JitsiTrack.prototype.isAudioTrack = function () {
  2135. return this.getType() === JitsiTrack.AUDIO;
  2136. };
  2137. /**
  2138. * Check if this is videotrack.
  2139. */
  2140. JitsiTrack.prototype.isVideoTrack = function () {
  2141. return this.getType() === JitsiTrack.VIDEO;
  2142. };
  2143. /**
  2144. * Returns the RTCMediaStream from the browser (?).
  2145. */
  2146. JitsiTrack.prototype.getOriginalStream = function() {
  2147. return this.stream;
  2148. }
  2149. /**
  2150. * Mutes the track.
  2151. */
  2152. JitsiTrack.prototype.mute = function () {
  2153. this._setMute(true);
  2154. }
  2155. /**
  2156. * Unmutes the stream.
  2157. */
  2158. JitsiTrack.prototype.unmute = function () {
  2159. this._setMute(false);
  2160. }
  2161. /**
  2162. * Attaches the MediaStream of this track to an HTML container (?).
  2163. * Adds the container to the list of containers that are displaying the track.
  2164. * @param container the HTML container
  2165. */
  2166. JitsiTrack.prototype.attach = function (container) {
  2167. if(this.stream)
  2168. require("./RTCUtils").attachMediaStream(container, this.stream);
  2169. this.containers.push(container);
  2170. }
  2171. /**
  2172. * Removes the track from the passed HTML container.
  2173. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  2174. */
  2175. JitsiTrack.prototype.detach = function (container) {
  2176. for(var i = 0; i < this.containers.length; i++)
  2177. {
  2178. if(this.containers[i].is(container))
  2179. {
  2180. this.containers.splice(i,1);
  2181. }
  2182. if(!container)
  2183. {
  2184. this.containers[i].find(">video").remove();
  2185. }
  2186. }
  2187. if(container)
  2188. $(container).find(">video").remove();
  2189. }
  2190. /**
  2191. * Stops sending the media track. And removes it from the HTML.
  2192. * NOTE: Works for local tracks only.
  2193. */
  2194. JitsiTrack.prototype.stop = function () {
  2195. }
  2196. /**
  2197. * Returns true if this is a video track and the source of the video is a
  2198. * screen capture as opposed to a camera.
  2199. */
  2200. JitsiTrack.prototype.isScreenSharing = function(){
  2201. }
  2202. /**
  2203. * Returns id of the track.
  2204. * @returns {string} id of the track or null if this is fake track.
  2205. */
  2206. JitsiTrack.prototype._getId = function () {
  2207. var tracks = this.stream.getTracks();
  2208. if(!tracks || tracks.length === 0)
  2209. return null;
  2210. return tracks[0].id;
  2211. };
  2212. /**
  2213. * Returns id of the track.
  2214. * @returns {string} id of the track or null if this is fake track.
  2215. */
  2216. JitsiTrack.prototype.getId = function () {
  2217. if(this.stream)
  2218. return RTC.getStreamID(this.stream);
  2219. else
  2220. return null;
  2221. };
  2222. /**
  2223. * Checks whether the MediaStream is avtive/not ended.
  2224. * When there is no check for active we don't have information and so
  2225. * will return that stream is active (in case of FF).
  2226. * @returns {boolean} whether MediaStream is active.
  2227. */
  2228. JitsiTrack.prototype.isActive = function () {
  2229. if((typeof this.stream.active !== "undefined"))
  2230. return this.stream.active;
  2231. else
  2232. return true;
  2233. };
  2234. /**
  2235. * Attaches a handler for events(For example - "audio level changed".).
  2236. * All possible event are defined in JitsiTrackEvents.
  2237. * @param eventId the event ID.
  2238. * @param handler handler for the event.
  2239. */
  2240. JitsiTrack.prototype.on = function (eventId, handler) {
  2241. if(this.eventEmitter)
  2242. this.eventEmitter.on(eventId, handler);
  2243. }
  2244. /**
  2245. * Removes event listener
  2246. * @param eventId the event ID.
  2247. * @param [handler] optional, the specific handler to unbind
  2248. */
  2249. JitsiTrack.prototype.off = function (eventId, handler) {
  2250. if(this.eventEmitter)
  2251. this.eventEmitter.removeListener(eventId, handler);
  2252. }
  2253. // Common aliases for event emitter
  2254. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2255. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2256. /**
  2257. * Sets the audio level for the stream
  2258. * @param audioLevel the new audio level
  2259. */
  2260. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2261. if(this.audioLevel !== audioLevel) {
  2262. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2263. audioLevel);
  2264. this.audioLevel = audioLevel;
  2265. }
  2266. }
  2267. module.exports = JitsiTrack;
  2268. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":46}],16:[function(require,module,exports){
  2269. /* global APP */
  2270. var EventEmitter = require("events");
  2271. var RTCBrowserType = require("./RTCBrowserType");
  2272. var RTCUtils = require("./RTCUtils.js");
  2273. var JitsiTrack = require("./JitsiTrack");
  2274. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2275. var DataChannels = require("./DataChannels");
  2276. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2277. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2278. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2279. function createLocalTracks(streams, options) {
  2280. var newStreams = []
  2281. var deviceId = null;
  2282. for (var i = 0; i < streams.length; i++) {
  2283. if (streams[i].type === 'audio') {
  2284. deviceId = options.micDeviceId;
  2285. } else if (streams[i].videoType === 'camera'){
  2286. deviceId = options.cameraDeviceId;
  2287. }
  2288. var localStream = new JitsiLocalTrack(streams[i].stream,
  2289. streams[i].videoType, streams[i].resolution, deviceId);
  2290. newStreams.push(localStream);
  2291. if (streams[i].isMuted === true)
  2292. localStream.setMute(true);
  2293. }
  2294. return newStreams;
  2295. }
  2296. function RTC(room, options) {
  2297. this.room = room;
  2298. this.localStreams = [];
  2299. //FIXME: we should start removing those streams.
  2300. //FIXME: We should support multiple streams per jid.
  2301. this.remoteStreams = {};
  2302. this.localAudio = null;
  2303. this.localVideo = null;
  2304. this.eventEmitter = new EventEmitter();
  2305. var self = this;
  2306. this.options = options || {};
  2307. room.addPresenceListener("videomuted", function (values, from) {
  2308. if(self.remoteStreams[from]) {
  2309. // If there is no video track, but we receive it is muted,
  2310. // we need to create a dummy track which we will mute, so we can
  2311. // notify interested about the muting
  2312. if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
  2313. var track = self.createRemoteStream(
  2314. {peerjid:room.roomjid + "/" + from,
  2315. videoType:"camera",
  2316. jitsiTrackType:JitsiTrack.VIDEO},
  2317. null, null);
  2318. self.eventEmitter
  2319. .emit(RTCEvents.FAKE_VIDEO_TRACK_CREATED, track);
  2320. }
  2321. self.remoteStreams[from][JitsiTrack.VIDEO]
  2322. .setMute(values.value == "true");
  2323. }
  2324. });
  2325. room.addPresenceListener("audiomuted", function (values, from) {
  2326. if(self.remoteStreams[from]) {
  2327. self.remoteStreams[from][JitsiTrack.AUDIO]
  2328. .setMute(values.value == "true");
  2329. }
  2330. });
  2331. }
  2332. /**
  2333. * Creates the local MediaStreams.
  2334. * @param {Object} [options] optional parameters
  2335. * @param {Array} options.devices the devices that will be requested
  2336. * @param {string} options.resolution resolution constraints
  2337. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2338. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2339. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2340. * @param {string} options.cameraDeviceId
  2341. * @param {string} options.micDeviceId
  2342. * @returns {*} Promise object that will receive the new JitsiTracks
  2343. */
  2344. RTC.obtainAudioAndVideoPermissions = function (options) {
  2345. return RTCUtils.obtainAudioAndVideoPermissions(options).then(function (streams) {
  2346. return createLocalTracks(streams, options);
  2347. });
  2348. }
  2349. RTC.prototype.onIncommingCall = function(event) {
  2350. if(this.options.config.openSctp)
  2351. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2352. for(var i = 0; i < this.localStreams.length; i++)
  2353. if(this.localStreams[i])
  2354. {
  2355. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2356. }
  2357. }
  2358. RTC.prototype.selectedEndpoint = function (id) {
  2359. if(this.dataChannels)
  2360. this.dataChannels.handleSelectedEndpointEvent(id);
  2361. }
  2362. RTC.prototype.pinEndpoint = function (id) {
  2363. if(this.dataChannels)
  2364. this.dataChannels.handlePinnedEndpointEvent(id);
  2365. }
  2366. RTC.prototype.addListener = function (type, listener) {
  2367. this.eventEmitter.on(type, listener);
  2368. };
  2369. RTC.prototype.removeListener = function (eventType, listener) {
  2370. this.eventEmitter.removeListener(eventType, listener);
  2371. };
  2372. RTC.addListener = function (eventType, listener) {
  2373. RTCUtils.addListener(eventType, listener);
  2374. }
  2375. RTC.removeListener = function (eventType, listener) {
  2376. RTCUtils.removeListener(eventType, listener)
  2377. }
  2378. RTC.isRTCReady = function () {
  2379. return RTCUtils.isRTCReady();
  2380. }
  2381. RTC.init = function (options) {
  2382. this.options = options || {};
  2383. return RTCUtils.init(this.options);
  2384. }
  2385. RTC.getDeviceAvailability = function () {
  2386. return RTCUtils.getDeviceAvailability();
  2387. }
  2388. RTC.prototype.addLocalStream = function (stream) {
  2389. this.localStreams.push(stream);
  2390. stream._setRTC(this);
  2391. if (stream.type == "audio") {
  2392. this.localAudio = stream;
  2393. } else {
  2394. this.localVideo = stream;
  2395. }
  2396. };
  2397. /**
  2398. * Set mute for all local audio streams attached to the conference.
  2399. * @param value the mute value
  2400. */
  2401. RTC.prototype.setAudioMute = function (value) {
  2402. for(var i = 0; i < this.localStreams.length; i++) {
  2403. var stream = this.localStreams[i];
  2404. if(stream.getType() !== "audio") {
  2405. continue;
  2406. }
  2407. stream._setMute(value);
  2408. }
  2409. }
  2410. RTC.prototype.removeLocalStream = function (track) {
  2411. var pos = this.localStreams.indexOf(track);
  2412. if (pos > -1) {
  2413. this.localStreams.splice(pos, 1);
  2414. }
  2415. };
  2416. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2417. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2418. if(!data.peerjid)
  2419. return;
  2420. var jid = Strophe.getResourceFromJid(data.peerjid);
  2421. if(!this.remoteStreams[jid]) {
  2422. this.remoteStreams[jid] = {};
  2423. }
  2424. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2425. return remoteStream;
  2426. };
  2427. RTC.getPCConstraints = function () {
  2428. return RTCUtils.pc_constraints;
  2429. };
  2430. RTC.attachMediaStream = function (elSelector, stream) {
  2431. RTCUtils.attachMediaStream(elSelector, stream);
  2432. };
  2433. RTC.getStreamID = function (stream) {
  2434. return RTCUtils.getStreamID(stream);
  2435. };
  2436. RTC.getVideoSrc = function (element) {
  2437. return RTCUtils.getVideoSrc(element);
  2438. };
  2439. /**
  2440. * Returns true if retrieving the the list of input devices is supported and
  2441. * false if not.
  2442. */
  2443. RTC.isDeviceListAvailable = function () {
  2444. return RTCUtils.isDeviceListAvailable();
  2445. };
  2446. /**
  2447. * Returns true if changing the camera / microphone device is supported and
  2448. * false if not.
  2449. */
  2450. RTC.isDeviceChangeAvailable = function () {
  2451. return RTCUtils.isDeviceChangeAvailable();
  2452. }
  2453. /**
  2454. * Allows to receive list of available cameras/microphones.
  2455. * @param {function} callback would receive array of devices as an argument
  2456. */
  2457. RTC.enumerateDevices = function (callback) {
  2458. RTCUtils.enumerateDevices(callback);
  2459. };
  2460. RTC.setVideoSrc = function (element, src) {
  2461. RTCUtils.setVideoSrc(element, src);
  2462. };
  2463. /**
  2464. * A method to handle stopping of the stream.
  2465. * One point to handle the differences in various implementations.
  2466. * @param mediaStream MediaStream object to stop.
  2467. */
  2468. RTC.stopMediaStream = function (mediaStream) {
  2469. RTCUtils.stopMediaStream(mediaStream);
  2470. };
  2471. /**
  2472. * Returns whether the desktop sharing is enabled or not.
  2473. * @returns {boolean}
  2474. */
  2475. RTC.isDesktopSharingEnabled = function () {
  2476. return RTCUtils.isDesktopSharingEnabled();
  2477. }
  2478. RTC.prototype.getVideoElementName = function () {
  2479. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2480. };
  2481. RTC.prototype.dispose = function() {
  2482. };
  2483. RTC.prototype.switchVideoStreams = function (newStream) {
  2484. this.localVideo.stream = newStream;
  2485. this.localStreams = [];
  2486. //in firefox we have only one stream object
  2487. if (this.localAudio.getOriginalStream() != newStream)
  2488. this.localStreams.push(this.localAudio);
  2489. this.localStreams.push(this.localVideo);
  2490. };
  2491. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2492. if(!jid)
  2493. return;
  2494. var resource = Strophe.getResourceFromJid(jid);
  2495. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2496. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2497. }
  2498. module.exports = RTC;
  2499. },{"../../service/RTC/MediaStreamTypes":136,"../../service/RTC/RTCEvents.js":137,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":46}],17:[function(require,module,exports){
  2500. var currentBrowser;
  2501. var browserVersion;
  2502. var isAndroid;
  2503. var RTCBrowserType = {
  2504. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2505. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2506. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2507. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2508. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2509. getBrowserType: function () {
  2510. return currentBrowser;
  2511. },
  2512. isChrome: function () {
  2513. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2514. },
  2515. isOpera: function () {
  2516. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2517. },
  2518. isFirefox: function () {
  2519. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2520. },
  2521. isIExplorer: function () {
  2522. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2523. },
  2524. isSafari: function () {
  2525. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2526. },
  2527. isTemasysPluginUsed: function () {
  2528. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2529. },
  2530. getFirefoxVersion: function () {
  2531. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2532. },
  2533. getChromeVersion: function () {
  2534. return RTCBrowserType.isChrome() ? browserVersion : null;
  2535. },
  2536. usesPlanB: function() {
  2537. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2538. RTCBrowserType.isTemasysPluginUsed();
  2539. },
  2540. usesUnifiedPlan: function() {
  2541. return RTCBrowserType.isFirefox();
  2542. },
  2543. /**
  2544. * Whether the browser is running on an android device.
  2545. */
  2546. isAndroid: function() {
  2547. return isAndroid;
  2548. }
  2549. // Add version getters for other browsers when needed
  2550. };
  2551. // detectOpera() must be called before detectChrome() !!!
  2552. // otherwise Opera wil be detected as Chrome
  2553. function detectChrome() {
  2554. if (navigator.webkitGetUserMedia) {
  2555. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2556. var userAgent = navigator.userAgent.toLowerCase();
  2557. // We can assume that user agent is chrome, because it's
  2558. // enforced when 'ext' streaming method is set
  2559. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2560. console.log("This appears to be Chrome, ver: " + ver);
  2561. return ver;
  2562. }
  2563. return null;
  2564. }
  2565. function detectOpera() {
  2566. var userAgent = navigator.userAgent;
  2567. if (userAgent.match(/Opera|OPR/)) {
  2568. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2569. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2570. console.info("This appears to be Opera, ver: " + version);
  2571. return version;
  2572. }
  2573. return null;
  2574. }
  2575. function detectFirefox() {
  2576. if (navigator.mozGetUserMedia) {
  2577. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2578. var version = parseInt(
  2579. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2580. console.log('This appears to be Firefox, ver: ' + version);
  2581. return version;
  2582. }
  2583. return null;
  2584. }
  2585. function detectSafari() {
  2586. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2587. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2588. console.info("This appears to be Safari");
  2589. // FIXME detect Safari version when needed
  2590. return 1;
  2591. }
  2592. return null;
  2593. }
  2594. function detectIE() {
  2595. var version;
  2596. var ua = window.navigator.userAgent;
  2597. var msie = ua.indexOf('MSIE ');
  2598. if (msie > 0) {
  2599. // IE 10 or older => return version number
  2600. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2601. }
  2602. var trident = ua.indexOf('Trident/');
  2603. if (!version && trident > 0) {
  2604. // IE 11 => return version number
  2605. var rv = ua.indexOf('rv:');
  2606. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2607. }
  2608. var edge = ua.indexOf('Edge/');
  2609. if (!version && edge > 0) {
  2610. // IE 12 => return version number
  2611. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2612. }
  2613. if (version) {
  2614. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2615. console.info("This appears to be IExplorer, ver: " + version);
  2616. }
  2617. return version;
  2618. }
  2619. function detectBrowser() {
  2620. var version;
  2621. var detectors = [
  2622. detectOpera,
  2623. detectChrome,
  2624. detectFirefox,
  2625. detectIE,
  2626. detectSafari
  2627. ];
  2628. // Try all browser detectors
  2629. for (var i = 0; i < detectors.length; i++) {
  2630. version = detectors[i]();
  2631. if (version)
  2632. return version;
  2633. }
  2634. console.warn("Browser type defaults to Safari ver 1");
  2635. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2636. return 1;
  2637. }
  2638. browserVersion = detectBrowser();
  2639. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2640. module.exports = RTCBrowserType;
  2641. },{}],18:[function(require,module,exports){
  2642. (function (__filename){
  2643. /* global config, require, attachMediaStream, getUserMedia,
  2644. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2645. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2646. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2647. */
  2648. /* jshint -W101 */
  2649. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2650. var RTCBrowserType = require("./RTCBrowserType");
  2651. var Resolutions = require("../../service/RTC/Resolutions");
  2652. var RTCEvents = require("../../service/RTC/RTCEvents");
  2653. var AdapterJS = require("./adapter.screenshare");
  2654. var SDPUtil = require("../xmpp/SDPUtil");
  2655. var EventEmitter = require("events");
  2656. var screenObtainer = require("./ScreenObtainer");
  2657. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2658. var eventEmitter = new EventEmitter();
  2659. var devices = {
  2660. audio: true,
  2661. video: true
  2662. };
  2663. var rtcReady = false;
  2664. function setResolutionConstraints(constraints, resolution) {
  2665. var isAndroid = RTCBrowserType.isAndroid();
  2666. if (Resolutions[resolution]) {
  2667. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2668. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2669. }
  2670. else if (isAndroid) {
  2671. // FIXME can't remember if the purpose of this was to always request
  2672. // low resolution on Android ? if yes it should be moved up front
  2673. constraints.video.mandatory.minWidth = 320;
  2674. constraints.video.mandatory.minHeight = 240;
  2675. constraints.video.mandatory.maxFrameRate = 15;
  2676. }
  2677. if (constraints.video.mandatory.minWidth)
  2678. constraints.video.mandatory.maxWidth =
  2679. constraints.video.mandatory.minWidth;
  2680. if (constraints.video.mandatory.minHeight)
  2681. constraints.video.mandatory.maxHeight =
  2682. constraints.video.mandatory.minHeight;
  2683. }
  2684. /**
  2685. * @param {string[]} um required user media types
  2686. *
  2687. * @param {Object} [options={}] optional parameters
  2688. * @param {string} options.resolution
  2689. * @param {number} options.bandwidth
  2690. * @param {number} options.fps
  2691. * @param {string} options.desktopStream
  2692. * @param {string} options.cameraDeviceId
  2693. * @param {string} options.micDeviceId
  2694. * @param {bool} firefox_fake_device
  2695. */
  2696. function getConstraints(um, options) {
  2697. var constraints = {audio: false, video: false};
  2698. if (um.indexOf('video') >= 0) {
  2699. // same behaviour as true
  2700. constraints.video = { mandatory: {}, optional: [] };
  2701. if (options.cameraDeviceId) {
  2702. constraints.video.optional.push({
  2703. sourceId: options.cameraDeviceId
  2704. });
  2705. }
  2706. constraints.video.optional.push({ googLeakyBucket: true });
  2707. setResolutionConstraints(constraints, options.resolution);
  2708. }
  2709. if (um.indexOf('audio') >= 0) {
  2710. if (!RTCBrowserType.isFirefox()) {
  2711. // same behaviour as true
  2712. constraints.audio = { mandatory: {}, optional: []};
  2713. if (options.micDeviceId) {
  2714. constraints.audio.optional.push({
  2715. sourceId: options.micDeviceId
  2716. });
  2717. }
  2718. // if it is good enough for hangouts...
  2719. constraints.audio.optional.push(
  2720. {googEchoCancellation: true},
  2721. {googAutoGainControl: true},
  2722. {googNoiseSupression: true},
  2723. {googHighpassFilter: true},
  2724. {googNoisesuppression2: true},
  2725. {googEchoCancellation2: true},
  2726. {googAutoGainControl2: true}
  2727. );
  2728. } else {
  2729. if (options.micDeviceId) {
  2730. constraints.audio = {
  2731. mandatory: {},
  2732. optional: [{
  2733. sourceId: options.micDeviceId
  2734. }]};
  2735. } else {
  2736. constraints.audio = true;
  2737. }
  2738. }
  2739. }
  2740. if (um.indexOf('screen') >= 0) {
  2741. if (RTCBrowserType.isChrome()) {
  2742. constraints.video = {
  2743. mandatory: {
  2744. chromeMediaSource: "screen",
  2745. googLeakyBucket: true,
  2746. maxWidth: window.screen.width,
  2747. maxHeight: window.screen.height,
  2748. maxFrameRate: 3
  2749. },
  2750. optional: []
  2751. };
  2752. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2753. constraints.video = {
  2754. optional: [
  2755. {
  2756. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2757. }
  2758. ]
  2759. };
  2760. } else if (RTCBrowserType.isFirefox()) {
  2761. constraints.video = {
  2762. mozMediaSource: "window",
  2763. mediaSource: "window"
  2764. };
  2765. } else {
  2766. logger.error(
  2767. "'screen' WebRTC media source is supported only in Chrome" +
  2768. " and with Temasys plugin");
  2769. }
  2770. }
  2771. if (um.indexOf('desktop') >= 0) {
  2772. constraints.video = {
  2773. mandatory: {
  2774. chromeMediaSource: "desktop",
  2775. chromeMediaSourceId: options.desktopStream,
  2776. googLeakyBucket: true,
  2777. maxWidth: window.screen.width,
  2778. maxHeight: window.screen.height,
  2779. maxFrameRate: 3
  2780. },
  2781. optional: []
  2782. };
  2783. }
  2784. if (options.bandwidth) {
  2785. if (!constraints.video) {
  2786. //same behaviour as true
  2787. constraints.video = {mandatory: {}, optional: []};
  2788. }
  2789. constraints.video.optional.push({bandwidth: options.bandwidth});
  2790. }
  2791. if (options.fps) {
  2792. // for some cameras it might be necessary to request 30fps
  2793. // so they choose 30fps mjpg over 10fps yuy2
  2794. if (!constraints.video) {
  2795. // same behaviour as true;
  2796. constraints.video = {mandatory: {}, optional: []};
  2797. }
  2798. constraints.video.mandatory.minFrameRate = options.fps;
  2799. }
  2800. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2801. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2802. // this later can be a problem with some of the tests
  2803. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2804. {
  2805. // seems to be fixed now, removing this experimental fix, as having
  2806. // multiple audio tracks brake the tests
  2807. //constraints.audio = true;
  2808. constraints.fake = true;
  2809. }
  2810. return constraints;
  2811. }
  2812. function setAvailableDevices(um, available) {
  2813. if (um.indexOf("video") != -1) {
  2814. devices.video = available;
  2815. }
  2816. if (um.indexOf("audio") != -1) {
  2817. devices.audio = available;
  2818. }
  2819. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2820. }
  2821. // In case of IE we continue from 'onReady' callback
  2822. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2823. // once it is initialized.
  2824. function onReady (options, GUM) {
  2825. rtcReady = true;
  2826. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2827. screenObtainer.init(options, GUM);
  2828. }
  2829. /**
  2830. * Apply function with arguments if function exists.
  2831. * Do nothing if function not provided.
  2832. * @param {function} [fn] function to apply
  2833. * @param {Array} [args=[]] arguments for function
  2834. */
  2835. function maybeApply(fn, args) {
  2836. if (fn) {
  2837. fn.apply(null, args || []);
  2838. }
  2839. }
  2840. var getUserMediaStatus = {
  2841. initialized: false,
  2842. callbacks: []
  2843. };
  2844. /**
  2845. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2846. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2847. * @param {Function} getUserMedia native function
  2848. * @returns {Function} wrapped function
  2849. */
  2850. function wrapGetUserMedia(getUserMedia) {
  2851. return function (constraints, successCallback, errorCallback) {
  2852. getUserMedia(constraints, function (stream) {
  2853. maybeApply(successCallback, [stream]);
  2854. if (!getUserMediaStatus.initialized) {
  2855. getUserMediaStatus.initialized = true;
  2856. getUserMediaStatus.callbacks.forEach(function (callback) {
  2857. callback();
  2858. });
  2859. getUserMediaStatus.callbacks.length = 0;
  2860. }
  2861. }, function (error) {
  2862. maybeApply(errorCallback, [error]);
  2863. });
  2864. };
  2865. }
  2866. /**
  2867. * Create stub device which equals to auto selected device.
  2868. * @param {string} kind if that should be `audio` or `video` device
  2869. * @returns {Object} stub device description in `enumerateDevices` format
  2870. */
  2871. function createAutoDeviceInfo(kind) {
  2872. return {
  2873. facing: null,
  2874. label: 'Auto',
  2875. kind: kind,
  2876. deviceId: '',
  2877. groupId: null
  2878. };
  2879. }
  2880. /**
  2881. * Execute function after getUserMedia was executed at least once.
  2882. * @param {Function} callback function to execute after getUserMedia
  2883. */
  2884. function afterUserMediaInitialized(callback) {
  2885. if (getUserMediaStatus.initialized) {
  2886. callback();
  2887. } else {
  2888. getUserMediaStatus.callbacks.push(callback);
  2889. }
  2890. }
  2891. /**
  2892. * Wrapper function which makes enumerateDevices to wait
  2893. * until someone executes getUserMedia first time.
  2894. * @param {Function} enumerateDevices native function
  2895. * @returns {Funtion} wrapped function
  2896. */
  2897. function wrapEnumerateDevices(enumerateDevices) {
  2898. return function (callback) {
  2899. // enumerate devices only after initial getUserMedia
  2900. afterUserMediaInitialized(function () {
  2901. enumerateDevices().then(function (devices) {
  2902. //add auto devices
  2903. devices.unshift(
  2904. createAutoDeviceInfo('audioinput'),
  2905. createAutoDeviceInfo('videoinput')
  2906. );
  2907. callback(devices);
  2908. }, function (err) {
  2909. console.error('cannot enumerate devices: ', err);
  2910. // return only auto devices
  2911. callback([createAutoDeviceInfo('audioInput'),
  2912. createAutoDeviceInfo('videoinput')]);
  2913. });
  2914. });
  2915. };
  2916. }
  2917. /**
  2918. * Use old MediaStreamTrack to get devices list and
  2919. * convert it to enumerateDevices format.
  2920. * @param {Function} callback function to call when received devices list.
  2921. */
  2922. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2923. MediaStreamTrack.getSources(function (sources) {
  2924. var devices = sources.map(function (source) {
  2925. var kind = (source.kind || '').toLowerCase();
  2926. return {
  2927. facing: source.facing || null,
  2928. label: source.label,
  2929. kind: kind ? kind + 'input': null,
  2930. deviceId: source.id,
  2931. groupId: source.groupId || null
  2932. };
  2933. });
  2934. //add auto devices
  2935. devices.unshift(
  2936. createAutoDeviceInfo('audioinput'),
  2937. createAutoDeviceInfo('videoinput')
  2938. );
  2939. callback(devices);
  2940. });
  2941. }
  2942. function obtainDevices(options) {
  2943. if(!options.devices || options.devices.length === 0) {
  2944. return options.successCallback(options.streams || {});
  2945. }
  2946. var device = options.devices.splice(0, 1);
  2947. var devices = [];
  2948. devices.push(device);
  2949. options.deviceGUM[device](function (stream) {
  2950. options.streams = options.streams || {};
  2951. options.streams[device] = stream;
  2952. obtainDevices(options);
  2953. },
  2954. function (error) {
  2955. Object.keys(options.streams).forEach(function(device) {
  2956. RTCUtils.stopMediaStream(options.streams[device]);
  2957. });
  2958. logger.error(
  2959. "failed to obtain " + device + " stream - stop", error);
  2960. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2961. });
  2962. }
  2963. /**
  2964. * Handles the newly created Media Streams.
  2965. * @param streams the new Media Streams
  2966. * @param resolution the resolution of the video streams
  2967. * @returns {*[]} object that describes the new streams
  2968. */
  2969. function handleLocalStream(streams, resolution) {
  2970. var audioStream, videoStream, desktopStream, res = [];
  2971. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2972. // an object with two properties: audioStream, videoStream.
  2973. if (window.webkitMediaStream) {
  2974. var audioVideo = streams.audioVideo;
  2975. if (audioVideo) {
  2976. var audioTracks = audioVideo.getAudioTracks();
  2977. if(audioTracks.length) {
  2978. audioStream = new webkitMediaStream();
  2979. for (var i = 0; i < audioTracks.length; i++) {
  2980. audioStream.addTrack(audioTracks[i]);
  2981. }
  2982. }
  2983. var videoTracks = audioVideo.getVideoTracks();
  2984. if(videoTracks.length) {
  2985. videoStream = new webkitMediaStream();
  2986. for (var j = 0; j < videoTracks.length; j++) {
  2987. videoStream.addTrack(videoTracks[j]);
  2988. }
  2989. }
  2990. }
  2991. if (streams && streams.desktopStream)
  2992. desktopStream = streams.desktopStream;
  2993. }
  2994. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2995. if (streams && streams.audio)
  2996. audioStream = streams.audio;
  2997. if (streams && streams.video)
  2998. videoStream = streams.video;
  2999. if(streams && streams.desktop)
  3000. desktopStream = streams.desktop;
  3001. }
  3002. if (desktopStream)
  3003. res.push({stream: desktopStream,
  3004. type: "video", videoType: "desktop"});
  3005. if(audioStream)
  3006. res.push({stream: audioStream, type: "audio", videoType: null});
  3007. if(videoStream)
  3008. res.push({stream: videoStream, type: "video", videoType: "camera",
  3009. resolution: resolution});
  3010. return res;
  3011. }
  3012. //Options parameter is to pass config options. Currently uses only "useIPv6".
  3013. var RTCUtils = {
  3014. init: function (options) {
  3015. return new Promise(function(resolve, reject) {
  3016. if (RTCBrowserType.isFirefox()) {
  3017. var FFversion = RTCBrowserType.getFirefoxVersion();
  3018. if (FFversion < 40) {
  3019. logger.error(
  3020. "Firefox version too old: " + FFversion +
  3021. ". Required >= 40.");
  3022. reject(new Error("Firefox version too old: " + FFversion +
  3023. ". Required >= 40."));
  3024. return;
  3025. }
  3026. this.peerconnection = mozRTCPeerConnection;
  3027. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  3028. this.enumerateDevices = wrapEnumerateDevices(
  3029. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  3030. );
  3031. this.pc_constraints = {};
  3032. this.attachMediaStream = function (element, stream) {
  3033. // srcObject is being standardized and FF will eventually
  3034. // support that unprefixed. FF also supports the
  3035. // "element.src = URL.createObjectURL(...)" combo, but that
  3036. // will be deprecated in favour of srcObject.
  3037. //
  3038. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  3039. // https://github.com/webrtc/samples/issues/302
  3040. if (!element[0])
  3041. return;
  3042. element[0].mozSrcObject = stream;
  3043. element[0].play();
  3044. };
  3045. this.getStreamID = function (stream) {
  3046. var id = stream.id;
  3047. if (!id) {
  3048. var tracks = stream.getVideoTracks();
  3049. if (!tracks || tracks.length === 0) {
  3050. tracks = stream.getAudioTracks();
  3051. }
  3052. id = tracks[0].id;
  3053. }
  3054. return SDPUtil.filter_special_chars(id);
  3055. };
  3056. this.getVideoSrc = function (element) {
  3057. if (!element)
  3058. return null;
  3059. return element.mozSrcObject;
  3060. };
  3061. this.setVideoSrc = function (element, src) {
  3062. if (element)
  3063. element.mozSrcObject = src;
  3064. };
  3065. RTCSessionDescription = mozRTCSessionDescription;
  3066. RTCIceCandidate = mozRTCIceCandidate;
  3067. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  3068. this.peerconnection = webkitRTCPeerConnection;
  3069. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3070. if (navigator.mediaDevices) {
  3071. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  3072. this.enumerateDevices = wrapEnumerateDevices(
  3073. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  3074. );
  3075. } else {
  3076. this.getUserMedia = getUserMedia;
  3077. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3078. }
  3079. this.attachMediaStream = function (element, stream) {
  3080. // saves the created url for the stream, so we can reuse it
  3081. // and not keep creating urls
  3082. if (!stream.jitsiObjectURL) {
  3083. stream.jitsiObjectURL
  3084. = webkitURL.createObjectURL(stream);
  3085. }
  3086. element.attr('src', stream.jitsiObjectURL);
  3087. };
  3088. this.getStreamID = function (stream) {
  3089. // streams from FF endpoints have the characters '{' and '}'
  3090. // that make jQuery choke.
  3091. return SDPUtil.filter_special_chars(stream.id);
  3092. };
  3093. this.getVideoSrc = function (element) {
  3094. if (!element)
  3095. return null;
  3096. return element.getAttribute("src");
  3097. };
  3098. this.setVideoSrc = function (element, src) {
  3099. if (element)
  3100. element.setAttribute("src", src);
  3101. };
  3102. // DTLS should now be enabled by default but..
  3103. this.pc_constraints = {'optional': [
  3104. {'DtlsSrtpKeyAgreement': 'true'}
  3105. ]};
  3106. if (options.useIPv6) {
  3107. // https://code.google.com/p/webrtc/issues/detail?id=2828
  3108. this.pc_constraints.optional.push({googIPv6: true});
  3109. }
  3110. if (RTCBrowserType.isAndroid()) {
  3111. this.pc_constraints = {}; // disable DTLS on Android
  3112. }
  3113. if (!webkitMediaStream.prototype.getVideoTracks) {
  3114. webkitMediaStream.prototype.getVideoTracks = function () {
  3115. return this.videoTracks;
  3116. };
  3117. }
  3118. if (!webkitMediaStream.prototype.getAudioTracks) {
  3119. webkitMediaStream.prototype.getAudioTracks = function () {
  3120. return this.audioTracks;
  3121. };
  3122. }
  3123. }
  3124. // Detect IE/Safari
  3125. else if (RTCBrowserType.isTemasysPluginUsed()) {
  3126. //AdapterJS.WebRTCPlugin.setLogLevel(
  3127. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  3128. var self = this;
  3129. AdapterJS.webRTCReady(function (isPlugin) {
  3130. self.peerconnection = RTCPeerConnection;
  3131. self.getUserMedia = window.getUserMedia;
  3132. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3133. self.attachMediaStream = function (elSel, stream) {
  3134. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  3135. return;
  3136. }
  3137. var isVideoStream = !!stream.getVideoTracks().length;
  3138. if (isVideoStream && !elSel.is(':visible')) {
  3139. throw new Error('video element must be visible to attach video stream');
  3140. }
  3141. attachMediaStream(elSel[0], stream);
  3142. };
  3143. self.getStreamID = function (stream) {
  3144. var id = SDPUtil.filter_special_chars(stream.label);
  3145. return id;
  3146. };
  3147. self.getVideoSrc = function (element) {
  3148. if (!element) {
  3149. logger.warn("Attempt to get video SRC of null element");
  3150. return null;
  3151. }
  3152. var children = element.children;
  3153. for (var i = 0; i !== children.length; ++i) {
  3154. if (children[i].name === 'streamId') {
  3155. return children[i].value;
  3156. }
  3157. }
  3158. //logger.info(element.id + " SRC: " + src);
  3159. return null;
  3160. };
  3161. self.setVideoSrc = function (element, src) {
  3162. //logger.info("Set video src: ", element, src);
  3163. if (!src) {
  3164. logger.warn("Not attaching video stream, 'src' is null");
  3165. return;
  3166. }
  3167. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3168. var stream = AdapterJS.WebRTCPlugin.plugin
  3169. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  3170. attachMediaStream(element, stream);
  3171. };
  3172. onReady(options, self.getUserMediaWithConstraints);
  3173. resolve();
  3174. });
  3175. } else {
  3176. try {
  3177. logger.error('Browser does not appear to be WebRTC-capable');
  3178. } catch (e) {
  3179. }
  3180. reject('Browser does not appear to be WebRTC-capable');
  3181. return;
  3182. }
  3183. // Call onReady() if Temasys plugin is not used
  3184. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3185. onReady(options, this.getUserMediaWithConstraints);
  3186. resolve();
  3187. }
  3188. }.bind(this));
  3189. },
  3190. /**
  3191. * @param {string[]} um required user media types
  3192. * @param {function} success_callback
  3193. * @param {Function} failure_callback
  3194. * @param {Object} [options] optional parameters
  3195. * @param {string} options.resolution
  3196. * @param {number} options.bandwidth
  3197. * @param {number} options.fps
  3198. * @param {string} options.desktopStream
  3199. * @param {string} options.cameraDeviceId
  3200. * @param {string} options.micDeviceId
  3201. **/
  3202. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3203. options = options || {};
  3204. var resolution = options.resolution;
  3205. var constraints = getConstraints(um, options);
  3206. logger.info("Get media constraints", constraints);
  3207. try {
  3208. this.getUserMedia(constraints,
  3209. function (stream) {
  3210. logger.log('onUserMediaSuccess');
  3211. setAvailableDevices(um, true);
  3212. success_callback(stream);
  3213. },
  3214. function (error) {
  3215. setAvailableDevices(um, false);
  3216. logger.warn('Failed to get access to local media. Error ',
  3217. error, constraints);
  3218. if (failure_callback) {
  3219. failure_callback(error, resolution);
  3220. }
  3221. });
  3222. } catch (e) {
  3223. logger.error('GUM failed: ', e);
  3224. if (failure_callback) {
  3225. failure_callback(e);
  3226. }
  3227. }
  3228. },
  3229. /**
  3230. * Creates the local MediaStreams.
  3231. * @param {Object} [options] optional parameters
  3232. * @param {Array} options.devices the devices that will be requested
  3233. * @param {string} options.resolution resolution constraints
  3234. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3235. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3236. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3237. * @param {string} options.cameraDeviceId
  3238. * @param {string} options.micDeviceId
  3239. * @returns {*} Promise object that will receive the new JitsiTracks
  3240. */
  3241. obtainAudioAndVideoPermissions: function (options) {
  3242. var self = this;
  3243. options = options || {};
  3244. return new Promise(function (resolve, reject) {
  3245. var successCallback = function (stream) {
  3246. resolve(handleLocalStream(stream, options.resolution));
  3247. };
  3248. options.devices = options.devices || ['audio', 'video'];
  3249. if(!screenObtainer.isSupported()
  3250. && options.devices.indexOf("desktop") !== -1){
  3251. reject(new Error("Desktop sharing is not supported!"));
  3252. }
  3253. if (RTCBrowserType.isFirefox() ||
  3254. RTCBrowserType.isTemasysPluginUsed()) {
  3255. var GUM = function (device, s, e) {
  3256. this.getUserMediaWithConstraints(device, s, e, options);
  3257. };
  3258. var deviceGUM = {
  3259. "audio": GUM.bind(self, ["audio"]),
  3260. "video": GUM.bind(self, ["video"])
  3261. };
  3262. if(screenObtainer.isSupported()){
  3263. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3264. screenObtainer);
  3265. }
  3266. // With FF/IE we can't split the stream into audio and video because FF
  3267. // doesn't support media stream constructors. So, we need to get the
  3268. // audio stream separately from the video stream using two distinct GUM
  3269. // calls. Not very user friendly :-( but we don't have many other
  3270. // options neither.
  3271. //
  3272. // Note that we pack those 2 streams in a single object and pass it to
  3273. // the successCallback method.
  3274. obtainDevices({
  3275. devices: options.devices,
  3276. streams: [],
  3277. successCallback: successCallback,
  3278. errorCallback: reject,
  3279. deviceGUM: deviceGUM
  3280. });
  3281. } else {
  3282. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3283. if (hasDesktop) {
  3284. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3285. }
  3286. options.resolution = options.resolution || '360';
  3287. if(options.devices.length) {
  3288. this.getUserMediaWithConstraints(
  3289. options.devices,
  3290. function (stream) {
  3291. if((options.devices.indexOf("audio") !== -1 &&
  3292. !stream.getAudioTracks().length) ||
  3293. (options.devices.indexOf("video") !== -1 &&
  3294. !stream.getVideoTracks().length))
  3295. {
  3296. self.stopMediaStream(stream);
  3297. reject(JitsiTrackErrors.parseError(
  3298. new Error("Unable to get the audio and " +
  3299. "video tracks."),
  3300. options.devices));
  3301. return;
  3302. }
  3303. if(hasDesktop) {
  3304. screenObtainer.obtainStream(
  3305. function (desktopStream) {
  3306. successCallback({audioVideo: stream,
  3307. desktopStream: desktopStream});
  3308. }, function (error) {
  3309. self.stopMediaStream(stream);
  3310. reject(
  3311. JitsiTrackErrors.parseError(error,
  3312. options.devices));
  3313. });
  3314. } else {
  3315. successCallback({audioVideo: stream});
  3316. }
  3317. },
  3318. function (error) {
  3319. reject(JitsiTrackErrors.parseError(error,
  3320. options.devices));
  3321. },
  3322. options);
  3323. } else if (hasDesktop) {
  3324. screenObtainer.obtainStream(
  3325. function (stream) {
  3326. successCallback({desktopStream: stream});
  3327. }, function (error) {
  3328. reject(
  3329. JitsiTrackErrors.parseError(error,
  3330. ["desktop"]));
  3331. });
  3332. }
  3333. }
  3334. }.bind(this));
  3335. },
  3336. addListener: function (eventType, listener) {
  3337. eventEmitter.on(eventType, listener);
  3338. },
  3339. removeListener: function (eventType, listener) {
  3340. eventEmitter.removeListener(eventType, listener);
  3341. },
  3342. getDeviceAvailability: function () {
  3343. return devices;
  3344. },
  3345. isRTCReady: function () {
  3346. return rtcReady;
  3347. },
  3348. /**
  3349. * Checks if its possible to enumerate available cameras/micropones.
  3350. * @returns {boolean} true if available, false otherwise.
  3351. */
  3352. isDeviceListAvailable: function () {
  3353. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3354. if (isEnumerateDevicesAvailable) {
  3355. return true;
  3356. }
  3357. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3358. },
  3359. /**
  3360. * Returns true if changing the camera / microphone device is supported and
  3361. * false if not.
  3362. */
  3363. isDeviceChangeAvailable: function () {
  3364. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3365. RTCBrowserType.isTemasysPluginUsed())
  3366. return true;
  3367. return false;
  3368. },
  3369. /**
  3370. * A method to handle stopping of the stream.
  3371. * One point to handle the differences in various implementations.
  3372. * @param mediaStream MediaStream object to stop.
  3373. */
  3374. stopMediaStream: function (mediaStream) {
  3375. mediaStream.getTracks().forEach(function (track) {
  3376. // stop() not supported with IE
  3377. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3378. track.stop();
  3379. }
  3380. });
  3381. // leave stop for implementation still using it
  3382. if (mediaStream.stop) {
  3383. mediaStream.stop();
  3384. }
  3385. // if we have done createObjectURL, lets clean it
  3386. if (mediaStream.jitsiObjectURL) {
  3387. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3388. }
  3389. },
  3390. /**
  3391. * Returns whether the desktop sharing is enabled or not.
  3392. * @returns {boolean}
  3393. */
  3394. isDesktopSharingEnabled: function () {
  3395. return screenObtainer.isSupported();
  3396. }
  3397. };
  3398. module.exports = RTCUtils;
  3399. }).call(this,"/modules/RTC/RTCUtils.js")
  3400. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":137,"../../service/RTC/Resolutions":138,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":46,"jitsi-meet-logger":50}],19:[function(require,module,exports){
  3401. (function (__filename){
  3402. /* global chrome, $, alert */
  3403. /* jshint -W003 */
  3404. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3405. var RTCBrowserType = require("./RTCBrowserType");
  3406. var AdapterJS = require("./adapter.screenshare");
  3407. var DesktopSharingEventTypes
  3408. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3409. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3410. /**
  3411. * Indicates whether the Chrome desktop sharing extension is installed.
  3412. * @type {boolean}
  3413. */
  3414. var chromeExtInstalled = false;
  3415. /**
  3416. * Indicates whether an update of the Chrome desktop sharing extension is
  3417. * required.
  3418. * @type {boolean}
  3419. */
  3420. var chromeExtUpdateRequired = false;
  3421. /**
  3422. * Whether the jidesha extension for firefox is installed for the domain on
  3423. * which we are running. Null designates an unknown value.
  3424. * @type {null}
  3425. */
  3426. var firefoxExtInstalled = null;
  3427. /**
  3428. * If set to true, detection of an installed firefox extension will be started
  3429. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3430. * user tries to enable screen sharing).
  3431. */
  3432. var reDetectFirefoxExtension = false;
  3433. var GUM = null;
  3434. /**
  3435. * Handles obtaining a stream from a screen capture on different browsers.
  3436. */
  3437. var ScreenObtainer = {
  3438. obtainStream: null,
  3439. /**
  3440. * Initializes the function used to obtain a screen capture
  3441. * (this.obtainStream).
  3442. *
  3443. * If the browser is Chrome, it uses the value of
  3444. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3445. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3446. * use the "screen" media source (if the value is 'webrtc'),
  3447. * or disable screen capture (if the value is other).
  3448. * Note that for the "screen" media source to work the
  3449. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3450. */
  3451. init: function(options, gum) {
  3452. var obtainDesktopStream = null;
  3453. this.options = options = options || {};
  3454. GUM = gum;
  3455. if (RTCBrowserType.isFirefox())
  3456. initFirefoxExtensionDetection(options);
  3457. // TODO remove this, options.desktopSharing is deprecated.
  3458. var chromeMethod =
  3459. (options.desktopSharingChromeMethod || options.desktopSharing);
  3460. if (RTCBrowserType.isTemasysPluginUsed()) {
  3461. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3462. logger.info("Screensharing not supported by this plugin " +
  3463. "version");
  3464. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3465. logger.info(
  3466. "Screensharing not available with Temasys plugin on" +
  3467. " this site");
  3468. } else {
  3469. obtainDesktopStream = obtainWebRTCScreen;
  3470. logger.info("Using Temasys plugin for desktop sharing");
  3471. }
  3472. } else if (RTCBrowserType.isChrome()) {
  3473. if (chromeMethod == "ext") {
  3474. if (RTCBrowserType.getChromeVersion() >= 34) {
  3475. obtainDesktopStream =
  3476. this.obtainScreenFromExtension;
  3477. logger.info("Using Chrome extension for desktop sharing");
  3478. initChromeExtension(options);
  3479. } else {
  3480. logger.info("Chrome extension not supported until ver 34");
  3481. }
  3482. } else if (chromeMethod == "webrtc") {
  3483. obtainDesktopStream = obtainWebRTCScreen;
  3484. logger.info("Using Chrome WebRTC for desktop sharing");
  3485. }
  3486. } else if (RTCBrowserType.isFirefox()) {
  3487. if (options.desktopSharingFirefoxDisabled) {
  3488. obtainDesktopStream = null;
  3489. } else if (window.location.protocol === "http:"){
  3490. logger.log("Screen sharing is not supported over HTTP. " +
  3491. "Use of HTTPS is required.");
  3492. obtainDesktopStream = null;
  3493. } else {
  3494. obtainDesktopStream = this.obtainScreenOnFirefox;
  3495. }
  3496. }
  3497. if (!obtainDesktopStream) {
  3498. logger.info("Desktop sharing disabled");
  3499. }
  3500. this.obtainStream = obtainDesktopStream;
  3501. },
  3502. /**
  3503. * Checks whether obtaining a screen capture is supported in the current
  3504. * environment.
  3505. * @returns {boolean}
  3506. */
  3507. isSupported: function() {
  3508. return !!this.obtainStream;
  3509. },
  3510. /**
  3511. * Obtains a screen capture stream on Firefox.
  3512. * @param callback
  3513. * @param errorCallback
  3514. */
  3515. obtainScreenOnFirefox:
  3516. function (callback, errorCallback) {
  3517. var self = this;
  3518. var extensionRequired = false;
  3519. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3520. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3521. RTCBrowserType.getFirefoxVersion() <=
  3522. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3523. extensionRequired = true;
  3524. logger.log("Jidesha extension required on firefox version " +
  3525. RTCBrowserType.getFirefoxVersion());
  3526. }
  3527. if (!extensionRequired || firefoxExtInstalled === true) {
  3528. obtainWebRTCScreen(callback, errorCallback);
  3529. return;
  3530. }
  3531. if (reDetectFirefoxExtension) {
  3532. reDetectFirefoxExtension = false;
  3533. initFirefoxExtensionDetection(this.options);
  3534. }
  3535. // Give it some (more) time to initialize, and assume lack of
  3536. // extension if it hasn't.
  3537. if (firefoxExtInstalled === null) {
  3538. window.setTimeout(
  3539. function() {
  3540. if (firefoxExtInstalled === null)
  3541. firefoxExtInstalled = false;
  3542. self.obtainScreenOnFirefox(callback, errorCallback);
  3543. },
  3544. 300
  3545. );
  3546. logger.log("Waiting for detection of jidesha on firefox to " +
  3547. "finish.");
  3548. return;
  3549. }
  3550. // We need an extension and it isn't installed.
  3551. // Make sure we check for the extension when the user clicks again.
  3552. firefoxExtInstalled = null;
  3553. reDetectFirefoxExtension = true;
  3554. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3555. // stuck in 'switching' mode.
  3556. errorCallback({
  3557. type: "jitsiError",
  3558. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3559. });
  3560. },
  3561. /**
  3562. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3563. * 'desktop' stream for returned stream token.
  3564. */
  3565. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3566. var self = this;
  3567. if (chromeExtInstalled) {
  3568. doGetStreamFromExtension(this.options, streamCallback,
  3569. failCallback);
  3570. } else {
  3571. if (chromeExtUpdateRequired) {
  3572. alert(
  3573. 'Jitsi Desktop Streamer requires update. ' +
  3574. 'Changes will take effect after next Chrome restart.');
  3575. }
  3576. chrome.webstore.install(
  3577. getWebStoreInstallUrl(this.options),
  3578. function (arg) {
  3579. logger.log("Extension installed successfully", arg);
  3580. chromeExtInstalled = true;
  3581. // We need to give a moment for the endpoint to become
  3582. // available
  3583. window.setTimeout(function () {
  3584. doGetStreamFromExtension(self.options, streamCallback,
  3585. failCallback);
  3586. }, 500);
  3587. },
  3588. function (arg) {
  3589. logger.log("Failed to install the extension", arg);
  3590. failCallback(arg);
  3591. }
  3592. );
  3593. }
  3594. }
  3595. };
  3596. /**
  3597. * Obtains a desktop stream using getUserMedia.
  3598. * For this to work on Chrome, the
  3599. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3600. *
  3601. * On firefox, the document's domain must be white-listed in the
  3602. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3603. * 'about:config'.
  3604. */
  3605. function obtainWebRTCScreen(streamCallback, failCallback) {
  3606. GUM(
  3607. ['screen'],
  3608. streamCallback,
  3609. failCallback
  3610. );
  3611. }
  3612. /**
  3613. * Constructs inline install URL for Chrome desktop streaming extension.
  3614. * The 'chromeExtensionId' must be defined in options parameter.
  3615. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3616. * @returns {string}
  3617. */
  3618. function getWebStoreInstallUrl(options)
  3619. {
  3620. //TODO remove chromeExtensionId (deprecated)
  3621. return "https://chrome.google.com/webstore/detail/" +
  3622. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3623. }
  3624. /**
  3625. * Checks whether an update of the Chrome extension is required.
  3626. * @param minVersion minimal required version
  3627. * @param extVersion current extension version
  3628. * @returns {boolean}
  3629. */
  3630. function isUpdateRequired(minVersion, extVersion) {
  3631. try {
  3632. var s1 = minVersion.split('.');
  3633. var s2 = extVersion.split('.');
  3634. var len = Math.max(s1.length, s2.length);
  3635. for (var i = 0; i < len; i++) {
  3636. var n1 = 0,
  3637. n2 = 0;
  3638. if (i < s1.length)
  3639. n1 = parseInt(s1[i]);
  3640. if (i < s2.length)
  3641. n2 = parseInt(s2[i]);
  3642. if (isNaN(n1) || isNaN(n2)) {
  3643. return true;
  3644. } else if (n1 !== n2) {
  3645. return n1 > n2;
  3646. }
  3647. }
  3648. // will happen if both versions have identical numbers in
  3649. // their components (even if one of them is longer, has more components)
  3650. return false;
  3651. }
  3652. catch (e) {
  3653. logger.error("Failed to parse extension version", e);
  3654. return true;
  3655. }
  3656. }
  3657. function checkChromeExtInstalled(callback, options) {
  3658. if (!chrome || !chrome.runtime) {
  3659. // No API, so no extension for sure
  3660. callback(false, false);
  3661. return;
  3662. }
  3663. chrome.runtime.sendMessage(
  3664. //TODO: remove chromeExtensionId (deprecated)
  3665. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3666. { getVersion: true },
  3667. function (response) {
  3668. if (!response || !response.version) {
  3669. // Communication failure - assume that no endpoint exists
  3670. logger.warn(
  3671. "Extension not installed?: ", chrome.runtime.lastError);
  3672. callback(false, false);
  3673. return;
  3674. }
  3675. // Check installed extension version
  3676. var extVersion = response.version;
  3677. logger.log('Extension version is: ' + extVersion);
  3678. //TODO: remove minChromeExtVersion (deprecated)
  3679. var updateRequired
  3680. = isUpdateRequired(
  3681. (options.desktopSharingChromeMinExtVersion ||
  3682. options.minChromeExtVersion),
  3683. extVersion);
  3684. callback(!updateRequired, updateRequired);
  3685. }
  3686. );
  3687. }
  3688. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3689. // Sends 'getStream' msg to the extension.
  3690. // Extension id must be defined in the config.
  3691. chrome.runtime.sendMessage(
  3692. //TODO: remove chromeExtensionId (deprecated)
  3693. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3694. {
  3695. getStream: true,
  3696. //TODO: remove desktopSharingSources (deprecated).
  3697. sources: (options.desktopSharingChromeSources ||
  3698. options.desktopSharingSources)
  3699. },
  3700. function (response) {
  3701. if (!response) {
  3702. failCallback(chrome.runtime.lastError);
  3703. return;
  3704. }
  3705. logger.log("Response from extension: " + response);
  3706. if (response.streamId) {
  3707. GUM(
  3708. ['desktop'],
  3709. function (stream) {
  3710. streamCallback(stream);
  3711. },
  3712. failCallback,
  3713. {desktopStream: response.streamId});
  3714. } else {
  3715. failCallback("Extension failed to get the stream");
  3716. }
  3717. }
  3718. );
  3719. }
  3720. /**
  3721. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3722. * config.js to support inline installs. Host site must be selected as main
  3723. * website of published extension.
  3724. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3725. */
  3726. function initInlineInstalls(options)
  3727. {
  3728. $("link[rel=chrome-webstore-item]").attr("href",
  3729. getWebStoreInstallUrl(options));
  3730. }
  3731. function initChromeExtension(options) {
  3732. // Initialize Chrome extension inline installs
  3733. initInlineInstalls(options);
  3734. // Check if extension is installed
  3735. checkChromeExtInstalled(function (installed, updateRequired) {
  3736. chromeExtInstalled = installed;
  3737. chromeExtUpdateRequired = updateRequired;
  3738. logger.info(
  3739. "Chrome extension installed: " + chromeExtInstalled +
  3740. " updateRequired: " + chromeExtUpdateRequired);
  3741. }, options);
  3742. }
  3743. /**
  3744. * Starts the detection of an installed jidesha extension for firefox.
  3745. * @param options supports "desktopSharingFirefoxDisabled",
  3746. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3747. */
  3748. function initFirefoxExtensionDetection(options) {
  3749. if (options.desktopSharingFirefoxDisabled) {
  3750. return;
  3751. }
  3752. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3753. return;
  3754. if (!options.desktopSharingFirefoxExtId) {
  3755. firefoxExtInstalled = false;
  3756. return;
  3757. }
  3758. var img = document.createElement('img');
  3759. img.onload = function(){
  3760. logger.log("Detected firefox screen sharing extension.");
  3761. firefoxExtInstalled = true;
  3762. };
  3763. img.onerror = function(){
  3764. logger.log("Detected lack of firefox screen sharing extension.");
  3765. firefoxExtInstalled = false;
  3766. };
  3767. // The jidesha extension exposes an empty image file under the url:
  3768. // "chrome://EXT_ID/content/DOMAIN.png"
  3769. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3770. // DOMAIN is a domain whitelisted by the extension.
  3771. var src = "chrome://" +
  3772. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3773. "/content/" + document.location.hostname + ".png";
  3774. img.setAttribute('src', src);
  3775. }
  3776. module.exports = ScreenObtainer;
  3777. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3778. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":140,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":50}],20:[function(require,module,exports){
  3779. (function (__filename){
  3780. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3781. var console = require("jitsi-meet-logger").getLogger(__filename);
  3782. // Adapter's interface.
  3783. var AdapterJS = AdapterJS || {};
  3784. // Browserify compatibility
  3785. if(typeof exports !== 'undefined') {
  3786. module.exports = AdapterJS;
  3787. }
  3788. AdapterJS.options = AdapterJS.options || {};
  3789. // uncomment to get virtual webcams
  3790. // AdapterJS.options.getAllCams = true;
  3791. // uncomment to prevent the install prompt when the plugin in not yet installed
  3792. // AdapterJS.options.hidePluginInstallPrompt = true;
  3793. // AdapterJS version
  3794. AdapterJS.VERSION = '0.12.3';
  3795. // This function will be called when the WebRTC API is ready to be used
  3796. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3797. // the plugin
  3798. // You may Override this function to synchronise the start of your application
  3799. // with the WebRTC API being ready.
  3800. // If you decide not to override use this synchronisation, it may result in
  3801. // an extensive CPU usage on the plugin start (once per tab loaded)
  3802. // Params:
  3803. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3804. //
  3805. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3806. // The WebRTC API is ready.
  3807. // Override me and do whatever you want here
  3808. };
  3809. // Sets a callback function to be called when the WebRTC interface is ready.
  3810. // The first argument is the function to callback.\
  3811. // Throws an error if the first argument is not a function
  3812. AdapterJS.webRTCReady = function (callback) {
  3813. if (typeof callback !== 'function') {
  3814. throw new Error('Callback provided is not a function');
  3815. }
  3816. if (true === AdapterJS.onwebrtcreadyDone) {
  3817. // All WebRTC interfaces are ready, just call the callback
  3818. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3819. } else {
  3820. // will be triggered automatically when your browser/plugin is ready.
  3821. AdapterJS.onwebrtcready = callback;
  3822. }
  3823. };
  3824. // Plugin namespace
  3825. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3826. // The object to store plugin information
  3827. AdapterJS.WebRTCPlugin.pluginInfo = {
  3828. prefix : 'Tem',
  3829. plugName : 'TemWebRTCPlugin',
  3830. pluginId : 'plugin0',
  3831. type : 'application/x-temwebrtcplugin',
  3832. onload : '__TemWebRTCReady0',
  3833. portalLink : 'http://skylink.io/plugin/',
  3834. downloadLink : null, //set below
  3835. companyName: 'Temasys'
  3836. };
  3837. if(!!navigator.platform.match(/^Mac/i)) {
  3838. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3839. }
  3840. else if(!!navigator.platform.match(/^Win/i)) {
  3841. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3842. }
  3843. AdapterJS.WebRTCPlugin.TAGS = {
  3844. NONE : 'none',
  3845. AUDIO : 'audio',
  3846. VIDEO : 'video'
  3847. };
  3848. // Unique identifier of each opened page
  3849. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3850. // Use this whenever you want to call the plugin.
  3851. AdapterJS.WebRTCPlugin.plugin = null;
  3852. // Set log level for the plugin once it is ready.
  3853. // The different values are
  3854. // This is an asynchronous function that will run when the plugin is ready
  3855. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3856. // Defines webrtc's JS interface according to the plugin's implementation.
  3857. // Define plugin Browsers as WebRTC Interface.
  3858. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3859. // This function detects whether or not a plugin is installed.
  3860. // Checks if Not IE (firefox, for example), else if it's IE,
  3861. // we're running IE and do something. If not it is not supported.
  3862. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3863. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3864. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3865. // Inject the HTML DOM object element into the page.
  3866. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3867. // States of readiness that the plugin goes through when
  3868. // being injected and stated
  3869. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3870. NONE : 0, // no plugin use
  3871. INITIALIZING : 1, // Detected need for plugin
  3872. INJECTING : 2, // Injecting plugin
  3873. INJECTED: 3, // Plugin element injected but not usable yet
  3874. READY: 4 // Plugin ready to be used
  3875. };
  3876. // Current state of the plugin. You cannot use the plugin before this is
  3877. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3878. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3879. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3880. // Used to make sure AdapterJS.onwebrtcready is only called once
  3881. AdapterJS.onwebrtcreadyDone = false;
  3882. // Log levels for the plugin.
  3883. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3884. /*
  3885. Log outputs are prefixed in some cases.
  3886. INFO: Information reported by the plugin.
  3887. ERROR: Errors originating from within the plugin.
  3888. WEBRTC: Error originating from within the libWebRTC library
  3889. */
  3890. // From the least verbose to the most verbose
  3891. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3892. NONE : 'NONE',
  3893. ERROR : 'ERROR',
  3894. WARNING : 'WARNING',
  3895. INFO: 'INFO',
  3896. VERBOSE: 'VERBOSE',
  3897. SENSITIVE: 'SENSITIVE'
  3898. };
  3899. // Does a waiting check before proceeding to load the plugin.
  3900. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3901. // This methid will use an interval to wait for the plugin to be ready.
  3902. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3903. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3904. // This function will be called when plugin is ready. It sends necessary
  3905. // details to the plugin.
  3906. // The function will wait for the document to be ready and the set the
  3907. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3908. // indicating that it can start being requested.
  3909. // This function is not in the IE/Safari condition brackets so that
  3910. // TemPluginLoaded function might be called on Chrome/Firefox.
  3911. // This function is the only private function that is not encapsulated to
  3912. // allow the plugin method to be called.
  3913. __TemWebRTCReady0 = function () {
  3914. if (document.readyState === 'complete') {
  3915. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3916. AdapterJS.maybeThroughWebRTCReady();
  3917. } else {
  3918. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3919. if (document.readyState === 'complete') {
  3920. // TODO: update comments, we wait for the document to be ready
  3921. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3922. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3923. AdapterJS.maybeThroughWebRTCReady();
  3924. }
  3925. }, 100);
  3926. }
  3927. };
  3928. AdapterJS.maybeThroughWebRTCReady = function() {
  3929. if (!AdapterJS.onwebrtcreadyDone) {
  3930. AdapterJS.onwebrtcreadyDone = true;
  3931. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3932. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3933. }
  3934. }
  3935. };
  3936. // Text namespace
  3937. AdapterJS.TEXT = {
  3938. PLUGIN: {
  3939. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3940. 'to work on this browser.',
  3941. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3942. BUTTON: 'Install Now'
  3943. },
  3944. REFRESH: {
  3945. REQUIRE_REFRESH: 'Please refresh page',
  3946. BUTTON: 'Refresh Page'
  3947. }
  3948. };
  3949. // The result of ice connection states.
  3950. // - starting: Ice connection is starting.
  3951. // - checking: Ice connection is checking.
  3952. // - connected Ice connection is connected.
  3953. // - completed Ice connection is connected.
  3954. // - done Ice connection has been completed.
  3955. // - disconnected Ice connection has been disconnected.
  3956. // - failed Ice connection has failed.
  3957. // - closed Ice connection is closed.
  3958. AdapterJS._iceConnectionStates = {
  3959. starting : 'starting',
  3960. checking : 'checking',
  3961. connected : 'connected',
  3962. completed : 'connected',
  3963. done : 'completed',
  3964. disconnected : 'disconnected',
  3965. failed : 'failed',
  3966. closed : 'closed'
  3967. };
  3968. //The IceConnection states that has been fired for each peer.
  3969. AdapterJS._iceConnectionFiredStates = [];
  3970. // Check if WebRTC Interface is defined.
  3971. AdapterJS.isDefined = null;
  3972. // This function helps to retrieve the webrtc detected browser information.
  3973. // This sets:
  3974. // - webrtcDetectedBrowser: The browser agent name.
  3975. // - webrtcDetectedVersion: The browser version.
  3976. // - webrtcDetectedType: The types of webRTC support.
  3977. // - 'moz': Mozilla implementation of webRTC.
  3978. // - 'webkit': WebKit implementation of webRTC.
  3979. // - 'plugin': Using the plugin implementation.
  3980. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3981. var hasMatch, checkMatch = navigator.userAgent.match(
  3982. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3983. if (/trident/i.test(checkMatch[1])) {
  3984. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3985. webrtcDetectedBrowser = 'IE';
  3986. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3987. } else if (checkMatch[1] === 'Chrome') {
  3988. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3989. if (hasMatch !== null) {
  3990. webrtcDetectedBrowser = 'opera';
  3991. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3992. }
  3993. }
  3994. if (navigator.userAgent.indexOf('Safari')) {
  3995. if (typeof InstallTrigger !== 'undefined') {
  3996. webrtcDetectedBrowser = 'firefox';
  3997. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3998. webrtcDetectedBrowser = 'IE';
  3999. } else if (
  4000. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  4001. webrtcDetectedBrowser = 'safari';
  4002. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  4003. webrtcDetectedBrowser = 'opera';
  4004. } else if (!!window.chrome) {
  4005. webrtcDetectedBrowser = 'chrome';
  4006. }
  4007. }
  4008. if (!webrtcDetectedBrowser) {
  4009. webrtcDetectedVersion = checkMatch[1];
  4010. }
  4011. if (!webrtcDetectedVersion) {
  4012. try {
  4013. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  4014. [navigator.appName, navigator.appVersion, '-?'];
  4015. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  4016. checkMatch.splice(1, 1, hasMatch[1]);
  4017. }
  4018. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  4019. } catch (error) { }
  4020. }
  4021. };
  4022. // To fix configuration as some browsers does not support
  4023. // the 'urls' attribute.
  4024. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  4025. if (pcConfig === null) {
  4026. return;
  4027. }
  4028. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  4029. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  4030. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  4031. delete pcConfig.iceServers[i].urls;
  4032. }
  4033. }
  4034. };
  4035. AdapterJS.addEvent = function(elem, evnt, func) {
  4036. if (elem.addEventListener) { // W3C DOM
  4037. elem.addEventListener(evnt, func, false);
  4038. } else if (elem.attachEvent) {// OLD IE DOM
  4039. elem.attachEvent('on'+evnt, func);
  4040. } else { // No much to do
  4041. elem[evnt] = func;
  4042. }
  4043. };
  4044. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  4045. // only inject once the page is ready
  4046. if (document.readyState !== 'complete') {
  4047. return;
  4048. }
  4049. var w = window;
  4050. var i = document.createElement('iframe');
  4051. i.style.position = 'fixed';
  4052. i.style.top = '-41px';
  4053. i.style.left = 0;
  4054. i.style.right = 0;
  4055. i.style.width = '100%';
  4056. i.style.height = '40px';
  4057. i.style.backgroundColor = '#ffffe1';
  4058. i.style.border = 'none';
  4059. i.style.borderBottom = '1px solid #888888';
  4060. i.style.zIndex = '9999999';
  4061. if(typeof i.style.webkitTransition === 'string') {
  4062. i.style.webkitTransition = 'all .5s ease-out';
  4063. } else if(typeof i.style.transition === 'string') {
  4064. i.style.transition = 'all .5s ease-out';
  4065. }
  4066. document.body.appendChild(i);
  4067. c = (i.contentWindow) ? i.contentWindow :
  4068. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  4069. c.document.open();
  4070. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  4071. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  4072. 'middle; cursor: default;">' + text + '</span>');
  4073. if(buttonText && buttonLink) {
  4074. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  4075. c.document.close();
  4076. // On click on okay
  4077. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  4078. if (!!displayRefreshBar) {
  4079. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  4080. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  4081. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  4082. }
  4083. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  4084. e.preventDefault();
  4085. try {
  4086. event.cancelBubble = true;
  4087. } catch(error) { }
  4088. var pluginInstallInterval = setInterval(function(){
  4089. if(! isIE) {
  4090. navigator.plugins.refresh(false);
  4091. }
  4092. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4093. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4094. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4095. function() { // plugin now installed
  4096. clearInterval(pluginInstallInterval);
  4097. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  4098. },
  4099. function() {
  4100. // still no plugin detected, nothing to do
  4101. });
  4102. } , 500);
  4103. });
  4104. // On click on Cancel
  4105. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  4106. w.document.body.removeChild(i);
  4107. });
  4108. } else {
  4109. c.document.close();
  4110. }
  4111. setTimeout(function() {
  4112. if(typeof i.style.webkitTransform === 'string') {
  4113. i.style.webkitTransform = 'translateY(40px)';
  4114. } else if(typeof i.style.transform === 'string') {
  4115. i.style.transform = 'translateY(40px)';
  4116. } else {
  4117. i.style.top = '0px';
  4118. }
  4119. }, 300);
  4120. };
  4121. // -----------------------------------------------------------
  4122. // Detected webrtc implementation. Types are:
  4123. // - 'moz': Mozilla implementation of webRTC.
  4124. // - 'webkit': WebKit implementation of webRTC.
  4125. // - 'plugin': Using the plugin implementation.
  4126. webrtcDetectedType = null;
  4127. // Detected webrtc datachannel support. Types are:
  4128. // - 'SCTP': SCTP datachannel support.
  4129. // - 'RTP': RTP datachannel support.
  4130. webrtcDetectedDCSupport = null;
  4131. // Set the settings for creating DataChannels, MediaStream for
  4132. // Cross-browser compability.
  4133. // - This is only for SCTP based support browsers.
  4134. // the 'urls' attribute.
  4135. checkMediaDataChannelSettings =
  4136. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  4137. if (typeof callback !== 'function') {
  4138. return;
  4139. }
  4140. var beOfferer = true;
  4141. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  4142. // Nightly version does not require MozDontOfferDataChannel for interop
  4143. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  4144. var isPeerFirefox = peerBrowserAgent === 'firefox';
  4145. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  4146. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  4147. // Resends an updated version of constraints for MozDataChannel to work
  4148. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  4149. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  4150. try {
  4151. delete constraints.mandatory.MozDontOfferDataChannel;
  4152. } catch (error) {
  4153. console.error('Failed deleting MozDontOfferDataChannel');
  4154. console.error(error);
  4155. }
  4156. } else if ((isLocalFirefox && !isPeerFirefox)) {
  4157. constraints.mandatory.MozDontOfferDataChannel = true;
  4158. }
  4159. if (!isLocalFirefox) {
  4160. // temporary measure to remove Moz* constraints in non Firefox browsers
  4161. for (var prop in constraints.mandatory) {
  4162. if (constraints.mandatory.hasOwnProperty(prop)) {
  4163. if (prop.indexOf('Moz') !== -1) {
  4164. delete constraints.mandatory[prop];
  4165. }
  4166. }
  4167. }
  4168. }
  4169. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  4170. // interopability of the media stream
  4171. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4172. beOfferer = false;
  4173. }
  4174. callback(beOfferer, constraints);
  4175. };
  4176. // Handles the differences for all browsers ice connection state output.
  4177. // - Tested outcomes are:
  4178. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4179. // - Chrome (answerer) : 'checking' > 'connected'
  4180. // - Firefox (offerer) : 'checking' > 'connected'
  4181. // - Firefox (answerer): 'checking' > 'connected'
  4182. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4183. if (typeof callback !== 'function') {
  4184. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4185. return;
  4186. }
  4187. peerId = (peerId) ? peerId : 'peer';
  4188. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4189. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4190. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4191. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4192. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4193. }
  4194. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4195. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4196. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4197. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4198. setTimeout(function () {
  4199. AdapterJS._iceConnectionFiredStates[peerId]
  4200. .push(AdapterJS._iceConnectionStates.done);
  4201. callback(AdapterJS._iceConnectionStates.done);
  4202. }, 1000);
  4203. }
  4204. callback(iceConnectionState);
  4205. }
  4206. return;
  4207. };
  4208. // Firefox:
  4209. // - Creates iceServer from the url for Firefox.
  4210. // - Create iceServer with stun url.
  4211. // - Create iceServer with turn url.
  4212. // - Ignore the transport parameter from TURN url for FF version <=27.
  4213. // - Return null for createIceServer if transport=tcp.
  4214. // - FF 27 and above supports transport parameters in TURN url,
  4215. // - So passing in the full url to create iceServer.
  4216. // Chrome:
  4217. // - Creates iceServer from the url for Chrome M33 and earlier.
  4218. // - Create iceServer with stun url.
  4219. // - Chrome M28 & above uses below TURN format.
  4220. // Plugin:
  4221. // - Creates Ice Server for Plugin Browsers
  4222. // - If Stun - Create iceServer with stun url.
  4223. // - Else - Create iceServer with turn url
  4224. // - This is a WebRTC Function
  4225. createIceServer = null;
  4226. // Firefox:
  4227. // - Creates IceServers for Firefox
  4228. // - Use .url for FireFox.
  4229. // - Multiple Urls support
  4230. // Chrome:
  4231. // - Creates iceServers from the urls for Chrome M34 and above.
  4232. // - .urls is supported since Chrome M34.
  4233. // - Multiple Urls support
  4234. // Plugin:
  4235. // - Creates Ice Servers for Plugin Browsers
  4236. // - Multiple Urls support
  4237. // - This is a WebRTC Function
  4238. createIceServers = null;
  4239. //------------------------------------------------------------
  4240. //The RTCPeerConnection object.
  4241. RTCPeerConnection = null;
  4242. // Creates RTCSessionDescription object for Plugin Browsers
  4243. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4244. RTCSessionDescription : null;
  4245. // Creates RTCIceCandidate object for Plugin Browsers
  4246. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4247. RTCIceCandidate : null;
  4248. // Get UserMedia (only difference is the prefix).
  4249. // Code from Adam Barth.
  4250. getUserMedia = null;
  4251. // Attach a media stream to an element.
  4252. attachMediaStream = null;
  4253. // Re-attach a media stream to an element.
  4254. reattachMediaStream = null;
  4255. // Detected browser agent name. Types are:
  4256. // - 'firefox': Firefox browser.
  4257. // - 'chrome': Chrome browser.
  4258. // - 'opera': Opera browser.
  4259. // - 'safari': Safari browser.
  4260. // - 'IE' - Internet Explorer browser.
  4261. webrtcDetectedBrowser = null;
  4262. // Detected browser version.
  4263. webrtcDetectedVersion = null;
  4264. // Check for browser types and react accordingly
  4265. if (navigator.mozGetUserMedia) {
  4266. webrtcDetectedBrowser = 'firefox';
  4267. webrtcDetectedVersion = parseInt(navigator
  4268. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4269. webrtcDetectedType = 'moz';
  4270. webrtcDetectedDCSupport = 'SCTP';
  4271. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4272. AdapterJS.maybeFixConfiguration(pcConfig);
  4273. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4274. };
  4275. // The RTCSessionDescription object.
  4276. RTCSessionDescription = mozRTCSessionDescription;
  4277. window.RTCSessionDescription = RTCSessionDescription;
  4278. // The RTCIceCandidate object.
  4279. RTCIceCandidate = mozRTCIceCandidate;
  4280. window.RTCIceCandidate = RTCIceCandidate;
  4281. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4282. navigator.getUserMedia = window.getUserMedia;
  4283. // Shim for MediaStreamTrack.getSources.
  4284. MediaStreamTrack.getSources = function(successCb) {
  4285. setTimeout(function() {
  4286. var infos = [
  4287. { kind: 'audio', id: 'default', label:'', facing:'' },
  4288. { kind: 'video', id: 'default', label:'', facing:'' }
  4289. ];
  4290. successCb(infos);
  4291. }, 0);
  4292. };
  4293. createIceServer = function (url, username, password) {
  4294. var iceServer = null;
  4295. var url_parts = url.split(':');
  4296. if (url_parts[0].indexOf('stun') === 0) {
  4297. iceServer = { url : url };
  4298. } else if (url_parts[0].indexOf('turn') === 0) {
  4299. if (webrtcDetectedVersion < 27) {
  4300. var turn_url_parts = url.split('?');
  4301. if (turn_url_parts.length === 1 ||
  4302. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4303. iceServer = {
  4304. url : turn_url_parts[0],
  4305. credential : password,
  4306. username : username
  4307. };
  4308. }
  4309. } else {
  4310. iceServer = {
  4311. url : url,
  4312. credential : password,
  4313. username : username
  4314. };
  4315. }
  4316. }
  4317. return iceServer;
  4318. };
  4319. createIceServers = function (urls, username, password) {
  4320. var iceServers = [];
  4321. for (var i = 0; i < urls.length; i++) {
  4322. var iceServer = createIceServer(urls[i], username, password);
  4323. if (iceServer !== null) {
  4324. iceServers.push(iceServer);
  4325. }
  4326. }
  4327. return iceServers;
  4328. };
  4329. attachMediaStream = function (element, stream) {
  4330. element.mozSrcObject = stream;
  4331. if (stream !== null)
  4332. element.play();
  4333. return element;
  4334. };
  4335. reattachMediaStream = function (to, from) {
  4336. to.mozSrcObject = from.mozSrcObject;
  4337. to.play();
  4338. return to;
  4339. };
  4340. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4341. if (!callback) {
  4342. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4343. ': 1 argument required, but only 0 present.');
  4344. }
  4345. return callback([]);
  4346. };
  4347. // Fake get{Video,Audio}Tracks
  4348. if (!MediaStream.prototype.getVideoTracks) {
  4349. MediaStream.prototype.getVideoTracks = function () {
  4350. return [];
  4351. };
  4352. }
  4353. if (!MediaStream.prototype.getAudioTracks) {
  4354. MediaStream.prototype.getAudioTracks = function () {
  4355. return [];
  4356. };
  4357. }
  4358. AdapterJS.maybeThroughWebRTCReady();
  4359. } else if (navigator.webkitGetUserMedia) {
  4360. webrtcDetectedBrowser = 'chrome';
  4361. webrtcDetectedType = 'webkit';
  4362. webrtcDetectedVersion = parseInt(navigator
  4363. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4364. // check if browser is opera 20+
  4365. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4366. if (checkIfOpera !== null) {
  4367. webrtcDetectedBrowser = 'opera';
  4368. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4369. }
  4370. // check browser datachannel support
  4371. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4372. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4373. webrtcDetectedDCSupport = 'SCTP';
  4374. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4375. webrtcDetectedVersion > 24) {
  4376. webrtcDetectedDCSupport = 'RTP';
  4377. } else {
  4378. webrtcDetectedDCSupport = '';
  4379. }
  4380. createIceServer = function (url, username, password) {
  4381. var iceServer = null;
  4382. var url_parts = url.split(':');
  4383. if (url_parts[0].indexOf('stun') === 0) {
  4384. iceServer = { 'url' : url };
  4385. } else if (url_parts[0].indexOf('turn') === 0) {
  4386. iceServer = {
  4387. 'url' : url,
  4388. 'credential' : password,
  4389. 'username' : username
  4390. };
  4391. }
  4392. return iceServer;
  4393. };
  4394. createIceServers = function (urls, username, password) {
  4395. var iceServers = [];
  4396. if (webrtcDetectedVersion >= 34) {
  4397. iceServers = {
  4398. 'urls' : urls,
  4399. 'credential' : password,
  4400. 'username' : username
  4401. };
  4402. } else {
  4403. for (var i = 0; i < urls.length; i++) {
  4404. var iceServer = createIceServer(urls[i], username, password);
  4405. if (iceServer !== null) {
  4406. iceServers.push(iceServer);
  4407. }
  4408. }
  4409. }
  4410. return iceServers;
  4411. };
  4412. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4413. if (webrtcDetectedVersion < 34) {
  4414. AdapterJS.maybeFixConfiguration(pcConfig);
  4415. }
  4416. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4417. };
  4418. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4419. navigator.getUserMedia = window.getUserMedia;
  4420. attachMediaStream = function (element, stream) {
  4421. if (typeof element.srcObject !== 'undefined') {
  4422. element.srcObject = stream;
  4423. } else if (typeof element.mozSrcObject !== 'undefined') {
  4424. element.mozSrcObject = stream;
  4425. } else if (typeof element.src !== 'undefined') {
  4426. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4427. } else {
  4428. console.log('Error attaching stream to element.');
  4429. }
  4430. return element;
  4431. };
  4432. reattachMediaStream = function (to, from) {
  4433. to.src = from.src;
  4434. return to;
  4435. };
  4436. AdapterJS.maybeThroughWebRTCReady();
  4437. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4438. /Edge\/(\d+).(\d+)$/)) {
  4439. webrtcDetectedBrowser = 'edge';
  4440. webrtcDetectedVersion =
  4441. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4442. // the minimum version still supported by adapter.
  4443. webrtcMinimumVersion = 12;
  4444. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4445. attachMediaStream = function(element, stream) {
  4446. element.srcObject = stream;
  4447. return element;
  4448. };
  4449. reattachMediaStream = function(to, from) {
  4450. to.srcObject = from.srcObject;
  4451. return to;
  4452. };
  4453. AdapterJS.maybeThroughWebRTCReady();
  4454. } else { // TRY TO USE PLUGIN
  4455. // IE 9 is not offering an implementation of console.log until you open a console
  4456. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4457. /* jshint -W020 */
  4458. console = {} || console;
  4459. // Implemented based on console specs from MDN
  4460. // You may override these functions
  4461. console.log = function (arg) {};
  4462. console.info = function (arg) {};
  4463. console.error = function (arg) {};
  4464. console.dir = function (arg) {};
  4465. console.exception = function (arg) {};
  4466. console.trace = function (arg) {};
  4467. console.warn = function (arg) {};
  4468. console.count = function (arg) {};
  4469. console.debug = function (arg) {};
  4470. console.count = function (arg) {};
  4471. console.time = function (arg) {};
  4472. console.timeEnd = function (arg) {};
  4473. console.group = function (arg) {};
  4474. console.groupCollapsed = function (arg) {};
  4475. console.groupEnd = function (arg) {};
  4476. /* jshint +W020 */
  4477. }
  4478. webrtcDetectedType = 'plugin';
  4479. webrtcDetectedDCSupport = 'plugin';
  4480. AdapterJS.parseWebrtcDetectedBrowser();
  4481. isIE = webrtcDetectedBrowser === 'IE';
  4482. /* jshint -W035 */
  4483. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4484. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4485. /* empty because it needs to prevent the function from running. */
  4486. }
  4487. };
  4488. /* jshint +W035 */
  4489. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4490. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4491. // Call immediately if possible
  4492. // Once the plugin is set, the code will always take this path
  4493. callback();
  4494. } else {
  4495. // otherwise start a 100ms interval
  4496. var checkPluginReadyState = setInterval(function () {
  4497. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4498. clearInterval(checkPluginReadyState);
  4499. callback();
  4500. }
  4501. }, 100);
  4502. }
  4503. };
  4504. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4505. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4506. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4507. });
  4508. };
  4509. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4510. // only inject once the page is ready
  4511. if (document.readyState !== 'complete') {
  4512. return;
  4513. }
  4514. // Prevent multiple injections
  4515. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4516. return;
  4517. }
  4518. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4519. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4520. var frag = document.createDocumentFragment();
  4521. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4522. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4523. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4524. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4525. '<param name="pluginId" value="' +
  4526. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4527. '<param name="windowless" value="false" /> ' +
  4528. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4529. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4530. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4531. // uncomment to be able to use virtual cams
  4532. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4533. '</object>';
  4534. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4535. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4536. }
  4537. document.body.appendChild(frag);
  4538. // Need to re-fetch the plugin
  4539. AdapterJS.WebRTCPlugin.plugin =
  4540. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4541. } else {
  4542. // Load Plugin
  4543. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4544. AdapterJS.WebRTCPlugin.plugin.id =
  4545. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4546. // IE will only start the plugin if it's ACTUALLY visible
  4547. if (isIE) {
  4548. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4549. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4550. } else { // The size of the plugin on Safari should be 0x0px
  4551. // so that the autorisation prompt is at the top
  4552. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4553. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4554. }
  4555. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4556. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4557. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4558. '<param name="pluginId" value="' +
  4559. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4560. '<param name="windowless" value="false" /> ' +
  4561. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4562. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4563. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4564. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4565. }
  4566. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4567. };
  4568. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4569. function (comName, plugName, installedCb, notInstalledCb) {
  4570. if (!isIE) {
  4571. var pluginArray = navigator.plugins;
  4572. for (var i = 0; i < pluginArray.length; i++) {
  4573. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4574. installedCb();
  4575. return;
  4576. }
  4577. }
  4578. notInstalledCb();
  4579. } else {
  4580. try {
  4581. var axo = new ActiveXObject(comName + '.' + plugName);
  4582. } catch (e) {
  4583. notInstalledCb();
  4584. return;
  4585. }
  4586. installedCb();
  4587. }
  4588. };
  4589. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4590. if (AdapterJS.WebRTCPlugin.pluginState ===
  4591. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4592. console.error("AdapterJS - WebRTC interface has already been defined");
  4593. return;
  4594. }
  4595. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4596. AdapterJS.isDefined = function (variable) {
  4597. return variable !== null && variable !== undefined;
  4598. };
  4599. createIceServer = function (url, username, password) {
  4600. var iceServer = null;
  4601. var url_parts = url.split(':');
  4602. if (url_parts[0].indexOf('stun') === 0) {
  4603. iceServer = {
  4604. 'url' : url,
  4605. 'hasCredentials' : false
  4606. };
  4607. } else if (url_parts[0].indexOf('turn') === 0) {
  4608. iceServer = {
  4609. 'url' : url,
  4610. 'hasCredentials' : true,
  4611. 'credential' : password,
  4612. 'username' : username
  4613. };
  4614. }
  4615. return iceServer;
  4616. };
  4617. createIceServers = function (urls, username, password) {
  4618. var iceServers = [];
  4619. for (var i = 0; i < urls.length; ++i) {
  4620. iceServers.push(createIceServer(urls[i], username, password));
  4621. }
  4622. return iceServers;
  4623. };
  4624. RTCSessionDescription = function (info) {
  4625. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4626. return AdapterJS.WebRTCPlugin.plugin.
  4627. ConstructSessionDescription(info.type, info.sdp);
  4628. };
  4629. RTCPeerConnection = function (servers, constraints) {
  4630. var iceServers = null;
  4631. if (servers) {
  4632. iceServers = servers.iceServers;
  4633. for (var i = 0; i < iceServers.length; i++) {
  4634. if (iceServers[i].urls && !iceServers[i].url) {
  4635. iceServers[i].url = iceServers[i].urls;
  4636. }
  4637. iceServers[i].hasCredentials = AdapterJS.
  4638. isDefined(iceServers[i].username) &&
  4639. AdapterJS.isDefined(iceServers[i].credential);
  4640. }
  4641. }
  4642. var mandatory = (constraints && constraints.mandatory) ?
  4643. constraints.mandatory : null;
  4644. var optional = (constraints && constraints.optional) ?
  4645. constraints.optional : null;
  4646. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4647. return AdapterJS.WebRTCPlugin.plugin.
  4648. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4649. iceServers, mandatory, optional);
  4650. };
  4651. MediaStreamTrack = {};
  4652. MediaStreamTrack.getSources = function (callback) {
  4653. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4654. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4655. });
  4656. };
  4657. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4658. constraints.audio = constraints.audio || false;
  4659. constraints.video = constraints.video || false;
  4660. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4661. AdapterJS.WebRTCPlugin.plugin.
  4662. getUserMedia(constraints, successCallback, failureCallback);
  4663. });
  4664. };
  4665. window.navigator.getUserMedia = window.getUserMedia;
  4666. attachMediaStream = function (element, stream) {
  4667. if (!element || !element.parentNode) {
  4668. return;
  4669. }
  4670. var streamId;
  4671. if (stream === null) {
  4672. streamId = '';
  4673. } else {
  4674. if (typeof stream.enableSoundTracks !== 'undefined') {
  4675. stream.enableSoundTracks(true);
  4676. }
  4677. streamId = stream.id;
  4678. }
  4679. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4680. var nodeName = element.nodeName.toLowerCase();
  4681. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4682. var tag;
  4683. switch(nodeName) {
  4684. case 'audio':
  4685. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4686. break;
  4687. case 'video':
  4688. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4689. break;
  4690. default:
  4691. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4692. }
  4693. var frag = document.createDocumentFragment();
  4694. var temp = document.createElement('div');
  4695. var classHTML = '';
  4696. if (element.className) {
  4697. classHTML = 'class="' + element.className + '" ';
  4698. } else if (element.attributes && element.attributes['class']) {
  4699. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4700. }
  4701. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4702. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4703. '<param name="pluginId" value="' + elementId + '" /> ' +
  4704. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4705. '<param name="windowless" value="true" /> ' +
  4706. '<param name="streamId" value="' + streamId + '" /> ' +
  4707. '<param name="tag" value="' + tag + '" /> ' +
  4708. '</object>';
  4709. while (temp.firstChild) {
  4710. frag.appendChild(temp.firstChild);
  4711. }
  4712. var height = '';
  4713. var width = '';
  4714. if (element.clientWidth || element.clientHeight) {
  4715. width = element.clientWidth;
  4716. height = element.clientHeight;
  4717. }
  4718. else if (element.width || element.height) {
  4719. width = element.width;
  4720. height = element.height;
  4721. }
  4722. element.parentNode.insertBefore(frag, element);
  4723. frag = document.getElementById(elementId);
  4724. frag.width = width;
  4725. frag.height = height;
  4726. element.parentNode.removeChild(element);
  4727. } else { // already an <object> tag, just change the stream id
  4728. var children = element.children;
  4729. for (var i = 0; i !== children.length; ++i) {
  4730. if (children[i].name === 'streamId') {
  4731. children[i].value = streamId;
  4732. break;
  4733. }
  4734. }
  4735. element.setStreamId(streamId);
  4736. }
  4737. var newElement = document.getElementById(elementId);
  4738. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4739. return newElement;
  4740. };
  4741. reattachMediaStream = function (to, from) {
  4742. var stream = null;
  4743. var children = from.children;
  4744. for (var i = 0; i !== children.length; ++i) {
  4745. if (children[i].name === 'streamId') {
  4746. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4747. stream = AdapterJS.WebRTCPlugin.plugin
  4748. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4749. break;
  4750. }
  4751. }
  4752. if (stream !== null) {
  4753. return attachMediaStream(to, stream);
  4754. } else {
  4755. console.log('Could not find the stream associated with this element');
  4756. }
  4757. };
  4758. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4759. properties = Object.getOwnPropertyNames( prototype );
  4760. for(prop in properties) {
  4761. propName = properties[prop];
  4762. if (typeof(propName.slice) === 'function') {
  4763. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4764. if (isIE) {
  4765. destElem.attachEvent(propName,srcElem[propName]);
  4766. } else {
  4767. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4768. }
  4769. } else {
  4770. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4771. }
  4772. }
  4773. }
  4774. var subPrototype = Object.getPrototypeOf(prototype)
  4775. if(subPrototype != null) {
  4776. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4777. }
  4778. }
  4779. RTCIceCandidate = function (candidate) {
  4780. if (!candidate.sdpMid) {
  4781. candidate.sdpMid = '';
  4782. }
  4783. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4784. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4785. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4786. );
  4787. };
  4788. // inject plugin
  4789. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4790. AdapterJS.WebRTCPlugin.injectPlugin();
  4791. };
  4792. // This function will be called if the plugin is needed (browser different
  4793. // from Chrome or Firefox), but the plugin is not installed.
  4794. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4795. function() {
  4796. AdapterJS.addEvent(document,
  4797. 'readystatechange',
  4798. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4799. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4800. };
  4801. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4802. if (AdapterJS.options.hidePluginInstallPrompt) {
  4803. return;
  4804. }
  4805. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4806. if(downloadLink) { // if download link
  4807. var popupString;
  4808. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4809. popupString = 'This website requires you to install the ' +
  4810. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4811. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4812. ' WebRTC Plugin</a>' +
  4813. ' to work on this browser.';
  4814. } else { // no portal link, just print a generic explanation
  4815. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4816. }
  4817. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4818. } else { // no download link, just print a generic explanation
  4819. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4820. }
  4821. };
  4822. // Try to detect the plugin and act accordingly
  4823. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4824. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4825. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4826. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4827. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4828. }
  4829. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4830. },{"jitsi-meet-logger":50}],21:[function(require,module,exports){
  4831. (function (__filename){
  4832. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4833. var UsernameGenerator = require('../util/UsernameGenerator');
  4834. function supportsLocalStorage() {
  4835. try {
  4836. return 'localStorage' in window && window.localStorage !== null;
  4837. } catch (e) {
  4838. logger.log("localstorage is not supported");
  4839. return false;
  4840. }
  4841. }
  4842. function generateUniqueId() {
  4843. function _p8() {
  4844. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4845. }
  4846. return _p8() + _p8() + _p8() + _p8();
  4847. }
  4848. function Settings(conferenceID) {
  4849. this.displayName = '';
  4850. this.userId;
  4851. this.confSettings = null;
  4852. this.conferenceID = conferenceID;
  4853. this.callStatsUserName;
  4854. if (supportsLocalStorage()) {
  4855. if(!window.localStorage.getItem(conferenceID))
  4856. this.confSettings = {};
  4857. else
  4858. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4859. if(!this.confSettings.jitsiMeetId) {
  4860. this.confSettings.jitsiMeetId = generateUniqueId();
  4861. logger.log("generated id",
  4862. this.confSettings.jitsiMeetId);
  4863. this.save();
  4864. }
  4865. if (!this.confSettings.callStatsUserName) {
  4866. this.confSettings.callStatsUserName
  4867. = UsernameGenerator.generateUsername();
  4868. logger.log('generated callstats uid',
  4869. this.confSettings.callStatsUserName);
  4870. this.save();
  4871. }
  4872. this.userId = this.confSettings.jitsiMeetId || '';
  4873. this.displayName = this.confSettings.displayname || '';
  4874. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4875. } else {
  4876. logger.log("local storage is not supported");
  4877. this.userId = generateUniqueId();
  4878. this.callStatsUserName = UsernameGenerator.generateUsername();
  4879. }
  4880. }
  4881. Settings.prototype.save = function () {
  4882. if(!supportsLocalStorage())
  4883. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4884. }
  4885. Settings.prototype.setDisplayName = function (newDisplayName) {
  4886. this.displayName = newDisplayName;
  4887. if(this.confSettings != null)
  4888. this.confSettings.displayname = displayName;
  4889. this.save();
  4890. return this.displayName;
  4891. }
  4892. Settings.prototype.getSettings = function () {
  4893. return {
  4894. displayName: this.displayName,
  4895. uid: this.userId
  4896. };
  4897. }
  4898. /**
  4899. * Returns fake username for callstats
  4900. * @returns {string} fake username for callstats
  4901. */
  4902. Settings.prototype.getCallStatsUserName = function () {
  4903. return this.callStatsUserName;
  4904. }
  4905. module.exports = Settings;
  4906. }).call(this,"/modules/settings/Settings.js")
  4907. },{"../util/UsernameGenerator":28,"jitsi-meet-logger":50}],22:[function(require,module,exports){
  4908. (function (__filename){
  4909. /* global $, Strophe, callstats */
  4910. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4911. var jsSHA = require('jssha');
  4912. var io = require('socket.io-client');
  4913. /**
  4914. * @const
  4915. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4916. */
  4917. var wrtcFuncNames = {
  4918. createOffer: "createOffer",
  4919. createAnswer: "createAnswer",
  4920. setLocalDescription: "setLocalDescription",
  4921. setRemoteDescription: "setRemoteDescription",
  4922. addIceCandidate: "addIceCandidate",
  4923. getUserMedia: "getUserMedia"
  4924. };
  4925. /**
  4926. * @const
  4927. * @see http://www.callstats.io/api/#enumeration-of-fabricevent
  4928. */
  4929. var fabricEvent = {
  4930. fabricSetupFailed:"fabricSetupFailed",
  4931. fabricHold:"fabricHold",
  4932. fabricResume:"fabricResume",
  4933. audioMute:"audioMute",
  4934. audioUnmute:"audioUnmute",
  4935. videoPause:"videoPause",
  4936. videoResume:"videoResume",
  4937. fabricUsageEvent:"fabricUsageEvent",
  4938. fabricStats:"fabricStats",
  4939. fabricTerminated:"fabricTerminated"
  4940. };
  4941. var callStats = null;
  4942. function initCallback (err, msg) {
  4943. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4944. // there is no lib, nothing to report to
  4945. if (err !== 'success')
  4946. return;
  4947. // notify callstats about failures if there were any
  4948. if (CallStats.reportsQueue.length) {
  4949. CallStats.reportsQueue.forEach(function (report) {
  4950. if (report.type === reportType.ERROR)
  4951. {
  4952. var error = report.data;
  4953. CallStats._reportError.call(this, error.type, error.error,
  4954. error.pc);
  4955. }
  4956. else if (report.type === reportType.EVENT)
  4957. {
  4958. var data = report.data;
  4959. callStats.sendFabricEvent(
  4960. this.peerconnection, data.event, this.confID);
  4961. }
  4962. }, this);
  4963. CallStats.reportsQueue.length = 0;
  4964. }
  4965. }
  4966. /**
  4967. * Returns a function which invokes f in a try/catch block, logs any exception
  4968. * to the console, and then swallows it.
  4969. *
  4970. * @param f the function to invoke in a try/catch block
  4971. * @return a function which invokes f in a try/catch block, logs any exception
  4972. * to the console, and then swallows it
  4973. */
  4974. function _try_catch (f) {
  4975. return function () {
  4976. try {
  4977. f.apply(this, arguments);
  4978. } catch (e) {
  4979. logger.error(e);
  4980. }
  4981. };
  4982. }
  4983. /**
  4984. * Creates new CallStats instance that handles all callstats API calls.
  4985. * @param peerConnection {JingleSessionPC} the session object
  4986. * @param Settings {Settings} the settings instance. Declared in
  4987. * /modules/settings/Settings.js
  4988. * @param options {object} credentials for callstats.
  4989. */
  4990. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4991. try{
  4992. //check weather that should work with more than 1 peerconnection
  4993. if(!callStats) {
  4994. callStats = new callstats($, io, jsSHA);
  4995. } else {
  4996. return;
  4997. }
  4998. this.session = jingleSession;
  4999. this.peerconnection = jingleSession.peerconnection.peerconnection;
  5000. this.userID = Settings.getCallStatsUserName();
  5001. //FIXME: change it to something else (maybe roomName)
  5002. var location = window.location;
  5003. this.confID = location.hostname + location.pathname;
  5004. //userID is generated or given by the origin server
  5005. callStats.initialize(options.callStatsID,
  5006. options.callStatsSecret,
  5007. this.userID,
  5008. initCallback.bind(this));
  5009. callStats.addNewFabric(this.peerconnection,
  5010. Strophe.getResourceFromJid(jingleSession.peerjid),
  5011. callStats.fabricUsage.multiplex,
  5012. this.confID,
  5013. this.pcCallback.bind(this));
  5014. } catch (e) {
  5015. // The callstats.io API failed to initialize (e.g. because its
  5016. // download failed to succeed in general or on time). Further
  5017. // attempts to utilize it cannot possibly succeed.
  5018. callStats = null;
  5019. logger.error(e);
  5020. }
  5021. });
  5022. // some errors/events may happen before CallStats init
  5023. // in this case we accumulate them in this array
  5024. // and send them to callstats on init
  5025. CallStats.reportsQueue = [];
  5026. /**
  5027. * Type of pending reports, can be event or an error.
  5028. * @type {{ERROR: string, EVENT: string}}
  5029. */
  5030. var reportType = {
  5031. ERROR: "error",
  5032. EVENT: "event"
  5033. };
  5034. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  5035. if (!callStats) {
  5036. return;
  5037. }
  5038. logger.log("Monitoring status: "+ err + " msg: " + msg);
  5039. });
  5040. /**
  5041. * Notifies CallStats for mute events
  5042. * @param mute {boolean} true for muted and false for not muted
  5043. * @param type {String} "audio"/"video"
  5044. */
  5045. CallStats.sendMuteEvent = _try_catch(function (mute, type, cs) {
  5046. var event = null;
  5047. if (type === "video") {
  5048. event = (mute? fabricEvent.videoPause : fabricEvent.videoResume);
  5049. }
  5050. else {
  5051. event = (mute? fabricEvent.audioMute : fabricEvent.audioUnmute);
  5052. }
  5053. CallStats._reportEvent.call(cs, event);
  5054. });
  5055. /**
  5056. * Reports an error to callstats.
  5057. *
  5058. * @param type the type of the error, which will be one of the wrtcFuncNames
  5059. * @param e the error
  5060. * @param pc the peerconnection
  5061. * @private
  5062. */
  5063. CallStats._reportEvent = function (event) {
  5064. if (callStats) {
  5065. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  5066. } else {
  5067. CallStats.reportsQueue.push({
  5068. type: reportType.EVENT,
  5069. data: {event: event}
  5070. });
  5071. }
  5072. };
  5073. /**
  5074. * Notifies CallStats for connection setup errors
  5075. */
  5076. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  5077. if(!callStats) {
  5078. return;
  5079. }
  5080. callStats.sendFabricEvent(this.peerconnection,
  5081. callStats.fabricEvent.fabricTerminated, this.confID);
  5082. });
  5083. /**
  5084. * Notifies CallStats for connection setup errors
  5085. */
  5086. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  5087. if(!callStats) {
  5088. return;
  5089. }
  5090. callStats.sendFabricEvent(this.peerconnection,
  5091. callStats.fabricEvent.fabricSetupFailed, this.confID);
  5092. });
  5093. /**
  5094. * Sends the given feedback through CallStats.
  5095. *
  5096. * @param overallFeedback an integer between 1 and 5 indicating the
  5097. * user feedback
  5098. * @param detailedFeedback detailed feedback from the user. Not yet used
  5099. */
  5100. CallStats.prototype.sendFeedback = _try_catch(
  5101. function(overallFeedback, detailedFeedback) {
  5102. if(!callStats) {
  5103. return;
  5104. }
  5105. var feedbackString = '{"userID":"' + this.userID + '"' +
  5106. ', "overall":' + overallFeedback +
  5107. ', "comment": "' + detailedFeedback + '"}';
  5108. var feedbackJSON = JSON.parse(feedbackString);
  5109. callStats.sendUserFeedback(this.confID, feedbackJSON);
  5110. });
  5111. /**
  5112. * Reports an error to callstats.
  5113. *
  5114. * @param type the type of the error, which will be one of the wrtcFuncNames
  5115. * @param e the error
  5116. * @param pc the peerconnection
  5117. * @private
  5118. */
  5119. CallStats._reportError = function (type, e, pc) {
  5120. if (callStats) {
  5121. callStats.reportError(pc, this.confID, type, e);
  5122. } else {
  5123. CallStats.reportsQueue.push({
  5124. type: reportType.ERROR,
  5125. data: { type: type, error: e, pc: pc}
  5126. });
  5127. }
  5128. // else just ignore it
  5129. };
  5130. /**
  5131. * Notifies CallStats that getUserMedia failed.
  5132. *
  5133. * @param {Error} e error to send
  5134. * @param {CallStats} cs callstats instance related to the error (optional)
  5135. */
  5136. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  5137. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  5138. });
  5139. /**
  5140. * Notifies CallStats that peer connection failed to create offer.
  5141. *
  5142. * @param {Error} e error to send
  5143. * @param {RTCPeerConnection} pc connection on which failure occured.
  5144. * @param {CallStats} cs callstats instance related to the error (optional)
  5145. */
  5146. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  5147. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  5148. });
  5149. /**
  5150. * Notifies CallStats that peer connection failed to create answer.
  5151. *
  5152. * @param {Error} e error to send
  5153. * @param {RTCPeerConnection} pc connection on which failure occured.
  5154. * @param {CallStats} cs callstats instance related to the error (optional)
  5155. */
  5156. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  5157. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  5158. });
  5159. /**
  5160. * Notifies CallStats that peer connection failed to set local description.
  5161. *
  5162. * @param {Error} e error to send
  5163. * @param {RTCPeerConnection} pc connection on which failure occured.
  5164. * @param {CallStats} cs callstats instance related to the error (optional)
  5165. */
  5166. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  5167. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  5168. });
  5169. /**
  5170. * Notifies CallStats that peer connection failed to set remote description.
  5171. *
  5172. * @param {Error} e error to send
  5173. * @param {RTCPeerConnection} pc connection on which failure occured.
  5174. * @param {CallStats} cs callstats instance related to the error (optional)
  5175. */
  5176. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  5177. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  5178. });
  5179. /**
  5180. * Notifies CallStats that peer connection failed to add ICE candidate.
  5181. *
  5182. * @param {Error} e error to send
  5183. * @param {RTCPeerConnection} pc connection on which failure occured.
  5184. * @param {CallStats} cs callstats instance related to the error (optional)
  5185. */
  5186. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  5187. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  5188. });
  5189. module.exports = CallStats;
  5190. }).call(this,"/modules/statistics/CallStats.js")
  5191. },{"jitsi-meet-logger":50,"jssha":51,"socket.io-client":86}],23:[function(require,module,exports){
  5192. /* global config */
  5193. /**
  5194. * Provides statistics for the local stream.
  5195. */
  5196. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5197. /**
  5198. * Size of the webaudio analyzer buffer.
  5199. * @type {number}
  5200. */
  5201. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  5202. /**
  5203. * Value of the webaudio analyzer smoothing time parameter.
  5204. * @type {number}
  5205. */
  5206. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  5207. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  5208. var context = null;
  5209. if(window.AudioContext) {
  5210. context = new AudioContext();
  5211. }
  5212. /**
  5213. * Converts time domain data array to audio level.
  5214. * @param samples the time domain data array.
  5215. * @returns {number} the audio level
  5216. */
  5217. function timeDomainDataToAudioLevel(samples) {
  5218. var maxVolume = 0;
  5219. var length = samples.length;
  5220. for (var i = 0; i < length; i++) {
  5221. if (maxVolume < samples[i])
  5222. maxVolume = samples[i];
  5223. }
  5224. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5225. }
  5226. /**
  5227. * Animates audio level change
  5228. * @param newLevel the new audio level
  5229. * @param lastLevel the last audio level
  5230. * @returns {Number} the audio level to be set
  5231. */
  5232. function animateLevel(newLevel, lastLevel) {
  5233. var value = 0;
  5234. var diff = lastLevel - newLevel;
  5235. if(diff > 0.2) {
  5236. value = lastLevel - 0.2;
  5237. }
  5238. else if(diff < -0.4) {
  5239. value = lastLevel + 0.4;
  5240. }
  5241. else {
  5242. value = newLevel;
  5243. }
  5244. return parseFloat(value.toFixed(3));
  5245. }
  5246. /**
  5247. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5248. *
  5249. * @param stream the local stream
  5250. * @param interval stats refresh interval given in ms.
  5251. * @param callback function that receives the audio levels.
  5252. * @constructor
  5253. */
  5254. function LocalStatsCollector(stream, interval, callback) {
  5255. this.stream = stream;
  5256. this.intervalId = null;
  5257. this.intervalMilis = interval;
  5258. this.audioLevel = 0;
  5259. this.callback = callback;
  5260. }
  5261. /**
  5262. * Starts the collecting the statistics.
  5263. */
  5264. LocalStatsCollector.prototype.start = function () {
  5265. if (!context ||
  5266. RTCBrowserType.isTemasysPluginUsed())
  5267. return;
  5268. var analyser = context.createAnalyser();
  5269. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5270. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5271. var source = context.createMediaStreamSource(this.stream);
  5272. source.connect(analyser);
  5273. var self = this;
  5274. this.intervalId = setInterval(
  5275. function () {
  5276. var array = new Uint8Array(analyser.frequencyBinCount);
  5277. analyser.getByteTimeDomainData(array);
  5278. var audioLevel = timeDomainDataToAudioLevel(array);
  5279. if (audioLevel != self.audioLevel) {
  5280. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5281. self.callback(self.audioLevel);
  5282. }
  5283. },
  5284. this.intervalMilis
  5285. );
  5286. };
  5287. /**
  5288. * Stops collecting the statistics.
  5289. */
  5290. LocalStatsCollector.prototype.stop = function () {
  5291. if (this.intervalId) {
  5292. clearInterval(this.intervalId);
  5293. this.intervalId = null;
  5294. }
  5295. };
  5296. module.exports = LocalStatsCollector;
  5297. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5298. (function (__filename){
  5299. /* global require, ssrc2jid */
  5300. /* jshint -W117 */
  5301. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5302. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5303. var StatisticsEvents = require("../../service/statistics/Events");
  5304. /* Whether we support the browser we are running into for logging statistics */
  5305. var browserSupported = RTCBrowserType.isChrome() ||
  5306. RTCBrowserType.isOpera();
  5307. var keyMap = {};
  5308. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5309. "ssrc": "ssrc",
  5310. "packetsReceived": "packetsReceived",
  5311. "packetsLost": "packetsLost",
  5312. "packetsSent": "packetsSent",
  5313. "bytesReceived": "bytesReceived",
  5314. "bytesSent": "bytesSent"
  5315. };
  5316. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5317. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5318. "sendBandwidth": "googAvailableSendBandwidth",
  5319. "remoteAddress": "googRemoteAddress",
  5320. "transportType": "googTransportType",
  5321. "localAddress": "googLocalAddress",
  5322. "activeConnection": "googActiveConnection",
  5323. "ssrc": "ssrc",
  5324. "packetsReceived": "packetsReceived",
  5325. "packetsSent": "packetsSent",
  5326. "packetsLost": "packetsLost",
  5327. "bytesReceived": "bytesReceived",
  5328. "bytesSent": "bytesSent",
  5329. "googFrameHeightReceived": "googFrameHeightReceived",
  5330. "googFrameWidthReceived": "googFrameWidthReceived",
  5331. "googFrameHeightSent": "googFrameHeightSent",
  5332. "googFrameWidthSent": "googFrameWidthSent",
  5333. "audioInputLevel": "audioInputLevel",
  5334. "audioOutputLevel": "audioOutputLevel"
  5335. };
  5336. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5337. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5338. /**
  5339. * Calculates packet lost percent using the number of lost packets and the
  5340. * number of all packet.
  5341. * @param lostPackets the number of lost packets
  5342. * @param totalPackets the number of all packets.
  5343. * @returns {number} packet loss percent
  5344. */
  5345. function calculatePacketLoss(lostPackets, totalPackets) {
  5346. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5347. return 0;
  5348. return Math.round((lostPackets/totalPackets)*100);
  5349. }
  5350. function getStatValue(item, name) {
  5351. var browserType = RTCBrowserType.getBrowserType();
  5352. if (!keyMap[browserType][name])
  5353. throw "The property isn't supported!";
  5354. var key = keyMap[browserType][name];
  5355. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5356. item.stat(key) : item[key];
  5357. }
  5358. function formatAudioLevel(audioLevel) {
  5359. return Math.min(Math.max(audioLevel, 0), 1);
  5360. }
  5361. /**
  5362. * Checks whether a certain record should be included in the logged statistics.
  5363. */
  5364. function acceptStat(reportId, reportType, statName) {
  5365. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5366. return false;
  5367. if (reportType == "ssrc") {
  5368. if (statName == "googTrackId" ||
  5369. statName == "transportId" ||
  5370. statName == "ssrc")
  5371. return false;
  5372. }
  5373. return true;
  5374. }
  5375. /**
  5376. * Checks whether a certain record should be included in the logged statistics.
  5377. */
  5378. function acceptReport(id, type) {
  5379. if (id.substring(0, 15) == "googCertificate" ||
  5380. id.substring(0, 9) == "googTrack" ||
  5381. id.substring(0, 20) == "googLibjingleSession")
  5382. return false;
  5383. if (type == "googComponent")
  5384. return false;
  5385. return true;
  5386. }
  5387. /**
  5388. * Peer statistics data holder.
  5389. * @constructor
  5390. */
  5391. function PeerStats()
  5392. {
  5393. this.ssrc2Loss = {};
  5394. this.ssrc2AudioLevel = {};
  5395. this.ssrc2bitrate = {};
  5396. this.ssrc2resolution = {};
  5397. }
  5398. /**
  5399. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5400. * represented by this instance.
  5401. * @param lossRate new packet loss rate value to be set.
  5402. */
  5403. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5404. {
  5405. this.ssrc2Loss = lossRate;
  5406. };
  5407. /**
  5408. * Sets resolution that belong to the ssrc
  5409. * represented by this instance.
  5410. * @param resolution new resolution value to be set.
  5411. */
  5412. PeerStats.prototype.setSsrcResolution = function (resolution)
  5413. {
  5414. if(resolution === null && this.ssrc2resolution[ssrc])
  5415. {
  5416. delete this.ssrc2resolution[ssrc];
  5417. }
  5418. else if(resolution !== null)
  5419. this.ssrc2resolution[ssrc] = resolution;
  5420. };
  5421. /**
  5422. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5423. * represented by this instance.
  5424. * @param ssrc audio or video RTP stream SSRC.
  5425. * @param bitrate new bitrate value to be set.
  5426. */
  5427. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5428. {
  5429. if(this.ssrc2bitrate[ssrc])
  5430. {
  5431. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5432. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5433. }
  5434. else {
  5435. this.ssrc2bitrate[ssrc] = bitrate;
  5436. }
  5437. };
  5438. /**
  5439. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5440. * the stream which belongs to the peer represented by this instance.
  5441. * @param ssrc RTP stream SSRC for which current audio level value will be
  5442. * updated.
  5443. * @param audioLevel the new audio level value to be set. Value is truncated to
  5444. * fit the range from 0 to 1.
  5445. */
  5446. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5447. {
  5448. // Range limit 0 - 1
  5449. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5450. };
  5451. function ConferenceStats() {
  5452. /**
  5453. * The bandwidth
  5454. * @type {{}}
  5455. */
  5456. this.bandwidth = {};
  5457. /**
  5458. * The bit rate
  5459. * @type {{}}
  5460. */
  5461. this.bitrate = {};
  5462. /**
  5463. * The packet loss rate
  5464. * @type {{}}
  5465. */
  5466. this.packetLoss = null;
  5467. /**
  5468. * Array with the transport information.
  5469. * @type {Array}
  5470. */
  5471. this.transport = [];
  5472. }
  5473. /**
  5474. * <tt>StatsCollector</tt> registers for stats updates of given
  5475. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5476. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5477. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5478. * instance as an event source.
  5479. *
  5480. * @param peerconnection webRTC peer connection object.
  5481. * @param interval stats refresh interval given in ms.
  5482. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5483. * called on stats update.
  5484. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5485. * @constructor
  5486. */
  5487. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5488. {
  5489. this.peerconnection = peerconnection;
  5490. this.baselineAudioLevelsReport = null;
  5491. this.currentAudioLevelsReport = null;
  5492. this.currentStatsReport = null;
  5493. this.baselineStatsReport = null;
  5494. this.audioLevelsIntervalId = null;
  5495. this.eventEmitter = eventEmitter;
  5496. this.config = config || {};
  5497. this.conferenceStats = new ConferenceStats();
  5498. /**
  5499. * Gather PeerConnection stats once every this many milliseconds.
  5500. */
  5501. this.GATHER_INTERVAL = 15000;
  5502. /**
  5503. * Log stats via the focus once every this many milliseconds.
  5504. */
  5505. this.LOG_INTERVAL = 60000;
  5506. /**
  5507. * Gather stats and store them in this.statsToBeLogged.
  5508. */
  5509. this.gatherStatsIntervalId = null;
  5510. /**
  5511. * Send the stats already saved in this.statsToBeLogged to be logged via
  5512. * the focus.
  5513. */
  5514. this.logStatsIntervalId = null;
  5515. /**
  5516. * Stores the statistics which will be send to the focus to be logged.
  5517. */
  5518. this.statsToBeLogged =
  5519. {
  5520. timestamps: [],
  5521. stats: {}
  5522. };
  5523. // Updates stats interval
  5524. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5525. this.statsIntervalId = null;
  5526. this.statsIntervalMilis = statsInterval;
  5527. // Map of ssrcs to PeerStats
  5528. this.ssrc2stats = {};
  5529. }
  5530. module.exports = StatsCollector;
  5531. /**
  5532. * Stops stats updates.
  5533. */
  5534. StatsCollector.prototype.stop = function () {
  5535. if (this.audioLevelsIntervalId) {
  5536. clearInterval(this.audioLevelsIntervalId);
  5537. this.audioLevelsIntervalId = null;
  5538. }
  5539. if (this.statsIntervalId)
  5540. {
  5541. clearInterval(this.statsIntervalId);
  5542. this.statsIntervalId = null;
  5543. }
  5544. if(this.logStatsIntervalId)
  5545. {
  5546. clearInterval(this.logStatsIntervalId);
  5547. this.logStatsIntervalId = null;
  5548. }
  5549. if(this.gatherStatsIntervalId)
  5550. {
  5551. clearInterval(this.gatherStatsIntervalId);
  5552. this.gatherStatsIntervalId = null;
  5553. }
  5554. };
  5555. /**
  5556. * Callback passed to <tt>getStats</tt> method.
  5557. * @param error an error that occurred on <tt>getStats</tt> call.
  5558. */
  5559. StatsCollector.prototype.errorCallback = function (error)
  5560. {
  5561. logger.error("Get stats error", error);
  5562. this.stop();
  5563. };
  5564. /**
  5565. * Starts stats updates.
  5566. */
  5567. StatsCollector.prototype.start = function ()
  5568. {
  5569. var self = this;
  5570. this.audioLevelsIntervalId = setInterval(
  5571. function () {
  5572. // Interval updates
  5573. self.peerconnection.getStats(
  5574. function (report) {
  5575. var results = null;
  5576. if (!report || !report.result ||
  5577. typeof report.result != 'function') {
  5578. results = report;
  5579. }
  5580. else {
  5581. results = report.result();
  5582. }
  5583. //logger.error("Got interval report", results);
  5584. self.currentAudioLevelsReport = results;
  5585. self.processAudioLevelReport();
  5586. self.baselineAudioLevelsReport =
  5587. self.currentAudioLevelsReport;
  5588. },
  5589. self.errorCallback
  5590. );
  5591. },
  5592. self.audioLevelsIntervalMilis
  5593. );
  5594. // if (!this.config.disableStats && browserSupported) {
  5595. // this.statsIntervalId = setInterval(
  5596. // function () {
  5597. // // Interval updates
  5598. // self.peerconnection.getStats(
  5599. // function (report) {
  5600. // var results = null;
  5601. // if (!report || !report.result ||
  5602. // typeof report.result != 'function') {
  5603. // //firefox
  5604. // results = report;
  5605. // }
  5606. // else {
  5607. // //chrome
  5608. // results = report.result();
  5609. // }
  5610. // //logger.error("Got interval report", results);
  5611. // self.currentStatsReport = results;
  5612. // try {
  5613. // self.processStatsReport();
  5614. // }
  5615. // catch (e) {
  5616. // logger.error("Unsupported key:" + e, e);
  5617. // }
  5618. //
  5619. // self.baselineStatsReport = self.currentStatsReport;
  5620. // },
  5621. // self.errorCallback
  5622. // );
  5623. // },
  5624. // self.statsIntervalMilis
  5625. // );
  5626. // }
  5627. //
  5628. // if (this.config.logStats && browserSupported) {
  5629. // this.gatherStatsIntervalId = setInterval(
  5630. // function () {
  5631. // self.peerconnection.getStats(
  5632. // function (report) {
  5633. // self.addStatsToBeLogged(report.result());
  5634. // },
  5635. // function () {
  5636. // }
  5637. // );
  5638. // },
  5639. // this.GATHER_INTERVAL
  5640. // );
  5641. //
  5642. // this.logStatsIntervalId = setInterval(
  5643. // function() { self.logStats(); },
  5644. // this.LOG_INTERVAL);
  5645. // }
  5646. };
  5647. /**
  5648. * Converts the stats to the format used for logging, and saves the data in
  5649. * this.statsToBeLogged.
  5650. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5651. */
  5652. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5653. var self = this;
  5654. var num_records = this.statsToBeLogged.timestamps.length;
  5655. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5656. reports.map(function (report) {
  5657. if (!acceptReport(report.id, report.type))
  5658. return;
  5659. var stat = self.statsToBeLogged.stats[report.id];
  5660. if (!stat) {
  5661. stat = self.statsToBeLogged.stats[report.id] = {};
  5662. }
  5663. stat.type = report.type;
  5664. report.names().map(function (name) {
  5665. if (!acceptStat(report.id, report.type, name))
  5666. return;
  5667. var values = stat[name];
  5668. if (!values) {
  5669. values = stat[name] = [];
  5670. }
  5671. while (values.length < num_records) {
  5672. values.push(null);
  5673. }
  5674. values.push(report.stat(name));
  5675. });
  5676. });
  5677. };
  5678. //FIXME:
  5679. //StatsCollector.prototype.logStats = function () {
  5680. //
  5681. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5682. // return;
  5683. // // Reset the stats
  5684. // this.statsToBeLogged.stats = {};
  5685. // this.statsToBeLogged.timestamps = [];
  5686. //};
  5687. /**
  5688. * Stats processing logic.
  5689. */
  5690. StatsCollector.prototype.processStatsReport = function () {
  5691. if (!this.baselineStatsReport) {
  5692. return;
  5693. }
  5694. for (var idx in this.currentStatsReport) {
  5695. var now = this.currentStatsReport[idx];
  5696. try {
  5697. if (getStatValue(now, 'receiveBandwidth') ||
  5698. getStatValue(now, 'sendBandwidth')) {
  5699. this.conferenceStats.bandwidth = {
  5700. "download": Math.round(
  5701. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5702. "upload": Math.round(
  5703. (getStatValue(now, 'sendBandwidth')) / 1000)
  5704. };
  5705. }
  5706. }
  5707. catch(e){/*not supported*/}
  5708. if(now.type == 'googCandidatePair')
  5709. {
  5710. var ip, type, localIP, active;
  5711. try {
  5712. ip = getStatValue(now, 'remoteAddress');
  5713. type = getStatValue(now, "transportType");
  5714. localIP = getStatValue(now, "localAddress");
  5715. active = getStatValue(now, "activeConnection");
  5716. }
  5717. catch(e){/*not supported*/}
  5718. if(!ip || !type || !localIP || active != "true")
  5719. continue;
  5720. var addressSaved = false;
  5721. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5722. {
  5723. if(this.conferenceStats.transport[i].ip == ip &&
  5724. this.conferenceStats.transport[i].type == type &&
  5725. this.conferenceStats.transport[i].localip == localIP)
  5726. {
  5727. addressSaved = true;
  5728. }
  5729. }
  5730. if(addressSaved)
  5731. continue;
  5732. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5733. continue;
  5734. }
  5735. if(now.type == "candidatepair")
  5736. {
  5737. if(now.state == "succeeded")
  5738. continue;
  5739. var local = this.currentStatsReport[now.localCandidateId];
  5740. var remote = this.currentStatsReport[now.remoteCandidateId];
  5741. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5742. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5743. }
  5744. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5745. now.type != "inboundrtp") {
  5746. continue;
  5747. }
  5748. var before = this.baselineStatsReport[idx];
  5749. if (!before) {
  5750. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5751. continue;
  5752. }
  5753. var ssrc = getStatValue(now, 'ssrc');
  5754. if(!ssrc)
  5755. continue;
  5756. var ssrcStats = this.ssrc2stats[ssrc];
  5757. if (!ssrcStats) {
  5758. ssrcStats = new PeerStats();
  5759. this.ssrc2stats[ssrc] = ssrcStats;
  5760. }
  5761. var isDownloadStream = true;
  5762. var key = 'packetsReceived';
  5763. var packetsNow = getStatValue(now, key);
  5764. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5765. isDownloadStream = false;
  5766. key = 'packetsSent';
  5767. packetsNow = getStatValue(now, key);
  5768. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5769. console.warn("No packetsReceived nor packetsSent stat found");
  5770. continue;
  5771. }
  5772. }
  5773. if (!packetsNow || packetsNow < 0)
  5774. packetsNow = 0;
  5775. var packetsBefore = getStatValue(before, key);
  5776. if (!packetsBefore || packetsBefore < 0)
  5777. packetsBefore = 0;
  5778. var packetRate = packetsNow - packetsBefore;
  5779. if (!packetRate || packetRate < 0)
  5780. packetRate = 0;
  5781. var currentLoss = getStatValue(now, 'packetsLost');
  5782. if (!currentLoss || currentLoss < 0)
  5783. currentLoss = 0;
  5784. var previousLoss = getStatValue(before, 'packetsLost');
  5785. if (!previousLoss || previousLoss < 0)
  5786. previousLoss = 0;
  5787. var lossRate = currentLoss - previousLoss;
  5788. if (!lossRate || lossRate < 0)
  5789. lossRate = 0;
  5790. var packetsTotal = (packetRate + lossRate);
  5791. ssrcStats.setSsrcLoss(ssrc,
  5792. {"packetsTotal": packetsTotal,
  5793. "packetsLost": lossRate,
  5794. "isDownloadStream": isDownloadStream});
  5795. var bytesReceived = 0, bytesSent = 0;
  5796. if(getStatValue(now, "bytesReceived")) {
  5797. bytesReceived = getStatValue(now, "bytesReceived") -
  5798. getStatValue(before, "bytesReceived");
  5799. }
  5800. if (getStatValue(now, "bytesSent")) {
  5801. bytesSent = getStatValue(now, "bytesSent") -
  5802. getStatValue(before, "bytesSent");
  5803. }
  5804. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5805. if (bytesReceived <= 0 || time <= 0) {
  5806. bytesReceived = 0;
  5807. } else {
  5808. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5809. }
  5810. if (bytesSent <= 0 || time <= 0) {
  5811. bytesSent = 0;
  5812. } else {
  5813. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5814. }
  5815. ssrcStats.setSsrcBitrate(ssrc, {
  5816. "download": bytesReceived,
  5817. "upload": bytesSent});
  5818. var resolution = {height: null, width: null};
  5819. try {
  5820. if (getStatValue(now, "googFrameHeightReceived") &&
  5821. getStatValue(now, "googFrameWidthReceived")) {
  5822. resolution.height =
  5823. getStatValue(now, "googFrameHeightReceived");
  5824. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5825. }
  5826. else if (getStatValue(now, "googFrameHeightSent") &&
  5827. getStatValue(now, "googFrameWidthSent")) {
  5828. resolution.height = getStatValue(now, "googFrameHeightSent");
  5829. resolution.width = getStatValue(now, "googFrameWidthSent");
  5830. }
  5831. }
  5832. catch(e){/*not supported*/}
  5833. if (resolution.height && resolution.width) {
  5834. ssrcStats.setSsrcResolution(ssrc, resolution);
  5835. } else {
  5836. ssrcStats.setSsrcResolution(ssrc, null);
  5837. }
  5838. }
  5839. var self = this;
  5840. // Jid stats
  5841. var totalPackets = {download: 0, upload: 0};
  5842. var lostPackets = {download: 0, upload: 0};
  5843. var bitrateDownload = 0;
  5844. var bitrateUpload = 0;
  5845. var resolutions = {};
  5846. Object.keys(this.ssrc2stats).forEach(
  5847. function (jid) {
  5848. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5849. function (ssrc) {
  5850. var type = "upload";
  5851. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5852. type = "download";
  5853. totalPackets[type] +=
  5854. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5855. lostPackets[type] +=
  5856. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5857. }
  5858. );
  5859. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5860. function (ssrc) {
  5861. bitrateDownload +=
  5862. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5863. bitrateUpload +=
  5864. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5865. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5866. }
  5867. );
  5868. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5869. }
  5870. );
  5871. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5872. this.conferenceStats.packetLoss = {
  5873. total:
  5874. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5875. totalPackets.download + totalPackets.upload),
  5876. download:
  5877. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5878. upload:
  5879. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5880. };
  5881. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5882. {
  5883. "bitrate": this.conferenceStats.bitrate,
  5884. "packetLoss": this.conferenceStats.packetLoss,
  5885. "bandwidth": this.conferenceStats.bandwidth,
  5886. "resolution": resolutions,
  5887. "transport": this.conferenceStats.transport
  5888. });
  5889. this.conferenceStats.transport = [];
  5890. };
  5891. /**
  5892. * Stats processing logic.
  5893. */
  5894. StatsCollector.prototype.processAudioLevelReport = function () {
  5895. if (!this.baselineAudioLevelsReport) {
  5896. return;
  5897. }
  5898. for (var idx in this.currentAudioLevelsReport) {
  5899. var now = this.currentAudioLevelsReport[idx];
  5900. //if we don't have "packetsReceived" this is local stream
  5901. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5902. continue;
  5903. }
  5904. var before = this.baselineAudioLevelsReport[idx];
  5905. if (!before) {
  5906. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5907. continue;
  5908. }
  5909. var ssrc = getStatValue(now, 'ssrc');
  5910. if (!ssrc) {
  5911. if((Date.now() - now.timestamp) < 3000)
  5912. logger.warn("No ssrc: ");
  5913. continue;
  5914. }
  5915. var ssrcStats = this.ssrc2stats[ssrc];
  5916. if (!ssrcStats) {
  5917. ssrcStats = new PeerStats();
  5918. this.ssrc2stats[ssrc] = ssrcStats;
  5919. }
  5920. // Audio level
  5921. var audioLevel = null;
  5922. try {
  5923. audioLevel = getStatValue(now, 'audioInputLevel');
  5924. if (!audioLevel)
  5925. audioLevel = getStatValue(now, 'audioOutputLevel');
  5926. }
  5927. catch(e) {/*not supported*/
  5928. logger.warn("Audio Levels are not available in the statistics.");
  5929. clearInterval(this.audioLevelsIntervalId);
  5930. return;
  5931. }
  5932. if (audioLevel) {
  5933. // TODO: can't find specs about what this value really is,
  5934. // but it seems to vary between 0 and around 32k.
  5935. audioLevel = audioLevel / 32767;
  5936. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5937. this.eventEmitter.emit(
  5938. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5939. }
  5940. }
  5941. };
  5942. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5943. },{"../../service/statistics/Events":141,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],25:[function(require,module,exports){
  5944. /* global require, APP */
  5945. var LocalStats = require("./LocalStatsCollector.js");
  5946. var RTPStats = require("./RTPStatsCollector.js");
  5947. var EventEmitter = require("events");
  5948. var StatisticsEvents = require("../../service/statistics/Events");
  5949. var CallStats = require("./CallStats");
  5950. var ScriptUtil = require('../util/ScriptUtil');
  5951. // Since callstats.io is a third party, we cannot guarantee the quality of
  5952. // their service. More specifically, their server may take noticeably long
  5953. // time to respond. Consequently, it is in our best interest (in the sense
  5954. // that the intergration of callstats.io is pretty important to us but not
  5955. // enough to allow it to prevent people from joining a conference) to (1)
  5956. // start downloading their API as soon as possible and (2) do the
  5957. // downloading asynchronously.
  5958. function loadCallStatsAPI() {
  5959. ScriptUtil.loadScript(
  5960. 'https://api.callstats.io/static/callstats.min.js',
  5961. /* async */ true,
  5962. /* prepend */ true);
  5963. // FIXME At the time of this writing, we hope that the callstats.io API will
  5964. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5965. }
  5966. var eventEmitter = new EventEmitter();
  5967. function Statistics(options) {
  5968. this.rtpStats = null;
  5969. this.eventEmitter = new EventEmitter();
  5970. this.options = options || {};
  5971. this.callStatsIntegrationEnabled
  5972. = this.options.callStatsID && this.options.callStatsSecret
  5973. // Even though AppID and AppSecret may be specified, the integration of
  5974. // callstats.io may be disabled because of globally-disallowed requests
  5975. // to any third parties.
  5976. && (this.options.disableThirdPartyRequests !== true);
  5977. if(this.callStatsIntegrationEnabled)
  5978. loadCallStatsAPI();
  5979. this.callStats = null;
  5980. }
  5981. Statistics.audioLevelsEnabled = false;
  5982. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5983. if(!Statistics.audioLevelsEnabled)
  5984. return;
  5985. if (this.rtpStats) {
  5986. this.rtpStats.stop();
  5987. }
  5988. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5989. this.rtpStats.start();
  5990. }
  5991. Statistics.localStats = [];
  5992. Statistics.startLocalStats = function (stream, callback) {
  5993. if(!Statistics.audioLevelsEnabled)
  5994. return;
  5995. var localStats = new LocalStats(stream, 200, callback);
  5996. this.localStats.push(localStats);
  5997. localStats.start();
  5998. }
  5999. Statistics.prototype.addAudioLevelListener = function(listener)
  6000. {
  6001. if(!Statistics.audioLevelsEnabled)
  6002. return;
  6003. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  6004. }
  6005. Statistics.prototype.removeAudioLevelListener = function(listener)
  6006. {
  6007. if(!Statistics.audioLevelsEnabled)
  6008. return;
  6009. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  6010. }
  6011. Statistics.prototype.dispose = function () {
  6012. if(Statistics.audioLevelsEnabled) {
  6013. Statistics.stopAllLocalStats();
  6014. this.stopRemote();
  6015. if(this.eventEmitter)
  6016. this.eventEmitter.removeAllListeners();
  6017. if(eventEmitter)
  6018. eventEmitter.removeAllListeners();
  6019. }
  6020. if(this.callstats)
  6021. {
  6022. this.callstats.sendTerminateEvent();
  6023. this.callstats = null;
  6024. }
  6025. }
  6026. Statistics.stopAllLocalStats = function () {
  6027. if(!Statistics.audioLevelsEnabled)
  6028. return;
  6029. for(var i = 0; i < this.localStats.length; i++)
  6030. this.localStats[i].stop();
  6031. this.localStats = [];
  6032. }
  6033. Statistics.stopLocalStats = function (stream) {
  6034. if(!Statistics.audioLevelsEnabled)
  6035. return;
  6036. for(var i = 0; i < Statistics.localStats.length; i++)
  6037. if(Statistics.localStats[i].stream === stream){
  6038. var localStats = Statistics.localStats.splice(i, 1);
  6039. localStats.stop();
  6040. break;
  6041. }
  6042. }
  6043. Statistics.prototype.stopRemote = function () {
  6044. if (this.rtpStats && Statistics.audioLevelsEnabled) {
  6045. this.rtpStats.stop();
  6046. this.eventEmitter.emit(StatisticsEvents.STOP);
  6047. this.rtpStats = null;
  6048. }
  6049. };
  6050. /**
  6051. * Obtains audio level reported in the stats for specified peer.
  6052. * @param peerJid full MUC jid of the user for whom we want to obtain last
  6053. * audio level.
  6054. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  6055. * level.
  6056. * @returns {*} a float form 0 to 1 that represents current audio level or
  6057. * <tt>null</tt> if for any reason the value is not available
  6058. * at this time.
  6059. */
  6060. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  6061. if(!Statistics.audioLevelsEnabled)
  6062. return;
  6063. var peerStats = this.rtpStats.jid2stats[peerJid];
  6064. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  6065. };
  6066. //CALSTATS METHODS
  6067. /**
  6068. * Initializes the callstats.io API.
  6069. * @param peerConnection {JingleSessionPC} the session object
  6070. * @param Settings {Settings} the settings instance. Declared in
  6071. * /modules/settings/Settings.js
  6072. */
  6073. Statistics.prototype.startCallStats = function (session, settings) {
  6074. if(this.callStatsIntegrationEnabled && !this.callstats) {
  6075. this.callstats = new CallStats(session, settings, this.options);
  6076. }
  6077. }
  6078. /**
  6079. * Returns true if the callstats integration is enabled, otherwise returns
  6080. * false.
  6081. *
  6082. * @returns true if the callstats integration is enabled, otherwise returns
  6083. * false.
  6084. */
  6085. Statistics.prototype.isCallstatsEnabled = function () {
  6086. return this.callStatsIntegrationEnabled;
  6087. }
  6088. /**
  6089. * Notifies CallStats for connection setup errors
  6090. */
  6091. Statistics.prototype.sendSetupFailedEvent = function () {
  6092. if(this.callStatsIntegrationEnabled && this.callstats)
  6093. this.callstats.sendSetupFailedEvent();
  6094. }
  6095. /**
  6096. * Notifies CallStats for mute events
  6097. * @param mute {boolean} true for muted and false for not muted
  6098. * @param type {String} "audio"/"video"
  6099. */
  6100. Statistics.prototype.sendMuteEvent = function (muted, type) {
  6101. if(this.callStatsIntegrationEnabled)
  6102. CallStats.sendMuteEvent(muted, type, this.callstats);
  6103. }
  6104. /**
  6105. * Notifies CallStats that getUserMedia failed.
  6106. *
  6107. * @param {Error} e error to send
  6108. */
  6109. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  6110. if(this.callStatsIntegrationEnabled)
  6111. CallStats.sendGetUserMediaFailed(e, this.callstats);
  6112. };
  6113. /**
  6114. * Notifies CallStats that getUserMedia failed.
  6115. *
  6116. * @param {Error} e error to send
  6117. */
  6118. Statistics.sendGetUserMediaFailed = function (e) {
  6119. CallStats.sendGetUserMediaFailed(e, null);
  6120. };
  6121. /**
  6122. * Notifies CallStats that peer connection failed to create offer.
  6123. *
  6124. * @param {Error} e error to send
  6125. * @param {RTCPeerConnection} pc connection on which failure occured.
  6126. */
  6127. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  6128. if(this.callStatsIntegrationEnabled)
  6129. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  6130. };
  6131. /**
  6132. * Notifies CallStats that peer connection failed to create answer.
  6133. *
  6134. * @param {Error} e error to send
  6135. * @param {RTCPeerConnection} pc connection on which failure occured.
  6136. */
  6137. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  6138. if(this.callStatsIntegrationEnabled)
  6139. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  6140. };
  6141. /**
  6142. * Notifies CallStats that peer connection failed to set local description.
  6143. *
  6144. * @param {Error} e error to send
  6145. * @param {RTCPeerConnection} pc connection on which failure occured.
  6146. */
  6147. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  6148. if(this.callStatsIntegrationEnabled)
  6149. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  6150. }
  6151. /**
  6152. * Notifies CallStats that peer connection failed to set remote description.
  6153. *
  6154. * @param {Error} e error to send
  6155. * @param {RTCPeerConnection} pc connection on which failure occured.
  6156. */
  6157. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  6158. if(this.callStatsIntegrationEnabled)
  6159. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  6160. }
  6161. /**
  6162. * Notifies CallStats that peer connection failed to add ICE candidate.
  6163. *
  6164. * @param {Error} e error to send
  6165. * @param {RTCPeerConnection} pc connection on which failure occured.
  6166. */
  6167. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  6168. if(this.callStatsIntegrationEnabled)
  6169. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  6170. }
  6171. /**
  6172. * Sends the given feedback through CallStats.
  6173. *
  6174. * @param overallFeedback an integer between 1 and 5 indicating the
  6175. * user feedback
  6176. * @param detailedFeedback detailed feedback from the user. Not yet used
  6177. */
  6178. Statistics.prototype.sendFeedback =
  6179. function(overallFeedback, detailedFeedback){
  6180. if(this.callStatsIntegrationEnabled && this.callstats)
  6181. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  6182. }
  6183. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  6184. module.exports = Statistics;
  6185. },{"../../service/statistics/Events":141,"../../service/statistics/constants":142,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":46}],26:[function(require,module,exports){
  6186. /**
  6187. /**
  6188. * @const
  6189. */
  6190. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6191. /**
  6192. * Hexadecimal digits.
  6193. * @const
  6194. */
  6195. var HEX_DIGITS = '0123456789abcdef';
  6196. /**
  6197. * Generates random int within the range [min, max]
  6198. * @param min the minimum value for the generated number
  6199. * @param max the maximum value for the generated number
  6200. * @returns random int number
  6201. */
  6202. function randomInt(min, max) {
  6203. return Math.floor(Math.random() * (max - min + 1)) + min;
  6204. }
  6205. /**
  6206. * Get random element from array or string.
  6207. * @param {Array|string} arr source
  6208. * @returns array element or string character
  6209. */
  6210. function randomElement(arr) {
  6211. return arr[randomInt(0, arr.length - 1)];
  6212. }
  6213. /**
  6214. * Generate random alphanumeric string.
  6215. * @param {number} length expected string length
  6216. * @returns {string} random string of specified length
  6217. */
  6218. function randomAlphanumStr(length) {
  6219. var result = '';
  6220. for (var i = 0; i < length; i += 1) {
  6221. result += randomElement(ALPHANUM);
  6222. }
  6223. return result;
  6224. }
  6225. /**
  6226. * Exported interface.
  6227. */
  6228. var RandomUtil = {
  6229. /**
  6230. * Returns a random hex digit.
  6231. * @returns {*}
  6232. */
  6233. randomHexDigit: function() {
  6234. return randomElement(HEX_DIGITS);
  6235. },
  6236. /**
  6237. * Returns a random string of hex digits with length 'len'.
  6238. * @param len the length.
  6239. */
  6240. randomHexString: function (len) {
  6241. var ret = '';
  6242. while (len--) {
  6243. ret += this.randomHexDigit();
  6244. }
  6245. return ret;
  6246. },
  6247. randomElement: randomElement,
  6248. randomAlphanumStr: randomAlphanumStr,
  6249. randomInt: randomInt
  6250. };
  6251. module.exports = RandomUtil;
  6252. },{}],27:[function(require,module,exports){
  6253. /**
  6254. * Implements utility functions which facilitate the dealing with scripts such
  6255. * as the download and execution of a JavaScript file.
  6256. */
  6257. var ScriptUtil = {
  6258. /**
  6259. * Loads a script from a specific source.
  6260. *
  6261. * @param src the source from the which the script is to be (down)loaded
  6262. * @param async true to asynchronously load the script or false to
  6263. * synchronously load the script
  6264. * @param prepend true to schedule the loading of the script as soon as
  6265. * possible or false to schedule the loading of the script at the end of the
  6266. * scripts known at the time
  6267. */
  6268. loadScript: function (src, async, prepend) {
  6269. var d = document;
  6270. var tagName = 'script';
  6271. var script = d.createElement(tagName);
  6272. var referenceNode = d.getElementsByTagName(tagName)[0];
  6273. script.async = async;
  6274. script.src = src;
  6275. if (prepend) {
  6276. referenceNode.parentNode.insertBefore(script, referenceNode);
  6277. } else {
  6278. referenceNode.parentNode.appendChild(script);
  6279. }
  6280. },
  6281. };
  6282. module.exports = ScriptUtil;
  6283. },{}],28:[function(require,module,exports){
  6284. var RandomUtil = require('./RandomUtil');
  6285. /**
  6286. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6287. * MIT License
  6288. * http://github.com/marak/faker.js/
  6289. *
  6290. * @const
  6291. */
  6292. var names = [
  6293. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6294. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6295. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6296. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6297. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6298. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6299. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6300. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6301. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6302. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6303. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6304. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6305. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6306. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6307. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6308. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6309. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6310. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6311. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6312. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6313. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6314. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6315. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6316. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6317. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6318. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6319. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6320. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6321. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6322. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6323. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6324. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6325. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6326. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6327. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6328. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6329. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6330. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6331. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6332. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6333. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6334. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6335. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6336. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6337. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6338. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6339. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6340. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6341. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6342. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6343. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6344. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6345. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6346. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6347. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6348. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6349. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6350. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6351. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6352. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6353. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6354. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6355. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6356. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6357. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6358. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6359. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6360. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6361. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6362. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6363. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6364. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6365. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6366. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6367. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6368. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6369. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6370. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6371. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6372. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6373. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6374. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6375. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6376. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6377. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6378. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6379. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6380. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6381. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6382. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6383. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6384. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6385. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6386. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6387. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6388. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6389. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6390. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6391. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6392. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6393. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6394. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6395. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6396. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6397. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6398. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6399. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6400. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6401. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6402. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6403. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6404. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6405. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6406. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6407. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6408. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6409. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6410. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6411. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6412. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6413. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6414. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6415. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6416. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6417. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6418. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6419. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6420. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6421. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6422. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6423. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6424. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6425. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6426. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6427. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6428. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6429. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6430. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6431. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6432. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6433. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6434. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6435. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6436. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6437. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6438. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6439. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6440. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6441. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6442. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6443. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6444. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6445. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6446. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6447. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6448. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6449. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6450. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6451. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6452. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6453. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6454. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6455. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6456. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6457. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6458. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6459. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6460. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6461. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6462. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6463. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6464. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6465. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6466. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6467. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6468. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6469. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6470. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6471. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6472. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6473. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6474. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6475. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6476. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6477. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6478. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6479. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6480. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6481. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6482. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6483. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6484. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6485. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6486. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6487. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6488. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6489. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6490. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6491. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6492. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6493. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6494. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6495. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6496. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6497. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6498. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6499. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6500. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6501. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6502. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6503. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6504. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6505. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6506. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6507. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6508. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6509. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6510. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6511. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6512. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6513. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6514. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6515. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6516. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6517. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6518. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6519. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6520. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6521. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6522. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6523. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6524. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6525. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6526. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6527. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6528. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6529. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6530. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6531. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6532. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6533. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6534. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6535. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6536. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6537. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6538. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6539. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6540. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6541. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6542. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6543. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6544. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6545. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6546. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6547. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6548. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6549. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6550. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6551. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6552. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6553. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6554. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6555. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6556. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6557. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6558. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6559. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6560. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6561. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6562. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6563. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6564. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6565. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6566. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6567. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6568. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6569. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6570. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6571. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6572. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6573. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6574. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6575. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6576. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6577. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6578. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6579. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6580. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6581. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6582. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6583. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6584. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6585. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6586. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6587. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6588. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6589. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6590. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6591. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6592. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6593. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6594. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6595. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6596. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6597. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6598. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6599. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6600. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6601. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6602. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6603. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6604. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6605. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6606. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6607. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6608. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6609. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6610. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6611. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6612. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6613. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6614. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6615. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6616. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6617. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6618. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6619. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6620. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6621. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6622. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6623. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6624. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6625. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6626. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6627. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6628. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6629. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6630. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6631. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6632. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6633. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6634. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6635. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6636. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6637. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6638. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6639. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6640. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6641. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6642. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6643. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6644. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6645. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6646. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6647. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6648. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6649. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6650. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6651. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6652. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6653. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6654. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6655. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6656. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6657. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6658. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6659. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6660. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6661. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6662. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6663. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6664. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6665. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6666. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6667. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6668. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6669. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6670. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6671. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6672. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6673. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6674. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6675. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6676. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6677. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6678. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6679. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6680. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6681. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6682. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6683. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6684. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6685. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6686. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6687. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6688. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6689. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6690. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6691. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6692. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6693. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6694. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6695. "Zora", "Zula"
  6696. ];
  6697. /**
  6698. * Generate random username.
  6699. * @returns {string} random username
  6700. */
  6701. function generateUsername () {
  6702. var name = RandomUtil.randomElement(names);
  6703. var suffix = RandomUtil.randomAlphanumStr(3);
  6704. return name + '-' + suffix;
  6705. }
  6706. module.exports = {
  6707. generateUsername: generateUsername
  6708. };
  6709. },{"./RandomUtil":26}],29:[function(require,module,exports){
  6710. (function (__filename){
  6711. /* global Strophe, $, $pres, $iq, $msg */
  6712. /* jshint -W101,-W069 */
  6713. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6714. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6715. var Moderator = require("./moderator");
  6716. var EventEmitter = require("events");
  6717. var Recorder = require("./recording");
  6718. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6719. var parser = {
  6720. packet2JSON: function (packet, nodes) {
  6721. var self = this;
  6722. $(packet).children().each(function (index) {
  6723. var tagName = $(this).prop("tagName");
  6724. var node = {
  6725. tagName: tagName
  6726. };
  6727. node.attributes = {};
  6728. $($(this)[0].attributes).each(function( index, attr ) {
  6729. node.attributes[ attr.name ] = attr.value;
  6730. });
  6731. var text = Strophe.getText($(this)[0]);
  6732. if (text) {
  6733. node.value = text;
  6734. }
  6735. node.children = [];
  6736. nodes.push(node);
  6737. self.packet2JSON($(this), node.children);
  6738. });
  6739. },
  6740. JSON2packet: function (nodes, packet) {
  6741. for(var i = 0; i < nodes.length; i++) {
  6742. var node = nodes[i];
  6743. if(!node || node === null){
  6744. continue;
  6745. }
  6746. packet.c(node.tagName, node.attributes);
  6747. if(node.value)
  6748. packet.t(node.value);
  6749. if(node.children)
  6750. this.JSON2packet(node.children, packet);
  6751. packet.up();
  6752. }
  6753. // packet.up();
  6754. }
  6755. };
  6756. /**
  6757. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6758. * @param pres the presence JSON
  6759. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6760. */
  6761. function filterNodeFromPresenceJSON(pres, nodeName){
  6762. var res = [];
  6763. for(var i = 0; i < pres.length; i++)
  6764. if(pres[i].tagName === nodeName)
  6765. res.push(pres[i]);
  6766. return res;
  6767. }
  6768. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6769. this.eventEmitter = new EventEmitter();
  6770. this.xmpp = XMPP;
  6771. this.connection = connection;
  6772. this.roomjid = Strophe.getBareJidFromJid(jid);
  6773. this.myroomjid = jid;
  6774. this.password = password;
  6775. logger.info("Joined MUC as " + this.myroomjid);
  6776. this.members = {};
  6777. this.presMap = {};
  6778. this.presHandlers = {};
  6779. this.joined = false;
  6780. this.role = 'none';
  6781. this.focusMucJid = null;
  6782. this.bridgeIsDown = false;
  6783. this.options = options || {};
  6784. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6785. settings);
  6786. this.initPresenceMap();
  6787. this.session = null;
  6788. var self = this;
  6789. this.lastPresences = {};
  6790. this.phoneNumber = null;
  6791. this.phonePin = null;
  6792. }
  6793. ChatRoom.prototype.initPresenceMap = function () {
  6794. this.presMap['to'] = this.myroomjid;
  6795. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6796. this.presMap["nodes"] = [];
  6797. this.presMap["nodes"].push( {
  6798. "tagName": "user-agent",
  6799. "value": navigator.userAgent,
  6800. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6801. });
  6802. };
  6803. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6804. this.presMap["nodes"].push( {
  6805. "tagName": "devices",
  6806. "children": [
  6807. {
  6808. "tagName": "audio",
  6809. "value": devices.audio,
  6810. },
  6811. {
  6812. "tagName": "video",
  6813. "value": devices.video,
  6814. }
  6815. ]
  6816. });
  6817. };
  6818. ChatRoom.prototype.join = function (password) {
  6819. if(password)
  6820. this.password = password;
  6821. var self = this;
  6822. this.moderator.allocateConferenceFocus(function()
  6823. {
  6824. self.sendPresence(true);
  6825. }.bind(this));
  6826. };
  6827. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6828. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6829. // Too early to send presence - not initialized
  6830. return;
  6831. }
  6832. var pres = $pres({to: this.presMap['to'] });
  6833. pres.c('x', {xmlns: this.presMap['xns']});
  6834. if (this.password) {
  6835. pres.c('password').t(this.password).up();
  6836. }
  6837. pres.up();
  6838. // Send XEP-0115 'c' stanza that contains our capabilities info
  6839. if (this.connection.caps) {
  6840. this.connection.caps.node = this.xmpp.options.clientNode;
  6841. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6842. }
  6843. parser.JSON2packet(this.presMap.nodes, pres);
  6844. this.connection.send(pres);
  6845. };
  6846. ChatRoom.prototype.doLeave = function () {
  6847. logger.log("do leave", this.myroomjid);
  6848. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6849. this.presMap.length = 0;
  6850. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  6851. // means that there may not be enough time to send the unavailable presence.
  6852. // Switching Strophe to synchronous sending is not much of an option because
  6853. // it may lead to a noticeable delay in navigating away from the current
  6854. // location. As a compromise, we will try to increase the chances of sending
  6855. // the unavailable presence within the short time span that we have upon
  6856. // unloading by invoking flush() on the connection. We flush() once before
  6857. // sending/queuing the unavailable presence in order to attemtp to have the
  6858. // unavailable presence at the top of the send queue. We flush() once more
  6859. // after sending/queuing the unavailable presence in order to attempt to
  6860. // have it sent as soon as possible.
  6861. this.connection.flush();
  6862. this.connection.send(pres);
  6863. this.connection.flush();
  6864. };
  6865. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6866. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6867. var getForm = $iq({type: 'get', to: this.roomjid})
  6868. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6869. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6870. var self = this;
  6871. this.connection.sendIQ(getForm, function (form) {
  6872. if (!$(form).find(
  6873. '>query>x[xmlns="jabber:x:data"]' +
  6874. '>field[var="muc#roomconfig_whois"]').length) {
  6875. logger.error('non-anonymous rooms not supported');
  6876. return;
  6877. }
  6878. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6879. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6880. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6881. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6882. .c('value')
  6883. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6884. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6885. .c('value').t('anyone').up().up();
  6886. self.connection.sendIQ(formSubmit);
  6887. }, function (error) {
  6888. logger.error("Error getting room configuration form");
  6889. });
  6890. };
  6891. ChatRoom.prototype.onPresence = function (pres) {
  6892. var from = pres.getAttribute('from');
  6893. // Parse roles.
  6894. var member = {};
  6895. member.show = $(pres).find('>show').text();
  6896. member.status = $(pres).find('>status').text();
  6897. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6898. member.affiliation = tmp.attr('affiliation');
  6899. member.role = tmp.attr('role');
  6900. // Focus recognition
  6901. member.jid = tmp.attr('jid');
  6902. member.isFocus = false;
  6903. if (member.jid
  6904. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6905. member.isFocus = true;
  6906. }
  6907. $(pres).find(">x").remove();
  6908. var nodes = [];
  6909. parser.packet2JSON(pres, nodes);
  6910. this.lastPresences[from] = nodes;
  6911. var jibri = null;
  6912. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6913. // events
  6914. for(var i = 0; i < nodes.length; i++)
  6915. {
  6916. var node = nodes[i];
  6917. switch(node.tagName)
  6918. {
  6919. case "nick":
  6920. member.nick = node.value;
  6921. break;
  6922. case "userId":
  6923. member.id = node.value;
  6924. break;
  6925. }
  6926. }
  6927. if (from == this.myroomjid) {
  6928. if (member.affiliation == 'owner'
  6929. && this.role !== member.role) {
  6930. this.role = member.role;
  6931. this.eventEmitter.emit(
  6932. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6933. }
  6934. if (!this.joined) {
  6935. this.joined = true;
  6936. console.log("(TIME) MUC joined:\t", window.performance.now());
  6937. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6938. }
  6939. } else if (this.members[from] === undefined) {
  6940. // new participant
  6941. this.members[from] = member;
  6942. logger.log('entered', from, member);
  6943. if (member.isFocus) {
  6944. this.focusMucJid = from;
  6945. if(!this.recording) {
  6946. this.recording = new Recorder(this.options.recordingType,
  6947. this.eventEmitter, this.connection, this.focusMucJid,
  6948. this.options.jirecon, this.roomjid);
  6949. if(this.lastJibri)
  6950. this.recording.handleJibriPresence(this.lastJibri);
  6951. }
  6952. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6953. }
  6954. else {
  6955. this.eventEmitter.emit(
  6956. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6957. }
  6958. } else {
  6959. // Presence update for existing participant
  6960. // Watch role change:
  6961. if (this.members[from].role != member.role) {
  6962. this.members[from].role = member.role;
  6963. this.eventEmitter.emit(
  6964. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6965. }
  6966. // store the new display name
  6967. if(member.displayName)
  6968. this.members[from].displayName = member.displayName;
  6969. }
  6970. // after we had fired member or room joined events, lets fire events
  6971. // for the rest info we got in presence
  6972. for(var i = 0; i < nodes.length; i++)
  6973. {
  6974. var node = nodes[i];
  6975. switch(node.tagName)
  6976. {
  6977. case "nick":
  6978. if(!member.isFocus) {
  6979. var displayName = !this.xmpp.options.displayJids
  6980. ? member.nick : Strophe.getResourceFromJid(from);
  6981. if (displayName && displayName.length > 0) {
  6982. this.eventEmitter.emit(
  6983. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6984. }
  6985. }
  6986. break;
  6987. case "bridgeIsDown":
  6988. if(!this.bridgeIsDown) {
  6989. this.bridgeIsDown = true;
  6990. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6991. }
  6992. break;
  6993. case "jibri-recording-status":
  6994. var jibri = node;
  6995. break;
  6996. case "call-control":
  6997. var att = node.attributes;
  6998. if(!att)
  6999. break;
  7000. this.phoneNumber = att.phone || null;
  7001. this.phonePin = att.pin || null;
  7002. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  7003. break;
  7004. default :
  7005. this.processNode(node, from);
  7006. }
  7007. }
  7008. // Trigger status message update
  7009. if (member.status) {
  7010. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  7011. }
  7012. if(jibri)
  7013. {
  7014. this.lastJibri = jibri;
  7015. if(this.recording)
  7016. this.recording.handleJibriPresence(jibri);
  7017. }
  7018. };
  7019. ChatRoom.prototype.processNode = function (node, from) {
  7020. if(this.presHandlers[node.tagName])
  7021. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  7022. };
  7023. ChatRoom.prototype.sendMessage = function (body, nickname) {
  7024. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  7025. msg.c('body', body).up();
  7026. if (nickname) {
  7027. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  7028. }
  7029. this.connection.send(msg);
  7030. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  7031. };
  7032. ChatRoom.prototype.setSubject = function (subject) {
  7033. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  7034. msg.c('subject', subject);
  7035. this.connection.send(msg);
  7036. };
  7037. ChatRoom.prototype.onParticipantLeft = function (jid) {
  7038. delete this.lastPresences[jid];
  7039. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  7040. this.moderator.onMucMemberLeft(jid);
  7041. };
  7042. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  7043. // room destroyed ?
  7044. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  7045. '>destroy').length) {
  7046. var reason;
  7047. var reasonSelect = $(pres).find(
  7048. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  7049. '>destroy>reason');
  7050. if (reasonSelect.length) {
  7051. reason = reasonSelect.text();
  7052. }
  7053. this.xmpp.leaveRoom(this.roomjid);
  7054. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  7055. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  7056. return true;
  7057. }
  7058. // Status code 110 indicates that this notification is "self-presence".
  7059. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  7060. delete this.members[from];
  7061. this.onParticipantLeft(from);
  7062. }
  7063. // If the status code is 110 this means we're leaving and we would like
  7064. // to remove everyone else from our view, so we trigger the event.
  7065. else if (Object.keys(this.members).length > 1) {
  7066. for (var i in this.members) {
  7067. var member = this.members[i];
  7068. delete this.members[i];
  7069. this.onParticipantLeft(member);
  7070. }
  7071. }
  7072. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  7073. if (this.myroomjid === from) {
  7074. this.xmpp.leaveRoom(this.roomjid);
  7075. this.eventEmitter.emit(XMPPEvents.KICKED);
  7076. }
  7077. }
  7078. };
  7079. ChatRoom.prototype.onMessage = function (msg, from) {
  7080. var nick =
  7081. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  7082. .text() ||
  7083. Strophe.getResourceFromJid(from);
  7084. var txt = $(msg).find('>body').text();
  7085. var type = msg.getAttribute("type");
  7086. if (type == "error") {
  7087. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  7088. $(msg).find('>text').text(), txt);
  7089. return true;
  7090. }
  7091. var subject = $(msg).find('>subject');
  7092. if (subject.length) {
  7093. var subjectText = subject.text();
  7094. if (subjectText || subjectText === "") {
  7095. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  7096. logger.log("Subject is changed to " + subjectText);
  7097. }
  7098. }
  7099. // xep-0203 delay
  7100. var stamp = $(msg).find('>delay').attr('stamp');
  7101. if (!stamp) {
  7102. // or xep-0091 delay, UTC timestamp
  7103. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  7104. if (stamp) {
  7105. // the format is CCYYMMDDThh:mm:ss
  7106. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  7107. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  7108. }
  7109. }
  7110. if (txt) {
  7111. logger.log('chat', nick, txt);
  7112. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  7113. from, nick, txt, this.myroomjid, stamp);
  7114. }
  7115. };
  7116. ChatRoom.prototype.onPresenceError = function (pres, from) {
  7117. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7118. logger.log('on password required', from);
  7119. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  7120. } else if ($(pres).find(
  7121. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7122. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  7123. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  7124. // enter the room by replying with 'not-authorized'. This would
  7125. // result in reconnection from authorized domain.
  7126. // We're either missing Jicofo/Prosody config for anonymous
  7127. // domains or something is wrong.
  7128. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  7129. } else {
  7130. logger.warn('onPresError ', pres);
  7131. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7132. }
  7133. } else {
  7134. logger.warn('onPresError ', pres);
  7135. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7136. }
  7137. };
  7138. ChatRoom.prototype.kick = function (jid) {
  7139. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  7140. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  7141. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  7142. .c('reason').t('You have been kicked.').up().up().up();
  7143. this.connection.sendIQ(
  7144. kickIQ,
  7145. function (result) {
  7146. logger.log('Kick participant with jid: ', jid, result);
  7147. },
  7148. function (error) {
  7149. logger.log('Kick participant error: ', error);
  7150. });
  7151. };
  7152. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  7153. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  7154. var ob = this;
  7155. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  7156. function (res) {
  7157. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  7158. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  7159. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  7160. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  7161. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  7162. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  7163. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  7164. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  7165. ob.connection.sendIQ(formsubmit,
  7166. onSuccess,
  7167. onError);
  7168. } else {
  7169. onNotSupported();
  7170. }
  7171. }, onError);
  7172. };
  7173. ChatRoom.prototype.addToPresence = function (key, values) {
  7174. values.tagName = key;
  7175. this.presMap["nodes"].push(values);
  7176. };
  7177. ChatRoom.prototype.removeFromPresence = function (key) {
  7178. for(var i = 0; i < this.presMap.nodes.length; i++)
  7179. {
  7180. if(key === this.presMap.nodes[i].tagName)
  7181. this.presMap.nodes.splice(i, 1);
  7182. }
  7183. };
  7184. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  7185. this.presHandlers[name] = handler;
  7186. };
  7187. ChatRoom.prototype.removePresenceListener = function (name) {
  7188. delete this.presHandlers[name];
  7189. };
  7190. ChatRoom.prototype.isModerator = function () {
  7191. return this.role === 'moderator';
  7192. };
  7193. ChatRoom.prototype.getMemberRole = function (peerJid) {
  7194. if (this.members[peerJid]) {
  7195. return this.members[peerJid].role;
  7196. }
  7197. return null;
  7198. };
  7199. ChatRoom.prototype.setJingleSession = function(session){
  7200. this.session = session;
  7201. this.session.room = this;
  7202. };
  7203. ChatRoom.prototype.removeStream = function (stream, callback) {
  7204. if(!this.session)
  7205. return;
  7206. this.session.removeStream(stream, callback);
  7207. };
  7208. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  7209. if(this.session) {
  7210. // FIXME: will block switchInProgress on true value in case of exception
  7211. this.session.switchStreams(stream, oldStream, callback, isAudio);
  7212. } else {
  7213. // We are done immediately
  7214. logger.warn("No conference handler or conference not started yet");
  7215. callback();
  7216. }
  7217. };
  7218. ChatRoom.prototype.addStream = function (stream, callback) {
  7219. if(this.session) {
  7220. // FIXME: will block switchInProgress on true value in case of exception
  7221. this.session.addStream(stream, callback);
  7222. } else {
  7223. // We are done immediately
  7224. logger.warn("No conference handler or conference not started yet");
  7225. callback();
  7226. }
  7227. };
  7228. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  7229. var self = this;
  7230. this.sendVideoInfoPresence(mute);
  7231. if(callback)
  7232. callback(mute);
  7233. };
  7234. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  7235. return this.sendAudioInfoPresence(mute, callback);
  7236. };
  7237. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  7238. this.removeFromPresence("audiomuted");
  7239. this.addToPresence("audiomuted",
  7240. {attributes:
  7241. {"audions": "http://jitsi.org/jitmeet/audio"},
  7242. value: mute.toString()});
  7243. };
  7244. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7245. this.addAudioInfoToPresence(mute);
  7246. if(this.connection) {
  7247. this.sendPresence();
  7248. }
  7249. if(callback)
  7250. callback();
  7251. };
  7252. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7253. this.removeFromPresence("videomuted");
  7254. this.addToPresence("videomuted",
  7255. {attributes:
  7256. {"videons": "http://jitsi.org/jitmeet/video"},
  7257. value: mute.toString()});
  7258. };
  7259. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7260. this.addVideoInfoToPresence(mute);
  7261. if(!this.connection)
  7262. return;
  7263. this.sendPresence();
  7264. };
  7265. ChatRoom.prototype.addListener = function(type, listener) {
  7266. this.eventEmitter.on(type, listener);
  7267. };
  7268. ChatRoom.prototype.removeListener = function (type, listener) {
  7269. this.eventEmitter.removeListener(type, listener);
  7270. };
  7271. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7272. if(this.lastPresences[data.peerjid])
  7273. {
  7274. var pres = this.lastPresences[data.peerjid];
  7275. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7276. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7277. data.videomuted = ((videomuted.length > 0
  7278. && videomuted[0]
  7279. && videomuted[0]["value"] === "true")? true : false);
  7280. data.audiomuted = ((audiomuted.length > 0
  7281. && audiomuted[0]
  7282. && audiomuted[0]["value"] === "true")? true : false);
  7283. }
  7284. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7285. };
  7286. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7287. if (!this.session)
  7288. return null;
  7289. return this.session.getSsrcOwner(ssrc);
  7290. };
  7291. /**
  7292. * Returns true if the recording is supproted and false if not.
  7293. */
  7294. ChatRoom.prototype.isRecordingSupported = function () {
  7295. if(this.recording)
  7296. return this.recording.isSupported();
  7297. return false;
  7298. };
  7299. /**
  7300. * Returns null if the recording is not supported, "on" if the recording started
  7301. * and "off" if the recording is not started.
  7302. */
  7303. ChatRoom.prototype.getRecordingState = function () {
  7304. if(this.recording)
  7305. return this.recording.getState();
  7306. return "off";
  7307. }
  7308. /**
  7309. * Returns the url of the recorded video.
  7310. */
  7311. ChatRoom.prototype.getRecordingURL = function () {
  7312. if(this.recording)
  7313. return this.recording.getURL();
  7314. return null;
  7315. }
  7316. /**
  7317. * Starts/stops the recording
  7318. * @param token token for authentication
  7319. * @param statusChangeHandler {function} receives the new status as argument.
  7320. */
  7321. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7322. if(this.recording)
  7323. return this.recording.toggleRecording(options, statusChangeHandler);
  7324. return statusChangeHandler("error",
  7325. new Error("The conference is not created yet!"));
  7326. }
  7327. /**
  7328. * Returns true if the SIP calls are supported and false otherwise
  7329. */
  7330. ChatRoom.prototype.isSIPCallingSupported = function () {
  7331. if(this.moderator)
  7332. return this.moderator.isSipGatewayEnabled();
  7333. return false;
  7334. }
  7335. /**
  7336. * Dials a number.
  7337. * @param number the number
  7338. */
  7339. ChatRoom.prototype.dial = function (number) {
  7340. return this.connection.rayo.dial(number, "fromnumber",
  7341. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7342. this.focusMucJid);
  7343. }
  7344. /**
  7345. * Hangup an existing call
  7346. */
  7347. ChatRoom.prototype.hangup = function () {
  7348. return this.connection.rayo.hangup();
  7349. }
  7350. /**
  7351. * Returns the phone number for joining the conference.
  7352. */
  7353. ChatRoom.prototype.getPhoneNumber = function () {
  7354. return this.phoneNumber;
  7355. }
  7356. /**
  7357. * Returns the pin for joining the conference with phone.
  7358. */
  7359. ChatRoom.prototype.getPhonePin = function () {
  7360. return this.phonePin;
  7361. }
  7362. /**
  7363. * Returns the connection state for the current session.
  7364. */
  7365. ChatRoom.prototype.getConnectionState = function () {
  7366. if(!this.session)
  7367. return null;
  7368. return this.session.getIceConnectionState();
  7369. }
  7370. /**
  7371. * Mutes remote participant.
  7372. * @param jid of the participant
  7373. * @param mute
  7374. */
  7375. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7376. logger.info("set mute", mute);
  7377. var iqToFocus = $iq(
  7378. {to: this.focusMucJid, type: 'set'})
  7379. .c('mute', {
  7380. xmlns: 'http://jitsi.org/jitmeet/audio',
  7381. jid: jid
  7382. })
  7383. .t(mute.toString())
  7384. .up();
  7385. this.connection.sendIQ(
  7386. iqToFocus,
  7387. function (result) {
  7388. logger.log('set mute', result);
  7389. },
  7390. function (error) {
  7391. logger.log('set mute error', error);
  7392. });
  7393. }
  7394. ChatRoom.prototype.onMute = function (iq) {
  7395. var from = iq.getAttribute('from');
  7396. if (from !== this.focusMucJid) {
  7397. logger.warn("Ignored mute from non focus peer");
  7398. return false;
  7399. }
  7400. var mute = $(iq).find('mute');
  7401. if (mute.length) {
  7402. var doMuteAudio = mute.text() === "true";
  7403. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7404. }
  7405. return true;
  7406. }
  7407. module.exports = ChatRoom;
  7408. }).call(this,"/modules/xmpp/ChatRoom.js")
  7409. },{"../../service/xmpp/XMPPEvents":143,"./moderator":36,"./recording":37,"events":46,"jitsi-meet-logger":50}],30:[function(require,module,exports){
  7410. (function (__filename){
  7411. /*
  7412. * JingleSession provides an API to manage a single Jingle session. We will
  7413. * have different implementations depending on the underlying interface used
  7414. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7415. */
  7416. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7417. function JingleSession(me, sid, connection, service, eventEmitter) {
  7418. /**
  7419. * Our JID.
  7420. */
  7421. this.me = me;
  7422. /**
  7423. * The Jingle session identifier.
  7424. */
  7425. this.sid = sid;
  7426. /**
  7427. * The XMPP connection.
  7428. */
  7429. this.connection = connection;
  7430. /**
  7431. * The XMPP service.
  7432. */
  7433. this.service = service;
  7434. /**
  7435. * The event emitter.
  7436. */
  7437. this.eventEmitter = eventEmitter;
  7438. /**
  7439. * Whether to use dripping or not. Dripping is sending trickle candidates
  7440. * not one-by-one.
  7441. * Note: currently we do not support 'false'.
  7442. */
  7443. this.usedrip = true;
  7444. /**
  7445. * When dripping is used, stores ICE candidates which are to be sent.
  7446. */
  7447. this.drip_container = [];
  7448. // Media constraints. Is this WebRTC only?
  7449. this.media_constraints = null;
  7450. // ICE servers config (RTCConfiguration?).
  7451. this.ice_config = {};
  7452. // The chat room instance associated with the session.
  7453. this.room = null;
  7454. }
  7455. /**
  7456. * Prepares this object to initiate a session.
  7457. * @param peerjid the JID of the remote peer.
  7458. * @param isInitiator whether we will be the Jingle initiator.
  7459. * @param media_constraints
  7460. * @param ice_config
  7461. */
  7462. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7463. media_constraints, ice_config) {
  7464. this.media_constraints = media_constraints;
  7465. this.ice_config = ice_config;
  7466. if (this.state !== null) {
  7467. logger.error('attempt to initiate on session ' + this.sid +
  7468. 'in state ' + this.state);
  7469. return;
  7470. }
  7471. this.state = 'pending';
  7472. this.initiator = isInitiator ? this.me : peerjid;
  7473. this.responder = !isInitiator ? this.me : peerjid;
  7474. this.peerjid = peerjid;
  7475. this.doInitialize();
  7476. };
  7477. /**
  7478. * Finishes initialization.
  7479. */
  7480. JingleSession.prototype.doInitialize = function() {};
  7481. /**
  7482. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7483. * Note: currently only used on transport-info
  7484. */
  7485. JingleSession.prototype.addIceCandidates = function(contents) {};
  7486. /**
  7487. * Handles an 'add-source' event.
  7488. *
  7489. * @param contents an array of Jingle 'content' elements.
  7490. */
  7491. JingleSession.prototype.addSources = function(contents) {};
  7492. /**
  7493. * Handles a 'remove-source' event.
  7494. *
  7495. * @param contents an array of Jingle 'content' elements.
  7496. */
  7497. JingleSession.prototype.removeSources = function(contents) {};
  7498. /**
  7499. * Terminates this Jingle session (stops sending media and closes the streams?)
  7500. */
  7501. JingleSession.prototype.terminate = function() {};
  7502. /**
  7503. * Sends a Jingle session-terminate message to the peer and terminates the
  7504. * session.
  7505. * @param reason
  7506. * @param text
  7507. */
  7508. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7509. /**
  7510. * Handles an offer from the remote peer (prepares to accept a session).
  7511. * @param jingle the 'jingle' XML element.
  7512. */
  7513. JingleSession.prototype.setOffer = function(jingle) {};
  7514. /**
  7515. * Handles an answer from the remote peer (prepares to accept a session).
  7516. * @param jingle the 'jingle' XML element.
  7517. */
  7518. JingleSession.prototype.setAnswer = function(jingle) {};
  7519. module.exports = JingleSession;
  7520. }).call(this,"/modules/xmpp/JingleSession.js")
  7521. },{"jitsi-meet-logger":50}],31:[function(require,module,exports){
  7522. (function (__filename){
  7523. /* jshint -W117 */
  7524. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7525. var JingleSession = require("./JingleSession");
  7526. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7527. var SDPDiffer = require("./SDPDiffer");
  7528. var SDPUtil = require("./SDPUtil");
  7529. var SDP = require("./SDP");
  7530. var async = require("async");
  7531. var transform = require("sdp-transform");
  7532. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7533. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7534. var RTC = require("../RTC/RTC");
  7535. // Jingle stuff
  7536. function JingleSessionPC(me, sid, connection, service) {
  7537. JingleSession.call(this, me, sid, connection, service);
  7538. this.initiator = null;
  7539. this.responder = null;
  7540. this.peerjid = null;
  7541. this.state = null;
  7542. this.localSDP = null;
  7543. this.remoteSDP = null;
  7544. this.relayedStreams = [];
  7545. this.usetrickle = true;
  7546. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7547. this.hadstuncandidate = false;
  7548. this.hadturncandidate = false;
  7549. this.lasticecandidate = false;
  7550. this.statsinterval = null;
  7551. this.reason = null;
  7552. this.addssrc = [];
  7553. this.removessrc = [];
  7554. this.pendingop = null;
  7555. this.switchstreams = false;
  7556. this.addingStreams = false;
  7557. this.wait = true;
  7558. /**
  7559. * A map that stores SSRCs of local streams
  7560. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7561. */
  7562. this.localStreamsSSRC = {};
  7563. this.ssrcOwners = {};
  7564. this.ssrcVideoTypes = {};
  7565. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7566. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7567. /**
  7568. * The indicator which determines whether the (local) video has been muted
  7569. * in response to a user command in contrast to an automatic decision made
  7570. * by the application logic.
  7571. */
  7572. this.videoMuteByUser = false;
  7573. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7574. // We start with the queue paused. We resume it when the signaling state is
  7575. // stable and the ice connection state is connected.
  7576. this.modifySourcesQueue.pause();
  7577. }
  7578. //XXX this is badly broken...
  7579. JingleSessionPC.prototype = JingleSession.prototype;
  7580. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7581. JingleSessionPC.prototype.setOffer = function(offer) {
  7582. this.setRemoteDescription(offer, 'offer');
  7583. };
  7584. JingleSessionPC.prototype.setAnswer = function(answer) {
  7585. this.setRemoteDescription(answer, 'answer');
  7586. };
  7587. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7588. var signalingState = this.peerconnection.signalingState;
  7589. var iceConnectionState = this.peerconnection.iceConnectionState;
  7590. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7591. this.modifySourcesQueue.resume();
  7592. } else {
  7593. this.modifySourcesQueue.pause();
  7594. }
  7595. };
  7596. JingleSessionPC.prototype.doInitialize = function () {
  7597. var self = this;
  7598. this.hadstuncandidate = false;
  7599. this.hadturncandidate = false;
  7600. this.lasticecandidate = false;
  7601. // True if reconnect is in progress
  7602. this.isreconnect = false;
  7603. // Set to true if the connection was ever stable
  7604. this.wasstable = false;
  7605. this.peerconnection = new TraceablePeerConnection(
  7606. this.connection.jingle.ice_config,
  7607. RTC.getPCConstraints(),
  7608. this);
  7609. this.peerconnection.onicecandidate = function (event) {
  7610. var protocol;
  7611. if (event && event.candidate) {
  7612. protocol = (typeof event.candidate.protocol === 'string')
  7613. ? event.candidate.protocol.toLowerCase() : '';
  7614. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7615. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7616. return;
  7617. }
  7618. }
  7619. self.sendIceCandidate(event.candidate);
  7620. };
  7621. this.peerconnection.onaddstream = function (event) {
  7622. if (event.stream.id !== 'default') {
  7623. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7624. self.remoteStreamAdded(event);
  7625. } else {
  7626. // This is a recvonly stream. Clients that implement Unified Plan,
  7627. // such as Firefox use recvonly "streams/channels/tracks" for
  7628. // receiving remote stream/tracks, as opposed to Plan B where there
  7629. // are only 3 channels: audio, video and data.
  7630. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7631. }
  7632. };
  7633. this.peerconnection.onremovestream = function (event) {
  7634. // Remove the stream from remoteStreams
  7635. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7636. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7637. };
  7638. this.peerconnection.onsignalingstatechange = function (event) {
  7639. if (!(self && self.peerconnection)) return;
  7640. if (self.peerconnection.signalingState === 'stable') {
  7641. self.wasstable = true;
  7642. }
  7643. self.updateModifySourcesQueue();
  7644. };
  7645. /**
  7646. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7647. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7648. * RTCPeerConnection.iceConnectionState changes.
  7649. *
  7650. * @param event the event containing information about the change
  7651. */
  7652. this.peerconnection.oniceconnectionstatechange = function (event) {
  7653. if (!(self && self.peerconnection)) return;
  7654. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7655. ":\t", window.performance.now());
  7656. self.updateModifySourcesQueue();
  7657. switch (self.peerconnection.iceConnectionState) {
  7658. case 'connected':
  7659. // Informs interested parties that the connection has been restored.
  7660. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7661. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7662. self.isreconnect = false;
  7663. break;
  7664. case 'disconnected':
  7665. self.isreconnect = true;
  7666. // Informs interested parties that the connection has been interrupted.
  7667. if (self.wasstable)
  7668. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7669. break;
  7670. case 'failed':
  7671. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7672. break;
  7673. }
  7674. onIceConnectionStateChange(self.sid, self);
  7675. };
  7676. this.peerconnection.onnegotiationneeded = function (event) {
  7677. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7678. };
  7679. this.relayedStreams.forEach(function(stream) {
  7680. self.peerconnection.addStream(stream);
  7681. });
  7682. };
  7683. function onIceConnectionStateChange(sid, session) {
  7684. switch (session.peerconnection.iceConnectionState) {
  7685. case 'checking':
  7686. session.timeChecking = (new Date()).getTime();
  7687. session.firstconnect = true;
  7688. break;
  7689. case 'completed': // on caller side
  7690. case 'connected':
  7691. if (session.firstconnect) {
  7692. session.firstconnect = false;
  7693. var metadata = {};
  7694. metadata.setupTime
  7695. = (new Date()).getTime() - session.timeChecking;
  7696. session.peerconnection.getStats(function (res) {
  7697. if(res && res.result) {
  7698. res.result().forEach(function (report) {
  7699. if (report.type == 'googCandidatePair' &&
  7700. report.stat('googActiveConnection') == 'true') {
  7701. metadata.localCandidateType
  7702. = report.stat('googLocalCandidateType');
  7703. metadata.remoteCandidateType
  7704. = report.stat('googRemoteCandidateType');
  7705. // log pair as well so we can get nice pie
  7706. // charts
  7707. metadata.candidatePair
  7708. = report.stat('googLocalCandidateType') +
  7709. ';' +
  7710. report.stat('googRemoteCandidateType');
  7711. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7712. {
  7713. metadata.ipv6 = true;
  7714. }
  7715. }
  7716. });
  7717. }
  7718. });
  7719. }
  7720. break;
  7721. }
  7722. }
  7723. JingleSessionPC.prototype.accept = function () {
  7724. this.state = 'active';
  7725. var pranswer = this.peerconnection.localDescription;
  7726. if (!pranswer || pranswer.type != 'pranswer') {
  7727. return;
  7728. }
  7729. logger.log('going from pranswer to answer');
  7730. if (this.usetrickle) {
  7731. // remove candidates already sent from session-accept
  7732. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7733. for (var i = 0; i < lines.length; i++) {
  7734. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7735. }
  7736. }
  7737. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7738. // FIXME: change any inactive to sendrecv or whatever they were originally
  7739. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7740. }
  7741. var prsdp = new SDP(pranswer.sdp);
  7742. if (this.webrtcIceTcpDisable) {
  7743. prsdp.removeTcpCandidates = true;
  7744. }
  7745. if (this.webrtcIceUdpDisable) {
  7746. prsdp.removeUdpCandidates = true;
  7747. }
  7748. var accept = $iq({to: this.peerjid,
  7749. type: 'set'})
  7750. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7751. action: 'session-accept',
  7752. initiator: this.initiator,
  7753. responder: this.responder,
  7754. sid: this.sid });
  7755. // FIXME why do we generate session-accept in 3 different places ?
  7756. prsdp.toJingle(
  7757. accept,
  7758. this.initiator == this.me ? 'initiator' : 'responder');
  7759. var sdp = this.peerconnection.localDescription.sdp;
  7760. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7761. // FIXME: change any inactive to sendrecv or whatever they were originally
  7762. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7763. }
  7764. var self = this;
  7765. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7766. function () {
  7767. //logger.log('setLocalDescription success');
  7768. self.setLocalDescription();
  7769. self.connection.sendIQ(accept,
  7770. function () {
  7771. var ack = {};
  7772. ack.source = 'answer';
  7773. $(document).trigger('ack.jingle', [self.sid, ack]);
  7774. },
  7775. function (stanza) {
  7776. var error = ($(stanza).find('error').length) ? {
  7777. code: $(stanza).find('error').attr('code'),
  7778. reason: $(stanza).find('error :first')[0].tagName
  7779. }:{};
  7780. error.source = 'answer';
  7781. JingleSessionPC.onJingleError(self.sid, error);
  7782. },
  7783. 10000);
  7784. },
  7785. function (e) {
  7786. logger.error('setLocalDescription failed', e);
  7787. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7788. }
  7789. );
  7790. };
  7791. JingleSessionPC.prototype.terminate = function (reason) {
  7792. this.state = 'ended';
  7793. this.reason = reason;
  7794. this.peerconnection.close();
  7795. if (this.statsinterval !== null) {
  7796. window.clearInterval(this.statsinterval);
  7797. this.statsinterval = null;
  7798. }
  7799. };
  7800. JingleSessionPC.prototype.active = function () {
  7801. return this.state == 'active';
  7802. };
  7803. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7804. var self = this;
  7805. if (candidate && !this.lasticecandidate) {
  7806. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7807. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7808. if (!(ice && jcand)) {
  7809. logger.error('failed to get ice && jcand');
  7810. return;
  7811. }
  7812. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7813. if (jcand.type === 'srflx') {
  7814. this.hadstuncandidate = true;
  7815. } else if (jcand.type === 'relay') {
  7816. this.hadturncandidate = true;
  7817. }
  7818. if (this.usetrickle) {
  7819. if (this.usedrip) {
  7820. if (this.drip_container.length === 0) {
  7821. // start 20ms callout
  7822. window.setTimeout(function () {
  7823. if (self.drip_container.length === 0) return;
  7824. self.sendIceCandidates(self.drip_container);
  7825. self.drip_container = [];
  7826. }, 20);
  7827. }
  7828. this.drip_container.push(candidate);
  7829. return;
  7830. } else {
  7831. self.sendIceCandidate([candidate]);
  7832. }
  7833. }
  7834. } else {
  7835. //logger.log('sendIceCandidate: last candidate.');
  7836. if (!this.usetrickle) {
  7837. //logger.log('should send full offer now...');
  7838. //FIXME why do we generate session-accept in 3 different places ?
  7839. var init = $iq({to: this.peerjid,
  7840. type: 'set'})
  7841. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7842. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7843. initiator: this.initiator,
  7844. sid: this.sid});
  7845. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7846. if (self.webrtcIceTcpDisable) {
  7847. this.localSDP.removeTcpCandidates = true;
  7848. }
  7849. if (self.webrtcIceUdpDisable) {
  7850. this.localSDP.removeUdpCandidates = true;
  7851. }
  7852. var sendJingle = function (ssrc) {
  7853. if(!ssrc)
  7854. ssrc = {};
  7855. self.localSDP.toJingle(
  7856. init,
  7857. self.initiator == self.me ? 'initiator' : 'responder',
  7858. ssrc);
  7859. self.connection.sendIQ(init,
  7860. function () {
  7861. //logger.log('session initiate ack');
  7862. var ack = {};
  7863. ack.source = 'offer';
  7864. $(document).trigger('ack.jingle', [self.sid, ack]);
  7865. },
  7866. function (stanza) {
  7867. self.state = 'error';
  7868. self.peerconnection.close();
  7869. var error = ($(stanza).find('error').length) ? {
  7870. code: $(stanza).find('error').attr('code'),
  7871. reason: $(stanza).find('error :first')[0].tagName,
  7872. }:{};
  7873. error.source = 'offer';
  7874. JingleSessionPC.onJingleError(self.sid, error);
  7875. },
  7876. 10000);
  7877. };
  7878. sendJingle();
  7879. }
  7880. this.lasticecandidate = true;
  7881. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7882. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7883. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7884. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7885. }
  7886. }
  7887. };
  7888. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7889. logger.log('sendIceCandidates', candidates);
  7890. var cand = $iq({to: this.peerjid, type: 'set'})
  7891. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7892. action: 'transport-info',
  7893. initiator: this.initiator,
  7894. sid: this.sid});
  7895. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7896. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7897. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7898. if (cands.length > 0) {
  7899. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7900. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7901. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7902. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7903. }).c('transport', ice);
  7904. for (var i = 0; i < cands.length; i++) {
  7905. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7906. }
  7907. // add fingerprint
  7908. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7909. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7910. tmp.required = true;
  7911. cand.c(
  7912. 'fingerprint',
  7913. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7914. .t(tmp.fingerprint);
  7915. delete tmp.fingerprint;
  7916. cand.attrs(tmp);
  7917. cand.up();
  7918. }
  7919. cand.up(); // transport
  7920. cand.up(); // content
  7921. }
  7922. }
  7923. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7924. //logger.log('was this the last candidate', this.lasticecandidate);
  7925. this.connection.sendIQ(cand,
  7926. function () {
  7927. var ack = {};
  7928. ack.source = 'transportinfo';
  7929. $(document).trigger('ack.jingle', [this.sid, ack]);
  7930. },
  7931. function (stanza) {
  7932. var error = ($(stanza).find('error').length) ? {
  7933. code: $(stanza).find('error').attr('code'),
  7934. reason: $(stanza).find('error :first')[0].tagName,
  7935. }:{};
  7936. error.source = 'transportinfo';
  7937. JingleSessionPC.onJingleError(this.sid, error);
  7938. },
  7939. 10000);
  7940. };
  7941. JingleSessionPC.prototype.sendOffer = function () {
  7942. //logger.log('sendOffer...');
  7943. var self = this;
  7944. this.peerconnection.createOffer(function (sdp) {
  7945. self.createdOffer(sdp);
  7946. },
  7947. function (e) {
  7948. logger.error('createOffer failed', e);
  7949. },
  7950. this.media_constraints
  7951. );
  7952. };
  7953. // FIXME createdOffer is never used in jitsi-meet
  7954. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7955. //logger.log('createdOffer', sdp);
  7956. var self = this;
  7957. this.localSDP = new SDP(sdp.sdp);
  7958. //this.localSDP.mangle();
  7959. var sendJingle = function () {
  7960. var init = $iq({to: this.peerjid,
  7961. type: 'set'})
  7962. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7963. action: 'session-initiate',
  7964. initiator: this.initiator,
  7965. sid: this.sid});
  7966. self.localSDP.toJingle(
  7967. init,
  7968. this.initiator == this.me ? 'initiator' : 'responder');
  7969. self.connection.sendIQ(init,
  7970. function () {
  7971. var ack = {};
  7972. ack.source = 'offer';
  7973. $(document).trigger('ack.jingle', [self.sid, ack]);
  7974. },
  7975. function (stanza) {
  7976. self.state = 'error';
  7977. self.peerconnection.close();
  7978. var error = ($(stanza).find('error').length) ? {
  7979. code: $(stanza).find('error').attr('code'),
  7980. reason: $(stanza).find('error :first')[0].tagName,
  7981. }:{};
  7982. error.source = 'offer';
  7983. JingleSessionPC.onJingleError(self.sid, error);
  7984. },
  7985. 10000);
  7986. }
  7987. sdp.sdp = this.localSDP.raw;
  7988. this.peerconnection.setLocalDescription(sdp,
  7989. function () {
  7990. if(self.usetrickle)
  7991. {
  7992. sendJingle();
  7993. }
  7994. self.setLocalDescription();
  7995. //logger.log('setLocalDescription success');
  7996. },
  7997. function (e) {
  7998. logger.error('setLocalDescription failed', e);
  7999. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8000. }
  8001. );
  8002. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8003. for (var i = 0; i < cands.length; i++) {
  8004. var cand = SDPUtil.parse_icecandidate(cands[i]);
  8005. if (cand.type == 'srflx') {
  8006. this.hadstuncandidate = true;
  8007. } else if (cand.type == 'relay') {
  8008. this.hadturncandidate = true;
  8009. }
  8010. }
  8011. };
  8012. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  8013. var self = this;
  8014. $(contents).each(function (idx, content) {
  8015. var name = $(content).attr('name');
  8016. var mediaType = this.getAttribute('name');
  8017. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  8018. ssrcs.each(function () {
  8019. var ssrc = this.getAttribute('ssrc');
  8020. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  8021. function () {
  8022. var owner = this.getAttribute('owner');
  8023. self.ssrcOwners[ssrc] = owner;
  8024. }
  8025. );
  8026. });
  8027. });
  8028. };
  8029. /**
  8030. * Returns the SSRC of local audio stream.
  8031. * @param mediaType 'audio' or 'video' media type
  8032. * @returns {*} the SSRC number of local audio or video stream.
  8033. */
  8034. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  8035. return this.localStreamsSSRC[mediaType];
  8036. };
  8037. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  8038. return this.ssrcOwners[ssrc];
  8039. };
  8040. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  8041. //logger.log('setting remote description... ', desctype);
  8042. this.remoteSDP = new SDP('');
  8043. if (this.webrtcIceTcpDisable) {
  8044. this.remoteSDP.removeTcpCandidates = true;
  8045. }
  8046. if (this.webrtcIceUdpDisable) {
  8047. this.remoteSDP.removeUdpCandidates = true;
  8048. }
  8049. this.remoteSDP.fromJingle(elem);
  8050. this.readSsrcInfo($(elem).find(">content"));
  8051. if (this.peerconnection.remoteDescription) {
  8052. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  8053. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  8054. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  8055. for (var i = 0; i < pranswer.media.length; i++) {
  8056. // make sure we have ice ufrag and pwd
  8057. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  8058. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  8059. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  8060. } else {
  8061. logger.warn('no ice ufrag?');
  8062. }
  8063. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  8064. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  8065. } else {
  8066. logger.warn('no ice pwd?');
  8067. }
  8068. }
  8069. // copy over candidates
  8070. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  8071. for (var j = 0; j < lines.length; j++) {
  8072. this.remoteSDP.media[i] += lines[j] + '\r\n';
  8073. }
  8074. }
  8075. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8076. }
  8077. }
  8078. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  8079. this.peerconnection.setRemoteDescription(remotedesc,
  8080. function () {
  8081. //logger.log('setRemoteDescription success');
  8082. },
  8083. function (e) {
  8084. logger.error('setRemoteDescription error', e);
  8085. JingleSessionPC.onJingleFatalError(self, e);
  8086. }
  8087. );
  8088. };
  8089. /**
  8090. * Adds remote ICE candidates to this Jingle session.
  8091. * @param elem An array of Jingle "content" elements?
  8092. */
  8093. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  8094. var self = this;
  8095. if (this.peerconnection.signalingState == 'closed') {
  8096. return;
  8097. }
  8098. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  8099. logger.log('trickle ice candidate arriving before session accept...');
  8100. // create a PRANSWER for setRemoteDescription
  8101. if (!this.remoteSDP) {
  8102. var cobbled = 'v=0\r\n' +
  8103. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8104. 's=-\r\n' +
  8105. 't=0 0\r\n';
  8106. // first, take some things from the local description
  8107. for (var i = 0; i < this.localSDP.media.length; i++) {
  8108. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  8109. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  8110. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  8111. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  8112. }
  8113. cobbled += 'a=inactive\r\n';
  8114. }
  8115. this.remoteSDP = new SDP(cobbled);
  8116. }
  8117. // then add things like ice and dtls from remote candidate
  8118. elem.each(function () {
  8119. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  8120. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8121. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8122. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  8123. var tmp = $(this).find('transport');
  8124. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  8125. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  8126. tmp = $(this).find('transport>fingerprint');
  8127. if (tmp.length) {
  8128. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  8129. } else {
  8130. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  8131. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  8132. }
  8133. break;
  8134. }
  8135. }
  8136. }
  8137. });
  8138. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8139. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  8140. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  8141. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  8142. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  8143. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  8144. }).length == this.remoteSDP.media.length;
  8145. if (iscomplete) {
  8146. logger.log('setting pranswer');
  8147. try {
  8148. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  8149. function() {
  8150. },
  8151. function(e) {
  8152. logger.log('setRemoteDescription pranswer failed', e.toString());
  8153. });
  8154. } catch (e) {
  8155. logger.error('setting pranswer failed', e);
  8156. }
  8157. } else {
  8158. //logger.log('not yet setting pranswer');
  8159. }
  8160. }
  8161. // operate on each content element
  8162. elem.each(function () {
  8163. // would love to deactivate this, but firefox still requires it
  8164. var idx = -1;
  8165. var i;
  8166. for (i = 0; i < self.remoteSDP.media.length; i++) {
  8167. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8168. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8169. idx = i;
  8170. break;
  8171. }
  8172. }
  8173. if (idx == -1) { // fall back to localdescription
  8174. for (i = 0; i < self.localSDP.media.length; i++) {
  8175. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8176. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8177. idx = i;
  8178. break;
  8179. }
  8180. }
  8181. }
  8182. var name = $(this).attr('name');
  8183. // TODO: check ice-pwd and ice-ufrag?
  8184. $(this).find('transport>candidate').each(function () {
  8185. var line, candidate;
  8186. var protocol = this.getAttribute('protocol');
  8187. protocol =
  8188. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  8189. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  8190. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  8191. return;
  8192. }
  8193. line = SDPUtil.candidateFromJingle(this);
  8194. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  8195. sdpMid: name,
  8196. candidate: line});
  8197. try {
  8198. self.peerconnection.addIceCandidate(candidate);
  8199. } catch (e) {
  8200. logger.error('addIceCandidate failed', e.toString(), line);
  8201. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  8202. err, self.peerconnection);
  8203. }
  8204. });
  8205. });
  8206. };
  8207. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  8208. //logger.log('createAnswer', provisional);
  8209. var self = this;
  8210. this.peerconnection.createAnswer(
  8211. function (sdp) {
  8212. self.createdAnswer(sdp, provisional);
  8213. },
  8214. function (e) {
  8215. logger.error('createAnswer failed', e);
  8216. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8217. },
  8218. this.media_constraints
  8219. );
  8220. };
  8221. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  8222. //logger.log('createAnswer callback');
  8223. var self = this;
  8224. this.localSDP = new SDP(sdp.sdp);
  8225. //this.localSDP.mangle();
  8226. this.usepranswer = provisional === true;
  8227. if (this.usetrickle) {
  8228. if (this.usepranswer) {
  8229. sdp.type = 'pranswer';
  8230. for (var i = 0; i < this.localSDP.media.length; i++) {
  8231. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  8232. }
  8233. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  8234. }
  8235. }
  8236. var self = this;
  8237. var sendJingle = function (ssrcs) {
  8238. // FIXME why do we generate session-accept in 3 different places ?
  8239. var accept = $iq({to: self.peerjid,
  8240. type: 'set'})
  8241. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8242. action: 'session-accept',
  8243. initiator: self.initiator,
  8244. responder: self.responder,
  8245. sid: self.sid });
  8246. if (self.webrtcIceTcpDisable) {
  8247. self.localSDP.removeTcpCandidates = true;
  8248. }
  8249. if (self.webrtcIceUdpDisable) {
  8250. self.localSDP.removeUdpCandidates = true;
  8251. }
  8252. self.localSDP.toJingle(
  8253. accept,
  8254. self.initiator == self.me ? 'initiator' : 'responder',
  8255. ssrcs);
  8256. self.connection.sendIQ(accept,
  8257. function () {
  8258. var ack = {};
  8259. ack.source = 'answer';
  8260. $(document).trigger('ack.jingle', [self.sid, ack]);
  8261. },
  8262. function (stanza) {
  8263. var error = ($(stanza).find('error').length) ? {
  8264. code: $(stanza).find('error').attr('code'),
  8265. reason: $(stanza).find('error :first')[0].tagName,
  8266. }:{};
  8267. error.source = 'answer';
  8268. JingleSessionPC.onJingleError(self.sid, error);
  8269. },
  8270. 10000);
  8271. }
  8272. sdp.sdp = this.localSDP.raw;
  8273. this.peerconnection.setLocalDescription(sdp,
  8274. function () {
  8275. //logger.log('setLocalDescription success');
  8276. if (self.usetrickle && !self.usepranswer) {
  8277. sendJingle();
  8278. }
  8279. self.setLocalDescription();
  8280. },
  8281. function (e) {
  8282. logger.error('setLocalDescription failed', e);
  8283. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8284. }
  8285. );
  8286. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8287. for (var j = 0; j < cands.length; j++) {
  8288. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8289. if (cand.type == 'srflx') {
  8290. this.hadstuncandidate = true;
  8291. } else if (cand.type == 'relay') {
  8292. this.hadturncandidate = true;
  8293. }
  8294. }
  8295. };
  8296. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8297. var self = this,
  8298. term = $iq({to: this.peerjid,
  8299. type: 'set'})
  8300. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8301. action: 'session-terminate',
  8302. initiator: this.initiator,
  8303. sid: this.sid})
  8304. .c('reason')
  8305. .c(reason || 'success');
  8306. if (text) {
  8307. term.up().c('text').t(text);
  8308. }
  8309. this.connection.sendIQ(term,
  8310. function () {
  8311. self.peerconnection.close();
  8312. self.peerconnection = null;
  8313. self.terminate();
  8314. var ack = {};
  8315. ack.source = 'terminate';
  8316. $(document).trigger('ack.jingle', [self.sid, ack]);
  8317. },
  8318. function (stanza) {
  8319. var error = ($(stanza).find('error').length) ? {
  8320. code: $(stanza).find('error').attr('code'),
  8321. reason: $(stanza).find('error :first')[0].tagName,
  8322. }:{};
  8323. $(document).trigger('ack.jingle', [self.sid, error]);
  8324. },
  8325. 10000);
  8326. if (this.statsinterval !== null) {
  8327. window.clearInterval(this.statsinterval);
  8328. this.statsinterval = null;
  8329. }
  8330. };
  8331. /**
  8332. * Handles a Jingle source-add message for this Jingle session.
  8333. * @param elem An array of Jingle "content" elements.
  8334. */
  8335. JingleSessionPC.prototype.addSource = function (elem) {
  8336. var self = this;
  8337. // FIXME: dirty waiting
  8338. if (!this.peerconnection.localDescription)
  8339. {
  8340. logger.warn("addSource - localDescription not ready yet")
  8341. setTimeout(function()
  8342. {
  8343. self.addSource(elem);
  8344. },
  8345. 200
  8346. );
  8347. return;
  8348. }
  8349. logger.log('addssrc', new Date().getTime());
  8350. logger.log('ice', this.peerconnection.iceConnectionState);
  8351. this.readSsrcInfo(elem);
  8352. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8353. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8354. $(elem).each(function (idx, content) {
  8355. var name = $(content).attr('name');
  8356. var lines = '';
  8357. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8358. var semantics = this.getAttribute('semantics');
  8359. var ssrcs = $(this).find('>source').map(function () {
  8360. return this.getAttribute('ssrc');
  8361. }).get();
  8362. if (ssrcs.length) {
  8363. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8364. }
  8365. });
  8366. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8367. tmp.each(function () {
  8368. var ssrc = $(this).attr('ssrc');
  8369. if(mySdp.containsSSRC(ssrc)){
  8370. /**
  8371. * This happens when multiple participants change their streams at the same time and
  8372. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8373. * addssrc are scheduled for update IQ. See
  8374. */
  8375. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8376. return;
  8377. }
  8378. if (sdp.containsSSRC(ssrc)) {
  8379. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8380. return;
  8381. }
  8382. $(this).find('>parameter').each(function () {
  8383. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8384. if ($(this).attr('value') && $(this).attr('value').length)
  8385. lines += ':' + $(this).attr('value');
  8386. lines += '\r\n';
  8387. });
  8388. });
  8389. sdp.media.forEach(function(media, idx) {
  8390. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8391. return;
  8392. sdp.media[idx] += lines;
  8393. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8394. self.addssrc[idx] += lines;
  8395. });
  8396. sdp.raw = sdp.session + sdp.media.join('');
  8397. });
  8398. this.modifySourcesQueue.push(function() {
  8399. // When a source is added and if this is FF, a new channel is allocated
  8400. // for receiving the added source. We need to diffuse the SSRC of this
  8401. // new recvonly channel to the rest of the peers.
  8402. logger.log('modify sources done');
  8403. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8404. logger.log("SDPs", mySdp, newSdp);
  8405. self.notifyMySSRCUpdate(mySdp, newSdp);
  8406. });
  8407. };
  8408. /**
  8409. * Handles a Jingle source-remove message for this Jingle session.
  8410. * @param elem An array of Jingle "content" elements.
  8411. */
  8412. JingleSessionPC.prototype.removeSource = function (elem) {
  8413. var self = this;
  8414. // FIXME: dirty waiting
  8415. if (!this.peerconnection.localDescription) {
  8416. logger.warn("removeSource - localDescription not ready yet");
  8417. setTimeout(function() {
  8418. self.removeSource(elem);
  8419. },
  8420. 200
  8421. );
  8422. return;
  8423. }
  8424. logger.log('removessrc', new Date().getTime());
  8425. logger.log('ice', this.peerconnection.iceConnectionState);
  8426. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8427. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8428. $(elem).each(function (idx, content) {
  8429. var name = $(content).attr('name');
  8430. var lines = '';
  8431. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8432. var semantics = this.getAttribute('semantics');
  8433. var ssrcs = $(this).find('>source').map(function () {
  8434. return this.getAttribute('ssrc');
  8435. }).get();
  8436. if (ssrcs.length) {
  8437. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8438. }
  8439. });
  8440. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8441. tmp.each(function () {
  8442. var ssrc = $(this).attr('ssrc');
  8443. // This should never happen, but can be useful for bug detection
  8444. if(mySdp.containsSSRC(ssrc)){
  8445. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8446. return;
  8447. }
  8448. $(this).find('>parameter').each(function () {
  8449. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8450. if ($(this).attr('value') && $(this).attr('value').length)
  8451. lines += ':' + $(this).attr('value');
  8452. lines += '\r\n';
  8453. });
  8454. });
  8455. sdp.media.forEach(function(media, idx) {
  8456. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8457. return;
  8458. sdp.media[idx] += lines;
  8459. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8460. self.removessrc[idx] += lines;
  8461. });
  8462. sdp.raw = sdp.session + sdp.media.join('');
  8463. });
  8464. this.modifySourcesQueue.push(function() {
  8465. // When a source is removed and if this is FF, the recvonly channel that
  8466. // receives the remote stream is deactivated . We need to diffuse the
  8467. // recvonly SSRC removal to the rest of the peers.
  8468. logger.log('modify sources done');
  8469. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8470. logger.log("SDPs", mySdp, newSdp);
  8471. self.notifyMySSRCUpdate(mySdp, newSdp);
  8472. });
  8473. };
  8474. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8475. var self = this;
  8476. if (this.peerconnection.signalingState == 'closed') return;
  8477. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8478. || this.switchstreams || this.addingStreams)){
  8479. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8480. this.setLocalDescription();
  8481. if(successCallback){
  8482. successCallback();
  8483. }
  8484. queueCallback();
  8485. return;
  8486. }
  8487. // Reset switch streams flags
  8488. this.switchstreams = false;
  8489. this.addingStreams = false;
  8490. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8491. // add sources
  8492. this.addssrc.forEach(function(lines, idx) {
  8493. sdp.media[idx] += lines;
  8494. });
  8495. this.addssrc = [];
  8496. // remove sources
  8497. this.removessrc.forEach(function(lines, idx) {
  8498. lines = lines.split('\r\n');
  8499. lines.pop(); // remove empty last element;
  8500. lines.forEach(function(line) {
  8501. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8502. });
  8503. });
  8504. this.removessrc = [];
  8505. sdp.raw = sdp.session + sdp.media.join('');
  8506. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8507. function() {
  8508. if(self.signalingState == 'closed') {
  8509. logger.error("createAnswer attempt on closed state");
  8510. queueCallback("createAnswer attempt on closed state");
  8511. return;
  8512. }
  8513. self.peerconnection.createAnswer(
  8514. function(modifiedAnswer) {
  8515. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8516. if (self.pendingop !== null) {
  8517. var sdp = new SDP(modifiedAnswer.sdp);
  8518. if (sdp.media.length > 1) {
  8519. switch(self.pendingop) {
  8520. case 'mute':
  8521. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8522. break;
  8523. case 'unmute':
  8524. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8525. break;
  8526. }
  8527. sdp.raw = sdp.session + sdp.media.join('');
  8528. modifiedAnswer.sdp = sdp.raw;
  8529. }
  8530. self.pendingop = null;
  8531. }
  8532. // FIXME: pushing down an answer while ice connection state
  8533. // is still checking is bad...
  8534. //logger.log(self.peerconnection.iceConnectionState);
  8535. // trying to work around another chrome bug
  8536. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8537. self.peerconnection.setLocalDescription(modifiedAnswer,
  8538. function() {
  8539. //logger.log('modified setLocalDescription ok');
  8540. self.setLocalDescription();
  8541. if(successCallback){
  8542. successCallback();
  8543. }
  8544. queueCallback();
  8545. },
  8546. function(error) {
  8547. logger.error('modified setLocalDescription failed', error);
  8548. queueCallback(error);
  8549. }
  8550. );
  8551. },
  8552. function(error) {
  8553. logger.error('modified answer failed', error);
  8554. queueCallback(error);
  8555. }
  8556. );
  8557. },
  8558. function(error) {
  8559. logger.error('modify failed', error);
  8560. queueCallback(error);
  8561. }
  8562. );
  8563. };
  8564. /**
  8565. * Switches video streams.
  8566. * @param newStream new stream that will be used as video of this session.
  8567. * @param oldStream old video stream of this session.
  8568. * @param successCallback callback executed after successful stream switch.
  8569. * @param isAudio whether the streams are audio (if true) or video (if false).
  8570. */
  8571. JingleSessionPC.prototype.switchStreams =
  8572. function (newStream, oldStream, successCallback, isAudio) {
  8573. var self = this;
  8574. var sender, newTrack;
  8575. var senderKind = isAudio ? 'audio' : 'video';
  8576. // Remember SDP to figure out added/removed SSRCs
  8577. var oldSdp = null;
  8578. if (self.peerconnection) {
  8579. if (self.peerconnection.localDescription) {
  8580. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8581. }
  8582. if (RTCBrowserType.getBrowserType() ===
  8583. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8584. // On Firefox we don't replace MediaStreams as this messes up the
  8585. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8586. // of complications. Instead, we use the RTPSender and replace just
  8587. // the track.
  8588. // Find the right sender (for audio or video)
  8589. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8590. if (s.track && s.track.kind === senderKind) {
  8591. sender = s;
  8592. return true;
  8593. }
  8594. });
  8595. if (sender) {
  8596. // We assume that our streams have a single track, either audio
  8597. // or video.
  8598. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8599. newStream.getVideoTracks()[0];
  8600. sender.replaceTrack(newTrack)
  8601. .then(function() {
  8602. console.log("Replaced a track, isAudio=" + isAudio);
  8603. })
  8604. .catch(function(err) {
  8605. console.log("Failed to replace a track: " + err);
  8606. });
  8607. } else {
  8608. console.log("Cannot switch tracks: no RTPSender.");
  8609. }
  8610. } else {
  8611. self.peerconnection.removeStream(oldStream, true);
  8612. if (newStream) {
  8613. self.peerconnection.addStream(newStream);
  8614. }
  8615. }
  8616. }
  8617. // Conference is not active
  8618. if (!oldSdp) {
  8619. successCallback();
  8620. return;
  8621. }
  8622. self.switchstreams = true;
  8623. self.modifySourcesQueue.push(function() {
  8624. logger.log('modify sources done');
  8625. successCallback();
  8626. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8627. logger.log("SDPs", oldSdp, newSdp);
  8628. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8629. });
  8630. };
  8631. /**
  8632. * Adds streams.
  8633. * @param stream new stream that will be added.
  8634. * @param success_callback callback executed after successful stream addition.
  8635. */
  8636. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8637. var self = this;
  8638. // Remember SDP to figure out added/removed SSRCs
  8639. var oldSdp = null;
  8640. if(this.peerconnection) {
  8641. if(this.peerconnection.localDescription) {
  8642. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8643. }
  8644. if(stream)
  8645. this.peerconnection.addStream(stream);
  8646. }
  8647. // Conference is not active
  8648. if(!oldSdp || !this.peerconnection) {
  8649. callback();
  8650. return;
  8651. }
  8652. this.addingStreams = true;
  8653. this.modifySourcesQueue.push(function() {
  8654. logger.log('modify sources done');
  8655. callback();
  8656. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8657. logger.log("SDPs", oldSdp, newSdp);
  8658. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8659. });
  8660. }
  8661. /**
  8662. * Remove streams.
  8663. * @param stream stream that will be removed.
  8664. * @param success_callback callback executed after successful stream addition.
  8665. */
  8666. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8667. var self = this;
  8668. // Remember SDP to figure out added/removed SSRCs
  8669. var oldSdp = null;
  8670. if(this.peerconnection) {
  8671. if(this.peerconnection.localDescription) {
  8672. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8673. }
  8674. if (RTCBrowserType.getBrowserType() ===
  8675. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8676. var sender = null;
  8677. // On Firefox we don't replace MediaStreams as this messes up the
  8678. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8679. // of complications. Instead, we use the RTPSender and replace just
  8680. // the track.
  8681. var track = null;
  8682. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8683. track = stream.getAudioTracks()[0];
  8684. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8685. {
  8686. track = stream.getVideoTracks()[0];
  8687. }
  8688. if(!track) {
  8689. console.log("Cannot switch tracks: no tracks.");
  8690. return;
  8691. }
  8692. // Find the right sender (for audio or video)
  8693. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8694. if (s.track === track) {
  8695. sender = s;
  8696. return true;
  8697. }
  8698. });
  8699. if (sender) {
  8700. self.peerconnection.peerconnection.removeTrack(sender);
  8701. // .then(function() {
  8702. // console.log("Replaced a track, isAudio=" + isAudio);
  8703. // })
  8704. // .catch(function(err) {
  8705. // console.log("Failed to replace a track: " + err);
  8706. // });
  8707. } else {
  8708. console.log("Cannot switch tracks: no RTPSender.");
  8709. }
  8710. } else if(stream)
  8711. this.peerconnection.removeStream(stream);
  8712. }
  8713. // Conference is not active
  8714. if(!oldSdp || !this.peerconnection) {
  8715. callback();
  8716. return;
  8717. }
  8718. this.addingStreams = true;
  8719. this.modifySourcesQueue.push(function() {
  8720. logger.log('modify sources done');
  8721. callback();
  8722. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8723. logger.log("SDPs", oldSdp, newSdp);
  8724. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8725. });
  8726. }
  8727. /**
  8728. * Figures out added/removed ssrcs and send update IQs.
  8729. * @param old_sdp SDP object for old description.
  8730. * @param new_sdp SDP object for new description.
  8731. */
  8732. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8733. if (!(this.peerconnection.signalingState == 'stable' &&
  8734. this.peerconnection.iceConnectionState == 'connected')){
  8735. logger.log("Too early to send updates");
  8736. return;
  8737. }
  8738. // send source-remove IQ.
  8739. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8740. var remove = $iq({to: this.peerjid, type: 'set'})
  8741. .c('jingle', {
  8742. xmlns: 'urn:xmpp:jingle:1',
  8743. action: 'source-remove',
  8744. initiator: this.initiator,
  8745. sid: this.sid
  8746. }
  8747. );
  8748. var removed = sdpDiffer.toJingle(remove);
  8749. if (removed && remove) {
  8750. logger.info("Sending source-remove", remove);
  8751. this.connection.sendIQ(remove,
  8752. function (res) {
  8753. logger.info('got remove result', res);
  8754. },
  8755. function (err) {
  8756. logger.error('got remove error', err);
  8757. }
  8758. );
  8759. } else {
  8760. logger.log('removal not necessary');
  8761. }
  8762. // send source-add IQ.
  8763. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8764. var add = $iq({to: this.peerjid, type: 'set'})
  8765. .c('jingle', {
  8766. xmlns: 'urn:xmpp:jingle:1',
  8767. action: 'source-add',
  8768. initiator: this.initiator,
  8769. sid: this.sid
  8770. }
  8771. );
  8772. var added = sdpDiffer.toJingle(add);
  8773. if (added && add) {
  8774. logger.info("Sending source-add", add);
  8775. this.connection.sendIQ(add,
  8776. function (res) {
  8777. logger.info('got add result', res);
  8778. },
  8779. function (err) {
  8780. logger.error('got add error', err);
  8781. }
  8782. );
  8783. } else {
  8784. logger.log('addition not necessary');
  8785. }
  8786. };
  8787. JingleSessionPC.prototype.getStats = function (interval) {
  8788. var self = this;
  8789. var recv = {audio: 0, video: 0};
  8790. var lost = {audio: 0, video: 0};
  8791. var lastrecv = {audio: 0, video: 0};
  8792. var lastlost = {audio: 0, video: 0};
  8793. var loss = {audio: 0, video: 0};
  8794. var delta = {audio: 0, video: 0};
  8795. this.statsinterval = window.setInterval(function () {
  8796. if (self && self.peerconnection && self.peerconnection.getStats) {
  8797. self.peerconnection.getStats(function (stats) {
  8798. var results = stats.result();
  8799. // TODO: there are so much statistics you can get from this..
  8800. for (var i = 0; i < results.length; ++i) {
  8801. if (results[i].type == 'ssrc') {
  8802. var packetsrecv = results[i].stat('packetsReceived');
  8803. var packetslost = results[i].stat('packetsLost');
  8804. if (packetsrecv && packetslost) {
  8805. packetsrecv = parseInt(packetsrecv, 10);
  8806. packetslost = parseInt(packetslost, 10);
  8807. if (results[i].stat('googFrameRateReceived')) {
  8808. lastlost.video = lost.video;
  8809. lastrecv.video = recv.video;
  8810. recv.video = packetsrecv;
  8811. lost.video = packetslost;
  8812. } else {
  8813. lastlost.audio = lost.audio;
  8814. lastrecv.audio = recv.audio;
  8815. recv.audio = packetsrecv;
  8816. lost.audio = packetslost;
  8817. }
  8818. }
  8819. }
  8820. }
  8821. delta.audio = recv.audio - lastrecv.audio;
  8822. delta.video = recv.video - lastrecv.video;
  8823. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8824. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8825. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8826. });
  8827. }
  8828. }, interval || 3000);
  8829. return this.statsinterval;
  8830. };
  8831. JingleSessionPC.onJingleError = function (session, error)
  8832. {
  8833. logger.error("Jingle error", error);
  8834. }
  8835. JingleSessionPC.onJingleFatalError = function (session, error)
  8836. {
  8837. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8838. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8839. }
  8840. JingleSessionPC.prototype.setLocalDescription = function () {
  8841. var self = this;
  8842. var newssrcs = [];
  8843. if(!this.peerconnection.localDescription)
  8844. return;
  8845. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8846. var i;
  8847. session.media.forEach(function (media) {
  8848. if (media.ssrcs && media.ssrcs.length > 0) {
  8849. // TODO(gp) maybe exclude FID streams?
  8850. media.ssrcs.forEach(function (ssrc) {
  8851. if (ssrc.attribute !== 'cname') {
  8852. return;
  8853. }
  8854. newssrcs.push({
  8855. 'ssrc': ssrc.id,
  8856. 'type': media.type
  8857. });
  8858. // FIXME allows for only one SSRC per media type
  8859. self.localStreamsSSRC[media.type] = ssrc.id;
  8860. });
  8861. }
  8862. });
  8863. logger.log('new ssrcs', newssrcs);
  8864. // Bind us as local SSRCs owner
  8865. if (newssrcs.length > 0) {
  8866. for (i = 0; i < newssrcs.length; i++) {
  8867. var ssrc = newssrcs[i].ssrc;
  8868. var myJid = self.me;
  8869. self.ssrcOwners[ssrc] = myJid;
  8870. }
  8871. }
  8872. }
  8873. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8874. JingleSessionPC.prototype.sendKeyframe = function () {
  8875. var pc = this.peerconnection;
  8876. logger.log('sendkeyframe', pc.iceConnectionState);
  8877. if (pc.iceConnectionState !== 'connected') return; // safe...
  8878. var self = this;
  8879. pc.setRemoteDescription(
  8880. pc.remoteDescription,
  8881. function () {
  8882. pc.createAnswer(
  8883. function (modifiedAnswer) {
  8884. pc.setLocalDescription(
  8885. modifiedAnswer,
  8886. function () {
  8887. // noop
  8888. },
  8889. function (error) {
  8890. logger.log('triggerKeyframe setLocalDescription failed', error);
  8891. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8892. }
  8893. );
  8894. },
  8895. function (error) {
  8896. logger.log('triggerKeyframe createAnswer failed', error);
  8897. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8898. }
  8899. );
  8900. },
  8901. function (error) {
  8902. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8903. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8904. }
  8905. );
  8906. }
  8907. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8908. var self = this;
  8909. var thessrc;
  8910. var streamId = RTC.getStreamID(data.stream);
  8911. // look up an associated JID for a stream id
  8912. if (!streamId) {
  8913. logger.error("No stream ID for", data.stream);
  8914. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8915. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8916. var ssrclines = this.peerconnection.remoteDescription?
  8917. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8918. ssrclines = ssrclines.filter(function (line) {
  8919. // NOTE(gp) previously we filtered on the mslabel, but that property
  8920. // is not always present.
  8921. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8922. if (RTCBrowserType.isTemasysPluginUsed()) {
  8923. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8924. } else {
  8925. return ((line.indexOf('msid:' + streamId) !== -1));
  8926. }
  8927. });
  8928. if (ssrclines.length) {
  8929. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8930. if (!self.ssrcOwners[thessrc]) {
  8931. logger.error("No SSRC owner known for: " + thessrc);
  8932. return;
  8933. }
  8934. data.peerjid = self.ssrcOwners[thessrc];
  8935. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8936. } else {
  8937. logger.error("No SSRC lines for ", streamId);
  8938. }
  8939. }
  8940. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8941. var isVideo = data.stream.getVideoTracks().length > 0;
  8942. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8943. if (isVideo &&
  8944. data.peerjid && this.peerjid === data.peerjid &&
  8945. data.stream.getVideoTracks().length === 0 &&
  8946. RTC.localVideo.getTracks().length > 0) {
  8947. window.setTimeout(function () {
  8948. self.sendKeyframe();
  8949. }, 3000);
  8950. }
  8951. }
  8952. /**
  8953. * Returns the ice connection state for the peer connection.
  8954. * @returns the ice connection state for the peer connection.
  8955. */
  8956. JingleSessionPC.prototype.getIceConnectionState = function () {
  8957. return this.peerconnection.iceConnectionState;
  8958. }
  8959. module.exports = JingleSessionPC;
  8960. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  8961. },{"../../service/xmpp/XMPPEvents":143,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":45,"jitsi-meet-logger":50,"sdp-transform":83}],32:[function(require,module,exports){
  8962. (function (__filename){
  8963. /* jshint -W117 */
  8964. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8965. var SDPUtil = require("./SDPUtil");
  8966. // SDP STUFF
  8967. function SDP(sdp) {
  8968. /**
  8969. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8970. * @type {boolean}
  8971. */
  8972. this.removeTcpCandidates = false;
  8973. /**
  8974. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8975. * @type {boolean}
  8976. */
  8977. this.removeUdpCandidates = false;
  8978. this.media = sdp.split('\r\nm=');
  8979. for (var i = 1; i < this.media.length; i++) {
  8980. this.media[i] = 'm=' + this.media[i];
  8981. if (i != this.media.length - 1) {
  8982. this.media[i] += '\r\n';
  8983. }
  8984. }
  8985. this.session = this.media.shift() + '\r\n';
  8986. this.raw = this.session + this.media.join('');
  8987. }
  8988. /**
  8989. * Returns map of MediaChannel mapped per channel idx.
  8990. */
  8991. SDP.prototype.getMediaSsrcMap = function() {
  8992. var self = this;
  8993. var media_ssrcs = {};
  8994. var tmp;
  8995. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8996. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8997. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8998. var media = {
  8999. mediaindex: mediaindex,
  9000. mid: mid,
  9001. ssrcs: {},
  9002. ssrcGroups: []
  9003. };
  9004. media_ssrcs[mediaindex] = media;
  9005. tmp.forEach(function (line) {
  9006. var linessrc = line.substring(7).split(' ')[0];
  9007. // allocate new ChannelSsrc
  9008. if(!media.ssrcs[linessrc]) {
  9009. media.ssrcs[linessrc] = {
  9010. ssrc: linessrc,
  9011. lines: []
  9012. };
  9013. }
  9014. media.ssrcs[linessrc].lines.push(line);
  9015. });
  9016. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  9017. tmp.forEach(function(line){
  9018. var idx = line.indexOf(' ');
  9019. var semantics = line.substr(0, idx).substr(13);
  9020. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9021. if (ssrcs.length) {
  9022. media.ssrcGroups.push({
  9023. semantics: semantics,
  9024. ssrcs: ssrcs
  9025. });
  9026. }
  9027. });
  9028. }
  9029. return media_ssrcs;
  9030. };
  9031. /**
  9032. * Returns <tt>true</tt> if this SDP contains given SSRC.
  9033. * @param ssrc the ssrc to check.
  9034. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  9035. */
  9036. SDP.prototype.containsSSRC = function (ssrc) {
  9037. // FIXME this code is really strange - improve it if you can
  9038. var medias = this.getMediaSsrcMap();
  9039. var result = false;
  9040. Object.keys(medias).forEach(function (mediaindex) {
  9041. if (result)
  9042. return;
  9043. if (medias[mediaindex].ssrcs[ssrc]) {
  9044. result = true;
  9045. }
  9046. });
  9047. return result;
  9048. };
  9049. // remove iSAC and CN from SDP
  9050. SDP.prototype.mangle = function () {
  9051. var i, j, mline, lines, rtpmap, newdesc;
  9052. for (i = 0; i < this.media.length; i++) {
  9053. lines = this.media[i].split('\r\n');
  9054. lines.pop(); // remove empty last element
  9055. mline = SDPUtil.parse_mline(lines.shift());
  9056. if (mline.media != 'audio')
  9057. continue;
  9058. newdesc = '';
  9059. mline.fmt.length = 0;
  9060. for (j = 0; j < lines.length; j++) {
  9061. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  9062. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  9063. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  9064. continue;
  9065. mline.fmt.push(rtpmap.id);
  9066. newdesc += lines[j] + '\r\n';
  9067. } else {
  9068. newdesc += lines[j] + '\r\n';
  9069. }
  9070. }
  9071. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  9072. this.media[i] += newdesc;
  9073. }
  9074. this.raw = this.session + this.media.join('');
  9075. };
  9076. // remove lines matching prefix from session section
  9077. SDP.prototype.removeSessionLines = function(prefix) {
  9078. var self = this;
  9079. var lines = SDPUtil.find_lines(this.session, prefix);
  9080. lines.forEach(function(line) {
  9081. self.session = self.session.replace(line + '\r\n', '');
  9082. });
  9083. this.raw = this.session + this.media.join('');
  9084. return lines;
  9085. }
  9086. // remove lines matching prefix from a media section specified by mediaindex
  9087. // TODO: non-numeric mediaindex could match mid
  9088. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  9089. var self = this;
  9090. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  9091. lines.forEach(function(line) {
  9092. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  9093. });
  9094. this.raw = this.session + this.media.join('');
  9095. return lines;
  9096. }
  9097. // add content's to a jingle element
  9098. SDP.prototype.toJingle = function (elem, thecreator) {
  9099. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  9100. var self = this;
  9101. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  9102. // new bundle plan
  9103. if (SDPUtil.find_line(this.session, 'a=group:')) {
  9104. lines = SDPUtil.find_lines(this.session, 'a=group:');
  9105. for (i = 0; i < lines.length; i++) {
  9106. tmp = lines[i].split(' ');
  9107. var semantics = tmp.shift().substr(8);
  9108. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  9109. for (j = 0; j < tmp.length; j++) {
  9110. elem.c('content', {name: tmp[j]}).up();
  9111. }
  9112. elem.up();
  9113. }
  9114. }
  9115. for (i = 0; i < this.media.length; i++) {
  9116. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  9117. if (!(mline.media === 'audio' ||
  9118. mline.media === 'video' ||
  9119. mline.media === 'application'))
  9120. {
  9121. continue;
  9122. }
  9123. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  9124. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  9125. } else {
  9126. ssrc = false;
  9127. }
  9128. elem.c('content', {creator: thecreator, name: mline.media});
  9129. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  9130. // prefer identifier from a=mid if present
  9131. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  9132. elem.attrs({ name: mid });
  9133. }
  9134. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  9135. elem.c('description',
  9136. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  9137. media: mline.media });
  9138. if (ssrc) {
  9139. elem.attrs({ssrc: ssrc});
  9140. }
  9141. for (j = 0; j < mline.fmt.length; j++) {
  9142. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  9143. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  9144. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  9145. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  9146. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  9147. for (k = 0; k < tmp.length; k++) {
  9148. elem.c('parameter', tmp[k]).up();
  9149. }
  9150. }
  9151. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  9152. elem.up();
  9153. }
  9154. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  9155. elem.c('encryption', {required: 1});
  9156. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  9157. crypto.forEach(function(line) {
  9158. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  9159. });
  9160. elem.up(); // end of encryption
  9161. }
  9162. if (ssrc) {
  9163. // new style mapping
  9164. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9165. // FIXME: group by ssrc and support multiple different ssrcs
  9166. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  9167. if(ssrclines.length > 0) {
  9168. ssrclines.forEach(function (line) {
  9169. var idx = line.indexOf(' ');
  9170. var linessrc = line.substr(0, idx).substr(7);
  9171. if (linessrc != ssrc) {
  9172. elem.up();
  9173. ssrc = linessrc;
  9174. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9175. }
  9176. var kv = line.substr(idx + 1);
  9177. elem.c('parameter');
  9178. if (kv.indexOf(':') == -1) {
  9179. elem.attrs({ name: kv });
  9180. } else {
  9181. var k = kv.split(':', 2)[0];
  9182. elem.attrs({ name: k });
  9183. var v = kv.split(':', 2)[1];
  9184. v = SDPUtil.filter_special_chars(v);
  9185. elem.attrs({ value: v });
  9186. }
  9187. elem.up();
  9188. });
  9189. } else {
  9190. elem.up();
  9191. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9192. elem.c('parameter');
  9193. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9194. elem.up();
  9195. var msid = null;
  9196. if(mline.media == "audio")
  9197. {
  9198. msid = APP.RTC.localAudio._getId();
  9199. }
  9200. else
  9201. {
  9202. msid = APP.RTC.localVideo._getId();
  9203. }
  9204. if(msid != null)
  9205. {
  9206. msid = SDPUtil.filter_special_chars(msid);
  9207. elem.c('parameter');
  9208. elem.attrs({name: "msid", value:msid});
  9209. elem.up();
  9210. elem.c('parameter');
  9211. elem.attrs({name: "mslabel", value:msid});
  9212. elem.up();
  9213. elem.c('parameter');
  9214. elem.attrs({name: "label", value:msid});
  9215. elem.up();
  9216. }
  9217. }
  9218. elem.up();
  9219. // XEP-0339 handle ssrc-group attributes
  9220. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9221. ssrc_group_lines.forEach(function(line) {
  9222. var idx = line.indexOf(' ');
  9223. var semantics = line.substr(0, idx).substr(13);
  9224. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9225. if (ssrcs.length) {
  9226. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9227. ssrcs.forEach(function(ssrc) {
  9228. elem.c('source', { ssrc: ssrc })
  9229. .up();
  9230. });
  9231. elem.up();
  9232. }
  9233. });
  9234. }
  9235. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9236. elem.c('rtcp-mux').up();
  9237. }
  9238. // XEP-0293 -- map a=rtcp-fb:*
  9239. this.rtcpFbToJingle(i, elem, '*');
  9240. // XEP-0294
  9241. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9242. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9243. for (j = 0; j < lines.length; j++) {
  9244. tmp = SDPUtil.parse_extmap(lines[j]);
  9245. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9246. uri: tmp.uri,
  9247. id: tmp.value });
  9248. if (tmp.hasOwnProperty('direction')) {
  9249. switch (tmp.direction) {
  9250. case 'sendonly':
  9251. elem.attrs({senders: 'responder'});
  9252. break;
  9253. case 'recvonly':
  9254. elem.attrs({senders: 'initiator'});
  9255. break;
  9256. case 'sendrecv':
  9257. elem.attrs({senders: 'both'});
  9258. break;
  9259. case 'inactive':
  9260. elem.attrs({senders: 'none'});
  9261. break;
  9262. }
  9263. }
  9264. // TODO: handle params
  9265. elem.up();
  9266. }
  9267. }
  9268. elem.up(); // end of description
  9269. }
  9270. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9271. this.transportToJingle(i, elem);
  9272. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9273. elem.attrs({senders: 'both'});
  9274. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9275. elem.attrs({senders: 'initiator'});
  9276. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9277. elem.attrs({senders: 'responder'});
  9278. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9279. elem.attrs({senders: 'none'});
  9280. }
  9281. if (mline.port == '0') {
  9282. // estos hack to reject an m-line
  9283. elem.attrs({senders: 'rejected'});
  9284. }
  9285. elem.up(); // end of content
  9286. }
  9287. elem.up();
  9288. return elem;
  9289. };
  9290. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9291. var tmp, sctpmap, sctpAttrs, fingerprints;
  9292. var self = this;
  9293. elem.c('transport');
  9294. // XEP-0343 DTLS/SCTP
  9295. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9296. {
  9297. sctpmap = SDPUtil.find_line(
  9298. this.media[mediaindex], 'a=sctpmap:', self.session);
  9299. if (sctpmap)
  9300. {
  9301. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9302. elem.c('sctpmap',
  9303. {
  9304. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9305. number: sctpAttrs[0], /* SCTP port */
  9306. protocol: sctpAttrs[1] /* protocol */
  9307. });
  9308. // Optional stream count attribute
  9309. if (sctpAttrs.length > 2)
  9310. elem.attrs({ streams: sctpAttrs[2]});
  9311. elem.up();
  9312. }
  9313. }
  9314. // XEP-0320
  9315. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9316. fingerprints.forEach(function(line) {
  9317. tmp = SDPUtil.parse_fingerprint(line);
  9318. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9319. elem.c('fingerprint').t(tmp.fingerprint);
  9320. delete tmp.fingerprint;
  9321. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9322. if (line) {
  9323. tmp.setup = line.substr(8);
  9324. }
  9325. elem.attrs(tmp);
  9326. elem.up(); // end of fingerprint
  9327. });
  9328. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9329. if (tmp) {
  9330. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9331. elem.attrs(tmp);
  9332. // XEP-0176
  9333. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9334. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9335. lines.forEach(function (line) {
  9336. var candidate = SDPUtil.candidateToJingle(line);
  9337. var protocol = (candidate &&
  9338. typeof candidate.protocol === 'string')
  9339. ? candidate.protocol.toLowerCase() : '';
  9340. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9341. (self.removeUdpCandidates && protocol === 'udp')) {
  9342. return;
  9343. }
  9344. elem.c('candidate', candidate).up();
  9345. });
  9346. }
  9347. }
  9348. elem.up(); // end of transport
  9349. }
  9350. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9351. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9352. lines.forEach(function (line) {
  9353. var tmp = SDPUtil.parse_rtcpfb(line);
  9354. if (tmp.type == 'trr-int') {
  9355. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9356. elem.up();
  9357. } else {
  9358. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9359. if (tmp.params.length > 0) {
  9360. elem.attrs({'subtype': tmp.params[0]});
  9361. }
  9362. elem.up();
  9363. }
  9364. });
  9365. };
  9366. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9367. var media = '';
  9368. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9369. if (tmp.length) {
  9370. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9371. if (tmp.attr('value')) {
  9372. media += tmp.attr('value');
  9373. } else {
  9374. media += '0';
  9375. }
  9376. media += '\r\n';
  9377. }
  9378. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9379. tmp.each(function () {
  9380. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9381. if ($(this).attr('subtype')) {
  9382. media += ' ' + $(this).attr('subtype');
  9383. }
  9384. media += '\r\n';
  9385. });
  9386. return media;
  9387. };
  9388. // construct an SDP from a jingle stanza
  9389. SDP.prototype.fromJingle = function (jingle) {
  9390. var self = this;
  9391. this.raw = 'v=0\r\n' +
  9392. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9393. 's=-\r\n' +
  9394. 't=0 0\r\n';
  9395. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9396. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9397. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9398. var contents = $(group).find('>content').map(function (idx, content) {
  9399. return content.getAttribute('name');
  9400. }).get();
  9401. if (contents.length > 0) {
  9402. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9403. }
  9404. });
  9405. }
  9406. this.session = this.raw;
  9407. jingle.find('>content').each(function () {
  9408. var m = self.jingle2media($(this));
  9409. self.media.push(m);
  9410. });
  9411. // reconstruct msid-semantic -- apparently not necessary
  9412. /*
  9413. var msid = SDPUtil.parse_ssrc(this.raw);
  9414. if (msid.hasOwnProperty('mslabel')) {
  9415. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9416. }
  9417. */
  9418. this.raw = this.session + this.media.join('');
  9419. };
  9420. // translate a jingle content element into an an SDP media part
  9421. SDP.prototype.jingle2media = function (content) {
  9422. var media = '',
  9423. desc = content.find('description'),
  9424. ssrc = desc.attr('ssrc'),
  9425. self = this,
  9426. tmp;
  9427. var sctp = content.find(
  9428. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9429. tmp = { media: desc.attr('media') };
  9430. tmp.port = '1';
  9431. if (content.attr('senders') == 'rejected') {
  9432. // estos hack to reject an m-line.
  9433. tmp.port = '0';
  9434. }
  9435. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9436. if (sctp.length)
  9437. tmp.proto = 'DTLS/SCTP';
  9438. else
  9439. tmp.proto = 'RTP/SAVPF';
  9440. } else {
  9441. tmp.proto = 'RTP/AVPF';
  9442. }
  9443. if (!sctp.length) {
  9444. tmp.fmt = desc.find('payload-type').map(
  9445. function () { return this.getAttribute('id'); }).get();
  9446. media += SDPUtil.build_mline(tmp) + '\r\n';
  9447. } else {
  9448. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9449. media += 'a=sctpmap:' + sctp.attr('number') +
  9450. ' ' + sctp.attr('protocol');
  9451. var streamCount = sctp.attr('streams');
  9452. if (streamCount)
  9453. media += ' ' + streamCount + '\r\n';
  9454. else
  9455. media += '\r\n';
  9456. }
  9457. media += 'c=IN IP4 0.0.0.0\r\n';
  9458. if (!sctp.length)
  9459. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9460. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9461. if (tmp.length) {
  9462. if (tmp.attr('ufrag')) {
  9463. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9464. }
  9465. if (tmp.attr('pwd')) {
  9466. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9467. }
  9468. tmp.find('>fingerprint').each(function () {
  9469. // FIXME: check namespace at some point
  9470. media += 'a=fingerprint:' + this.getAttribute('hash');
  9471. media += ' ' + $(this).text();
  9472. media += '\r\n';
  9473. if (this.getAttribute('setup')) {
  9474. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9475. }
  9476. });
  9477. }
  9478. switch (content.attr('senders')) {
  9479. case 'initiator':
  9480. media += 'a=sendonly\r\n';
  9481. break;
  9482. case 'responder':
  9483. media += 'a=recvonly\r\n';
  9484. break;
  9485. case 'none':
  9486. media += 'a=inactive\r\n';
  9487. break;
  9488. case 'both':
  9489. media += 'a=sendrecv\r\n';
  9490. break;
  9491. }
  9492. media += 'a=mid:' + content.attr('name') + '\r\n';
  9493. // <description><rtcp-mux/></description>
  9494. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9495. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9496. if (desc.find('rtcp-mux').length) {
  9497. media += 'a=rtcp-mux\r\n';
  9498. }
  9499. if (desc.find('encryption').length) {
  9500. desc.find('encryption>crypto').each(function () {
  9501. media += 'a=crypto:' + this.getAttribute('tag');
  9502. media += ' ' + this.getAttribute('crypto-suite');
  9503. media += ' ' + this.getAttribute('key-params');
  9504. if (this.getAttribute('session-params')) {
  9505. media += ' ' + this.getAttribute('session-params');
  9506. }
  9507. media += '\r\n';
  9508. });
  9509. }
  9510. desc.find('payload-type').each(function () {
  9511. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9512. if ($(this).find('>parameter').length) {
  9513. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9514. media += $(this).find('parameter').map(function () {
  9515. return (this.getAttribute('name')
  9516. ? (this.getAttribute('name') + '=') : '') +
  9517. this.getAttribute('value');
  9518. }).get().join('; ');
  9519. media += '\r\n';
  9520. }
  9521. // xep-0293
  9522. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9523. });
  9524. // xep-0293
  9525. media += self.rtcpFbFromJingle(desc, '*');
  9526. // xep-0294
  9527. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9528. tmp.each(function () {
  9529. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9530. });
  9531. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9532. var protocol = this.getAttribute('protocol');
  9533. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9534. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9535. (self.removeUdpCandidates && protocol === 'udp')) {
  9536. return;
  9537. }
  9538. media += SDPUtil.candidateFromJingle(this);
  9539. });
  9540. // XEP-0339 handle ssrc-group attributes
  9541. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9542. var semantics = this.getAttribute('semantics');
  9543. var ssrcs = $(this).find('>source').map(function() {
  9544. return this.getAttribute('ssrc');
  9545. }).get();
  9546. if (ssrcs.length) {
  9547. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9548. }
  9549. });
  9550. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9551. tmp.each(function () {
  9552. var ssrc = this.getAttribute('ssrc');
  9553. $(this).find('>parameter').each(function () {
  9554. var name = this.getAttribute('name');
  9555. var value = this.getAttribute('value');
  9556. value = SDPUtil.filter_special_chars(value);
  9557. media += 'a=ssrc:' + ssrc + ' ' + name;
  9558. if (value && value.length)
  9559. media += ':' + value;
  9560. media += '\r\n';
  9561. });
  9562. });
  9563. return media;
  9564. };
  9565. module.exports = SDP;
  9566. }).call(this,"/modules/xmpp/SDP.js")
  9567. },{"./SDPUtil":34,"jitsi-meet-logger":50}],33:[function(require,module,exports){
  9568. var SDPUtil = require("./SDPUtil");
  9569. function SDPDiffer(mySDP, otherSDP)
  9570. {
  9571. this.mySDP = mySDP;
  9572. this.otherSDP = otherSDP;
  9573. }
  9574. /**
  9575. * Returns map of MediaChannel that contains media contained in
  9576. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9577. */
  9578. SDPDiffer.prototype.getNewMedia = function() {
  9579. // this could be useful in Array.prototype.
  9580. function arrayEquals(array) {
  9581. // if the other array is a falsy value, return
  9582. if (!array)
  9583. return false;
  9584. // compare lengths - can save a lot of time
  9585. if (this.length != array.length)
  9586. return false;
  9587. for (var i = 0, l=this.length; i < l; i++) {
  9588. // Check if we have nested arrays
  9589. if (this[i] instanceof Array && array[i] instanceof Array) {
  9590. // recurse into the nested arrays
  9591. if (!this[i].equals(array[i]))
  9592. return false;
  9593. }
  9594. else if (this[i] != array[i]) {
  9595. // Warning - two different object instances will never be
  9596. // equal: {x:20} != {x:20}
  9597. return false;
  9598. }
  9599. }
  9600. return true;
  9601. }
  9602. var myMedias = this.mySDP.getMediaSsrcMap();
  9603. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9604. var newMedia = {};
  9605. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9606. var myMedia = myMedias[othersMediaIdx];
  9607. var othersMedia = othersMedias[othersMediaIdx];
  9608. if(!myMedia && othersMedia) {
  9609. // Add whole channel
  9610. newMedia[othersMediaIdx] = othersMedia;
  9611. return;
  9612. }
  9613. // Look for new ssrcs across the channel
  9614. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9615. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9616. // Allocate channel if we've found ssrc that doesn't exist in
  9617. // our channel
  9618. if(!newMedia[othersMediaIdx]){
  9619. newMedia[othersMediaIdx] = {
  9620. mediaindex: othersMedia.mediaindex,
  9621. mid: othersMedia.mid,
  9622. ssrcs: {},
  9623. ssrcGroups: []
  9624. };
  9625. }
  9626. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9627. }
  9628. });
  9629. // Look for new ssrc groups across the channels
  9630. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9631. // try to match the other ssrc-group with an ssrc-group of ours
  9632. var matched = false;
  9633. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9634. var mySsrcGroup = myMedia.ssrcGroups[i];
  9635. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9636. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9637. [mySsrcGroup.ssrcs])) {
  9638. matched = true;
  9639. break;
  9640. }
  9641. }
  9642. if (!matched) {
  9643. // Allocate channel if we've found an ssrc-group that doesn't
  9644. // exist in our channel
  9645. if(!newMedia[othersMediaIdx]){
  9646. newMedia[othersMediaIdx] = {
  9647. mediaindex: othersMedia.mediaindex,
  9648. mid: othersMedia.mid,
  9649. ssrcs: {},
  9650. ssrcGroups: []
  9651. };
  9652. }
  9653. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9654. }
  9655. });
  9656. });
  9657. return newMedia;
  9658. };
  9659. /**
  9660. * TODO: document!
  9661. */
  9662. SDPDiffer.prototype.toJingle = function(modify) {
  9663. var sdpMediaSsrcs = this.getNewMedia();
  9664. var modified = false;
  9665. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9666. modified = true;
  9667. var media = sdpMediaSsrcs[mediaindex];
  9668. modify.c('content', {name: media.mid});
  9669. modify.c('description',
  9670. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9671. // FIXME: not completely sure this operates on blocks and / or handles
  9672. // different ssrcs correctly
  9673. // generate sources from lines
  9674. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9675. var mediaSsrc = media.ssrcs[ssrcNum];
  9676. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9677. modify.attrs({ssrc: mediaSsrc.ssrc});
  9678. // iterate over ssrc lines
  9679. mediaSsrc.lines.forEach(function (line) {
  9680. var idx = line.indexOf(' ');
  9681. var kv = line.substr(idx + 1);
  9682. modify.c('parameter');
  9683. if (kv.indexOf(':') == -1) {
  9684. modify.attrs({ name: kv });
  9685. } else {
  9686. var nv = kv.split(':', 2);
  9687. var name = nv[0];
  9688. var value = SDPUtil.filter_special_chars(nv[1]);
  9689. modify.attrs({ name: name });
  9690. modify.attrs({ value: value });
  9691. }
  9692. modify.up(); // end of parameter
  9693. });
  9694. modify.up(); // end of source
  9695. });
  9696. // generate source groups from lines
  9697. media.ssrcGroups.forEach(function(ssrcGroup) {
  9698. if (ssrcGroup.ssrcs.length) {
  9699. modify.c('ssrc-group', {
  9700. semantics: ssrcGroup.semantics,
  9701. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9702. });
  9703. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9704. modify.c('source', { ssrc: ssrc })
  9705. .up(); // end of source
  9706. });
  9707. modify.up(); // end of ssrc-group
  9708. }
  9709. });
  9710. modify.up(); // end of description
  9711. modify.up(); // end of content
  9712. });
  9713. return modified;
  9714. };
  9715. module.exports = SDPDiffer;
  9716. },{"./SDPUtil":34}],34:[function(require,module,exports){
  9717. (function (__filename){
  9718. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9719. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9720. SDPUtil = {
  9721. filter_special_chars: function (text) {
  9722. return text.replace(/[\\\/\{,\}\+]/g, "");
  9723. },
  9724. iceparams: function (mediadesc, sessiondesc) {
  9725. var data = null;
  9726. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9727. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9728. data = {
  9729. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9730. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9731. };
  9732. }
  9733. return data;
  9734. },
  9735. parse_iceufrag: function (line) {
  9736. return line.substring(12);
  9737. },
  9738. build_iceufrag: function (frag) {
  9739. return 'a=ice-ufrag:' + frag;
  9740. },
  9741. parse_icepwd: function (line) {
  9742. return line.substring(10);
  9743. },
  9744. build_icepwd: function (pwd) {
  9745. return 'a=ice-pwd:' + pwd;
  9746. },
  9747. parse_mid: function (line) {
  9748. return line.substring(6);
  9749. },
  9750. parse_mline: function (line) {
  9751. var parts = line.substring(2).split(' '),
  9752. data = {};
  9753. data.media = parts.shift();
  9754. data.port = parts.shift();
  9755. data.proto = parts.shift();
  9756. if (parts[parts.length - 1] === '') { // trailing whitespace
  9757. parts.pop();
  9758. }
  9759. data.fmt = parts;
  9760. return data;
  9761. },
  9762. build_mline: function (mline) {
  9763. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9764. },
  9765. parse_rtpmap: function (line) {
  9766. var parts = line.substring(9).split(' '),
  9767. data = {};
  9768. data.id = parts.shift();
  9769. parts = parts[0].split('/');
  9770. data.name = parts.shift();
  9771. data.clockrate = parts.shift();
  9772. data.channels = parts.length ? parts.shift() : '1';
  9773. return data;
  9774. },
  9775. /**
  9776. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9777. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9778. * @returns [SCTP port number, protocol, streams]
  9779. */
  9780. parse_sctpmap: function (line)
  9781. {
  9782. var parts = line.substring(10).split(' ');
  9783. var sctpPort = parts[0];
  9784. var protocol = parts[1];
  9785. // Stream count is optional
  9786. var streamCount = parts.length > 2 ? parts[2] : null;
  9787. return [sctpPort, protocol, streamCount];// SCTP port
  9788. },
  9789. build_rtpmap: function (el) {
  9790. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9791. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9792. line += '/' + el.getAttribute('channels');
  9793. }
  9794. return line;
  9795. },
  9796. parse_crypto: function (line) {
  9797. var parts = line.substring(9).split(' '),
  9798. data = {};
  9799. data.tag = parts.shift();
  9800. data['crypto-suite'] = parts.shift();
  9801. data['key-params'] = parts.shift();
  9802. if (parts.length) {
  9803. data['session-params'] = parts.join(' ');
  9804. }
  9805. return data;
  9806. },
  9807. parse_fingerprint: function (line) { // RFC 4572
  9808. var parts = line.substring(14).split(' '),
  9809. data = {};
  9810. data.hash = parts.shift();
  9811. data.fingerprint = parts.shift();
  9812. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9813. return data;
  9814. },
  9815. parse_fmtp: function (line) {
  9816. var parts = line.split(' '),
  9817. i, key, value,
  9818. data = [];
  9819. parts.shift();
  9820. parts = parts.join(' ').split(';');
  9821. for (i = 0; i < parts.length; i++) {
  9822. key = parts[i].split('=')[0];
  9823. while (key.length && key[0] == ' ') {
  9824. key = key.substring(1);
  9825. }
  9826. value = parts[i].split('=')[1];
  9827. if (key && value) {
  9828. data.push({name: key, value: value});
  9829. } else if (key) {
  9830. // rfc 4733 (DTMF) style stuff
  9831. data.push({name: '', value: key});
  9832. }
  9833. }
  9834. return data;
  9835. },
  9836. parse_icecandidate: function (line) {
  9837. var candidate = {},
  9838. elems = line.split(' ');
  9839. candidate.foundation = elems[0].substring(12);
  9840. candidate.component = elems[1];
  9841. candidate.protocol = elems[2].toLowerCase();
  9842. candidate.priority = elems[3];
  9843. candidate.ip = elems[4];
  9844. candidate.port = elems[5];
  9845. // elems[6] => "typ"
  9846. candidate.type = elems[7];
  9847. candidate.generation = 0; // default value, may be overwritten below
  9848. for (var i = 8; i < elems.length; i += 2) {
  9849. switch (elems[i]) {
  9850. case 'raddr':
  9851. candidate['rel-addr'] = elems[i + 1];
  9852. break;
  9853. case 'rport':
  9854. candidate['rel-port'] = elems[i + 1];
  9855. break;
  9856. case 'generation':
  9857. candidate.generation = elems[i + 1];
  9858. break;
  9859. case 'tcptype':
  9860. candidate.tcptype = elems[i + 1];
  9861. break;
  9862. default: // TODO
  9863. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9864. }
  9865. }
  9866. candidate.network = '1';
  9867. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9868. return candidate;
  9869. },
  9870. build_icecandidate: function (cand) {
  9871. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9872. line += ' ';
  9873. switch (cand.type) {
  9874. case 'srflx':
  9875. case 'prflx':
  9876. case 'relay':
  9877. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9878. line += 'raddr';
  9879. line += ' ';
  9880. line += cand['rel-addr'];
  9881. line += ' ';
  9882. line += 'rport';
  9883. line += ' ';
  9884. line += cand['rel-port'];
  9885. line += ' ';
  9886. }
  9887. break;
  9888. }
  9889. if (cand.hasOwnAttribute('tcptype')) {
  9890. line += 'tcptype';
  9891. line += ' ';
  9892. line += cand.tcptype;
  9893. line += ' ';
  9894. }
  9895. line += 'generation';
  9896. line += ' ';
  9897. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9898. return line;
  9899. },
  9900. parse_ssrc: function (desc) {
  9901. // proprietary mapping of a=ssrc lines
  9902. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9903. // and parse according to that
  9904. var lines = desc.split('\r\n'),
  9905. data = {};
  9906. for (var i = 0; i < lines.length; i++) {
  9907. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9908. var idx = lines[i].indexOf(' ');
  9909. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9910. }
  9911. }
  9912. return data;
  9913. },
  9914. parse_rtcpfb: function (line) {
  9915. var parts = line.substr(10).split(' ');
  9916. var data = {};
  9917. data.pt = parts.shift();
  9918. data.type = parts.shift();
  9919. data.params = parts;
  9920. return data;
  9921. },
  9922. parse_extmap: function (line) {
  9923. var parts = line.substr(9).split(' ');
  9924. var data = {};
  9925. data.value = parts.shift();
  9926. if (data.value.indexOf('/') != -1) {
  9927. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9928. data.value = data.value.substr(0, data.value.indexOf('/'));
  9929. } else {
  9930. data.direction = 'both';
  9931. }
  9932. data.uri = parts.shift();
  9933. data.params = parts;
  9934. return data;
  9935. },
  9936. find_line: function (haystack, needle, sessionpart) {
  9937. var lines = haystack.split('\r\n');
  9938. for (var i = 0; i < lines.length; i++) {
  9939. if (lines[i].substring(0, needle.length) == needle) {
  9940. return lines[i];
  9941. }
  9942. }
  9943. if (!sessionpart) {
  9944. return false;
  9945. }
  9946. // search session part
  9947. lines = sessionpart.split('\r\n');
  9948. for (var j = 0; j < lines.length; j++) {
  9949. if (lines[j].substring(0, needle.length) == needle) {
  9950. return lines[j];
  9951. }
  9952. }
  9953. return false;
  9954. },
  9955. find_lines: function (haystack, needle, sessionpart) {
  9956. var lines = haystack.split('\r\n'),
  9957. needles = [];
  9958. for (var i = 0; i < lines.length; i++) {
  9959. if (lines[i].substring(0, needle.length) == needle)
  9960. needles.push(lines[i]);
  9961. }
  9962. if (needles.length || !sessionpart) {
  9963. return needles;
  9964. }
  9965. // search session part
  9966. lines = sessionpart.split('\r\n');
  9967. for (var j = 0; j < lines.length; j++) {
  9968. if (lines[j].substring(0, needle.length) == needle) {
  9969. needles.push(lines[j]);
  9970. }
  9971. }
  9972. return needles;
  9973. },
  9974. candidateToJingle: function (line) {
  9975. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9976. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9977. if (line.indexOf('candidate:') === 0) {
  9978. line = 'a=' + line;
  9979. } else if (line.substring(0, 12) != 'a=candidate:') {
  9980. logger.log('parseCandidate called with a line that is not a candidate line');
  9981. logger.log(line);
  9982. return null;
  9983. }
  9984. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9985. line = line.substring(0, line.length - 2);
  9986. var candidate = {},
  9987. elems = line.split(' '),
  9988. i;
  9989. if (elems[6] != 'typ') {
  9990. logger.log('did not find typ in the right place');
  9991. logger.log(line);
  9992. return null;
  9993. }
  9994. candidate.foundation = elems[0].substring(12);
  9995. candidate.component = elems[1];
  9996. candidate.protocol = elems[2].toLowerCase();
  9997. candidate.priority = elems[3];
  9998. candidate.ip = elems[4];
  9999. candidate.port = elems[5];
  10000. // elems[6] => "typ"
  10001. candidate.type = elems[7];
  10002. candidate.generation = '0'; // default, may be overwritten below
  10003. for (i = 8; i < elems.length; i += 2) {
  10004. switch (elems[i]) {
  10005. case 'raddr':
  10006. candidate['rel-addr'] = elems[i + 1];
  10007. break;
  10008. case 'rport':
  10009. candidate['rel-port'] = elems[i + 1];
  10010. break;
  10011. case 'generation':
  10012. candidate.generation = elems[i + 1];
  10013. break;
  10014. case 'tcptype':
  10015. candidate.tcptype = elems[i + 1];
  10016. break;
  10017. default: // TODO
  10018. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  10019. }
  10020. }
  10021. candidate.network = '1';
  10022. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  10023. return candidate;
  10024. },
  10025. candidateFromJingle: function (cand) {
  10026. var line = 'a=candidate:';
  10027. line += cand.getAttribute('foundation');
  10028. line += ' ';
  10029. line += cand.getAttribute('component');
  10030. line += ' ';
  10031. var protocol = cand.getAttribute('protocol');
  10032. // use tcp candidates for FF
  10033. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  10034. protocol = 'tcp';
  10035. }
  10036. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  10037. line += ' ';
  10038. line += cand.getAttribute('priority');
  10039. line += ' ';
  10040. line += cand.getAttribute('ip');
  10041. line += ' ';
  10042. line += cand.getAttribute('port');
  10043. line += ' ';
  10044. line += 'typ';
  10045. line += ' ' + cand.getAttribute('type');
  10046. line += ' ';
  10047. switch (cand.getAttribute('type')) {
  10048. case 'srflx':
  10049. case 'prflx':
  10050. case 'relay':
  10051. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  10052. line += 'raddr';
  10053. line += ' ';
  10054. line += cand.getAttribute('rel-addr');
  10055. line += ' ';
  10056. line += 'rport';
  10057. line += ' ';
  10058. line += cand.getAttribute('rel-port');
  10059. line += ' ';
  10060. }
  10061. break;
  10062. }
  10063. if (protocol.toLowerCase() == 'tcp') {
  10064. line += 'tcptype';
  10065. line += ' ';
  10066. line += cand.getAttribute('tcptype');
  10067. line += ' ';
  10068. }
  10069. line += 'generation';
  10070. line += ' ';
  10071. line += cand.getAttribute('generation') || '0';
  10072. return line + '\r\n';
  10073. }
  10074. };
  10075. module.exports = SDPUtil;
  10076. }).call(this,"/modules/xmpp/SDPUtil.js")
  10077. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],35:[function(require,module,exports){
  10078. (function (__filename){
  10079. /* global $ */
  10080. var RTC = require('../RTC/RTC');
  10081. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10082. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  10083. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10084. function TraceablePeerConnection(ice_config, constraints, session) {
  10085. var self = this;
  10086. this.session = session;
  10087. this.recvOnlySSRCs = {};
  10088. var RTCPeerConnectionType = null;
  10089. if (RTCBrowserType.isFirefox()) {
  10090. RTCPeerConnectionType = mozRTCPeerConnection;
  10091. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  10092. RTCPeerConnectionType = RTCPeerConnection;
  10093. } else {
  10094. RTCPeerConnectionType = webkitRTCPeerConnection;
  10095. }
  10096. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  10097. this.updateLog = [];
  10098. this.stats = {};
  10099. this.statsinterval = null;
  10100. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  10101. var Interop = require('sdp-interop').Interop;
  10102. this.interop = new Interop();
  10103. var Simulcast = require('sdp-simulcast');
  10104. this.simulcast = new Simulcast({numOfLayers: 3,
  10105. explodeRemoteSimulcast: false});
  10106. this.eventEmitter = this.session.room.eventEmitter;
  10107. // override as desired
  10108. this.trace = function (what, info) {
  10109. /*logger.warn('WTRACE', what, info);
  10110. if (info && RTCBrowserType.isIExplorer()) {
  10111. if (info.length > 1024) {
  10112. logger.warn('WTRACE', what, info.substr(1024));
  10113. }
  10114. if (info.length > 2048) {
  10115. logger.warn('WTRACE', what, info.substr(2048));
  10116. }
  10117. }*/
  10118. self.updateLog.push({
  10119. time: new Date(),
  10120. type: what,
  10121. value: info || ""
  10122. });
  10123. };
  10124. this.onicecandidate = null;
  10125. this.peerconnection.onicecandidate = function (event) {
  10126. // FIXME: this causes stack overflow with Temasys Plugin
  10127. if (!RTCBrowserType.isTemasysPluginUsed())
  10128. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  10129. if (self.onicecandidate !== null) {
  10130. self.onicecandidate(event);
  10131. }
  10132. };
  10133. this.onaddstream = null;
  10134. this.peerconnection.onaddstream = function (event) {
  10135. self.trace('onaddstream', event.stream.id);
  10136. if (self.onaddstream !== null) {
  10137. self.onaddstream(event);
  10138. }
  10139. };
  10140. this.onremovestream = null;
  10141. this.peerconnection.onremovestream = function (event) {
  10142. self.trace('onremovestream', event.stream.id);
  10143. if (self.onremovestream !== null) {
  10144. self.onremovestream(event);
  10145. }
  10146. };
  10147. this.onsignalingstatechange = null;
  10148. this.peerconnection.onsignalingstatechange = function (event) {
  10149. self.trace('onsignalingstatechange', self.signalingState);
  10150. if (self.onsignalingstatechange !== null) {
  10151. self.onsignalingstatechange(event);
  10152. }
  10153. };
  10154. this.oniceconnectionstatechange = null;
  10155. this.peerconnection.oniceconnectionstatechange = function (event) {
  10156. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  10157. if (self.oniceconnectionstatechange !== null) {
  10158. self.oniceconnectionstatechange(event);
  10159. }
  10160. };
  10161. this.onnegotiationneeded = null;
  10162. this.peerconnection.onnegotiationneeded = function (event) {
  10163. self.trace('onnegotiationneeded');
  10164. if (self.onnegotiationneeded !== null) {
  10165. self.onnegotiationneeded(event);
  10166. }
  10167. };
  10168. self.ondatachannel = null;
  10169. this.peerconnection.ondatachannel = function (event) {
  10170. self.trace('ondatachannel', event);
  10171. if (self.ondatachannel !== null) {
  10172. self.ondatachannel(event);
  10173. }
  10174. };
  10175. // XXX: do all non-firefox browsers which we support also support this?
  10176. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10177. this.statsinterval = window.setInterval(function() {
  10178. self.peerconnection.getStats(function(stats) {
  10179. var results = stats.result();
  10180. var now = new Date();
  10181. for (var i = 0; i < results.length; ++i) {
  10182. results[i].names().forEach(function (name) {
  10183. var id = results[i].id + '-' + name;
  10184. if (!self.stats[id]) {
  10185. self.stats[id] = {
  10186. startTime: now,
  10187. endTime: now,
  10188. values: [],
  10189. times: []
  10190. };
  10191. }
  10192. self.stats[id].values.push(results[i].stat(name));
  10193. self.stats[id].times.push(now.getTime());
  10194. if (self.stats[id].values.length > self.maxstats) {
  10195. self.stats[id].values.shift();
  10196. self.stats[id].times.shift();
  10197. }
  10198. self.stats[id].endTime = now;
  10199. });
  10200. }
  10201. });
  10202. }, 1000);
  10203. }
  10204. }
  10205. /**
  10206. * Returns a string representation of a SessionDescription object.
  10207. */
  10208. var dumpSDP = function(description) {
  10209. if (typeof description === 'undefined' || description == null) {
  10210. return '';
  10211. }
  10212. return 'type: ' + description.type + '\r\n' + description.sdp;
  10213. };
  10214. /**
  10215. * Injects receive only SSRC in the sdp if there are not other SSRCs.
  10216. * @param desc the SDP that will be modified.
  10217. * @returns the modified SDP.
  10218. */
  10219. TraceablePeerConnection.prototype.insertRecvOnlySSRC = function (desc) {
  10220. if (typeof desc !== 'object' || desc === null ||
  10221. typeof desc.sdp !== 'string') {
  10222. console.warn('An empty description was passed as an argument.');
  10223. return desc;
  10224. }
  10225. var transform = require('sdp-transform');
  10226. var RandomUtil = require('../util/RandomUtil');
  10227. var session = transform.parse(desc.sdp);
  10228. if (!Array.isArray(session.media))
  10229. {
  10230. return;
  10231. }
  10232. var modded = false;
  10233. session.media.forEach(function (bLine) {
  10234. if (bLine.direction != 'recvonly')
  10235. {
  10236. return;
  10237. }
  10238. modded = true;
  10239. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10240. {
  10241. var ssrc = this.recvOnlySSRCs[bLine.type]
  10242. = this.recvOnlySSRCs[bLine.type] ||
  10243. RandomUtil.randomInt(1, 0xffffffff);
  10244. bLine.ssrcs = [{
  10245. id: ssrc,
  10246. attribute: 'cname',
  10247. value: ['recvonly-', ssrc].join('')
  10248. }];
  10249. }
  10250. }.bind(this));
  10251. return (!modded) ? desc : new RTCSessionDescription({
  10252. type: desc.type,
  10253. sdp: transform.write(session),
  10254. });
  10255. };
  10256. /**
  10257. * Takes a SessionDescription object and returns a "normalized" version.
  10258. * Currently it only takes care of ordering the a=ssrc lines.
  10259. */
  10260. var normalizePlanB = function(desc) {
  10261. if (typeof desc !== 'object' || desc === null ||
  10262. typeof desc.sdp !== 'string') {
  10263. logger.warn('An empty description was passed as an argument.');
  10264. return desc;
  10265. }
  10266. var transform = require('sdp-transform');
  10267. var session = transform.parse(desc.sdp);
  10268. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10269. Array.isArray(session.media)) {
  10270. session.media.forEach(function (mLine) {
  10271. // Chrome appears to be picky about the order in which a=ssrc lines
  10272. // are listed in an m-line when rtx is enabled (and thus there are
  10273. // a=ssrc-group lines with FID semantics). Specifically if we have
  10274. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10275. // the "a=ssrc:S1" lines, SRD fails.
  10276. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10277. // first.
  10278. var firstSsrcs = [];
  10279. var newSsrcLines = [];
  10280. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10281. mLine.ssrcGroups.forEach(function (group) {
  10282. if (typeof group.semantics !== 'undefined' &&
  10283. group.semantics === 'FID') {
  10284. if (typeof group.ssrcs !== 'undefined') {
  10285. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10286. }
  10287. }
  10288. });
  10289. }
  10290. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10291. var i;
  10292. for (i = 0; i<mLine.ssrcs.length; i++){
  10293. if (typeof mLine.ssrcs[i] === 'object'
  10294. && typeof mLine.ssrcs[i].id !== 'undefined'
  10295. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10296. newSsrcLines.push(mLine.ssrcs[i]);
  10297. delete mLine.ssrcs[i];
  10298. }
  10299. }
  10300. for (i = 0; i<mLine.ssrcs.length; i++){
  10301. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10302. newSsrcLines.push(mLine.ssrcs[i]);
  10303. }
  10304. }
  10305. mLine.ssrcs = newSsrcLines;
  10306. }
  10307. });
  10308. }
  10309. var resStr = transform.write(session);
  10310. return new RTCSessionDescription({
  10311. type: desc.type,
  10312. sdp: resStr
  10313. });
  10314. };
  10315. var getters = {
  10316. signalingState: function () {
  10317. return this.peerconnection.signalingState;
  10318. },
  10319. iceConnectionState: function () {
  10320. return this.peerconnection.iceConnectionState;
  10321. },
  10322. localDescription: function() {
  10323. var desc = this.peerconnection.localDescription;
  10324. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10325. // if we're running on FF, transform to Plan B first.
  10326. if (RTCBrowserType.usesUnifiedPlan()) {
  10327. desc = this.interop.toPlanB(desc);
  10328. this.trace('getLocalDescription::postTransform (Plan B)',
  10329. dumpSDP(desc));
  10330. }
  10331. return desc;
  10332. },
  10333. remoteDescription: function() {
  10334. var desc = this.peerconnection.remoteDescription;
  10335. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10336. // if we're running on FF, transform to Plan B first.
  10337. if (RTCBrowserType.usesUnifiedPlan()) {
  10338. desc = this.interop.toPlanB(desc);
  10339. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10340. }
  10341. return desc;
  10342. }
  10343. };
  10344. Object.keys(getters).forEach(function (prop) {
  10345. Object.defineProperty(
  10346. TraceablePeerConnection.prototype,
  10347. prop, {
  10348. get: getters[prop]
  10349. }
  10350. );
  10351. });
  10352. TraceablePeerConnection.prototype.addStream = function (stream) {
  10353. this.trace('addStream', stream.id);
  10354. try
  10355. {
  10356. this.peerconnection.addStream(stream);
  10357. }
  10358. catch (e)
  10359. {
  10360. logger.error(e);
  10361. }
  10362. };
  10363. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10364. this.trace('removeStream', stream.id);
  10365. if(stopStreams) {
  10366. RTC.stopMediaStream(stream);
  10367. }
  10368. try {
  10369. // FF doesn't support this yet.
  10370. if (this.peerconnection.removeStream)
  10371. this.peerconnection.removeStream(stream);
  10372. } catch (e) {
  10373. logger.error(e);
  10374. }
  10375. };
  10376. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10377. this.trace('createDataChannel', label, opts);
  10378. return this.peerconnection.createDataChannel(label, opts);
  10379. };
  10380. TraceablePeerConnection.prototype.setLocalDescription
  10381. = function (description, successCallback, failureCallback) {
  10382. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10383. // if we're running on FF, transform to Plan A first.
  10384. if (RTCBrowserType.usesUnifiedPlan()) {
  10385. description = this.interop.toUnifiedPlan(description);
  10386. this.trace('setLocalDescription::postTransform (Plan A)',
  10387. dumpSDP(description));
  10388. }
  10389. var self = this;
  10390. this.peerconnection.setLocalDescription(description,
  10391. function () {
  10392. self.trace('setLocalDescriptionOnSuccess');
  10393. successCallback();
  10394. },
  10395. function (err) {
  10396. self.trace('setLocalDescriptionOnFailure', err);
  10397. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10398. err, self.peerconnection);
  10399. failureCallback(err);
  10400. }
  10401. );
  10402. };
  10403. TraceablePeerConnection.prototype.setRemoteDescription
  10404. = function (description, successCallback, failureCallback) {
  10405. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10406. // TODO the focus should squeze or explode the remote simulcast
  10407. description = this.simulcast.mungeRemoteDescription(description);
  10408. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10409. // if we're running on FF, transform to Plan A first.
  10410. if (RTCBrowserType.usesUnifiedPlan()) {
  10411. description = this.interop.toUnifiedPlan(description);
  10412. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10413. }
  10414. if (RTCBrowserType.usesPlanB()) {
  10415. description = normalizePlanB(description);
  10416. }
  10417. var self = this;
  10418. this.peerconnection.setRemoteDescription(description,
  10419. function () {
  10420. self.trace('setRemoteDescriptionOnSuccess');
  10421. successCallback();
  10422. },
  10423. function (err) {
  10424. self.trace('setRemoteDescriptionOnFailure', err);
  10425. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10426. err, self.peerconnection);
  10427. failureCallback(err);
  10428. }
  10429. );
  10430. /*
  10431. if (this.statsinterval === null && this.maxstats > 0) {
  10432. // start gathering stats
  10433. }
  10434. */
  10435. };
  10436. TraceablePeerConnection.prototype.close = function () {
  10437. this.trace('stop');
  10438. if (this.statsinterval !== null) {
  10439. window.clearInterval(this.statsinterval);
  10440. this.statsinterval = null;
  10441. }
  10442. this.peerconnection.close();
  10443. };
  10444. TraceablePeerConnection.prototype.createOffer
  10445. = function (successCallback, failureCallback, constraints) {
  10446. var self = this;
  10447. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10448. this.peerconnection.createOffer(
  10449. function (offer) {
  10450. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10451. // NOTE this is not tested because in meet the focus generates the
  10452. // offer.
  10453. // if we're running on FF, transform to Plan B first.
  10454. if (RTCBrowserType.usesUnifiedPlan()) {
  10455. offer = self.interop.toPlanB(offer);
  10456. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10457. }
  10458. if (RTCBrowserType.isChrome())
  10459. {
  10460. offer = self.insertRecvOnlySSRC(offer);
  10461. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC',
  10462. dumpSDP(offer));
  10463. }
  10464. if (!self.session.room.options.disableSimulcast
  10465. && self.simulcast.isSupported()) {
  10466. offer = self.simulcast.mungeLocalDescription(offer);
  10467. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10468. dumpSDP(offer));
  10469. }
  10470. successCallback(offer);
  10471. },
  10472. function(err) {
  10473. self.trace('createOfferOnFailure', err);
  10474. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10475. self.peerconnection);
  10476. failureCallback(err);
  10477. },
  10478. constraints
  10479. );
  10480. };
  10481. TraceablePeerConnection.prototype.createAnswer
  10482. = function (successCallback, failureCallback, constraints) {
  10483. var self = this;
  10484. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10485. this.peerconnection.createAnswer(
  10486. function (answer) {
  10487. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10488. // if we're running on FF, transform to Plan A first.
  10489. if (RTCBrowserType.usesUnifiedPlan()) {
  10490. answer = self.interop.toPlanB(answer);
  10491. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10492. dumpSDP(answer));
  10493. }
  10494. if (RTCBrowserType.isChrome())
  10495. {
  10496. answer = self.insertRecvOnlySSRC(answer);
  10497. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC',
  10498. dumpSDP(answer));
  10499. }
  10500. if (!self.session.room.options.disableSimulcast
  10501. && self.simulcast.isSupported()) {
  10502. answer = self.simulcast.mungeLocalDescription(answer);
  10503. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10504. dumpSDP(answer));
  10505. }
  10506. successCallback(answer);
  10507. },
  10508. function(err) {
  10509. self.trace('createAnswerOnFailure', err);
  10510. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10511. self.peerconnection);
  10512. failureCallback(err);
  10513. },
  10514. constraints
  10515. );
  10516. };
  10517. TraceablePeerConnection.prototype.addIceCandidate
  10518. = function (candidate, successCallback, failureCallback) {
  10519. //var self = this;
  10520. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10521. this.peerconnection.addIceCandidate(candidate);
  10522. /* maybe later
  10523. this.peerconnection.addIceCandidate(candidate,
  10524. function () {
  10525. self.trace('addIceCandidateOnSuccess');
  10526. successCallback();
  10527. },
  10528. function (err) {
  10529. self.trace('addIceCandidateOnFailure', err);
  10530. failureCallback(err);
  10531. }
  10532. );
  10533. */
  10534. };
  10535. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10536. // TODO: Is this the correct way to handle Opera, Temasys?
  10537. if (RTCBrowserType.isFirefox()) {
  10538. // ignore for now...
  10539. if(!errback)
  10540. errback = function () {};
  10541. this.peerconnection.getStats(null, callback, errback);
  10542. } else {
  10543. this.peerconnection.getStats(callback);
  10544. }
  10545. };
  10546. module.exports = TraceablePeerConnection;
  10547. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10548. },{"../../service/xmpp/XMPPEvents":143,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":50,"sdp-interop":69,"sdp-simulcast":76,"sdp-transform":83}],36:[function(require,module,exports){
  10549. (function (__filename){
  10550. /* global $, $iq, Promise, Strophe */
  10551. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10552. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10553. var AuthenticationEvents
  10554. = require("../../service/authentication/AuthenticationEvents");
  10555. function createExpBackoffTimer(step) {
  10556. var count = 1;
  10557. return function (reset) {
  10558. // Reset call
  10559. if (reset) {
  10560. count = 1;
  10561. return;
  10562. }
  10563. // Calculate next timeout
  10564. var timeout = Math.pow(2, count - 1);
  10565. count += 1;
  10566. return timeout * step;
  10567. };
  10568. }
  10569. function Moderator(roomName, xmpp, emitter, settings) {
  10570. this.roomName = roomName;
  10571. this.xmppService = xmpp;
  10572. this.getNextTimeout = createExpBackoffTimer(1000);
  10573. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10574. // External authentication stuff
  10575. this.externalAuthEnabled = false;
  10576. this.settings = settings;
  10577. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10578. // it will be enabled automatically if focus detects the component through
  10579. // service discovery.
  10580. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10581. this.xmppService.options.hosts.call_control !== undefined;
  10582. this.eventEmitter = emitter;
  10583. this.connection = this.xmppService.connection;
  10584. this.focusUserJid;
  10585. //FIXME:
  10586. // Message listener that talks to POPUP window
  10587. function listener(event) {
  10588. if (event.data && event.data.sessionId) {
  10589. if (event.origin !== window.location.origin) {
  10590. logger.warn("Ignoring sessionId from different origin: " +
  10591. event.origin);
  10592. return;
  10593. }
  10594. localStorage.setItem('sessionId', event.data.sessionId);
  10595. // After popup is closed we will authenticate
  10596. }
  10597. }
  10598. // Register
  10599. if (window.addEventListener) {
  10600. window.addEventListener("message", listener, false);
  10601. } else {
  10602. window.attachEvent("onmessage", listener);
  10603. }
  10604. }
  10605. Moderator.prototype.isExternalAuthEnabled = function () {
  10606. return this.externalAuthEnabled;
  10607. };
  10608. Moderator.prototype.isSipGatewayEnabled = function () {
  10609. return this.sipGatewayEnabled;
  10610. };
  10611. Moderator.prototype.onMucMemberLeft = function (jid) {
  10612. logger.info("Someone left is it focus ? " + jid);
  10613. var resource = Strophe.getResourceFromJid(jid);
  10614. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10615. logger.info(
  10616. "Focus has left the room - leaving conference");
  10617. //hangUp();
  10618. // We'd rather reload to have everything re-initialized
  10619. //FIXME: show some message before reload
  10620. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10621. }
  10622. };
  10623. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10624. if (!this.focusUserJid) {
  10625. this.focusUserJid = focusJid;
  10626. logger.info("Focus jid set to: " + this.focusUserJid);
  10627. }
  10628. };
  10629. Moderator.prototype.getFocusUserJid = function () {
  10630. return this.focusUserJid;
  10631. };
  10632. Moderator.prototype.getFocusComponent = function () {
  10633. // Get focus component address
  10634. var focusComponent = this.xmppService.options.hosts.focus;
  10635. // If not specified use default: 'focus.domain'
  10636. if (!focusComponent) {
  10637. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10638. }
  10639. return focusComponent;
  10640. };
  10641. Moderator.prototype.createConferenceIq = function () {
  10642. // Generate create conference IQ
  10643. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10644. // Session Id used for authentication
  10645. var sessionId = localStorage.getItem('sessionId');
  10646. var machineUID = this.settings.getSettings().uid;
  10647. logger.info(
  10648. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10649. elem.c('conference', {
  10650. xmlns: 'http://jitsi.org/protocol/focus',
  10651. room: this.roomName,
  10652. 'machine-uid': machineUID
  10653. });
  10654. if (sessionId) {
  10655. elem.attrs({ 'session-id': sessionId});
  10656. }
  10657. if (this.xmppService.options.hosts.bridge !== undefined) {
  10658. elem.c(
  10659. 'property', {
  10660. name: 'bridge',
  10661. value: this.xmppService.options.hosts.bridge
  10662. }).up();
  10663. }
  10664. if (this.xmppService.options.enforcedBridge !== undefined) {
  10665. elem.c(
  10666. 'property', {
  10667. name: 'enforcedBridge',
  10668. value: this.xmppService.options.enforcedBridge
  10669. }).up();
  10670. }
  10671. // Tell the focus we have Jigasi configured
  10672. if (this.xmppService.options.hosts.call_control !== undefined) {
  10673. elem.c(
  10674. 'property', {
  10675. name: 'call_control',
  10676. value: this.xmppService.options.hosts.call_control
  10677. }).up();
  10678. }
  10679. if (this.xmppService.options.channelLastN !== undefined) {
  10680. elem.c(
  10681. 'property', {
  10682. name: 'channelLastN',
  10683. value: this.xmppService.options.channelLastN
  10684. }).up();
  10685. }
  10686. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10687. elem.c(
  10688. 'property', {
  10689. name: 'adaptiveLastN',
  10690. value: this.xmppService.options.adaptiveLastN
  10691. }).up();
  10692. }
  10693. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10694. elem.c(
  10695. 'property', {
  10696. name: 'adaptiveSimulcast',
  10697. value: this.xmppService.options.adaptiveSimulcast
  10698. }).up();
  10699. }
  10700. if (this.xmppService.options.openSctp !== undefined) {
  10701. elem.c(
  10702. 'property', {
  10703. name: 'openSctp',
  10704. value: this.xmppService.options.openSctp
  10705. }).up();
  10706. }
  10707. if (this.xmppService.options.startAudioMuted !== undefined)
  10708. {
  10709. elem.c(
  10710. 'property', {
  10711. name: 'startAudioMuted',
  10712. value: this.xmppService.options.startAudioMuted
  10713. }).up();
  10714. }
  10715. if (this.xmppService.options.startVideoMuted !== undefined)
  10716. {
  10717. elem.c(
  10718. 'property', {
  10719. name: 'startVideoMuted',
  10720. value: this.xmppService.options.startVideoMuted
  10721. }).up();
  10722. }
  10723. elem.c(
  10724. 'property', {
  10725. name: 'simulcastMode',
  10726. value: 'rewriting'
  10727. }).up();
  10728. elem.up();
  10729. return elem;
  10730. };
  10731. Moderator.prototype.parseSessionId = function (resultIq) {
  10732. var sessionId = $(resultIq).find('conference').attr('session-id');
  10733. if (sessionId) {
  10734. logger.info('Received sessionId: ' + sessionId);
  10735. localStorage.setItem('sessionId', sessionId);
  10736. }
  10737. };
  10738. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10739. this.setFocusUserJid(
  10740. $(resultIq).find('conference').attr('focusjid'));
  10741. var authenticationEnabled
  10742. = $(resultIq).find(
  10743. '>conference>property' +
  10744. '[name=\'authentication\'][value=\'true\']').length > 0;
  10745. logger.info("Authentication enabled: " + authenticationEnabled);
  10746. this.externalAuthEnabled = $(resultIq).find(
  10747. '>conference>property' +
  10748. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10749. console.info(
  10750. 'External authentication enabled: ' + this.externalAuthEnabled);
  10751. if (!this.externalAuthEnabled) {
  10752. // We expect to receive sessionId in 'internal' authentication mode
  10753. this.parseSessionId(resultIq);
  10754. }
  10755. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10756. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10757. authenticationEnabled, authIdentity);
  10758. // Check if focus has auto-detected Jigasi component(this will be also
  10759. // included if we have passed our host from the config)
  10760. if ($(resultIq).find(
  10761. '>conference>property' +
  10762. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10763. this.sipGatewayEnabled = true;
  10764. }
  10765. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10766. };
  10767. // FIXME = we need to show the fact that we're waiting for the focus
  10768. // to the user(or that focus is not available)
  10769. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10770. // Try to use focus user JID from the config
  10771. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10772. // Send create conference IQ
  10773. var iq = this.createConferenceIq();
  10774. var self = this;
  10775. this.connection.sendIQ(
  10776. iq,
  10777. function (result) {
  10778. // Setup config options
  10779. self.parseConfigOptions(result);
  10780. if ('true' === $(result).find('conference').attr('ready')) {
  10781. // Reset both timers
  10782. self.getNextTimeout(true);
  10783. self.getNextErrorTimeout(true);
  10784. // Exec callback
  10785. callback();
  10786. } else {
  10787. var waitMs = self.getNextTimeout();
  10788. logger.info("Waiting for the focus... " + waitMs);
  10789. // Reset error timeout
  10790. self.getNextErrorTimeout(true);
  10791. window.setTimeout(
  10792. function () {
  10793. self.allocateConferenceFocus(callback);
  10794. }, waitMs);
  10795. }
  10796. },
  10797. function (error) {
  10798. // Invalid session ? remove and try again
  10799. // without session ID to get a new one
  10800. var invalidSession
  10801. = $(error).find('>error>session-invalid').length;
  10802. if (invalidSession) {
  10803. logger.info("Session expired! - removing");
  10804. localStorage.removeItem("sessionId");
  10805. }
  10806. if ($(error).find('>error>graceful-shutdown').length) {
  10807. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10808. return;
  10809. }
  10810. // Check for error returned by the reservation system
  10811. var reservationErr = $(error).find('>error>reservation-error');
  10812. if (reservationErr.length) {
  10813. // Trigger error event
  10814. var errorCode = reservationErr.attr('error-code');
  10815. var errorMsg;
  10816. if ($(error).find('>error>text')) {
  10817. errorMsg = $(error).find('>error>text').text();
  10818. }
  10819. self.eventEmitter.emit(
  10820. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10821. return;
  10822. }
  10823. // Not authorized to create new room
  10824. if ($(error).find('>error>not-authorized').length) {
  10825. logger.warn("Unauthorized to start the conference", error);
  10826. var toDomain
  10827. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10828. if (toDomain !==
  10829. this.xmppService.options.hosts.anonymousdomain) {
  10830. //FIXME: "is external" should come either from
  10831. // the focus or config.js
  10832. self.externalAuthEnabled = true;
  10833. }
  10834. self.eventEmitter.emit(
  10835. XMPPEvents.AUTHENTICATION_REQUIRED,
  10836. function () {
  10837. self.allocateConferenceFocus(
  10838. callback);
  10839. });
  10840. return;
  10841. }
  10842. var waitMs = self.getNextErrorTimeout();
  10843. logger.error("Focus error, retry after " + waitMs, error);
  10844. // Show message
  10845. var focusComponent = self.getFocusComponent();
  10846. var retrySec = waitMs / 1000;
  10847. //FIXME: message is duplicated ?
  10848. // Do not show in case of session invalid
  10849. // which means just a retry
  10850. if (!invalidSession) {
  10851. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10852. focusComponent, retrySec);
  10853. }
  10854. // Reset response timeout
  10855. self.getNextTimeout(true);
  10856. window.setTimeout(
  10857. function () {
  10858. self.allocateConferenceFocus(callback);
  10859. }, waitMs);
  10860. }
  10861. );
  10862. };
  10863. Moderator.prototype.authenticate = function () {
  10864. var self = this;
  10865. return new Promise(function (resolve, reject) {
  10866. self.connection.sendIQ(
  10867. self.createConferenceIq(),
  10868. function (result) {
  10869. self.parseSessionId(result);
  10870. resolve();
  10871. }, function (error) {
  10872. var code = $(error).find('>error').attr('code');
  10873. reject(error, code);
  10874. }
  10875. );
  10876. });
  10877. };
  10878. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10879. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10880. iq.c('login-url', {
  10881. xmlns: 'http://jitsi.org/protocol/focus',
  10882. room: this.roomName,
  10883. 'machine-uid': this.settings.getSettings().uid
  10884. });
  10885. this.connection.sendIQ(
  10886. iq,
  10887. function (result) {
  10888. var url = $(result).find('login-url').attr('url');
  10889. url = url = decodeURIComponent(url);
  10890. if (url) {
  10891. logger.info("Got auth url: " + url);
  10892. urlCallback(url);
  10893. } else {
  10894. logger.error(
  10895. "Failed to get auth url from the focus", result);
  10896. failureCallback(result);
  10897. }
  10898. },
  10899. function (error) {
  10900. logger.error("Get auth url error", error);
  10901. failureCallback(error);
  10902. }
  10903. );
  10904. };
  10905. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10906. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10907. iq.c('login-url', {
  10908. xmlns: 'http://jitsi.org/protocol/focus',
  10909. room: this.roomName,
  10910. 'machine-uid': this.settings.getSettings().uid,
  10911. popup: true
  10912. });
  10913. this.connection.sendIQ(
  10914. iq,
  10915. function (result) {
  10916. var url = $(result).find('login-url').attr('url');
  10917. url = url = decodeURIComponent(url);
  10918. if (url) {
  10919. logger.info("Got POPUP auth url: " + url);
  10920. urlCallback(url);
  10921. } else {
  10922. logger.error(
  10923. "Failed to get POPUP auth url from the focus", result);
  10924. failureCallback(result);
  10925. }
  10926. },
  10927. function (error) {
  10928. logger.error('Get POPUP auth url error', error);
  10929. failureCallback(error);
  10930. }
  10931. );
  10932. };
  10933. Moderator.prototype.logout = function (callback) {
  10934. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10935. var sessionId = localStorage.getItem('sessionId');
  10936. if (!sessionId) {
  10937. callback();
  10938. return;
  10939. }
  10940. iq.c('logout', {
  10941. xmlns: 'http://jitsi.org/protocol/focus',
  10942. 'session-id': sessionId
  10943. });
  10944. this.connection.sendIQ(
  10945. iq,
  10946. function (result) {
  10947. var logoutUrl = $(result).find('logout').attr('logout-url');
  10948. if (logoutUrl) {
  10949. logoutUrl = decodeURIComponent(logoutUrl);
  10950. }
  10951. logger.info("Log out OK, url: " + logoutUrl, result);
  10952. localStorage.removeItem('sessionId');
  10953. callback(logoutUrl);
  10954. },
  10955. function (error) {
  10956. logger.error("Logout error", error);
  10957. }
  10958. );
  10959. };
  10960. module.exports = Moderator;
  10961. }).call(this,"/modules/xmpp/moderator.js")
  10962. },{"../../service/authentication/AuthenticationEvents":139,"../../service/xmpp/XMPPEvents":143,"jitsi-meet-logger":50}],37:[function(require,module,exports){
  10963. (function (__filename){
  10964. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10965. Toolbar, Util, Promise */
  10966. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10967. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10968. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10969. roomjid) {
  10970. this.eventEmitter = eventEmitter;
  10971. this.connection = connection;
  10972. this.state = "off";
  10973. this.focusMucJid = focusMucJid;
  10974. this.jirecon = jirecon;
  10975. this.url = null;
  10976. this.type = type;
  10977. this._isSupported = ((type === Recording.types.JIBRI)
  10978. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10979. /**
  10980. * The ID of the jirecon recording session. Jirecon generates it when we
  10981. * initially start recording, and it needs to be used in subsequent requests
  10982. * to jirecon.
  10983. */
  10984. this.jireconRid = null;
  10985. this.roomjid = roomjid;
  10986. }
  10987. Recording.types = {
  10988. COLIBRI: "colibri",
  10989. JIRECON: "jirecon",
  10990. JIBRI: "jibri"
  10991. };
  10992. Recording.prototype.handleJibriPresence = function (jibri) {
  10993. var attributes = jibri.attributes;
  10994. if(!attributes)
  10995. return;
  10996. this._isSupported =
  10997. (attributes.status && attributes.status !== "undefined");
  10998. if(this._isSupported) {
  10999. this.url = attributes.url || null;
  11000. this.state = attributes.status || "off";
  11001. }
  11002. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  11003. };
  11004. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  11005. options) {
  11006. if (state == this.state){
  11007. errCallback(new Error("Invalid state!"));
  11008. }
  11009. options = options || {};
  11010. // FIXME jibri does not accept IQ without 'url' attribute set ?
  11011. var iq = $iq({to: this.focusMucJid, type: 'set'})
  11012. .c('jibri', {
  11013. "xmlns": 'http://jitsi.org/protocol/jibri',
  11014. "action": (state === 'on') ? 'start' : 'stop',
  11015. "streamid": options.streamId,
  11016. "follow-entity": options.followEntity
  11017. }).up();
  11018. logger.log('Set jibri recording: '+state, iq.nodeTree);
  11019. console.log(iq.nodeTree);
  11020. this.connection.sendIQ(
  11021. iq,
  11022. function (result) {
  11023. callback($(result).find('jibri').attr('state'),
  11024. $(result).find('jibri').attr('url'));
  11025. },
  11026. function (error) {
  11027. logger.log('Failed to start recording, error: ', error);
  11028. errCallback(error);
  11029. });
  11030. };
  11031. Recording.prototype.setRecordingJirecon =
  11032. function (state, callback, errCallback, options) {
  11033. if (state == this.state){
  11034. errCallback(new Error("Invalid state!"));
  11035. }
  11036. var iq = $iq({to: this.jirecon, type: 'set'})
  11037. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  11038. action: (state === 'on') ? 'start' : 'stop',
  11039. mucjid: this.roomjid});
  11040. if (state === 'off'){
  11041. iq.attrs({rid: this.jireconRid});
  11042. }
  11043. console.log('Start recording');
  11044. var self = this;
  11045. this.connection.sendIQ(
  11046. iq,
  11047. function (result) {
  11048. // TODO wait for an IQ with the real status, since this is
  11049. // provisional?
  11050. self.jireconRid = $(result).find('recording').attr('rid');
  11051. console.log('Recording ' +
  11052. ((state === 'on') ? 'started' : 'stopped') +
  11053. '(jirecon)' + result);
  11054. self.state = state;
  11055. if (state === 'off'){
  11056. self.jireconRid = null;
  11057. }
  11058. callback(state);
  11059. },
  11060. function (error) {
  11061. console.log('Failed to start recording, error: ', error);
  11062. errCallback(error);
  11063. });
  11064. };
  11065. // Sends a COLIBRI message which enables or disables (according to 'state')
  11066. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  11067. // with the new recording state, according to the IQ.
  11068. Recording.prototype.setRecordingColibri =
  11069. function (state, callback, errCallback, options) {
  11070. var elem = $iq({to: this.focusMucJid, type: 'set'});
  11071. elem.c('conference', {
  11072. xmlns: 'http://jitsi.org/protocol/colibri'
  11073. });
  11074. elem.c('recording', {state: state, token: options.token});
  11075. var self = this;
  11076. this.connection.sendIQ(elem,
  11077. function (result) {
  11078. console.log('Set recording "', state, '". Result:', result);
  11079. var recordingElem = $(result).find('>conference>recording');
  11080. var newState = recordingElem.attr('state');
  11081. self.state = newState;
  11082. callback(newState);
  11083. if (newState === 'pending') {
  11084. self.connection.addHandler(function(iq){
  11085. var state = $(iq).find('recording').attr('state');
  11086. if (state) {
  11087. self.state = newState;
  11088. callback(state);
  11089. }
  11090. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  11091. }
  11092. },
  11093. function (error) {
  11094. console.warn(error);
  11095. errCallback(error);
  11096. }
  11097. );
  11098. };
  11099. Recording.prototype.setRecording =
  11100. function (state, callback, errCallback, options) {
  11101. switch(this.type){
  11102. case Recording.types.JIRECON:
  11103. this.setRecordingJirecon(state, callback, errCallback, options);
  11104. break;
  11105. case Recording.types.COLIBRI:
  11106. this.setRecordingColibri(state, callback, errCallback, options);
  11107. break;
  11108. case Recording.types.JIBRI:
  11109. this.setRecordingJibri(state, callback, errCallback, options);
  11110. break;
  11111. default:
  11112. console.error("Unknown recording type!");
  11113. return;
  11114. }
  11115. };
  11116. /**
  11117. *Starts/stops the recording
  11118. * @param token token for authentication
  11119. * @param statusChangeHandler {function} receives the new status as argument.
  11120. */
  11121. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  11122. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  11123. (!options.streamId && this.type === Recording.types.JIBRI)){
  11124. statusChangeHandler("error", new Error("No token passed!"));
  11125. logger.error("No token passed!");
  11126. return;
  11127. }
  11128. var oldState = this.state;
  11129. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  11130. var self = this;
  11131. this.setRecording(newState,
  11132. function (state, url) {
  11133. logger.log("New recording state: ", state);
  11134. if (state && state !== oldState) {
  11135. self.state = state;
  11136. self.url = url;
  11137. statusChangeHandler(state);
  11138. } else {
  11139. statusChangeHandler("error", new Error("Status not changed!"));
  11140. }
  11141. }, function (error) {
  11142. statusChangeHandler("error", error);
  11143. }, options);
  11144. };
  11145. /**
  11146. * Returns true if the recording is supproted and false if not.
  11147. */
  11148. Recording.prototype.isSupported = function () {
  11149. return this._isSupported;
  11150. };
  11151. /**
  11152. * Returns null if the recording is not supported, "on" if the recording started
  11153. * and "off" if the recording is not started.
  11154. */
  11155. Recording.prototype.getState = function () {
  11156. return this.state;
  11157. };
  11158. /**
  11159. * Returns the url of the recorded video.
  11160. */
  11161. Recording.prototype.getURL = function () {
  11162. return this.url;
  11163. };
  11164. module.exports = Recording;
  11165. }).call(this,"/modules/xmpp/recording.js")
  11166. },{"../../service/xmpp/XMPPEvents":143,"jitsi-meet-logger":50}],38:[function(require,module,exports){
  11167. (function (__filename){
  11168. /* jshint -W117 */
  11169. /* a simple MUC connection plugin
  11170. * can only handle a single MUC room
  11171. */
  11172. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11173. var ChatRoom = require("./ChatRoom");
  11174. module.exports = function(XMPP) {
  11175. Strophe.addConnectionPlugin('emuc', {
  11176. connection: null,
  11177. rooms: {},//map with the rooms
  11178. init: function (conn) {
  11179. this.connection = conn;
  11180. // add handlers (just once)
  11181. this.connection.addHandler(this.onPresence.bind(this), null,
  11182. 'presence', null, null, null, null);
  11183. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11184. null, 'presence', 'unavailable', null);
  11185. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11186. 'presence', 'error', null);
  11187. this.connection.addHandler(this.onMessage.bind(this), null,
  11188. 'message', null, null);
  11189. this.connection.addHandler(this.onMute.bind(this),
  11190. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11191. },
  11192. createRoom: function (jid, password, options, settings) {
  11193. var roomJid = Strophe.getBareJidFromJid(jid);
  11194. if (this.rooms[roomJid]) {
  11195. logger.error("You are already in the room!");
  11196. return;
  11197. }
  11198. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11199. password, XMPP, options, settings);
  11200. return this.rooms[roomJid];
  11201. },
  11202. doLeave: function (jid) {
  11203. this.rooms[jid].doLeave();
  11204. delete this.rooms[jid];
  11205. },
  11206. onPresence: function (pres) {
  11207. var from = pres.getAttribute('from');
  11208. // What is this for? A workaround for something?
  11209. if (pres.getAttribute('type')) {
  11210. return true;
  11211. }
  11212. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11213. if(!room)
  11214. return;
  11215. // Parse status.
  11216. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11217. room.createNonAnonymousRoom();
  11218. }
  11219. room.onPresence(pres);
  11220. return true;
  11221. },
  11222. onPresenceUnavailable: function (pres) {
  11223. var from = pres.getAttribute('from');
  11224. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11225. if(!room)
  11226. return;
  11227. room.onPresenceUnavailable(pres, from);
  11228. return true;
  11229. },
  11230. onPresenceError: function (pres) {
  11231. var from = pres.getAttribute('from');
  11232. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11233. if(!room)
  11234. return;
  11235. room.onPresenceError(pres, from);
  11236. return true;
  11237. },
  11238. onMessage: function (msg) {
  11239. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11240. var from = msg.getAttribute('from');
  11241. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11242. if(!room)
  11243. return;
  11244. room.onMessage(msg, from);
  11245. return true;
  11246. },
  11247. setJingleSession: function (from, session) {
  11248. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11249. if(!room)
  11250. return;
  11251. room.setJingleSession(session);
  11252. },
  11253. onMute: function(iq) {
  11254. var from = iq.getAttribute('from');
  11255. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11256. if(!room)
  11257. return;
  11258. room.onMute(iq);
  11259. return true;
  11260. }
  11261. });
  11262. };
  11263. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11264. },{"./ChatRoom":29,"jitsi-meet-logger":50}],39:[function(require,module,exports){
  11265. (function (__filename){
  11266. /* jshint -W117 */
  11267. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11268. var JingleSession = require("./JingleSessionPC");
  11269. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11270. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11271. module.exports = function(XMPP, eventEmitter) {
  11272. Strophe.addConnectionPlugin('jingle', {
  11273. connection: null,
  11274. sessions: {},
  11275. jid2session: {},
  11276. ice_config: {iceServers: []},
  11277. media_constraints: {
  11278. mandatory: {
  11279. 'OfferToReceiveAudio': true,
  11280. 'OfferToReceiveVideo': true
  11281. }
  11282. // MozDontOfferDataChannel: true when this is firefox
  11283. },
  11284. init: function (conn) {
  11285. this.connection = conn;
  11286. if (this.connection.disco) {
  11287. // http://xmpp.org/extensions/xep-0167.html#support
  11288. // http://xmpp.org/extensions/xep-0176.html#support
  11289. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11290. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11291. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11292. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11293. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11294. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11295. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11296. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11297. || RTCBrowserType.isTemasysPluginUsed()) {
  11298. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11299. }
  11300. // this is dealt with by SDP O/A so we don't need to announce this
  11301. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11302. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11303. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11304. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11305. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11306. }
  11307. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11308. },
  11309. onJingle: function (iq) {
  11310. var sid = $(iq).find('jingle').attr('sid');
  11311. var action = $(iq).find('jingle').attr('action');
  11312. var fromJid = iq.getAttribute('from');
  11313. // send ack first
  11314. var ack = $iq({type: 'result',
  11315. to: fromJid,
  11316. id: iq.getAttribute('id')
  11317. });
  11318. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11319. var sess = this.sessions[sid];
  11320. if ('session-initiate' != action) {
  11321. if (sess === null) {
  11322. ack.type = 'error';
  11323. ack.c('error', {type: 'cancel'})
  11324. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11325. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11326. this.connection.send(ack);
  11327. return true;
  11328. }
  11329. // local jid is not checked
  11330. if (fromJid != sess.peerjid) {
  11331. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11332. ack.type = 'error';
  11333. ack.c('error', {type: 'cancel'})
  11334. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11335. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11336. this.connection.send(ack);
  11337. return true;
  11338. }
  11339. } else if (sess !== undefined) {
  11340. // existing session with same session id
  11341. // this might be out-of-order if the sess.peerjid is the same as from
  11342. ack.type = 'error';
  11343. ack.c('error', {type: 'cancel'})
  11344. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11345. logger.warn('duplicate session id', sid);
  11346. this.connection.send(ack);
  11347. return true;
  11348. }
  11349. // FIXME: check for a defined action
  11350. this.connection.send(ack);
  11351. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11352. switch (action) {
  11353. case 'session-initiate':
  11354. console.log("(TIME) received session-initiate:\t",
  11355. window.performance.now());
  11356. var startMuted = $(iq).find('jingle>startmuted');
  11357. if (startMuted && startMuted.length > 0) {
  11358. var audioMuted = startMuted.attr("audio");
  11359. var videoMuted = startMuted.attr("video");
  11360. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11361. audioMuted === "true", videoMuted === "true");
  11362. }
  11363. sess = new JingleSession(
  11364. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11365. this.connection, XMPP);
  11366. // configure session
  11367. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11368. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11369. sess.media_constraints = this.media_constraints;
  11370. sess.ice_config = this.ice_config;
  11371. sess.initialize(fromJid, false);
  11372. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11373. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11374. sess.setOffer($(iq).find('>jingle'));
  11375. this.sessions[sess.sid] = sess;
  11376. this.jid2session[sess.peerjid] = sess;
  11377. // the callback should either
  11378. // .sendAnswer and .accept
  11379. // or .sendTerminate -- not necessarily synchronous
  11380. sess.sendAnswer();
  11381. sess.accept();
  11382. break;
  11383. case 'session-accept':
  11384. sess.setAnswer($(iq).find('>jingle'));
  11385. sess.accept();
  11386. break;
  11387. case 'session-terminate':
  11388. // If this is not the focus sending the terminate, we have
  11389. // nothing more to do here.
  11390. if (Object.keys(this.sessions).length < 1
  11391. || !(this.sessions[Object.keys(this.sessions)[0]]
  11392. instanceof JingleSession))
  11393. {
  11394. break;
  11395. }
  11396. logger.log('terminating...', sess.sid);
  11397. sess.terminate();
  11398. this.terminate(sess.sid);
  11399. if ($(iq).find('>jingle>reason').length) {
  11400. $(document).trigger('callterminated.jingle', [
  11401. sess.sid,
  11402. sess.peerjid,
  11403. $(iq).find('>jingle>reason>:first')[0].tagName,
  11404. $(iq).find('>jingle>reason>text').text()
  11405. ]);
  11406. } else {
  11407. $(document).trigger('callterminated.jingle',
  11408. [sess.sid, sess.peerjid]);
  11409. }
  11410. break;
  11411. case 'transport-info':
  11412. sess.addIceCandidate($(iq).find('>jingle>content'));
  11413. break;
  11414. case 'session-info':
  11415. var affected;
  11416. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11417. $(document).trigger('ringing.jingle', [sess.sid]);
  11418. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11419. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11420. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11421. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11422. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11423. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11424. }
  11425. break;
  11426. case 'addsource': // FIXME: proprietary, un-jingleish
  11427. case 'source-add': // FIXME: proprietary
  11428. sess.addSource($(iq).find('>jingle>content'));
  11429. break;
  11430. case 'removesource': // FIXME: proprietary, un-jingleish
  11431. case 'source-remove': // FIXME: proprietary
  11432. sess.removeSource($(iq).find('>jingle>content'));
  11433. break;
  11434. default:
  11435. logger.warn('jingle action not implemented', action);
  11436. break;
  11437. }
  11438. return true;
  11439. },
  11440. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11441. if (sid === null || sid === undefined) {
  11442. for (sid in this.sessions) {
  11443. if (this.sessions[sid].state != 'ended') {
  11444. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11445. this.sessions[sid].terminate();
  11446. }
  11447. delete this.jid2session[this.sessions[sid].peerjid];
  11448. delete this.sessions[sid];
  11449. }
  11450. } else if (this.sessions.hasOwnProperty(sid)) {
  11451. if (this.sessions[sid].state != 'ended') {
  11452. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11453. this.sessions[sid].terminate();
  11454. }
  11455. delete this.jid2session[this.sessions[sid].peerjid];
  11456. delete this.sessions[sid];
  11457. }
  11458. },
  11459. getStunAndTurnCredentials: function () {
  11460. // get stun and turn configuration from server via xep-0215
  11461. // uses time-limited credentials as described in
  11462. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11463. //
  11464. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11465. // for a prosody module which implements this
  11466. //
  11467. // currently, this doesn't work with updateIce and therefore credentials with a long
  11468. // validity have to be fetched before creating the peerconnection
  11469. // TODO: implement refresh via updateIce as described in
  11470. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11471. var self = this;
  11472. this.connection.sendIQ(
  11473. $iq({type: 'get', to: this.connection.domain})
  11474. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11475. function (res) {
  11476. var iceservers = [];
  11477. $(res).find('>services>service').each(function (idx, el) {
  11478. el = $(el);
  11479. var dict = {};
  11480. var type = el.attr('type');
  11481. switch (type) {
  11482. case 'stun':
  11483. dict.url = 'stun:' + el.attr('host');
  11484. if (el.attr('port')) {
  11485. dict.url += ':' + el.attr('port');
  11486. }
  11487. iceservers.push(dict);
  11488. break;
  11489. case 'turn':
  11490. case 'turns':
  11491. dict.url = type + ':';
  11492. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11493. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11494. dict.url += el.attr('username') + '@';
  11495. } else {
  11496. dict.username = el.attr('username'); // only works in M28
  11497. }
  11498. }
  11499. dict.url += el.attr('host');
  11500. if (el.attr('port') && el.attr('port') != '3478') {
  11501. dict.url += ':' + el.attr('port');
  11502. }
  11503. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11504. dict.url += '?transport=' + el.attr('transport');
  11505. }
  11506. if (el.attr('password')) {
  11507. dict.credential = el.attr('password');
  11508. }
  11509. iceservers.push(dict);
  11510. break;
  11511. }
  11512. });
  11513. self.ice_config.iceServers = iceservers;
  11514. },
  11515. function (err) {
  11516. logger.warn('getting turn credentials failed', err);
  11517. logger.warn('is mod_turncredentials or similar installed?');
  11518. }
  11519. );
  11520. // implement push?
  11521. },
  11522. /**
  11523. * Returns the data saved in 'updateLog' in a format to be logged.
  11524. */
  11525. getLog: function () {
  11526. var data = {};
  11527. var self = this;
  11528. Object.keys(this.sessions).forEach(function (sid) {
  11529. var session = self.sessions[sid];
  11530. if (session.peerconnection && session.peerconnection.updateLog) {
  11531. // FIXME: should probably be a .dump call
  11532. data["jingle_" + session.sid] = {
  11533. updateLog: session.peerconnection.updateLog,
  11534. stats: session.peerconnection.stats,
  11535. url: window.location.href
  11536. };
  11537. }
  11538. });
  11539. return data;
  11540. }
  11541. });
  11542. };
  11543. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11544. },{"../../service/xmpp/XMPPEvents":143,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":50}],40:[function(require,module,exports){
  11545. /* global Strophe */
  11546. module.exports = function () {
  11547. Strophe.addConnectionPlugin('logger', {
  11548. // logs raw stanzas and makes them available for download as JSON
  11549. connection: null,
  11550. log: [],
  11551. init: function (conn) {
  11552. this.connection = conn;
  11553. this.connection.rawInput = this.log_incoming.bind(this);
  11554. this.connection.rawOutput = this.log_outgoing.bind(this);
  11555. },
  11556. log_incoming: function (stanza) {
  11557. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11558. },
  11559. log_outgoing: function (stanza) {
  11560. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11561. }
  11562. });
  11563. };
  11564. },{}],41:[function(require,module,exports){
  11565. (function (__filename){
  11566. /* global $, $iq, Strophe */
  11567. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11568. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11569. /**
  11570. * Ping every 10 sec
  11571. */
  11572. var PING_INTERVAL = 10000;
  11573. /**
  11574. * Ping timeout error after 15 sec of waiting.
  11575. */
  11576. var PING_TIMEOUT = 15000;
  11577. /**
  11578. * Will close the connection after 3 consecutive ping errors.
  11579. */
  11580. var PING_THRESHOLD = 3;
  11581. /**
  11582. * XEP-0199 ping plugin.
  11583. *
  11584. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11585. */
  11586. module.exports = function (XMPP, eventEmitter) {
  11587. Strophe.addConnectionPlugin('ping', {
  11588. connection: null,
  11589. failedPings: 0,
  11590. /**
  11591. * Initializes the plugin. Method called by Strophe.
  11592. * @param connection Strophe connection instance.
  11593. */
  11594. init: function (connection) {
  11595. this.connection = connection;
  11596. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11597. },
  11598. /**
  11599. * Sends "ping" to given <tt>jid</tt>
  11600. * @param jid the JID to which ping request will be sent.
  11601. * @param success callback called on success.
  11602. * @param error callback called on error.
  11603. * @param timeout ms how long are we going to wait for the response. On
  11604. * timeout <tt>error<//t> callback is called with undefined error
  11605. * argument.
  11606. */
  11607. ping: function (jid, success, error, timeout) {
  11608. var iq = $iq({type: 'get', to: jid});
  11609. iq.c('ping', {xmlns: Strophe.NS.PING});
  11610. this.connection.sendIQ(iq, success, error, timeout);
  11611. },
  11612. /**
  11613. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11614. * @param jid the JID to be checked for ping support.
  11615. * @param callback function with boolean argument which will be
  11616. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11617. */
  11618. hasPingSupport: function (jid, callback) {
  11619. this.connection.disco.info(
  11620. jid, null,
  11621. function (result) {
  11622. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11623. callback(ping.length > 0);
  11624. },
  11625. function (error) {
  11626. logger.error("Ping feature discovery error", error);
  11627. callback(false);
  11628. }
  11629. );
  11630. },
  11631. /**
  11632. * Starts to send ping in given interval to specified remote JID.
  11633. * This plugin supports only one such task and <tt>stopInterval</tt>
  11634. * must be called before starting a new one.
  11635. * @param remoteJid remote JID to which ping requests will be sent to.
  11636. * @param interval task interval in ms.
  11637. */
  11638. startInterval: function (remoteJid, interval) {
  11639. if (this.intervalId) {
  11640. logger.error("Ping task scheduled already");
  11641. return;
  11642. }
  11643. if (!interval)
  11644. interval = PING_INTERVAL;
  11645. var self = this;
  11646. this.intervalId = window.setInterval(function () {
  11647. self.ping(remoteJid,
  11648. function (result) {
  11649. // Ping OK
  11650. self.failedPings = 0;
  11651. },
  11652. function (error) {
  11653. self.failedPings += 1;
  11654. logger.error(
  11655. "Ping " + (error ? "error" : "timeout"), error);
  11656. if (self.failedPings >= PING_THRESHOLD) {
  11657. self.connection.disconnect();
  11658. }
  11659. }, PING_TIMEOUT);
  11660. }, interval);
  11661. logger.info("XMPP pings will be sent every " + interval + " ms");
  11662. },
  11663. /**
  11664. * Stops current "ping" interval task.
  11665. */
  11666. stopInterval: function () {
  11667. if (this.intervalId) {
  11668. window.clearInterval(this.intervalId);
  11669. this.intervalId = null;
  11670. this.failedPings = 0;
  11671. logger.info("Ping interval cleared");
  11672. }
  11673. }
  11674. });
  11675. };
  11676. }).call(this,"/modules/xmpp/strophe.ping.js")
  11677. },{"../../service/xmpp/XMPPEvents":143,"jitsi-meet-logger":50}],42:[function(require,module,exports){
  11678. (function (__filename){
  11679. /* jshint -W117 */
  11680. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11681. module.exports = function() {
  11682. Strophe.addConnectionPlugin('rayo',
  11683. {
  11684. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11685. connection: null,
  11686. init: function (conn) {
  11687. this.connection = conn;
  11688. if (this.connection.disco) {
  11689. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11690. }
  11691. this.connection.addHandler(
  11692. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11693. null, null);
  11694. },
  11695. onRayo: function (iq) {
  11696. logger.info("Rayo IQ", iq);
  11697. },
  11698. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11699. var self = this;
  11700. return new Promise(function (resolve, reject) {
  11701. if(!focusMucJid) {
  11702. reject(new Error("Internal error!"));
  11703. return;
  11704. }
  11705. var req = $iq(
  11706. {
  11707. type: 'set',
  11708. to: focusMucJid
  11709. }
  11710. );
  11711. req.c('dial',
  11712. {
  11713. xmlns: self.RAYO_XMLNS,
  11714. to: to,
  11715. from: from
  11716. });
  11717. req.c('header',
  11718. {
  11719. name: 'JvbRoomName',
  11720. value: roomName
  11721. }).up();
  11722. if (roomPass !== null && roomPass.length) {
  11723. req.c('header',
  11724. {
  11725. name: 'JvbRoomPassword',
  11726. value: roomPass
  11727. }).up();
  11728. }
  11729. self.connection.sendIQ(
  11730. req,
  11731. function (result) {
  11732. logger.info('Dial result ', result);
  11733. var resource = $(result).find('ref').attr('uri');
  11734. self.call_resource =
  11735. resource.substr('xmpp:'.length);
  11736. logger.info(
  11737. "Received call resource: " +
  11738. self.call_resource);
  11739. resolve();
  11740. },
  11741. function (error) {
  11742. logger.info('Dial error ', error);
  11743. reject(error);
  11744. }
  11745. );
  11746. });
  11747. },
  11748. hangup: function () {
  11749. var self = this;
  11750. return new Promise(function (resolve, reject) {
  11751. if (!self.call_resource) {
  11752. reject(new Error("No call in progress"));
  11753. logger.warn("No call in progress");
  11754. return;
  11755. }
  11756. var req = $iq(
  11757. {
  11758. type: 'set',
  11759. to: self.call_resource
  11760. }
  11761. );
  11762. req.c('hangup',
  11763. {
  11764. xmlns: self.RAYO_XMLNS
  11765. });
  11766. self.connection.sendIQ(
  11767. req,
  11768. function (result) {
  11769. logger.info('Hangup result ', result);
  11770. self.call_resource = null;
  11771. resolve();
  11772. },
  11773. function (error) {
  11774. logger.info('Hangup error ', error);
  11775. self.call_resource = null;
  11776. reject(new Error('Hangup error '));
  11777. }
  11778. );
  11779. });
  11780. }
  11781. }
  11782. );
  11783. };
  11784. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11785. },{"jitsi-meet-logger":50}],43:[function(require,module,exports){
  11786. (function (__filename){
  11787. /* global Strophe */
  11788. /**
  11789. * Strophe logger implementation. Logs from level WARN and above.
  11790. */
  11791. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11792. module.exports = function () {
  11793. Strophe.log = function (level, msg) {
  11794. switch (level) {
  11795. case Strophe.LogLevel.WARN:
  11796. logger.warn("Strophe: " + msg);
  11797. break;
  11798. case Strophe.LogLevel.ERROR:
  11799. case Strophe.LogLevel.FATAL:
  11800. logger.error("Strophe: " + msg);
  11801. break;
  11802. }
  11803. };
  11804. Strophe.getStatusString = function (status) {
  11805. switch (status) {
  11806. case Strophe.Status.ERROR:
  11807. return "ERROR";
  11808. case Strophe.Status.CONNECTING:
  11809. return "CONNECTING";
  11810. case Strophe.Status.CONNFAIL:
  11811. return "CONNFAIL";
  11812. case Strophe.Status.AUTHENTICATING:
  11813. return "AUTHENTICATING";
  11814. case Strophe.Status.AUTHFAIL:
  11815. return "AUTHFAIL";
  11816. case Strophe.Status.CONNECTED:
  11817. return "CONNECTED";
  11818. case Strophe.Status.DISCONNECTED:
  11819. return "DISCONNECTED";
  11820. case Strophe.Status.DISCONNECTING:
  11821. return "DISCONNECTING";
  11822. case Strophe.Status.ATTACHED:
  11823. return "ATTACHED";
  11824. default:
  11825. return "unknown";
  11826. }
  11827. };
  11828. };
  11829. }).call(this,"/modules/xmpp/strophe.util.js")
  11830. },{"jitsi-meet-logger":50}],44:[function(require,module,exports){
  11831. (function (__filename){
  11832. /* global $, APP, config, Strophe */
  11833. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11834. var EventEmitter = require("events");
  11835. var Pako = require("pako");
  11836. var RTCEvents = require("../../service/RTC/RTCEvents");
  11837. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11838. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11839. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11840. var RTC = require("../RTC/RTC");
  11841. var authenticatedUser = false;
  11842. function createConnection(bosh) {
  11843. bosh = bosh || '/http-bind';
  11844. // Append token as URL param
  11845. if (this.token) {
  11846. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + this.token;
  11847. }
  11848. return new Strophe.Connection(bosh);
  11849. };
  11850. //!!!!!!!!!! FIXME: ...
  11851. function initStrophePlugins(XMPP) {
  11852. require("./strophe.emuc")(XMPP);
  11853. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11854. // require("./strophe.moderate")(XMPP, eventEmitter);
  11855. require("./strophe.util")();
  11856. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11857. require("./strophe.rayo")();
  11858. require("./strophe.logger")();
  11859. }
  11860. //!!!!!!!!!! FIXME: ...
  11861. ///**
  11862. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11863. // * video type in MUC presence.
  11864. // * @param localStream new or modified <tt>LocalStream</tt>.
  11865. // */
  11866. //function broadcastLocalVideoType(localStream) {
  11867. // if (localStream.videoType)
  11868. // XMPP.addToPresence('videoType', localStream.videoType);
  11869. //}
  11870. //
  11871. //function registerListeners() {
  11872. // RTC.addStreamListener(
  11873. // broadcastLocalVideoType,
  11874. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11875. // );
  11876. //}
  11877. function XMPP(options) {
  11878. this.eventEmitter = new EventEmitter();
  11879. this.connection = null;
  11880. this.disconnectInProgress = false;
  11881. this.forceMuted = false;
  11882. this.options = options;
  11883. initStrophePlugins(this);
  11884. // registerListeners();
  11885. this.connection = createConnection(options.bosh);
  11886. // Setup a disconnect on unload as a way to facilitate API consumers. It
  11887. // sounds like they would want that. A problem for them though may be if
  11888. // they wanted to utilize the connected connection in an unload handler of
  11889. // their own. However, it should be fairly easy for them to do that by
  11890. // registering their unload handler before us.
  11891. $(window).on('beforeunload unload', this.disconnect.bind(this));
  11892. }
  11893. XMPP.prototype.getConnection = function () { return this.connection; };
  11894. XMPP.prototype._connect = function (jid, password) {
  11895. var self = this;
  11896. // connection.connect() starts the connection process.
  11897. //
  11898. // As the connection process proceeds, the user supplied callback will
  11899. // be triggered multiple times with status updates. The callback should
  11900. // take two arguments - the status code and the error condition.
  11901. //
  11902. // The status code will be one of the values in the Strophe.Status
  11903. // constants. The error condition will be one of the conditions defined
  11904. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11905. //
  11906. // The Parameters wait, hold and route are optional and only relevant
  11907. // for BOSH connections. Please see XEP 124 for a more detailed
  11908. // explanation of the optional parameters.
  11909. //
  11910. // Connection status constants for use by the connection handler
  11911. // callback.
  11912. //
  11913. // Status.ERROR - An error has occurred (websockets specific)
  11914. // Status.CONNECTING - The connection is currently being made
  11915. // Status.CONNFAIL - The connection attempt failed
  11916. // Status.AUTHENTICATING - The connection is authenticating
  11917. // Status.AUTHFAIL - The authentication attempt failed
  11918. // Status.CONNECTED - The connection has succeeded
  11919. // Status.DISCONNECTED - The connection has been terminated
  11920. // Status.DISCONNECTING - The connection is currently being terminated
  11921. // Status.ATTACHED - The connection has been attached
  11922. var anonymousConnectionFailed = false;
  11923. var connectionFailed = false;
  11924. var lastErrorMsg;
  11925. this.connection.connect(jid, password, function (status, msg) {
  11926. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11927. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11928. if (status === Strophe.Status.CONNECTED) {
  11929. if (self.options.useStunTurn) {
  11930. self.connection.jingle.getStunAndTurnCredentials();
  11931. }
  11932. logger.info("My Jabber ID: " + self.connection.jid);
  11933. // Schedule ping ?
  11934. var pingJid = self.connection.domain;
  11935. self.connection.ping.hasPingSupport(
  11936. pingJid,
  11937. function (hasPing) {
  11938. if (hasPing)
  11939. self.connection.ping.startInterval(pingJid);
  11940. else
  11941. logger.warn("Ping NOT supported by " + pingJid);
  11942. }
  11943. );
  11944. if (password)
  11945. authenticatedUser = true;
  11946. if (self.connection && self.connection.connected &&
  11947. Strophe.getResourceFromJid(self.connection.jid)) {
  11948. // .connected is true while connecting?
  11949. // self.connection.send($pres());
  11950. self.eventEmitter.emit(
  11951. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11952. Strophe.getResourceFromJid(self.connection.jid));
  11953. }
  11954. } else if (status === Strophe.Status.CONNFAIL) {
  11955. if (msg === 'x-strophe-bad-non-anon-jid') {
  11956. anonymousConnectionFailed = true;
  11957. } else {
  11958. connectionFailed = true;
  11959. }
  11960. lastErrorMsg = msg;
  11961. } else if (status === Strophe.Status.DISCONNECTED) {
  11962. // Stop ping interval
  11963. self.connection.ping.stopInterval();
  11964. self.disconnectInProgress = false;
  11965. if (anonymousConnectionFailed) {
  11966. // prompt user for username and password
  11967. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11968. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11969. } else if(connectionFailed) {
  11970. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11971. JitsiConnectionErrors.OTHER_ERROR,
  11972. msg ? msg : lastErrorMsg);
  11973. } else {
  11974. self.eventEmitter.emit(
  11975. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11976. msg ? msg : lastErrorMsg);
  11977. }
  11978. } else if (status === Strophe.Status.AUTHFAIL) {
  11979. // wrong password or username, prompt user
  11980. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11981. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11982. }
  11983. });
  11984. }
  11985. XMPP.prototype.connect = function (jid, password) {
  11986. if (!jid) {
  11987. var configDomain
  11988. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11989. // Force authenticated domain if room is appended with '?login=true'
  11990. if (this.options.hosts.anonymousdomain
  11991. && window.location.search.indexOf("login=true") !== -1) {
  11992. configDomain = this.options.hosts.domain;
  11993. }
  11994. jid = configDomain || window.location.hostname;
  11995. }
  11996. return this._connect(jid, password);
  11997. };
  11998. XMPP.prototype.createRoom = function (roomName, options, settings) {
  11999. var roomjid = roomName + '@' + this.options.hosts.muc;
  12000. if (options.useNicks) {
  12001. if (options.nick) {
  12002. roomjid += '/' + options.nick;
  12003. } else {
  12004. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  12005. }
  12006. } else {
  12007. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  12008. if (!authenticatedUser)
  12009. tmpJid = tmpJid.substr(0, 8);
  12010. roomjid += '/' + tmpJid;
  12011. }
  12012. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  12013. }
  12014. XMPP.prototype.addListener = function(type, listener) {
  12015. this.eventEmitter.on(type, listener);
  12016. };
  12017. XMPP.prototype.removeListener = function (type, listener) {
  12018. this.eventEmitter.removeListener(type, listener);
  12019. };
  12020. //FIXME: this should work with the room
  12021. XMPP.prototype.leaveRoom = function (jid) {
  12022. var handler = this.connection.jingle.jid2session[jid];
  12023. if (handler && handler.peerconnection) {
  12024. // FIXME: probably removing streams is not required and close() should
  12025. // be enough
  12026. if (RTC.localAudio) {
  12027. handler.peerconnection.removeStream(
  12028. RTC.localAudio.getOriginalStream(), true);
  12029. }
  12030. if (RTC.localVideo) {
  12031. handler.peerconnection.removeStream(
  12032. RTC.localVideo.getOriginalStream(), true);
  12033. }
  12034. handler.peerconnection.close();
  12035. }
  12036. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  12037. this.connection.emuc.doLeave(jid);
  12038. };
  12039. /**
  12040. * Sends 'data' as a log message to the focus. Returns true iff a message
  12041. * was sent.
  12042. * @param data
  12043. * @returns {boolean} true iff a message was sent.
  12044. */
  12045. XMPP.prototype.sendLogs = function (data) {
  12046. if (!this.connection.emuc.focusMucJid)
  12047. return false;
  12048. var deflate = true;
  12049. var content = JSON.stringify(data);
  12050. if (deflate) {
  12051. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  12052. }
  12053. content = Base64.encode(content);
  12054. // XEP-0337-ish
  12055. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  12056. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  12057. message.c('message').t(content).up();
  12058. if (deflate) {
  12059. message.c('tag', {name: "deflated", value: "true"}).up();
  12060. }
  12061. message.up();
  12062. this.connection.send(message);
  12063. return true;
  12064. };
  12065. // Gets the logs from strophe.jingle.
  12066. XMPP.prototype.getJingleLog = function () {
  12067. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  12068. };
  12069. // Gets the logs from strophe.
  12070. XMPP.prototype.getXmppLog = function () {
  12071. return this.connection.logger ? this.connection.logger.log : null;
  12072. };
  12073. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  12074. this.connection.rayo.dial(to, from, roomName,roomPass);
  12075. };
  12076. XMPP.prototype.setMute = function (jid, mute) {
  12077. this.connection.moderate.setMute(jid, mute);
  12078. };
  12079. XMPP.prototype.eject = function (jid) {
  12080. this.connection.moderate.eject(jid);
  12081. };
  12082. XMPP.prototype.getSessions = function () {
  12083. return this.connection.jingle.sessions;
  12084. };
  12085. /**
  12086. * Disconnects this from the XMPP server (if this is connected).
  12087. *
  12088. * @param ev optionally, the event which triggered the necessity to disconnect
  12089. * from the XMPP server (e.g. beforeunload, unload)
  12090. */
  12091. XMPP.prototype.disconnect = function (ev) {
  12092. if (this.disconnectInProgress
  12093. || !this.connection
  12094. || !this.connection.connected) {
  12095. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  12096. return;
  12097. }
  12098. this.disconnectInProgress = true;
  12099. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  12100. // means that there may not be enough time to send an unavailable presence
  12101. // or disconnect at all. Switching Strophe to synchronous sending is not
  12102. // much of an option because it may lead to a noticeable delay in navigating
  12103. // away from the current location. As a compromise, we will try to increase
  12104. // the chances of sending an unavailable presence and/or disconecting within
  12105. // the short time span that we have upon unloading by invoking flush() on
  12106. // the connection. We flush() once before disconnect() in order to attemtp
  12107. // to have its unavailable presence at the top of the send queue. We flush()
  12108. // once more after disconnect() in order to attempt to have its unavailable
  12109. // presence sent as soon as possible.
  12110. this.connection.flush();
  12111. if (ev !== null && typeof ev !== 'undefined') {
  12112. var evType = ev.type;
  12113. if (evType == 'beforeunload' || evType == 'unload') {
  12114. // XXX Whatever we said above, synchronous sending is the best
  12115. // (known) way to properly disconnect from the XMPP server.
  12116. // Consequently, it may be fine to have the source code and comment
  12117. // it in or out depending on whether we want to run with it for some
  12118. // time.
  12119. this.connection.options.sync = true;
  12120. }
  12121. }
  12122. this.connection.disconnect();
  12123. if (this.connection.options.sync !== true) {
  12124. this.connection.flush();
  12125. }
  12126. };
  12127. module.exports = XMPP;
  12128. }).call(this,"/modules/xmpp/xmpp.js")
  12129. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":137,"../../service/xmpp/XMPPEvents":143,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":46,"jitsi-meet-logger":50,"pako":52}],45:[function(require,module,exports){
  12130. (function (process){
  12131. /*!
  12132. * async
  12133. * https://github.com/caolan/async
  12134. *
  12135. * Copyright 2010-2014 Caolan McMahon
  12136. * Released under the MIT license
  12137. */
  12138. /*jshint onevar: false, indent:4 */
  12139. /*global setImmediate: false, setTimeout: false, console: false */
  12140. (function () {
  12141. var async = {};
  12142. // global on the server, window in the browser
  12143. var root, previous_async;
  12144. root = this;
  12145. if (root != null) {
  12146. previous_async = root.async;
  12147. }
  12148. async.noConflict = function () {
  12149. root.async = previous_async;
  12150. return async;
  12151. };
  12152. function only_once(fn) {
  12153. var called = false;
  12154. return function() {
  12155. if (called) throw new Error("Callback was already called.");
  12156. called = true;
  12157. fn.apply(root, arguments);
  12158. }
  12159. }
  12160. //// cross-browser compatiblity functions ////
  12161. var _toString = Object.prototype.toString;
  12162. var _isArray = Array.isArray || function (obj) {
  12163. return _toString.call(obj) === '[object Array]';
  12164. };
  12165. var _each = function (arr, iterator) {
  12166. if (arr.forEach) {
  12167. return arr.forEach(iterator);
  12168. }
  12169. for (var i = 0; i < arr.length; i += 1) {
  12170. iterator(arr[i], i, arr);
  12171. }
  12172. };
  12173. var _map = function (arr, iterator) {
  12174. if (arr.map) {
  12175. return arr.map(iterator);
  12176. }
  12177. var results = [];
  12178. _each(arr, function (x, i, a) {
  12179. results.push(iterator(x, i, a));
  12180. });
  12181. return results;
  12182. };
  12183. var _reduce = function (arr, iterator, memo) {
  12184. if (arr.reduce) {
  12185. return arr.reduce(iterator, memo);
  12186. }
  12187. _each(arr, function (x, i, a) {
  12188. memo = iterator(memo, x, i, a);
  12189. });
  12190. return memo;
  12191. };
  12192. var _keys = function (obj) {
  12193. if (Object.keys) {
  12194. return Object.keys(obj);
  12195. }
  12196. var keys = [];
  12197. for (var k in obj) {
  12198. if (obj.hasOwnProperty(k)) {
  12199. keys.push(k);
  12200. }
  12201. }
  12202. return keys;
  12203. };
  12204. //// exported async module functions ////
  12205. //// nextTick implementation with browser-compatible fallback ////
  12206. if (typeof process === 'undefined' || !(process.nextTick)) {
  12207. if (typeof setImmediate === 'function') {
  12208. async.nextTick = function (fn) {
  12209. // not a direct alias for IE10 compatibility
  12210. setImmediate(fn);
  12211. };
  12212. async.setImmediate = async.nextTick;
  12213. }
  12214. else {
  12215. async.nextTick = function (fn) {
  12216. setTimeout(fn, 0);
  12217. };
  12218. async.setImmediate = async.nextTick;
  12219. }
  12220. }
  12221. else {
  12222. async.nextTick = process.nextTick;
  12223. if (typeof setImmediate !== 'undefined') {
  12224. async.setImmediate = function (fn) {
  12225. // not a direct alias for IE10 compatibility
  12226. setImmediate(fn);
  12227. };
  12228. }
  12229. else {
  12230. async.setImmediate = async.nextTick;
  12231. }
  12232. }
  12233. async.each = function (arr, iterator, callback) {
  12234. callback = callback || function () {};
  12235. if (!arr.length) {
  12236. return callback();
  12237. }
  12238. var completed = 0;
  12239. _each(arr, function (x) {
  12240. iterator(x, only_once(done) );
  12241. });
  12242. function done(err) {
  12243. if (err) {
  12244. callback(err);
  12245. callback = function () {};
  12246. }
  12247. else {
  12248. completed += 1;
  12249. if (completed >= arr.length) {
  12250. callback();
  12251. }
  12252. }
  12253. }
  12254. };
  12255. async.forEach = async.each;
  12256. async.eachSeries = function (arr, iterator, callback) {
  12257. callback = callback || function () {};
  12258. if (!arr.length) {
  12259. return callback();
  12260. }
  12261. var completed = 0;
  12262. var iterate = function () {
  12263. iterator(arr[completed], function (err) {
  12264. if (err) {
  12265. callback(err);
  12266. callback = function () {};
  12267. }
  12268. else {
  12269. completed += 1;
  12270. if (completed >= arr.length) {
  12271. callback();
  12272. }
  12273. else {
  12274. iterate();
  12275. }
  12276. }
  12277. });
  12278. };
  12279. iterate();
  12280. };
  12281. async.forEachSeries = async.eachSeries;
  12282. async.eachLimit = function (arr, limit, iterator, callback) {
  12283. var fn = _eachLimit(limit);
  12284. fn.apply(null, [arr, iterator, callback]);
  12285. };
  12286. async.forEachLimit = async.eachLimit;
  12287. var _eachLimit = function (limit) {
  12288. return function (arr, iterator, callback) {
  12289. callback = callback || function () {};
  12290. if (!arr.length || limit <= 0) {
  12291. return callback();
  12292. }
  12293. var completed = 0;
  12294. var started = 0;
  12295. var running = 0;
  12296. (function replenish () {
  12297. if (completed >= arr.length) {
  12298. return callback();
  12299. }
  12300. while (running < limit && started < arr.length) {
  12301. started += 1;
  12302. running += 1;
  12303. iterator(arr[started - 1], function (err) {
  12304. if (err) {
  12305. callback(err);
  12306. callback = function () {};
  12307. }
  12308. else {
  12309. completed += 1;
  12310. running -= 1;
  12311. if (completed >= arr.length) {
  12312. callback();
  12313. }
  12314. else {
  12315. replenish();
  12316. }
  12317. }
  12318. });
  12319. }
  12320. })();
  12321. };
  12322. };
  12323. var doParallel = function (fn) {
  12324. return function () {
  12325. var args = Array.prototype.slice.call(arguments);
  12326. return fn.apply(null, [async.each].concat(args));
  12327. };
  12328. };
  12329. var doParallelLimit = function(limit, fn) {
  12330. return function () {
  12331. var args = Array.prototype.slice.call(arguments);
  12332. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12333. };
  12334. };
  12335. var doSeries = function (fn) {
  12336. return function () {
  12337. var args = Array.prototype.slice.call(arguments);
  12338. return fn.apply(null, [async.eachSeries].concat(args));
  12339. };
  12340. };
  12341. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12342. arr = _map(arr, function (x, i) {
  12343. return {index: i, value: x};
  12344. });
  12345. if (!callback) {
  12346. eachfn(arr, function (x, callback) {
  12347. iterator(x.value, function (err) {
  12348. callback(err);
  12349. });
  12350. });
  12351. } else {
  12352. var results = [];
  12353. eachfn(arr, function (x, callback) {
  12354. iterator(x.value, function (err, v) {
  12355. results[x.index] = v;
  12356. callback(err);
  12357. });
  12358. }, function (err) {
  12359. callback(err, results);
  12360. });
  12361. }
  12362. };
  12363. async.map = doParallel(_asyncMap);
  12364. async.mapSeries = doSeries(_asyncMap);
  12365. async.mapLimit = function (arr, limit, iterator, callback) {
  12366. return _mapLimit(limit)(arr, iterator, callback);
  12367. };
  12368. var _mapLimit = function(limit) {
  12369. return doParallelLimit(limit, _asyncMap);
  12370. };
  12371. // reduce only has a series version, as doing reduce in parallel won't
  12372. // work in many situations.
  12373. async.reduce = function (arr, memo, iterator, callback) {
  12374. async.eachSeries(arr, function (x, callback) {
  12375. iterator(memo, x, function (err, v) {
  12376. memo = v;
  12377. callback(err);
  12378. });
  12379. }, function (err) {
  12380. callback(err, memo);
  12381. });
  12382. };
  12383. // inject alias
  12384. async.inject = async.reduce;
  12385. // foldl alias
  12386. async.foldl = async.reduce;
  12387. async.reduceRight = function (arr, memo, iterator, callback) {
  12388. var reversed = _map(arr, function (x) {
  12389. return x;
  12390. }).reverse();
  12391. async.reduce(reversed, memo, iterator, callback);
  12392. };
  12393. // foldr alias
  12394. async.foldr = async.reduceRight;
  12395. var _filter = function (eachfn, arr, iterator, callback) {
  12396. var results = [];
  12397. arr = _map(arr, function (x, i) {
  12398. return {index: i, value: x};
  12399. });
  12400. eachfn(arr, function (x, callback) {
  12401. iterator(x.value, function (v) {
  12402. if (v) {
  12403. results.push(x);
  12404. }
  12405. callback();
  12406. });
  12407. }, function (err) {
  12408. callback(_map(results.sort(function (a, b) {
  12409. return a.index - b.index;
  12410. }), function (x) {
  12411. return x.value;
  12412. }));
  12413. });
  12414. };
  12415. async.filter = doParallel(_filter);
  12416. async.filterSeries = doSeries(_filter);
  12417. // select alias
  12418. async.select = async.filter;
  12419. async.selectSeries = async.filterSeries;
  12420. var _reject = function (eachfn, arr, iterator, callback) {
  12421. var results = [];
  12422. arr = _map(arr, function (x, i) {
  12423. return {index: i, value: x};
  12424. });
  12425. eachfn(arr, function (x, callback) {
  12426. iterator(x.value, function (v) {
  12427. if (!v) {
  12428. results.push(x);
  12429. }
  12430. callback();
  12431. });
  12432. }, function (err) {
  12433. callback(_map(results.sort(function (a, b) {
  12434. return a.index - b.index;
  12435. }), function (x) {
  12436. return x.value;
  12437. }));
  12438. });
  12439. };
  12440. async.reject = doParallel(_reject);
  12441. async.rejectSeries = doSeries(_reject);
  12442. var _detect = function (eachfn, arr, iterator, main_callback) {
  12443. eachfn(arr, function (x, callback) {
  12444. iterator(x, function (result) {
  12445. if (result) {
  12446. main_callback(x);
  12447. main_callback = function () {};
  12448. }
  12449. else {
  12450. callback();
  12451. }
  12452. });
  12453. }, function (err) {
  12454. main_callback();
  12455. });
  12456. };
  12457. async.detect = doParallel(_detect);
  12458. async.detectSeries = doSeries(_detect);
  12459. async.some = function (arr, iterator, main_callback) {
  12460. async.each(arr, function (x, callback) {
  12461. iterator(x, function (v) {
  12462. if (v) {
  12463. main_callback(true);
  12464. main_callback = function () {};
  12465. }
  12466. callback();
  12467. });
  12468. }, function (err) {
  12469. main_callback(false);
  12470. });
  12471. };
  12472. // any alias
  12473. async.any = async.some;
  12474. async.every = function (arr, iterator, main_callback) {
  12475. async.each(arr, function (x, callback) {
  12476. iterator(x, function (v) {
  12477. if (!v) {
  12478. main_callback(false);
  12479. main_callback = function () {};
  12480. }
  12481. callback();
  12482. });
  12483. }, function (err) {
  12484. main_callback(true);
  12485. });
  12486. };
  12487. // all alias
  12488. async.all = async.every;
  12489. async.sortBy = function (arr, iterator, callback) {
  12490. async.map(arr, function (x, callback) {
  12491. iterator(x, function (err, criteria) {
  12492. if (err) {
  12493. callback(err);
  12494. }
  12495. else {
  12496. callback(null, {value: x, criteria: criteria});
  12497. }
  12498. });
  12499. }, function (err, results) {
  12500. if (err) {
  12501. return callback(err);
  12502. }
  12503. else {
  12504. var fn = function (left, right) {
  12505. var a = left.criteria, b = right.criteria;
  12506. return a < b ? -1 : a > b ? 1 : 0;
  12507. };
  12508. callback(null, _map(results.sort(fn), function (x) {
  12509. return x.value;
  12510. }));
  12511. }
  12512. });
  12513. };
  12514. async.auto = function (tasks, callback) {
  12515. callback = callback || function () {};
  12516. var keys = _keys(tasks);
  12517. var remainingTasks = keys.length
  12518. if (!remainingTasks) {
  12519. return callback();
  12520. }
  12521. var results = {};
  12522. var listeners = [];
  12523. var addListener = function (fn) {
  12524. listeners.unshift(fn);
  12525. };
  12526. var removeListener = function (fn) {
  12527. for (var i = 0; i < listeners.length; i += 1) {
  12528. if (listeners[i] === fn) {
  12529. listeners.splice(i, 1);
  12530. return;
  12531. }
  12532. }
  12533. };
  12534. var taskComplete = function () {
  12535. remainingTasks--
  12536. _each(listeners.slice(0), function (fn) {
  12537. fn();
  12538. });
  12539. };
  12540. addListener(function () {
  12541. if (!remainingTasks) {
  12542. var theCallback = callback;
  12543. // prevent final callback from calling itself if it errors
  12544. callback = function () {};
  12545. theCallback(null, results);
  12546. }
  12547. });
  12548. _each(keys, function (k) {
  12549. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12550. var taskCallback = function (err) {
  12551. var args = Array.prototype.slice.call(arguments, 1);
  12552. if (args.length <= 1) {
  12553. args = args[0];
  12554. }
  12555. if (err) {
  12556. var safeResults = {};
  12557. _each(_keys(results), function(rkey) {
  12558. safeResults[rkey] = results[rkey];
  12559. });
  12560. safeResults[k] = args;
  12561. callback(err, safeResults);
  12562. // stop subsequent errors hitting callback multiple times
  12563. callback = function () {};
  12564. }
  12565. else {
  12566. results[k] = args;
  12567. async.setImmediate(taskComplete);
  12568. }
  12569. };
  12570. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12571. var ready = function () {
  12572. return _reduce(requires, function (a, x) {
  12573. return (a && results.hasOwnProperty(x));
  12574. }, true) && !results.hasOwnProperty(k);
  12575. };
  12576. if (ready()) {
  12577. task[task.length - 1](taskCallback, results);
  12578. }
  12579. else {
  12580. var listener = function () {
  12581. if (ready()) {
  12582. removeListener(listener);
  12583. task[task.length - 1](taskCallback, results);
  12584. }
  12585. };
  12586. addListener(listener);
  12587. }
  12588. });
  12589. };
  12590. async.retry = function(times, task, callback) {
  12591. var DEFAULT_TIMES = 5;
  12592. var attempts = [];
  12593. // Use defaults if times not passed
  12594. if (typeof times === 'function') {
  12595. callback = task;
  12596. task = times;
  12597. times = DEFAULT_TIMES;
  12598. }
  12599. // Make sure times is a number
  12600. times = parseInt(times, 10) || DEFAULT_TIMES;
  12601. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12602. var retryAttempt = function(task, finalAttempt) {
  12603. return function(seriesCallback) {
  12604. task(function(err, result){
  12605. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12606. }, wrappedResults);
  12607. };
  12608. };
  12609. while (times) {
  12610. attempts.push(retryAttempt(task, !(times-=1)));
  12611. }
  12612. async.series(attempts, function(done, data){
  12613. data = data[data.length - 1];
  12614. (wrappedCallback || callback)(data.err, data.result);
  12615. });
  12616. }
  12617. // If a callback is passed, run this as a controll flow
  12618. return callback ? wrappedTask() : wrappedTask
  12619. };
  12620. async.waterfall = function (tasks, callback) {
  12621. callback = callback || function () {};
  12622. if (!_isArray(tasks)) {
  12623. var err = new Error('First argument to waterfall must be an array of functions');
  12624. return callback(err);
  12625. }
  12626. if (!tasks.length) {
  12627. return callback();
  12628. }
  12629. var wrapIterator = function (iterator) {
  12630. return function (err) {
  12631. if (err) {
  12632. callback.apply(null, arguments);
  12633. callback = function () {};
  12634. }
  12635. else {
  12636. var args = Array.prototype.slice.call(arguments, 1);
  12637. var next = iterator.next();
  12638. if (next) {
  12639. args.push(wrapIterator(next));
  12640. }
  12641. else {
  12642. args.push(callback);
  12643. }
  12644. async.setImmediate(function () {
  12645. iterator.apply(null, args);
  12646. });
  12647. }
  12648. };
  12649. };
  12650. wrapIterator(async.iterator(tasks))();
  12651. };
  12652. var _parallel = function(eachfn, tasks, callback) {
  12653. callback = callback || function () {};
  12654. if (_isArray(tasks)) {
  12655. eachfn.map(tasks, function (fn, callback) {
  12656. if (fn) {
  12657. fn(function (err) {
  12658. var args = Array.prototype.slice.call(arguments, 1);
  12659. if (args.length <= 1) {
  12660. args = args[0];
  12661. }
  12662. callback.call(null, err, args);
  12663. });
  12664. }
  12665. }, callback);
  12666. }
  12667. else {
  12668. var results = {};
  12669. eachfn.each(_keys(tasks), function (k, callback) {
  12670. tasks[k](function (err) {
  12671. var args = Array.prototype.slice.call(arguments, 1);
  12672. if (args.length <= 1) {
  12673. args = args[0];
  12674. }
  12675. results[k] = args;
  12676. callback(err);
  12677. });
  12678. }, function (err) {
  12679. callback(err, results);
  12680. });
  12681. }
  12682. };
  12683. async.parallel = function (tasks, callback) {
  12684. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12685. };
  12686. async.parallelLimit = function(tasks, limit, callback) {
  12687. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12688. };
  12689. async.series = function (tasks, callback) {
  12690. callback = callback || function () {};
  12691. if (_isArray(tasks)) {
  12692. async.mapSeries(tasks, function (fn, callback) {
  12693. if (fn) {
  12694. fn(function (err) {
  12695. var args = Array.prototype.slice.call(arguments, 1);
  12696. if (args.length <= 1) {
  12697. args = args[0];
  12698. }
  12699. callback.call(null, err, args);
  12700. });
  12701. }
  12702. }, callback);
  12703. }
  12704. else {
  12705. var results = {};
  12706. async.eachSeries(_keys(tasks), function (k, callback) {
  12707. tasks[k](function (err) {
  12708. var args = Array.prototype.slice.call(arguments, 1);
  12709. if (args.length <= 1) {
  12710. args = args[0];
  12711. }
  12712. results[k] = args;
  12713. callback(err);
  12714. });
  12715. }, function (err) {
  12716. callback(err, results);
  12717. });
  12718. }
  12719. };
  12720. async.iterator = function (tasks) {
  12721. var makeCallback = function (index) {
  12722. var fn = function () {
  12723. if (tasks.length) {
  12724. tasks[index].apply(null, arguments);
  12725. }
  12726. return fn.next();
  12727. };
  12728. fn.next = function () {
  12729. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12730. };
  12731. return fn;
  12732. };
  12733. return makeCallback(0);
  12734. };
  12735. async.apply = function (fn) {
  12736. var args = Array.prototype.slice.call(arguments, 1);
  12737. return function () {
  12738. return fn.apply(
  12739. null, args.concat(Array.prototype.slice.call(arguments))
  12740. );
  12741. };
  12742. };
  12743. var _concat = function (eachfn, arr, fn, callback) {
  12744. var r = [];
  12745. eachfn(arr, function (x, cb) {
  12746. fn(x, function (err, y) {
  12747. r = r.concat(y || []);
  12748. cb(err);
  12749. });
  12750. }, function (err) {
  12751. callback(err, r);
  12752. });
  12753. };
  12754. async.concat = doParallel(_concat);
  12755. async.concatSeries = doSeries(_concat);
  12756. async.whilst = function (test, iterator, callback) {
  12757. if (test()) {
  12758. iterator(function (err) {
  12759. if (err) {
  12760. return callback(err);
  12761. }
  12762. async.whilst(test, iterator, callback);
  12763. });
  12764. }
  12765. else {
  12766. callback();
  12767. }
  12768. };
  12769. async.doWhilst = function (iterator, test, callback) {
  12770. iterator(function (err) {
  12771. if (err) {
  12772. return callback(err);
  12773. }
  12774. var args = Array.prototype.slice.call(arguments, 1);
  12775. if (test.apply(null, args)) {
  12776. async.doWhilst(iterator, test, callback);
  12777. }
  12778. else {
  12779. callback();
  12780. }
  12781. });
  12782. };
  12783. async.until = function (test, iterator, callback) {
  12784. if (!test()) {
  12785. iterator(function (err) {
  12786. if (err) {
  12787. return callback(err);
  12788. }
  12789. async.until(test, iterator, callback);
  12790. });
  12791. }
  12792. else {
  12793. callback();
  12794. }
  12795. };
  12796. async.doUntil = function (iterator, test, callback) {
  12797. iterator(function (err) {
  12798. if (err) {
  12799. return callback(err);
  12800. }
  12801. var args = Array.prototype.slice.call(arguments, 1);
  12802. if (!test.apply(null, args)) {
  12803. async.doUntil(iterator, test, callback);
  12804. }
  12805. else {
  12806. callback();
  12807. }
  12808. });
  12809. };
  12810. async.queue = function (worker, concurrency) {
  12811. if (concurrency === undefined) {
  12812. concurrency = 1;
  12813. }
  12814. function _insert(q, data, pos, callback) {
  12815. if (!q.started){
  12816. q.started = true;
  12817. }
  12818. if (!_isArray(data)) {
  12819. data = [data];
  12820. }
  12821. if(data.length == 0) {
  12822. // call drain immediately if there are no tasks
  12823. return async.setImmediate(function() {
  12824. if (q.drain) {
  12825. q.drain();
  12826. }
  12827. });
  12828. }
  12829. _each(data, function(task) {
  12830. var item = {
  12831. data: task,
  12832. callback: typeof callback === 'function' ? callback : null
  12833. };
  12834. if (pos) {
  12835. q.tasks.unshift(item);
  12836. } else {
  12837. q.tasks.push(item);
  12838. }
  12839. if (q.saturated && q.tasks.length === q.concurrency) {
  12840. q.saturated();
  12841. }
  12842. async.setImmediate(q.process);
  12843. });
  12844. }
  12845. var workers = 0;
  12846. var q = {
  12847. tasks: [],
  12848. concurrency: concurrency,
  12849. saturated: null,
  12850. empty: null,
  12851. drain: null,
  12852. started: false,
  12853. paused: false,
  12854. push: function (data, callback) {
  12855. _insert(q, data, false, callback);
  12856. },
  12857. kill: function () {
  12858. q.drain = null;
  12859. q.tasks = [];
  12860. },
  12861. unshift: function (data, callback) {
  12862. _insert(q, data, true, callback);
  12863. },
  12864. process: function () {
  12865. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12866. var task = q.tasks.shift();
  12867. if (q.empty && q.tasks.length === 0) {
  12868. q.empty();
  12869. }
  12870. workers += 1;
  12871. var next = function () {
  12872. workers -= 1;
  12873. if (task.callback) {
  12874. task.callback.apply(task, arguments);
  12875. }
  12876. if (q.drain && q.tasks.length + workers === 0) {
  12877. q.drain();
  12878. }
  12879. q.process();
  12880. };
  12881. var cb = only_once(next);
  12882. worker(task.data, cb);
  12883. }
  12884. },
  12885. length: function () {
  12886. return q.tasks.length;
  12887. },
  12888. running: function () {
  12889. return workers;
  12890. },
  12891. idle: function() {
  12892. return q.tasks.length + workers === 0;
  12893. },
  12894. pause: function () {
  12895. if (q.paused === true) { return; }
  12896. q.paused = true;
  12897. q.process();
  12898. },
  12899. resume: function () {
  12900. if (q.paused === false) { return; }
  12901. q.paused = false;
  12902. q.process();
  12903. }
  12904. };
  12905. return q;
  12906. };
  12907. async.priorityQueue = function (worker, concurrency) {
  12908. function _compareTasks(a, b){
  12909. return a.priority - b.priority;
  12910. };
  12911. function _binarySearch(sequence, item, compare) {
  12912. var beg = -1,
  12913. end = sequence.length - 1;
  12914. while (beg < end) {
  12915. var mid = beg + ((end - beg + 1) >>> 1);
  12916. if (compare(item, sequence[mid]) >= 0) {
  12917. beg = mid;
  12918. } else {
  12919. end = mid - 1;
  12920. }
  12921. }
  12922. return beg;
  12923. }
  12924. function _insert(q, data, priority, callback) {
  12925. if (!q.started){
  12926. q.started = true;
  12927. }
  12928. if (!_isArray(data)) {
  12929. data = [data];
  12930. }
  12931. if(data.length == 0) {
  12932. // call drain immediately if there are no tasks
  12933. return async.setImmediate(function() {
  12934. if (q.drain) {
  12935. q.drain();
  12936. }
  12937. });
  12938. }
  12939. _each(data, function(task) {
  12940. var item = {
  12941. data: task,
  12942. priority: priority,
  12943. callback: typeof callback === 'function' ? callback : null
  12944. };
  12945. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12946. if (q.saturated && q.tasks.length === q.concurrency) {
  12947. q.saturated();
  12948. }
  12949. async.setImmediate(q.process);
  12950. });
  12951. }
  12952. // Start with a normal queue
  12953. var q = async.queue(worker, concurrency);
  12954. // Override push to accept second parameter representing priority
  12955. q.push = function (data, priority, callback) {
  12956. _insert(q, data, priority, callback);
  12957. };
  12958. // Remove unshift function
  12959. delete q.unshift;
  12960. return q;
  12961. };
  12962. async.cargo = function (worker, payload) {
  12963. var working = false,
  12964. tasks = [];
  12965. var cargo = {
  12966. tasks: tasks,
  12967. payload: payload,
  12968. saturated: null,
  12969. empty: null,
  12970. drain: null,
  12971. drained: true,
  12972. push: function (data, callback) {
  12973. if (!_isArray(data)) {
  12974. data = [data];
  12975. }
  12976. _each(data, function(task) {
  12977. tasks.push({
  12978. data: task,
  12979. callback: typeof callback === 'function' ? callback : null
  12980. });
  12981. cargo.drained = false;
  12982. if (cargo.saturated && tasks.length === payload) {
  12983. cargo.saturated();
  12984. }
  12985. });
  12986. async.setImmediate(cargo.process);
  12987. },
  12988. process: function process() {
  12989. if (working) return;
  12990. if (tasks.length === 0) {
  12991. if(cargo.drain && !cargo.drained) cargo.drain();
  12992. cargo.drained = true;
  12993. return;
  12994. }
  12995. var ts = typeof payload === 'number'
  12996. ? tasks.splice(0, payload)
  12997. : tasks.splice(0, tasks.length);
  12998. var ds = _map(ts, function (task) {
  12999. return task.data;
  13000. });
  13001. if(cargo.empty) cargo.empty();
  13002. working = true;
  13003. worker(ds, function () {
  13004. working = false;
  13005. var args = arguments;
  13006. _each(ts, function (data) {
  13007. if (data.callback) {
  13008. data.callback.apply(null, args);
  13009. }
  13010. });
  13011. process();
  13012. });
  13013. },
  13014. length: function () {
  13015. return tasks.length;
  13016. },
  13017. running: function () {
  13018. return working;
  13019. }
  13020. };
  13021. return cargo;
  13022. };
  13023. var _console_fn = function (name) {
  13024. return function (fn) {
  13025. var args = Array.prototype.slice.call(arguments, 1);
  13026. fn.apply(null, args.concat([function (err) {
  13027. var args = Array.prototype.slice.call(arguments, 1);
  13028. if (typeof console !== 'undefined') {
  13029. if (err) {
  13030. if (console.error) {
  13031. console.error(err);
  13032. }
  13033. }
  13034. else if (console[name]) {
  13035. _each(args, function (x) {
  13036. console[name](x);
  13037. });
  13038. }
  13039. }
  13040. }]));
  13041. };
  13042. };
  13043. async.log = _console_fn('log');
  13044. async.dir = _console_fn('dir');
  13045. /*async.info = _console_fn('info');
  13046. async.warn = _console_fn('warn');
  13047. async.error = _console_fn('error');*/
  13048. async.memoize = function (fn, hasher) {
  13049. var memo = {};
  13050. var queues = {};
  13051. hasher = hasher || function (x) {
  13052. return x;
  13053. };
  13054. var memoized = function () {
  13055. var args = Array.prototype.slice.call(arguments);
  13056. var callback = args.pop();
  13057. var key = hasher.apply(null, args);
  13058. if (key in memo) {
  13059. async.nextTick(function () {
  13060. callback.apply(null, memo[key]);
  13061. });
  13062. }
  13063. else if (key in queues) {
  13064. queues[key].push(callback);
  13065. }
  13066. else {
  13067. queues[key] = [callback];
  13068. fn.apply(null, args.concat([function () {
  13069. memo[key] = arguments;
  13070. var q = queues[key];
  13071. delete queues[key];
  13072. for (var i = 0, l = q.length; i < l; i++) {
  13073. q[i].apply(null, arguments);
  13074. }
  13075. }]));
  13076. }
  13077. };
  13078. memoized.memo = memo;
  13079. memoized.unmemoized = fn;
  13080. return memoized;
  13081. };
  13082. async.unmemoize = function (fn) {
  13083. return function () {
  13084. return (fn.unmemoized || fn).apply(null, arguments);
  13085. };
  13086. };
  13087. async.times = function (count, iterator, callback) {
  13088. var counter = [];
  13089. for (var i = 0; i < count; i++) {
  13090. counter.push(i);
  13091. }
  13092. return async.map(counter, iterator, callback);
  13093. };
  13094. async.timesSeries = function (count, iterator, callback) {
  13095. var counter = [];
  13096. for (var i = 0; i < count; i++) {
  13097. counter.push(i);
  13098. }
  13099. return async.mapSeries(counter, iterator, callback);
  13100. };
  13101. async.seq = function (/* functions... */) {
  13102. var fns = arguments;
  13103. return function () {
  13104. var that = this;
  13105. var args = Array.prototype.slice.call(arguments);
  13106. var callback = args.pop();
  13107. async.reduce(fns, args, function (newargs, fn, cb) {
  13108. fn.apply(that, newargs.concat([function () {
  13109. var err = arguments[0];
  13110. var nextargs = Array.prototype.slice.call(arguments, 1);
  13111. cb(err, nextargs);
  13112. }]))
  13113. },
  13114. function (err, results) {
  13115. callback.apply(that, [err].concat(results));
  13116. });
  13117. };
  13118. };
  13119. async.compose = function (/* functions... */) {
  13120. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  13121. };
  13122. var _applyEach = function (eachfn, fns /*args...*/) {
  13123. var go = function () {
  13124. var that = this;
  13125. var args = Array.prototype.slice.call(arguments);
  13126. var callback = args.pop();
  13127. return eachfn(fns, function (fn, cb) {
  13128. fn.apply(that, args.concat([cb]));
  13129. },
  13130. callback);
  13131. };
  13132. if (arguments.length > 2) {
  13133. var args = Array.prototype.slice.call(arguments, 2);
  13134. return go.apply(this, args);
  13135. }
  13136. else {
  13137. return go;
  13138. }
  13139. };
  13140. async.applyEach = doParallel(_applyEach);
  13141. async.applyEachSeries = doSeries(_applyEach);
  13142. async.forever = function (fn, callback) {
  13143. function next(err) {
  13144. if (err) {
  13145. if (callback) {
  13146. return callback(err);
  13147. }
  13148. throw err;
  13149. }
  13150. fn(next);
  13151. }
  13152. next();
  13153. };
  13154. // Node.js
  13155. if (typeof module !== 'undefined' && module.exports) {
  13156. module.exports = async;
  13157. }
  13158. // AMD / RequireJS
  13159. else if (typeof define !== 'undefined' && define.amd) {
  13160. define([], function () {
  13161. return async;
  13162. });
  13163. }
  13164. // included directly via <script> tag
  13165. else {
  13166. root.async = async;
  13167. }
  13168. }());
  13169. }).call(this,require('_process'))
  13170. },{"_process":47}],46:[function(require,module,exports){
  13171. // Copyright Joyent, Inc. and other Node contributors.
  13172. //
  13173. // Permission is hereby granted, free of charge, to any person obtaining a
  13174. // copy of this software and associated documentation files (the
  13175. // "Software"), to deal in the Software without restriction, including
  13176. // without limitation the rights to use, copy, modify, merge, publish,
  13177. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13178. // persons to whom the Software is furnished to do so, subject to the
  13179. // following conditions:
  13180. //
  13181. // The above copyright notice and this permission notice shall be included
  13182. // in all copies or substantial portions of the Software.
  13183. //
  13184. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13185. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13186. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13187. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13188. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13189. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13190. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13191. function EventEmitter() {
  13192. this._events = this._events || {};
  13193. this._maxListeners = this._maxListeners || undefined;
  13194. }
  13195. module.exports = EventEmitter;
  13196. // Backwards-compat with node 0.10.x
  13197. EventEmitter.EventEmitter = EventEmitter;
  13198. EventEmitter.prototype._events = undefined;
  13199. EventEmitter.prototype._maxListeners = undefined;
  13200. // By default EventEmitters will print a warning if more than 10 listeners are
  13201. // added to it. This is a useful default which helps finding memory leaks.
  13202. EventEmitter.defaultMaxListeners = 10;
  13203. // Obviously not all Emitters should be limited to 10. This function allows
  13204. // that to be increased. Set to zero for unlimited.
  13205. EventEmitter.prototype.setMaxListeners = function(n) {
  13206. if (!isNumber(n) || n < 0 || isNaN(n))
  13207. throw TypeError('n must be a positive number');
  13208. this._maxListeners = n;
  13209. return this;
  13210. };
  13211. EventEmitter.prototype.emit = function(type) {
  13212. var er, handler, len, args, i, listeners;
  13213. if (!this._events)
  13214. this._events = {};
  13215. // If there is no 'error' event listener then throw.
  13216. if (type === 'error') {
  13217. if (!this._events.error ||
  13218. (isObject(this._events.error) && !this._events.error.length)) {
  13219. er = arguments[1];
  13220. if (er instanceof Error) {
  13221. throw er; // Unhandled 'error' event
  13222. }
  13223. throw TypeError('Uncaught, unspecified "error" event.');
  13224. }
  13225. }
  13226. handler = this._events[type];
  13227. if (isUndefined(handler))
  13228. return false;
  13229. if (isFunction(handler)) {
  13230. switch (arguments.length) {
  13231. // fast cases
  13232. case 1:
  13233. handler.call(this);
  13234. break;
  13235. case 2:
  13236. handler.call(this, arguments[1]);
  13237. break;
  13238. case 3:
  13239. handler.call(this, arguments[1], arguments[2]);
  13240. break;
  13241. // slower
  13242. default:
  13243. len = arguments.length;
  13244. args = new Array(len - 1);
  13245. for (i = 1; i < len; i++)
  13246. args[i - 1] = arguments[i];
  13247. handler.apply(this, args);
  13248. }
  13249. } else if (isObject(handler)) {
  13250. len = arguments.length;
  13251. args = new Array(len - 1);
  13252. for (i = 1; i < len; i++)
  13253. args[i - 1] = arguments[i];
  13254. listeners = handler.slice();
  13255. len = listeners.length;
  13256. for (i = 0; i < len; i++)
  13257. listeners[i].apply(this, args);
  13258. }
  13259. return true;
  13260. };
  13261. EventEmitter.prototype.addListener = function(type, listener) {
  13262. var m;
  13263. if (!isFunction(listener))
  13264. throw TypeError('listener must be a function');
  13265. if (!this._events)
  13266. this._events = {};
  13267. // To avoid recursion in the case that type === "newListener"! Before
  13268. // adding it to the listeners, first emit "newListener".
  13269. if (this._events.newListener)
  13270. this.emit('newListener', type,
  13271. isFunction(listener.listener) ?
  13272. listener.listener : listener);
  13273. if (!this._events[type])
  13274. // Optimize the case of one listener. Don't need the extra array object.
  13275. this._events[type] = listener;
  13276. else if (isObject(this._events[type]))
  13277. // If we've already got an array, just append.
  13278. this._events[type].push(listener);
  13279. else
  13280. // Adding the second element, need to change to array.
  13281. this._events[type] = [this._events[type], listener];
  13282. // Check for listener leak
  13283. if (isObject(this._events[type]) && !this._events[type].warned) {
  13284. var m;
  13285. if (!isUndefined(this._maxListeners)) {
  13286. m = this._maxListeners;
  13287. } else {
  13288. m = EventEmitter.defaultMaxListeners;
  13289. }
  13290. if (m && m > 0 && this._events[type].length > m) {
  13291. this._events[type].warned = true;
  13292. console.error('(node) warning: possible EventEmitter memory ' +
  13293. 'leak detected. %d listeners added. ' +
  13294. 'Use emitter.setMaxListeners() to increase limit.',
  13295. this._events[type].length);
  13296. if (typeof console.trace === 'function') {
  13297. // not supported in IE 10
  13298. console.trace();
  13299. }
  13300. }
  13301. }
  13302. return this;
  13303. };
  13304. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13305. EventEmitter.prototype.once = function(type, listener) {
  13306. if (!isFunction(listener))
  13307. throw TypeError('listener must be a function');
  13308. var fired = false;
  13309. function g() {
  13310. this.removeListener(type, g);
  13311. if (!fired) {
  13312. fired = true;
  13313. listener.apply(this, arguments);
  13314. }
  13315. }
  13316. g.listener = listener;
  13317. this.on(type, g);
  13318. return this;
  13319. };
  13320. // emits a 'removeListener' event iff the listener was removed
  13321. EventEmitter.prototype.removeListener = function(type, listener) {
  13322. var list, position, length, i;
  13323. if (!isFunction(listener))
  13324. throw TypeError('listener must be a function');
  13325. if (!this._events || !this._events[type])
  13326. return this;
  13327. list = this._events[type];
  13328. length = list.length;
  13329. position = -1;
  13330. if (list === listener ||
  13331. (isFunction(list.listener) && list.listener === listener)) {
  13332. delete this._events[type];
  13333. if (this._events.removeListener)
  13334. this.emit('removeListener', type, listener);
  13335. } else if (isObject(list)) {
  13336. for (i = length; i-- > 0;) {
  13337. if (list[i] === listener ||
  13338. (list[i].listener && list[i].listener === listener)) {
  13339. position = i;
  13340. break;
  13341. }
  13342. }
  13343. if (position < 0)
  13344. return this;
  13345. if (list.length === 1) {
  13346. list.length = 0;
  13347. delete this._events[type];
  13348. } else {
  13349. list.splice(position, 1);
  13350. }
  13351. if (this._events.removeListener)
  13352. this.emit('removeListener', type, listener);
  13353. }
  13354. return this;
  13355. };
  13356. EventEmitter.prototype.removeAllListeners = function(type) {
  13357. var key, listeners;
  13358. if (!this._events)
  13359. return this;
  13360. // not listening for removeListener, no need to emit
  13361. if (!this._events.removeListener) {
  13362. if (arguments.length === 0)
  13363. this._events = {};
  13364. else if (this._events[type])
  13365. delete this._events[type];
  13366. return this;
  13367. }
  13368. // emit removeListener for all listeners on all events
  13369. if (arguments.length === 0) {
  13370. for (key in this._events) {
  13371. if (key === 'removeListener') continue;
  13372. this.removeAllListeners(key);
  13373. }
  13374. this.removeAllListeners('removeListener');
  13375. this._events = {};
  13376. return this;
  13377. }
  13378. listeners = this._events[type];
  13379. if (isFunction(listeners)) {
  13380. this.removeListener(type, listeners);
  13381. } else {
  13382. // LIFO order
  13383. while (listeners.length)
  13384. this.removeListener(type, listeners[listeners.length - 1]);
  13385. }
  13386. delete this._events[type];
  13387. return this;
  13388. };
  13389. EventEmitter.prototype.listeners = function(type) {
  13390. var ret;
  13391. if (!this._events || !this._events[type])
  13392. ret = [];
  13393. else if (isFunction(this._events[type]))
  13394. ret = [this._events[type]];
  13395. else
  13396. ret = this._events[type].slice();
  13397. return ret;
  13398. };
  13399. EventEmitter.listenerCount = function(emitter, type) {
  13400. var ret;
  13401. if (!emitter._events || !emitter._events[type])
  13402. ret = 0;
  13403. else if (isFunction(emitter._events[type]))
  13404. ret = 1;
  13405. else
  13406. ret = emitter._events[type].length;
  13407. return ret;
  13408. };
  13409. function isFunction(arg) {
  13410. return typeof arg === 'function';
  13411. }
  13412. function isNumber(arg) {
  13413. return typeof arg === 'number';
  13414. }
  13415. function isObject(arg) {
  13416. return typeof arg === 'object' && arg !== null;
  13417. }
  13418. function isUndefined(arg) {
  13419. return arg === void 0;
  13420. }
  13421. },{}],47:[function(require,module,exports){
  13422. // shim for using process in browser
  13423. var process = module.exports = {};
  13424. var queue = [];
  13425. var draining = false;
  13426. var currentQueue;
  13427. var queueIndex = -1;
  13428. function cleanUpNextTick() {
  13429. draining = false;
  13430. if (currentQueue.length) {
  13431. queue = currentQueue.concat(queue);
  13432. } else {
  13433. queueIndex = -1;
  13434. }
  13435. if (queue.length) {
  13436. drainQueue();
  13437. }
  13438. }
  13439. function drainQueue() {
  13440. if (draining) {
  13441. return;
  13442. }
  13443. var timeout = setTimeout(cleanUpNextTick);
  13444. draining = true;
  13445. var len = queue.length;
  13446. while(len) {
  13447. currentQueue = queue;
  13448. queue = [];
  13449. while (++queueIndex < len) {
  13450. if (currentQueue) {
  13451. currentQueue[queueIndex].run();
  13452. }
  13453. }
  13454. queueIndex = -1;
  13455. len = queue.length;
  13456. }
  13457. currentQueue = null;
  13458. draining = false;
  13459. clearTimeout(timeout);
  13460. }
  13461. process.nextTick = function (fun) {
  13462. var args = new Array(arguments.length - 1);
  13463. if (arguments.length > 1) {
  13464. for (var i = 1; i < arguments.length; i++) {
  13465. args[i - 1] = arguments[i];
  13466. }
  13467. }
  13468. queue.push(new Item(fun, args));
  13469. if (queue.length === 1 && !draining) {
  13470. setTimeout(drainQueue, 0);
  13471. }
  13472. };
  13473. // v8 likes predictible objects
  13474. function Item(fun, array) {
  13475. this.fun = fun;
  13476. this.array = array;
  13477. }
  13478. Item.prototype.run = function () {
  13479. this.fun.apply(null, this.array);
  13480. };
  13481. process.title = 'browser';
  13482. process.browser = true;
  13483. process.env = {};
  13484. process.argv = [];
  13485. process.version = ''; // empty string to avoid regexp issues
  13486. process.versions = {};
  13487. function noop() {}
  13488. process.on = noop;
  13489. process.addListener = noop;
  13490. process.once = noop;
  13491. process.off = noop;
  13492. process.removeListener = noop;
  13493. process.removeAllListeners = noop;
  13494. process.emit = noop;
  13495. process.binding = function (name) {
  13496. throw new Error('process.binding is not supported');
  13497. };
  13498. process.cwd = function () { return '/' };
  13499. process.chdir = function (dir) {
  13500. throw new Error('process.chdir is not supported');
  13501. };
  13502. process.umask = function() { return 0; };
  13503. },{}],48:[function(require,module,exports){
  13504. (function (process,global){
  13505. /*!
  13506. * @overview es6-promise - a tiny implementation of Promises/A+.
  13507. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13508. * @license Licensed under MIT license
  13509. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13510. * @version 3.0.2
  13511. */
  13512. (function() {
  13513. "use strict";
  13514. function lib$es6$promise$utils$$objectOrFunction(x) {
  13515. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  13516. }
  13517. function lib$es6$promise$utils$$isFunction(x) {
  13518. return typeof x === 'function';
  13519. }
  13520. function lib$es6$promise$utils$$isMaybeThenable(x) {
  13521. return typeof x === 'object' && x !== null;
  13522. }
  13523. var lib$es6$promise$utils$$_isArray;
  13524. if (!Array.isArray) {
  13525. lib$es6$promise$utils$$_isArray = function (x) {
  13526. return Object.prototype.toString.call(x) === '[object Array]';
  13527. };
  13528. } else {
  13529. lib$es6$promise$utils$$_isArray = Array.isArray;
  13530. }
  13531. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  13532. var lib$es6$promise$asap$$len = 0;
  13533. var lib$es6$promise$asap$$toString = {}.toString;
  13534. var lib$es6$promise$asap$$vertxNext;
  13535. var lib$es6$promise$asap$$customSchedulerFn;
  13536. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  13537. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  13538. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  13539. lib$es6$promise$asap$$len += 2;
  13540. if (lib$es6$promise$asap$$len === 2) {
  13541. // If len is 2, that means that we need to schedule an async flush.
  13542. // If additional callbacks are queued before the queue is flushed, they
  13543. // will be processed by this flush that we are scheduling.
  13544. if (lib$es6$promise$asap$$customSchedulerFn) {
  13545. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  13546. } else {
  13547. lib$es6$promise$asap$$scheduleFlush();
  13548. }
  13549. }
  13550. }
  13551. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  13552. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  13553. }
  13554. function lib$es6$promise$asap$$setAsap(asapFn) {
  13555. lib$es6$promise$asap$$asap = asapFn;
  13556. }
  13557. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  13558. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  13559. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  13560. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  13561. // test for web worker but not in IE10
  13562. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  13563. typeof importScripts !== 'undefined' &&
  13564. typeof MessageChannel !== 'undefined';
  13565. // node
  13566. function lib$es6$promise$asap$$useNextTick() {
  13567. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  13568. // see https://github.com/cujojs/when/issues/410 for details
  13569. return function() {
  13570. process.nextTick(lib$es6$promise$asap$$flush);
  13571. };
  13572. }
  13573. // vertx
  13574. function lib$es6$promise$asap$$useVertxTimer() {
  13575. return function() {
  13576. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  13577. };
  13578. }
  13579. function lib$es6$promise$asap$$useMutationObserver() {
  13580. var iterations = 0;
  13581. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  13582. var node = document.createTextNode('');
  13583. observer.observe(node, { characterData: true });
  13584. return function() {
  13585. node.data = (iterations = ++iterations % 2);
  13586. };
  13587. }
  13588. // web worker
  13589. function lib$es6$promise$asap$$useMessageChannel() {
  13590. var channel = new MessageChannel();
  13591. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  13592. return function () {
  13593. channel.port2.postMessage(0);
  13594. };
  13595. }
  13596. function lib$es6$promise$asap$$useSetTimeout() {
  13597. return function() {
  13598. setTimeout(lib$es6$promise$asap$$flush, 1);
  13599. };
  13600. }
  13601. var lib$es6$promise$asap$$queue = new Array(1000);
  13602. function lib$es6$promise$asap$$flush() {
  13603. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  13604. var callback = lib$es6$promise$asap$$queue[i];
  13605. var arg = lib$es6$promise$asap$$queue[i+1];
  13606. callback(arg);
  13607. lib$es6$promise$asap$$queue[i] = undefined;
  13608. lib$es6$promise$asap$$queue[i+1] = undefined;
  13609. }
  13610. lib$es6$promise$asap$$len = 0;
  13611. }
  13612. function lib$es6$promise$asap$$attemptVertx() {
  13613. try {
  13614. var r = require;
  13615. var vertx = r('vertx');
  13616. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  13617. return lib$es6$promise$asap$$useVertxTimer();
  13618. } catch(e) {
  13619. return lib$es6$promise$asap$$useSetTimeout();
  13620. }
  13621. }
  13622. var lib$es6$promise$asap$$scheduleFlush;
  13623. // Decide what async method to use to triggering processing of queued callbacks:
  13624. if (lib$es6$promise$asap$$isNode) {
  13625. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  13626. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  13627. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  13628. } else if (lib$es6$promise$asap$$isWorker) {
  13629. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  13630. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  13631. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  13632. } else {
  13633. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  13634. }
  13635. function lib$es6$promise$$internal$$noop() {}
  13636. var lib$es6$promise$$internal$$PENDING = void 0;
  13637. var lib$es6$promise$$internal$$FULFILLED = 1;
  13638. var lib$es6$promise$$internal$$REJECTED = 2;
  13639. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13640. function lib$es6$promise$$internal$$selfFulfillment() {
  13641. return new TypeError("You cannot resolve a promise with itself");
  13642. }
  13643. function lib$es6$promise$$internal$$cannotReturnOwn() {
  13644. return new TypeError('A promises callback cannot return that same promise.');
  13645. }
  13646. function lib$es6$promise$$internal$$getThen(promise) {
  13647. try {
  13648. return promise.then;
  13649. } catch(error) {
  13650. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  13651. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  13652. }
  13653. }
  13654. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  13655. try {
  13656. then.call(value, fulfillmentHandler, rejectionHandler);
  13657. } catch(e) {
  13658. return e;
  13659. }
  13660. }
  13661. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  13662. lib$es6$promise$asap$$asap(function(promise) {
  13663. var sealed = false;
  13664. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  13665. if (sealed) { return; }
  13666. sealed = true;
  13667. if (thenable !== value) {
  13668. lib$es6$promise$$internal$$resolve(promise, value);
  13669. } else {
  13670. lib$es6$promise$$internal$$fulfill(promise, value);
  13671. }
  13672. }, function(reason) {
  13673. if (sealed) { return; }
  13674. sealed = true;
  13675. lib$es6$promise$$internal$$reject(promise, reason);
  13676. }, 'Settle: ' + (promise._label || ' unknown promise'));
  13677. if (!sealed && error) {
  13678. sealed = true;
  13679. lib$es6$promise$$internal$$reject(promise, error);
  13680. }
  13681. }, promise);
  13682. }
  13683. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  13684. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  13685. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  13686. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  13687. lib$es6$promise$$internal$$reject(promise, thenable._result);
  13688. } else {
  13689. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  13690. lib$es6$promise$$internal$$resolve(promise, value);
  13691. }, function(reason) {
  13692. lib$es6$promise$$internal$$reject(promise, reason);
  13693. });
  13694. }
  13695. }
  13696. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  13697. if (maybeThenable.constructor === promise.constructor) {
  13698. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  13699. } else {
  13700. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  13701. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  13702. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  13703. } else if (then === undefined) {
  13704. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13705. } else if (lib$es6$promise$utils$$isFunction(then)) {
  13706. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  13707. } else {
  13708. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13709. }
  13710. }
  13711. }
  13712. function lib$es6$promise$$internal$$resolve(promise, value) {
  13713. if (promise === value) {
  13714. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  13715. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  13716. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  13717. } else {
  13718. lib$es6$promise$$internal$$fulfill(promise, value);
  13719. }
  13720. }
  13721. function lib$es6$promise$$internal$$publishRejection(promise) {
  13722. if (promise._onerror) {
  13723. promise._onerror(promise._result);
  13724. }
  13725. lib$es6$promise$$internal$$publish(promise);
  13726. }
  13727. function lib$es6$promise$$internal$$fulfill(promise, value) {
  13728. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13729. promise._result = value;
  13730. promise._state = lib$es6$promise$$internal$$FULFILLED;
  13731. if (promise._subscribers.length !== 0) {
  13732. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  13733. }
  13734. }
  13735. function lib$es6$promise$$internal$$reject(promise, reason) {
  13736. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13737. promise._state = lib$es6$promise$$internal$$REJECTED;
  13738. promise._result = reason;
  13739. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  13740. }
  13741. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  13742. var subscribers = parent._subscribers;
  13743. var length = subscribers.length;
  13744. parent._onerror = null;
  13745. subscribers[length] = child;
  13746. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  13747. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  13748. if (length === 0 && parent._state) {
  13749. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  13750. }
  13751. }
  13752. function lib$es6$promise$$internal$$publish(promise) {
  13753. var subscribers = promise._subscribers;
  13754. var settled = promise._state;
  13755. if (subscribers.length === 0) { return; }
  13756. var child, callback, detail = promise._result;
  13757. for (var i = 0; i < subscribers.length; i += 3) {
  13758. child = subscribers[i];
  13759. callback = subscribers[i + settled];
  13760. if (child) {
  13761. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  13762. } else {
  13763. callback(detail);
  13764. }
  13765. }
  13766. promise._subscribers.length = 0;
  13767. }
  13768. function lib$es6$promise$$internal$$ErrorObject() {
  13769. this.error = null;
  13770. }
  13771. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13772. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  13773. try {
  13774. return callback(detail);
  13775. } catch(e) {
  13776. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  13777. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  13778. }
  13779. }
  13780. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  13781. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  13782. value, error, succeeded, failed;
  13783. if (hasCallback) {
  13784. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  13785. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  13786. failed = true;
  13787. error = value.error;
  13788. value = null;
  13789. } else {
  13790. succeeded = true;
  13791. }
  13792. if (promise === value) {
  13793. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  13794. return;
  13795. }
  13796. } else {
  13797. value = detail;
  13798. succeeded = true;
  13799. }
  13800. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  13801. // noop
  13802. } else if (hasCallback && succeeded) {
  13803. lib$es6$promise$$internal$$resolve(promise, value);
  13804. } else if (failed) {
  13805. lib$es6$promise$$internal$$reject(promise, error);
  13806. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  13807. lib$es6$promise$$internal$$fulfill(promise, value);
  13808. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  13809. lib$es6$promise$$internal$$reject(promise, value);
  13810. }
  13811. }
  13812. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  13813. try {
  13814. resolver(function resolvePromise(value){
  13815. lib$es6$promise$$internal$$resolve(promise, value);
  13816. }, function rejectPromise(reason) {
  13817. lib$es6$promise$$internal$$reject(promise, reason);
  13818. });
  13819. } catch(e) {
  13820. lib$es6$promise$$internal$$reject(promise, e);
  13821. }
  13822. }
  13823. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  13824. var enumerator = this;
  13825. enumerator._instanceConstructor = Constructor;
  13826. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  13827. if (enumerator._validateInput(input)) {
  13828. enumerator._input = input;
  13829. enumerator.length = input.length;
  13830. enumerator._remaining = input.length;
  13831. enumerator._init();
  13832. if (enumerator.length === 0) {
  13833. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13834. } else {
  13835. enumerator.length = enumerator.length || 0;
  13836. enumerator._enumerate();
  13837. if (enumerator._remaining === 0) {
  13838. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13839. }
  13840. }
  13841. } else {
  13842. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  13843. }
  13844. }
  13845. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  13846. return lib$es6$promise$utils$$isArray(input);
  13847. };
  13848. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  13849. return new Error('Array Methods must be provided an Array');
  13850. };
  13851. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13852. this._result = new Array(this.length);
  13853. };
  13854. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13855. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13856. var enumerator = this;
  13857. var length = enumerator.length;
  13858. var promise = enumerator.promise;
  13859. var input = enumerator._input;
  13860. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13861. enumerator._eachEntry(input[i], i);
  13862. }
  13863. };
  13864. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13865. var enumerator = this;
  13866. var c = enumerator._instanceConstructor;
  13867. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13868. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13869. entry._onerror = null;
  13870. enumerator._settledAt(entry._state, i, entry._result);
  13871. } else {
  13872. enumerator._willSettleAt(c.resolve(entry), i);
  13873. }
  13874. } else {
  13875. enumerator._remaining--;
  13876. enumerator._result[i] = entry;
  13877. }
  13878. };
  13879. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13880. var enumerator = this;
  13881. var promise = enumerator.promise;
  13882. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13883. enumerator._remaining--;
  13884. if (state === lib$es6$promise$$internal$$REJECTED) {
  13885. lib$es6$promise$$internal$$reject(promise, value);
  13886. } else {
  13887. enumerator._result[i] = value;
  13888. }
  13889. }
  13890. if (enumerator._remaining === 0) {
  13891. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13892. }
  13893. };
  13894. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13895. var enumerator = this;
  13896. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13897. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13898. }, function(reason) {
  13899. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13900. });
  13901. };
  13902. function lib$es6$promise$promise$all$$all(entries) {
  13903. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13904. }
  13905. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13906. function lib$es6$promise$promise$race$$race(entries) {
  13907. /*jshint validthis:true */
  13908. var Constructor = this;
  13909. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13910. if (!lib$es6$promise$utils$$isArray(entries)) {
  13911. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13912. return promise;
  13913. }
  13914. var length = entries.length;
  13915. function onFulfillment(value) {
  13916. lib$es6$promise$$internal$$resolve(promise, value);
  13917. }
  13918. function onRejection(reason) {
  13919. lib$es6$promise$$internal$$reject(promise, reason);
  13920. }
  13921. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13922. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13923. }
  13924. return promise;
  13925. }
  13926. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13927. function lib$es6$promise$promise$resolve$$resolve(object) {
  13928. /*jshint validthis:true */
  13929. var Constructor = this;
  13930. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13931. return object;
  13932. }
  13933. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13934. lib$es6$promise$$internal$$resolve(promise, object);
  13935. return promise;
  13936. }
  13937. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13938. function lib$es6$promise$promise$reject$$reject(reason) {
  13939. /*jshint validthis:true */
  13940. var Constructor = this;
  13941. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13942. lib$es6$promise$$internal$$reject(promise, reason);
  13943. return promise;
  13944. }
  13945. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13946. var lib$es6$promise$promise$$counter = 0;
  13947. function lib$es6$promise$promise$$needsResolver() {
  13948. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13949. }
  13950. function lib$es6$promise$promise$$needsNew() {
  13951. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13952. }
  13953. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13954. /**
  13955. Promise objects represent the eventual result of an asynchronous operation. The
  13956. primary way of interacting with a promise is through its `then` method, which
  13957. registers callbacks to receive either a promise's eventual value or the reason
  13958. why the promise cannot be fulfilled.
  13959. Terminology
  13960. -----------
  13961. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13962. - `thenable` is an object or function that defines a `then` method.
  13963. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13964. - `exception` is a value that is thrown using the throw statement.
  13965. - `reason` is a value that indicates why a promise was rejected.
  13966. - `settled` the final resting state of a promise, fulfilled or rejected.
  13967. A promise can be in one of three states: pending, fulfilled, or rejected.
  13968. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13969. state. Promises that are rejected have a rejection reason and are in the
  13970. rejected state. A fulfillment value is never a thenable.
  13971. Promises can also be said to *resolve* a value. If this value is also a
  13972. promise, then the original promise's settled state will match the value's
  13973. settled state. So a promise that *resolves* a promise that rejects will
  13974. itself reject, and a promise that *resolves* a promise that fulfills will
  13975. itself fulfill.
  13976. Basic Usage:
  13977. ------------
  13978. ```js
  13979. var promise = new Promise(function(resolve, reject) {
  13980. // on success
  13981. resolve(value);
  13982. // on failure
  13983. reject(reason);
  13984. });
  13985. promise.then(function(value) {
  13986. // on fulfillment
  13987. }, function(reason) {
  13988. // on rejection
  13989. });
  13990. ```
  13991. Advanced Usage:
  13992. ---------------
  13993. Promises shine when abstracting away asynchronous interactions such as
  13994. `XMLHttpRequest`s.
  13995. ```js
  13996. function getJSON(url) {
  13997. return new Promise(function(resolve, reject){
  13998. var xhr = new XMLHttpRequest();
  13999. xhr.open('GET', url);
  14000. xhr.onreadystatechange = handler;
  14001. xhr.responseType = 'json';
  14002. xhr.setRequestHeader('Accept', 'application/json');
  14003. xhr.send();
  14004. function handler() {
  14005. if (this.readyState === this.DONE) {
  14006. if (this.status === 200) {
  14007. resolve(this.response);
  14008. } else {
  14009. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  14010. }
  14011. }
  14012. };
  14013. });
  14014. }
  14015. getJSON('/posts.json').then(function(json) {
  14016. // on fulfillment
  14017. }, function(reason) {
  14018. // on rejection
  14019. });
  14020. ```
  14021. Unlike callbacks, promises are great composable primitives.
  14022. ```js
  14023. Promise.all([
  14024. getJSON('/posts'),
  14025. getJSON('/comments')
  14026. ]).then(function(values){
  14027. values[0] // => postsJSON
  14028. values[1] // => commentsJSON
  14029. return values;
  14030. });
  14031. ```
  14032. @class Promise
  14033. @param {function} resolver
  14034. Useful for tooling.
  14035. @constructor
  14036. */
  14037. function lib$es6$promise$promise$$Promise(resolver) {
  14038. this._id = lib$es6$promise$promise$$counter++;
  14039. this._state = undefined;
  14040. this._result = undefined;
  14041. this._subscribers = [];
  14042. if (lib$es6$promise$$internal$$noop !== resolver) {
  14043. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  14044. lib$es6$promise$promise$$needsResolver();
  14045. }
  14046. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  14047. lib$es6$promise$promise$$needsNew();
  14048. }
  14049. lib$es6$promise$$internal$$initializePromise(this, resolver);
  14050. }
  14051. }
  14052. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  14053. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  14054. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  14055. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  14056. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  14057. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  14058. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  14059. lib$es6$promise$promise$$Promise.prototype = {
  14060. constructor: lib$es6$promise$promise$$Promise,
  14061. /**
  14062. The primary way of interacting with a promise is through its `then` method,
  14063. which registers callbacks to receive either a promise's eventual value or the
  14064. reason why the promise cannot be fulfilled.
  14065. ```js
  14066. findUser().then(function(user){
  14067. // user is available
  14068. }, function(reason){
  14069. // user is unavailable, and you are given the reason why
  14070. });
  14071. ```
  14072. Chaining
  14073. --------
  14074. The return value of `then` is itself a promise. This second, 'downstream'
  14075. promise is resolved with the return value of the first promise's fulfillment
  14076. or rejection handler, or rejected if the handler throws an exception.
  14077. ```js
  14078. findUser().then(function (user) {
  14079. return user.name;
  14080. }, function (reason) {
  14081. return 'default name';
  14082. }).then(function (userName) {
  14083. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  14084. // will be `'default name'`
  14085. });
  14086. findUser().then(function (user) {
  14087. throw new Error('Found user, but still unhappy');
  14088. }, function (reason) {
  14089. throw new Error('`findUser` rejected and we're unhappy');
  14090. }).then(function (value) {
  14091. // never reached
  14092. }, function (reason) {
  14093. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  14094. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  14095. });
  14096. ```
  14097. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  14098. ```js
  14099. findUser().then(function (user) {
  14100. throw new PedagogicalException('Upstream error');
  14101. }).then(function (value) {
  14102. // never reached
  14103. }).then(function (value) {
  14104. // never reached
  14105. }, function (reason) {
  14106. // The `PedgagocialException` is propagated all the way down to here
  14107. });
  14108. ```
  14109. Assimilation
  14110. ------------
  14111. Sometimes the value you want to propagate to a downstream promise can only be
  14112. retrieved asynchronously. This can be achieved by returning a promise in the
  14113. fulfillment or rejection handler. The downstream promise will then be pending
  14114. until the returned promise is settled. This is called *assimilation*.
  14115. ```js
  14116. findUser().then(function (user) {
  14117. return findCommentsByAuthor(user);
  14118. }).then(function (comments) {
  14119. // The user's comments are now available
  14120. });
  14121. ```
  14122. If the assimliated promise rejects, then the downstream promise will also reject.
  14123. ```js
  14124. findUser().then(function (user) {
  14125. return findCommentsByAuthor(user);
  14126. }).then(function (comments) {
  14127. // If `findCommentsByAuthor` fulfills, we'll have the value here
  14128. }, function (reason) {
  14129. // If `findCommentsByAuthor` rejects, we'll have the reason here
  14130. });
  14131. ```
  14132. Simple Example
  14133. --------------
  14134. Synchronous Example
  14135. ```javascript
  14136. var result;
  14137. try {
  14138. result = findResult();
  14139. // success
  14140. } catch(reason) {
  14141. // failure
  14142. }
  14143. ```
  14144. Errback Example
  14145. ```js
  14146. findResult(function(result, err){
  14147. if (err) {
  14148. // failure
  14149. } else {
  14150. // success
  14151. }
  14152. });
  14153. ```
  14154. Promise Example;
  14155. ```javascript
  14156. findResult().then(function(result){
  14157. // success
  14158. }, function(reason){
  14159. // failure
  14160. });
  14161. ```
  14162. Advanced Example
  14163. --------------
  14164. Synchronous Example
  14165. ```javascript
  14166. var author, books;
  14167. try {
  14168. author = findAuthor();
  14169. books = findBooksByAuthor(author);
  14170. // success
  14171. } catch(reason) {
  14172. // failure
  14173. }
  14174. ```
  14175. Errback Example
  14176. ```js
  14177. function foundBooks(books) {
  14178. }
  14179. function failure(reason) {
  14180. }
  14181. findAuthor(function(author, err){
  14182. if (err) {
  14183. failure(err);
  14184. // failure
  14185. } else {
  14186. try {
  14187. findBoooksByAuthor(author, function(books, err) {
  14188. if (err) {
  14189. failure(err);
  14190. } else {
  14191. try {
  14192. foundBooks(books);
  14193. } catch(reason) {
  14194. failure(reason);
  14195. }
  14196. }
  14197. });
  14198. } catch(error) {
  14199. failure(err);
  14200. }
  14201. // success
  14202. }
  14203. });
  14204. ```
  14205. Promise Example;
  14206. ```javascript
  14207. findAuthor().
  14208. then(findBooksByAuthor).
  14209. then(function(books){
  14210. // found books
  14211. }).catch(function(reason){
  14212. // something went wrong
  14213. });
  14214. ```
  14215. @method then
  14216. @param {Function} onFulfilled
  14217. @param {Function} onRejected
  14218. Useful for tooling.
  14219. @return {Promise}
  14220. */
  14221. then: function(onFulfillment, onRejection) {
  14222. var parent = this;
  14223. var state = parent._state;
  14224. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  14225. return this;
  14226. }
  14227. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  14228. var result = parent._result;
  14229. if (state) {
  14230. var callback = arguments[state - 1];
  14231. lib$es6$promise$asap$$asap(function(){
  14232. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  14233. });
  14234. } else {
  14235. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  14236. }
  14237. return child;
  14238. },
  14239. /**
  14240. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  14241. as the catch block of a try/catch statement.
  14242. ```js
  14243. function findAuthor(){
  14244. throw new Error('couldn't find that author');
  14245. }
  14246. // synchronous
  14247. try {
  14248. findAuthor();
  14249. } catch(reason) {
  14250. // something went wrong
  14251. }
  14252. // async with promises
  14253. findAuthor().catch(function(reason){
  14254. // something went wrong
  14255. });
  14256. ```
  14257. @method catch
  14258. @param {Function} onRejection
  14259. Useful for tooling.
  14260. @return {Promise}
  14261. */
  14262. 'catch': function(onRejection) {
  14263. return this.then(null, onRejection);
  14264. }
  14265. };
  14266. function lib$es6$promise$polyfill$$polyfill() {
  14267. var local;
  14268. if (typeof global !== 'undefined') {
  14269. local = global;
  14270. } else if (typeof self !== 'undefined') {
  14271. local = self;
  14272. } else {
  14273. try {
  14274. local = Function('return this')();
  14275. } catch (e) {
  14276. throw new Error('polyfill failed because global object is unavailable in this environment');
  14277. }
  14278. }
  14279. var P = local.Promise;
  14280. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  14281. return;
  14282. }
  14283. local.Promise = lib$es6$promise$promise$$default;
  14284. }
  14285. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  14286. var lib$es6$promise$umd$$ES6Promise = {
  14287. 'Promise': lib$es6$promise$promise$$default,
  14288. 'polyfill': lib$es6$promise$polyfill$$default
  14289. };
  14290. /* global define:true module:true window: true */
  14291. if (typeof define === 'function' && define['amd']) {
  14292. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  14293. } else if (typeof module !== 'undefined' && module['exports']) {
  14294. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  14295. } else if (typeof this !== 'undefined') {
  14296. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  14297. }
  14298. lib$es6$promise$polyfill$$default();
  14299. }).call(this);
  14300. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14301. },{"_process":47}],49:[function(require,module,exports){
  14302. /* Copyright @ 2015 Atlassian Pty Ltd
  14303. *
  14304. * Licensed under the Apache License, Version 2.0 (the "License");
  14305. * you may not use this file except in compliance with the License.
  14306. * You may obtain a copy of the License at
  14307. *
  14308. * http://www.apache.org/licenses/LICENSE-2.0
  14309. *
  14310. * Unless required by applicable law or agreed to in writing, software
  14311. * distributed under the License is distributed on an "AS IS" BASIS,
  14312. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14313. * See the License for the specific language governing permissions and
  14314. * limitations under the License.
  14315. */
  14316. /**
  14317. * Ordered log levels.
  14318. */
  14319. var levels = {
  14320. "trace": 0,
  14321. "debug": 1,
  14322. "info": 2,
  14323. "log": 3,
  14324. "warn": 4,
  14325. "error": 5
  14326. };
  14327. /**
  14328. * Parses Error's object stack trace and extracts information about the last
  14329. * caller before the log method was called.
  14330. * @returns JS object with info about the caller - method name, file location,
  14331. * line and column.
  14332. */
  14333. function getCallerInfo() {
  14334. var callerInfo = {
  14335. methodName: "",
  14336. fileLocation: "",
  14337. line: null,
  14338. column: null
  14339. };
  14340. //gets the part of the stack without the logger wrappers
  14341. var error = new Error();
  14342. var stack = error.stack? error.stack.split("\n") : [];
  14343. if(!stack || stack.length < 1) {
  14344. return callerInfo;
  14345. }
  14346. var m = null;
  14347. if(stack[3]) {
  14348. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  14349. }
  14350. if(!m || m.length <= 4) {
  14351. //Firefox && Safari
  14352. if(stack[2].indexOf("log@") === 0){
  14353. //Safari
  14354. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  14355. } else {
  14356. //Firefox
  14357. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  14358. }
  14359. return callerInfo;
  14360. }
  14361. callerInfo.methodName = m[1];
  14362. callerInfo.fileLocation = m[2];
  14363. callerInfo.line = m[3];
  14364. callerInfo.column = m[4];
  14365. return callerInfo;
  14366. }
  14367. /**
  14368. * Logs messages using the transports and level from the logger.
  14369. * @param logger a logger instance.
  14370. * @param level the log level of the message. See the levels variable.
  14371. * @param arguments array with arguments that will be logged.
  14372. */
  14373. function log() {
  14374. var logger = arguments[0], level = arguments[1],
  14375. args = Array.prototype.slice.call(arguments, 2);
  14376. if(levels[level] <= logger.level) {
  14377. return;
  14378. }
  14379. var callerInfo = getCallerInfo();
  14380. for(var i = 0; i < logger.transports.length; i++) {
  14381. var t = logger.transports[i];
  14382. var l = t[level];
  14383. if(l && typeof(l) === "function") {
  14384. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  14385. .apply(t, args);
  14386. }
  14387. }
  14388. }
  14389. /**
  14390. *
  14391. * Constructs new logger object.
  14392. * @param level the logging level for the new logger
  14393. * @param id optional identifier for the logger instance.
  14394. * @param transports optional list of handlers(objects) for the logs.
  14395. * The handlers must support - log, warn, error, debug, info, trace.
  14396. * @param format optional (NOT implemented) string.
  14397. */
  14398. function Logger(level, id, transports, format) {
  14399. this.id = id;
  14400. this.format = format;
  14401. if(!this.transports) {
  14402. this.transports = [];
  14403. this.transports.push(Logger.consoleTransport);
  14404. }
  14405. this.level = levels[level];
  14406. var methods = Object.keys(levels);
  14407. for(var i = 0; i < methods.length; i++){
  14408. this[methods[i]] =
  14409. log.bind(null, this, methods[i]);
  14410. }
  14411. }
  14412. /**
  14413. * Sets the log level for the logger.
  14414. * @param level the new log level.
  14415. */
  14416. Logger.prototype.setLevel = function (level) {
  14417. this.level = levels[level];
  14418. };
  14419. module.exports = Logger;
  14420. /**
  14421. * The default transport - console
  14422. */
  14423. Logger.consoleTransport = console;
  14424. /**
  14425. * Enum for the supported log levels.
  14426. */
  14427. Logger.levels = {
  14428. TRACE: "trace",
  14429. DEBUG: "debug",
  14430. INFO: "info",
  14431. LOG: "log",
  14432. WARN: "warn",
  14433. ERROR: "error"
  14434. };
  14435. },{}],50:[function(require,module,exports){
  14436. /* Copyright @ 2015 Atlassian Pty Ltd
  14437. *
  14438. * Licensed under the Apache License, Version 2.0 (the "License");
  14439. * you may not use this file except in compliance with the License.
  14440. * You may obtain a copy of the License at
  14441. *
  14442. * http://www.apache.org/licenses/LICENSE-2.0
  14443. *
  14444. * Unless required by applicable law or agreed to in writing, software
  14445. * distributed under the License is distributed on an "AS IS" BASIS,
  14446. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14447. * See the License for the specific language governing permissions and
  14448. * limitations under the License.
  14449. */
  14450. var Logger = require("./Logger");
  14451. /**
  14452. * Map with the created loggers with ID.
  14453. */
  14454. var idLoggers = {};
  14455. /**
  14456. * Array with the loggers without id.
  14457. */
  14458. var loggers = [];
  14459. /**
  14460. * Log level for the lbrary.
  14461. */
  14462. var curLevel = Logger.levels.TRACE;
  14463. module.exports = {
  14464. /**
  14465. * Creates new logger.
  14466. * @arguments the same as Logger constructor
  14467. */
  14468. getLogger: function(id, transports, format) {
  14469. var logger = new Logger(curLevel, id, transports, format);
  14470. if(id) {
  14471. idLoggers[id] = idLoggers[id] || [];
  14472. idLoggers[id].push(logger);
  14473. } else {
  14474. loggers.push(logger);
  14475. }
  14476. return logger;
  14477. },
  14478. /**
  14479. * Changes the log level for the existing loggers by id.
  14480. * @param level the new log level.
  14481. * @param id if specified the level will be changed only for loggers with the
  14482. * same id. Otherwise the operation will affect all loggers that don't
  14483. * have id.
  14484. */
  14485. setLogLevelById: function(level, id) {
  14486. var l = id? (idLoggers[id] || []) : loggers;
  14487. for(var i = 0; i < l.length; i++) {
  14488. l[i].setLevel(level);
  14489. }
  14490. },
  14491. /**
  14492. * Changes the log level for all existing loggers.
  14493. * @param level the new log level.
  14494. */
  14495. setLogLevel: function (level) {
  14496. curLevel = level;
  14497. var i = 0;
  14498. for(; i < loggers.length; i++) {
  14499. loggers[i].setLevel(level);
  14500. }
  14501. for(var id in idLoggers) {
  14502. var l = idLoggers[id] || [];
  14503. for(i = 0; i < l.length; i++) {
  14504. l[i].setLevel(level);
  14505. }
  14506. }
  14507. },
  14508. /**
  14509. * The supported log levels.
  14510. */
  14511. levels: Logger.levels
  14512. };
  14513. },{"./Logger":49}],51:[function(require,module,exports){
  14514. /*
  14515. A JavaScript implementation of the SHA family of hashes, as
  14516. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  14517. as defined in FIPS PUB 198a
  14518. Copyright Brian Turek 2008-2013
  14519. Distributed under the BSD License
  14520. See http://caligatio.github.com/jsSHA/ for more information
  14521. Several functions taken from Paul Johnston
  14522. */
  14523. (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"!==
  14524. 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";
  14525. 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"===
  14526. 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|
  14527. (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,
  14528. 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,
  14529. 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=
  14530. {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):
  14531. 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,
  14532. 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>>>
  14533. 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>>>
  14534. 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>>>
  14535. 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-
  14536. 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,
  14537. 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,
  14538. 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],
  14539. 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),
  14540. 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),
  14541. 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,
  14542. 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,
  14543. 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?
  14544. 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,
  14545. 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);
  14546. },{}],52:[function(require,module,exports){
  14547. // Top level file is just a mixin of submodules & constants
  14548. 'use strict';
  14549. var assign = require('./lib/utils/common').assign;
  14550. var deflate = require('./lib/deflate');
  14551. var inflate = require('./lib/inflate');
  14552. var constants = require('./lib/zlib/constants');
  14553. var pako = {};
  14554. assign(pako, deflate, inflate, constants);
  14555. module.exports = pako;
  14556. },{"./lib/deflate":53,"./lib/inflate":54,"./lib/utils/common":55,"./lib/zlib/constants":58}],53:[function(require,module,exports){
  14557. 'use strict';
  14558. var zlib_deflate = require('./zlib/deflate.js');
  14559. var utils = require('./utils/common');
  14560. var strings = require('./utils/strings');
  14561. var msg = require('./zlib/messages');
  14562. var zstream = require('./zlib/zstream');
  14563. var toString = Object.prototype.toString;
  14564. /* Public constants ==========================================================*/
  14565. /* ===========================================================================*/
  14566. var Z_NO_FLUSH = 0;
  14567. var Z_FINISH = 4;
  14568. var Z_OK = 0;
  14569. var Z_STREAM_END = 1;
  14570. var Z_SYNC_FLUSH = 2;
  14571. var Z_DEFAULT_COMPRESSION = -1;
  14572. var Z_DEFAULT_STRATEGY = 0;
  14573. var Z_DEFLATED = 8;
  14574. /* ===========================================================================*/
  14575. /**
  14576. * class Deflate
  14577. *
  14578. * Generic JS-style wrapper for zlib calls. If you don't need
  14579. * streaming behaviour - use more simple functions: [[deflate]],
  14580. * [[deflateRaw]] and [[gzip]].
  14581. **/
  14582. /* internal
  14583. * Deflate.chunks -> Array
  14584. *
  14585. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14586. **/
  14587. /**
  14588. * Deflate.result -> Uint8Array|Array
  14589. *
  14590. * Compressed result, generated by default [[Deflate#onData]]
  14591. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14592. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14593. * push a chunk with explicit flush (call [[Deflate#push]] with
  14594. * `Z_SYNC_FLUSH` param).
  14595. **/
  14596. /**
  14597. * Deflate.err -> Number
  14598. *
  14599. * Error code after deflate finished. 0 (Z_OK) on success.
  14600. * You will not need it in real life, because deflate errors
  14601. * are possible only on wrong options or bad `onData` / `onEnd`
  14602. * custom handlers.
  14603. **/
  14604. /**
  14605. * Deflate.msg -> String
  14606. *
  14607. * Error message, if [[Deflate.err]] != 0
  14608. **/
  14609. /**
  14610. * new Deflate(options)
  14611. * - options (Object): zlib deflate options.
  14612. *
  14613. * Creates new deflator instance with specified params. Throws exception
  14614. * on bad params. Supported options:
  14615. *
  14616. * - `level`
  14617. * - `windowBits`
  14618. * - `memLevel`
  14619. * - `strategy`
  14620. *
  14621. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14622. * for more information on these.
  14623. *
  14624. * Additional options, for internal needs:
  14625. *
  14626. * - `chunkSize` - size of generated data chunks (16K by default)
  14627. * - `raw` (Boolean) - do raw deflate
  14628. * - `gzip` (Boolean) - create gzip wrapper
  14629. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14630. * (each char code [0..255])
  14631. * - `header` (Object) - custom header for gzip
  14632. * - `text` (Boolean) - true if compressed data believed to be text
  14633. * - `time` (Number) - modification time, unix timestamp
  14634. * - `os` (Number) - operation system code
  14635. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14636. * - `name` (String) - file name (binary string)
  14637. * - `comment` (String) - comment (binary string)
  14638. * - `hcrc` (Boolean) - true if header crc should be added
  14639. *
  14640. * ##### Example:
  14641. *
  14642. * ```javascript
  14643. * var pako = require('pako')
  14644. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14645. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14646. *
  14647. * var deflate = new pako.Deflate({ level: 3});
  14648. *
  14649. * deflate.push(chunk1, false);
  14650. * deflate.push(chunk2, true); // true -> last chunk
  14651. *
  14652. * if (deflate.err) { throw new Error(deflate.err); }
  14653. *
  14654. * console.log(deflate.result);
  14655. * ```
  14656. **/
  14657. var Deflate = function(options) {
  14658. this.options = utils.assign({
  14659. level: Z_DEFAULT_COMPRESSION,
  14660. method: Z_DEFLATED,
  14661. chunkSize: 16384,
  14662. windowBits: 15,
  14663. memLevel: 8,
  14664. strategy: Z_DEFAULT_STRATEGY,
  14665. to: ''
  14666. }, options || {});
  14667. var opt = this.options;
  14668. if (opt.raw && (opt.windowBits > 0)) {
  14669. opt.windowBits = -opt.windowBits;
  14670. }
  14671. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14672. opt.windowBits += 16;
  14673. }
  14674. this.err = 0; // error code, if happens (0 = Z_OK)
  14675. this.msg = ''; // error message
  14676. this.ended = false; // used to avoid multiple onEnd() calls
  14677. this.chunks = []; // chunks of compressed data
  14678. this.strm = new zstream();
  14679. this.strm.avail_out = 0;
  14680. var status = zlib_deflate.deflateInit2(
  14681. this.strm,
  14682. opt.level,
  14683. opt.method,
  14684. opt.windowBits,
  14685. opt.memLevel,
  14686. opt.strategy
  14687. );
  14688. if (status !== Z_OK) {
  14689. throw new Error(msg[status]);
  14690. }
  14691. if (opt.header) {
  14692. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14693. }
  14694. };
  14695. /**
  14696. * Deflate#push(data[, mode]) -> Boolean
  14697. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  14698. * converted to utf8 byte sequence.
  14699. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14700. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14701. *
  14702. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14703. * new compressed chunks. Returns `true` on success. The last data block must have
  14704. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14705. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14706. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  14707. *
  14708. * On fail call [[Deflate#onEnd]] with error code and return false.
  14709. *
  14710. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14711. * array format is detected automatically). Also, don't skip last param and always
  14712. * use the same type in your code (boolean or number). That will improve JS speed.
  14713. *
  14714. * For regular `Array`-s make sure all elements are [0..255].
  14715. *
  14716. * ##### Example
  14717. *
  14718. * ```javascript
  14719. * push(chunk, false); // push one of data chunks
  14720. * ...
  14721. * push(chunk, true); // push last chunk
  14722. * ```
  14723. **/
  14724. Deflate.prototype.push = function(data, mode) {
  14725. var strm = this.strm;
  14726. var chunkSize = this.options.chunkSize;
  14727. var status, _mode;
  14728. if (this.ended) { return false; }
  14729. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14730. // Convert data if needed
  14731. if (typeof data === 'string') {
  14732. // If we need to compress text, change encoding to utf8.
  14733. strm.input = strings.string2buf(data);
  14734. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14735. strm.input = new Uint8Array(data);
  14736. } else {
  14737. strm.input = data;
  14738. }
  14739. strm.next_in = 0;
  14740. strm.avail_in = strm.input.length;
  14741. do {
  14742. if (strm.avail_out === 0) {
  14743. strm.output = new utils.Buf8(chunkSize);
  14744. strm.next_out = 0;
  14745. strm.avail_out = chunkSize;
  14746. }
  14747. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14748. if (status !== Z_STREAM_END && status !== Z_OK) {
  14749. this.onEnd(status);
  14750. this.ended = true;
  14751. return false;
  14752. }
  14753. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  14754. if (this.options.to === 'string') {
  14755. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14756. } else {
  14757. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14758. }
  14759. }
  14760. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14761. // Finalize on the last chunk.
  14762. if (_mode === Z_FINISH) {
  14763. status = zlib_deflate.deflateEnd(this.strm);
  14764. this.onEnd(status);
  14765. this.ended = true;
  14766. return status === Z_OK;
  14767. }
  14768. // callback interim results if Z_SYNC_FLUSH.
  14769. if (_mode === Z_SYNC_FLUSH) {
  14770. this.onEnd(Z_OK);
  14771. strm.avail_out = 0;
  14772. return true;
  14773. }
  14774. return true;
  14775. };
  14776. /**
  14777. * Deflate#onData(chunk) -> Void
  14778. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14779. * on js engine support. When string output requested, each chunk
  14780. * will be string.
  14781. *
  14782. * By default, stores data blocks in `chunks[]` property and glue
  14783. * those in `onEnd`. Override this handler, if you need another behaviour.
  14784. **/
  14785. Deflate.prototype.onData = function(chunk) {
  14786. this.chunks.push(chunk);
  14787. };
  14788. /**
  14789. * Deflate#onEnd(status) -> Void
  14790. * - status (Number): deflate status. 0 (Z_OK) on success,
  14791. * other if not.
  14792. *
  14793. * Called once after you tell deflate that the input stream is
  14794. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14795. * or if an error happened. By default - join collected chunks,
  14796. * free memory and fill `results` / `err` properties.
  14797. **/
  14798. Deflate.prototype.onEnd = function(status) {
  14799. // On success - join
  14800. if (status === Z_OK) {
  14801. if (this.options.to === 'string') {
  14802. this.result = this.chunks.join('');
  14803. } else {
  14804. this.result = utils.flattenChunks(this.chunks);
  14805. }
  14806. }
  14807. this.chunks = [];
  14808. this.err = status;
  14809. this.msg = this.strm.msg;
  14810. };
  14811. /**
  14812. * deflate(data[, options]) -> Uint8Array|Array|String
  14813. * - data (Uint8Array|Array|String): input data to compress.
  14814. * - options (Object): zlib deflate options.
  14815. *
  14816. * Compress `data` with deflate alrorythm and `options`.
  14817. *
  14818. * Supported options are:
  14819. *
  14820. * - level
  14821. * - windowBits
  14822. * - memLevel
  14823. * - strategy
  14824. *
  14825. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14826. * for more information on these.
  14827. *
  14828. * Sugar (options):
  14829. *
  14830. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14831. * negative windowBits implicitly.
  14832. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14833. * (each char code [0..255])
  14834. *
  14835. * ##### Example:
  14836. *
  14837. * ```javascript
  14838. * var pako = require('pako')
  14839. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14840. *
  14841. * console.log(pako.deflate(data));
  14842. * ```
  14843. **/
  14844. function deflate(input, options) {
  14845. var deflator = new Deflate(options);
  14846. deflator.push(input, true);
  14847. // That will never happens, if you don't cheat with options :)
  14848. if (deflator.err) { throw deflator.msg; }
  14849. return deflator.result;
  14850. }
  14851. /**
  14852. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14853. * - data (Uint8Array|Array|String): input data to compress.
  14854. * - options (Object): zlib deflate options.
  14855. *
  14856. * The same as [[deflate]], but creates raw data, without wrapper
  14857. * (header and adler32 crc).
  14858. **/
  14859. function deflateRaw(input, options) {
  14860. options = options || {};
  14861. options.raw = true;
  14862. return deflate(input, options);
  14863. }
  14864. /**
  14865. * gzip(data[, options]) -> Uint8Array|Array|String
  14866. * - data (Uint8Array|Array|String): input data to compress.
  14867. * - options (Object): zlib deflate options.
  14868. *
  14869. * The same as [[deflate]], but create gzip wrapper instead of
  14870. * deflate one.
  14871. **/
  14872. function gzip(input, options) {
  14873. options = options || {};
  14874. options.gzip = true;
  14875. return deflate(input, options);
  14876. }
  14877. exports.Deflate = Deflate;
  14878. exports.deflate = deflate;
  14879. exports.deflateRaw = deflateRaw;
  14880. exports.gzip = gzip;
  14881. },{"./utils/common":55,"./utils/strings":56,"./zlib/deflate.js":60,"./zlib/messages":65,"./zlib/zstream":67}],54:[function(require,module,exports){
  14882. 'use strict';
  14883. var zlib_inflate = require('./zlib/inflate.js');
  14884. var utils = require('./utils/common');
  14885. var strings = require('./utils/strings');
  14886. var c = require('./zlib/constants');
  14887. var msg = require('./zlib/messages');
  14888. var zstream = require('./zlib/zstream');
  14889. var gzheader = require('./zlib/gzheader');
  14890. var toString = Object.prototype.toString;
  14891. /**
  14892. * class Inflate
  14893. *
  14894. * Generic JS-style wrapper for zlib calls. If you don't need
  14895. * streaming behaviour - use more simple functions: [[inflate]]
  14896. * and [[inflateRaw]].
  14897. **/
  14898. /* internal
  14899. * inflate.chunks -> Array
  14900. *
  14901. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14902. **/
  14903. /**
  14904. * Inflate.result -> Uint8Array|Array|String
  14905. *
  14906. * Uncompressed result, generated by default [[Inflate#onData]]
  14907. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14908. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14909. * push a chunk with explicit flush (call [[Inflate#push]] with
  14910. * `Z_SYNC_FLUSH` param).
  14911. **/
  14912. /**
  14913. * Inflate.err -> Number
  14914. *
  14915. * Error code after inflate finished. 0 (Z_OK) on success.
  14916. * Should be checked if broken data possible.
  14917. **/
  14918. /**
  14919. * Inflate.msg -> String
  14920. *
  14921. * Error message, if [[Inflate.err]] != 0
  14922. **/
  14923. /**
  14924. * new Inflate(options)
  14925. * - options (Object): zlib inflate options.
  14926. *
  14927. * Creates new inflator instance with specified params. Throws exception
  14928. * on bad params. Supported options:
  14929. *
  14930. * - `windowBits`
  14931. *
  14932. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14933. * for more information on these.
  14934. *
  14935. * Additional options, for internal needs:
  14936. *
  14937. * - `chunkSize` - size of generated data chunks (16K by default)
  14938. * - `raw` (Boolean) - do raw inflate
  14939. * - `to` (String) - if equal to 'string', then result will be converted
  14940. * from utf8 to utf16 (javascript) string. When string output requested,
  14941. * chunk length can differ from `chunkSize`, depending on content.
  14942. *
  14943. * By default, when no options set, autodetect deflate/gzip data format via
  14944. * wrapper header.
  14945. *
  14946. * ##### Example:
  14947. *
  14948. * ```javascript
  14949. * var pako = require('pako')
  14950. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14951. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14952. *
  14953. * var inflate = new pako.Inflate({ level: 3});
  14954. *
  14955. * inflate.push(chunk1, false);
  14956. * inflate.push(chunk2, true); // true -> last chunk
  14957. *
  14958. * if (inflate.err) { throw new Error(inflate.err); }
  14959. *
  14960. * console.log(inflate.result);
  14961. * ```
  14962. **/
  14963. var Inflate = function(options) {
  14964. this.options = utils.assign({
  14965. chunkSize: 16384,
  14966. windowBits: 0,
  14967. to: ''
  14968. }, options || {});
  14969. var opt = this.options;
  14970. // Force window size for `raw` data, if not set directly,
  14971. // because we have no header for autodetect.
  14972. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14973. opt.windowBits = -opt.windowBits;
  14974. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14975. }
  14976. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14977. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14978. !(options && options.windowBits)) {
  14979. opt.windowBits += 32;
  14980. }
  14981. // Gzip header has no info about windows size, we can do autodetect only
  14982. // for deflate. So, if window size not set, force it to max when gzip possible
  14983. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14984. // bit 3 (16) -> gzipped data
  14985. // bit 4 (32) -> autodetect gzip/deflate
  14986. if ((opt.windowBits & 15) === 0) {
  14987. opt.windowBits |= 15;
  14988. }
  14989. }
  14990. this.err = 0; // error code, if happens (0 = Z_OK)
  14991. this.msg = ''; // error message
  14992. this.ended = false; // used to avoid multiple onEnd() calls
  14993. this.chunks = []; // chunks of compressed data
  14994. this.strm = new zstream();
  14995. this.strm.avail_out = 0;
  14996. var status = zlib_inflate.inflateInit2(
  14997. this.strm,
  14998. opt.windowBits
  14999. );
  15000. if (status !== c.Z_OK) {
  15001. throw new Error(msg[status]);
  15002. }
  15003. this.header = new gzheader();
  15004. zlib_inflate.inflateGetHeader(this.strm, this.header);
  15005. };
  15006. /**
  15007. * Inflate#push(data[, mode]) -> Boolean
  15008. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  15009. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15010. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15011. *
  15012. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  15013. * new output chunks. Returns `true` on success. The last data block must have
  15014. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15015. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15016. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  15017. *
  15018. * On fail call [[Inflate#onEnd]] with error code and return false.
  15019. *
  15020. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15021. * format is detected automatically). Also, don't skip last param and always
  15022. * use the same type in your code (boolean or number). That will improve JS speed.
  15023. *
  15024. * For regular `Array`-s make sure all elements are [0..255].
  15025. *
  15026. * ##### Example
  15027. *
  15028. * ```javascript
  15029. * push(chunk, false); // push one of data chunks
  15030. * ...
  15031. * push(chunk, true); // push last chunk
  15032. * ```
  15033. **/
  15034. Inflate.prototype.push = function(data, mode) {
  15035. var strm = this.strm;
  15036. var chunkSize = this.options.chunkSize;
  15037. var status, _mode;
  15038. var next_out_utf8, tail, utf8str;
  15039. // Flag to properly process Z_BUF_ERROR on testing inflate call
  15040. // when we check that all output data was flushed.
  15041. var allowBufError = false;
  15042. if (this.ended) { return false; }
  15043. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  15044. // Convert data if needed
  15045. if (typeof data === 'string') {
  15046. // Only binary strings can be decompressed on practice
  15047. strm.input = strings.binstring2buf(data);
  15048. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15049. strm.input = new Uint8Array(data);
  15050. } else {
  15051. strm.input = data;
  15052. }
  15053. strm.next_in = 0;
  15054. strm.avail_in = strm.input.length;
  15055. do {
  15056. if (strm.avail_out === 0) {
  15057. strm.output = new utils.Buf8(chunkSize);
  15058. strm.next_out = 0;
  15059. strm.avail_out = chunkSize;
  15060. }
  15061. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  15062. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  15063. status = c.Z_OK;
  15064. allowBufError = false;
  15065. }
  15066. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  15067. this.onEnd(status);
  15068. this.ended = true;
  15069. return false;
  15070. }
  15071. if (strm.next_out) {
  15072. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  15073. if (this.options.to === 'string') {
  15074. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  15075. tail = strm.next_out - next_out_utf8;
  15076. utf8str = strings.buf2string(strm.output, next_out_utf8);
  15077. // move tail
  15078. strm.next_out = tail;
  15079. strm.avail_out = chunkSize - tail;
  15080. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  15081. this.onData(utf8str);
  15082. } else {
  15083. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15084. }
  15085. }
  15086. }
  15087. // When no more input data, we should check that internal inflate buffers
  15088. // are flushed. The only way to do it when avail_out = 0 - run one more
  15089. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  15090. // Here we set flag to process this error properly.
  15091. //
  15092. // NOTE. Deflate does not return error in this case and does not needs such
  15093. // logic.
  15094. if (strm.avail_in === 0 && strm.avail_out === 0) {
  15095. allowBufError = true;
  15096. }
  15097. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  15098. if (status === c.Z_STREAM_END) {
  15099. _mode = c.Z_FINISH;
  15100. }
  15101. // Finalize on the last chunk.
  15102. if (_mode === c.Z_FINISH) {
  15103. status = zlib_inflate.inflateEnd(this.strm);
  15104. this.onEnd(status);
  15105. this.ended = true;
  15106. return status === c.Z_OK;
  15107. }
  15108. // callback interim results if Z_SYNC_FLUSH.
  15109. if (_mode === c.Z_SYNC_FLUSH) {
  15110. this.onEnd(c.Z_OK);
  15111. strm.avail_out = 0;
  15112. return true;
  15113. }
  15114. return true;
  15115. };
  15116. /**
  15117. * Inflate#onData(chunk) -> Void
  15118. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15119. * on js engine support. When string output requested, each chunk
  15120. * will be string.
  15121. *
  15122. * By default, stores data blocks in `chunks[]` property and glue
  15123. * those in `onEnd`. Override this handler, if you need another behaviour.
  15124. **/
  15125. Inflate.prototype.onData = function(chunk) {
  15126. this.chunks.push(chunk);
  15127. };
  15128. /**
  15129. * Inflate#onEnd(status) -> Void
  15130. * - status (Number): inflate status. 0 (Z_OK) on success,
  15131. * other if not.
  15132. *
  15133. * Called either after you tell inflate that the input stream is
  15134. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15135. * or if an error happened. By default - join collected chunks,
  15136. * free memory and fill `results` / `err` properties.
  15137. **/
  15138. Inflate.prototype.onEnd = function(status) {
  15139. // On success - join
  15140. if (status === c.Z_OK) {
  15141. if (this.options.to === 'string') {
  15142. // Glue & convert here, until we teach pako to send
  15143. // utf8 alligned strings to onData
  15144. this.result = this.chunks.join('');
  15145. } else {
  15146. this.result = utils.flattenChunks(this.chunks);
  15147. }
  15148. }
  15149. this.chunks = [];
  15150. this.err = status;
  15151. this.msg = this.strm.msg;
  15152. };
  15153. /**
  15154. * inflate(data[, options]) -> Uint8Array|Array|String
  15155. * - data (Uint8Array|Array|String): input data to decompress.
  15156. * - options (Object): zlib inflate options.
  15157. *
  15158. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  15159. * format via wrapper header by default. That's why we don't provide
  15160. * separate `ungzip` method.
  15161. *
  15162. * Supported options are:
  15163. *
  15164. * - windowBits
  15165. *
  15166. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15167. * for more information.
  15168. *
  15169. * Sugar (options):
  15170. *
  15171. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15172. * negative windowBits implicitly.
  15173. * - `to` (String) - if equal to 'string', then result will be converted
  15174. * from utf8 to utf16 (javascript) string. When string output requested,
  15175. * chunk length can differ from `chunkSize`, depending on content.
  15176. *
  15177. *
  15178. * ##### Example:
  15179. *
  15180. * ```javascript
  15181. * var pako = require('pako')
  15182. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  15183. * , output;
  15184. *
  15185. * try {
  15186. * output = pako.inflate(input);
  15187. * } catch (err)
  15188. * console.log(err);
  15189. * }
  15190. * ```
  15191. **/
  15192. function inflate(input, options) {
  15193. var inflator = new Inflate(options);
  15194. inflator.push(input, true);
  15195. // That will never happens, if you don't cheat with options :)
  15196. if (inflator.err) { throw inflator.msg; }
  15197. return inflator.result;
  15198. }
  15199. /**
  15200. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15201. * - data (Uint8Array|Array|String): input data to decompress.
  15202. * - options (Object): zlib inflate options.
  15203. *
  15204. * The same as [[inflate]], but creates raw data, without wrapper
  15205. * (header and adler32 crc).
  15206. **/
  15207. function inflateRaw(input, options) {
  15208. options = options || {};
  15209. options.raw = true;
  15210. return inflate(input, options);
  15211. }
  15212. /**
  15213. * ungzip(data[, options]) -> Uint8Array|Array|String
  15214. * - data (Uint8Array|Array|String): input data to decompress.
  15215. * - options (Object): zlib inflate options.
  15216. *
  15217. * Just shortcut to [[inflate]], because it autodetects format
  15218. * by header.content. Done for convenience.
  15219. **/
  15220. exports.Inflate = Inflate;
  15221. exports.inflate = inflate;
  15222. exports.inflateRaw = inflateRaw;
  15223. exports.ungzip = inflate;
  15224. },{"./utils/common":55,"./utils/strings":56,"./zlib/constants":58,"./zlib/gzheader":61,"./zlib/inflate.js":63,"./zlib/messages":65,"./zlib/zstream":67}],55:[function(require,module,exports){
  15225. 'use strict';
  15226. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15227. (typeof Uint16Array !== 'undefined') &&
  15228. (typeof Int32Array !== 'undefined');
  15229. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15230. var sources = Array.prototype.slice.call(arguments, 1);
  15231. while (sources.length) {
  15232. var source = sources.shift();
  15233. if (!source) { continue; }
  15234. if (typeof source !== 'object') {
  15235. throw new TypeError(source + 'must be non-object');
  15236. }
  15237. for (var p in source) {
  15238. if (source.hasOwnProperty(p)) {
  15239. obj[p] = source[p];
  15240. }
  15241. }
  15242. }
  15243. return obj;
  15244. };
  15245. // reduce buffer size, avoiding mem copy
  15246. exports.shrinkBuf = function (buf, size) {
  15247. if (buf.length === size) { return buf; }
  15248. if (buf.subarray) { return buf.subarray(0, size); }
  15249. buf.length = size;
  15250. return buf;
  15251. };
  15252. var fnTyped = {
  15253. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15254. if (src.subarray && dest.subarray) {
  15255. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15256. return;
  15257. }
  15258. // Fallback to ordinary array
  15259. for (var i=0; i<len; i++) {
  15260. dest[dest_offs + i] = src[src_offs + i];
  15261. }
  15262. },
  15263. // Join array of chunks to single array.
  15264. flattenChunks: function(chunks) {
  15265. var i, l, len, pos, chunk, result;
  15266. // calculate data length
  15267. len = 0;
  15268. for (i=0, l=chunks.length; i<l; i++) {
  15269. len += chunks[i].length;
  15270. }
  15271. // join chunks
  15272. result = new Uint8Array(len);
  15273. pos = 0;
  15274. for (i=0, l=chunks.length; i<l; i++) {
  15275. chunk = chunks[i];
  15276. result.set(chunk, pos);
  15277. pos += chunk.length;
  15278. }
  15279. return result;
  15280. }
  15281. };
  15282. var fnUntyped = {
  15283. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15284. for (var i=0; i<len; i++) {
  15285. dest[dest_offs + i] = src[src_offs + i];
  15286. }
  15287. },
  15288. // Join array of chunks to single array.
  15289. flattenChunks: function(chunks) {
  15290. return [].concat.apply([], chunks);
  15291. }
  15292. };
  15293. // Enable/Disable typed arrays use, for testing
  15294. //
  15295. exports.setTyped = function (on) {
  15296. if (on) {
  15297. exports.Buf8 = Uint8Array;
  15298. exports.Buf16 = Uint16Array;
  15299. exports.Buf32 = Int32Array;
  15300. exports.assign(exports, fnTyped);
  15301. } else {
  15302. exports.Buf8 = Array;
  15303. exports.Buf16 = Array;
  15304. exports.Buf32 = Array;
  15305. exports.assign(exports, fnUntyped);
  15306. }
  15307. };
  15308. exports.setTyped(TYPED_OK);
  15309. },{}],56:[function(require,module,exports){
  15310. // String encode/decode helpers
  15311. 'use strict';
  15312. var utils = require('./common');
  15313. // Quick check if we can use fast array to bin string conversion
  15314. //
  15315. // - apply(Array) can fail on Android 2.2
  15316. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15317. //
  15318. var STR_APPLY_OK = true;
  15319. var STR_APPLY_UIA_OK = true;
  15320. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15321. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15322. // Table with utf8 lengths (calculated by first byte of sequence)
  15323. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15324. // because max possible codepoint is 0x10ffff
  15325. var _utf8len = new utils.Buf8(256);
  15326. for (var q=0; q<256; q++) {
  15327. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15328. }
  15329. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15330. // convert string to array (typed, when possible)
  15331. exports.string2buf = function (str) {
  15332. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15333. // count binary size
  15334. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15335. c = str.charCodeAt(m_pos);
  15336. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15337. c2 = str.charCodeAt(m_pos+1);
  15338. if ((c2 & 0xfc00) === 0xdc00) {
  15339. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15340. m_pos++;
  15341. }
  15342. }
  15343. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15344. }
  15345. // allocate buffer
  15346. buf = new utils.Buf8(buf_len);
  15347. // convert
  15348. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15349. c = str.charCodeAt(m_pos);
  15350. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15351. c2 = str.charCodeAt(m_pos+1);
  15352. if ((c2 & 0xfc00) === 0xdc00) {
  15353. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15354. m_pos++;
  15355. }
  15356. }
  15357. if (c < 0x80) {
  15358. /* one byte */
  15359. buf[i++] = c;
  15360. } else if (c < 0x800) {
  15361. /* two bytes */
  15362. buf[i++] = 0xC0 | (c >>> 6);
  15363. buf[i++] = 0x80 | (c & 0x3f);
  15364. } else if (c < 0x10000) {
  15365. /* three bytes */
  15366. buf[i++] = 0xE0 | (c >>> 12);
  15367. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15368. buf[i++] = 0x80 | (c & 0x3f);
  15369. } else {
  15370. /* four bytes */
  15371. buf[i++] = 0xf0 | (c >>> 18);
  15372. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15373. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15374. buf[i++] = 0x80 | (c & 0x3f);
  15375. }
  15376. }
  15377. return buf;
  15378. };
  15379. // Helper (used in 2 places)
  15380. function buf2binstring(buf, len) {
  15381. // use fallback for big arrays to avoid stack overflow
  15382. if (len < 65537) {
  15383. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15384. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15385. }
  15386. }
  15387. var result = '';
  15388. for (var i=0; i < len; i++) {
  15389. result += String.fromCharCode(buf[i]);
  15390. }
  15391. return result;
  15392. }
  15393. // Convert byte array to binary string
  15394. exports.buf2binstring = function(buf) {
  15395. return buf2binstring(buf, buf.length);
  15396. };
  15397. // Convert binary string (typed, when possible)
  15398. exports.binstring2buf = function(str) {
  15399. var buf = new utils.Buf8(str.length);
  15400. for (var i=0, len=buf.length; i < len; i++) {
  15401. buf[i] = str.charCodeAt(i);
  15402. }
  15403. return buf;
  15404. };
  15405. // convert array to string
  15406. exports.buf2string = function (buf, max) {
  15407. var i, out, c, c_len;
  15408. var len = max || buf.length;
  15409. // Reserve max possible length (2 words per char)
  15410. // NB: by unknown reasons, Array is significantly faster for
  15411. // String.fromCharCode.apply than Uint16Array.
  15412. var utf16buf = new Array(len*2);
  15413. for (out=0, i=0; i<len;) {
  15414. c = buf[i++];
  15415. // quick process ascii
  15416. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15417. c_len = _utf8len[c];
  15418. // skip 5 & 6 byte codes
  15419. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15420. // apply mask on first byte
  15421. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15422. // join the rest
  15423. while (c_len > 1 && i < len) {
  15424. c = (c << 6) | (buf[i++] & 0x3f);
  15425. c_len--;
  15426. }
  15427. // terminated by end of string?
  15428. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15429. if (c < 0x10000) {
  15430. utf16buf[out++] = c;
  15431. } else {
  15432. c -= 0x10000;
  15433. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15434. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15435. }
  15436. }
  15437. return buf2binstring(utf16buf, out);
  15438. };
  15439. // Calculate max possible position in utf8 buffer,
  15440. // that will not break sequence. If that's not possible
  15441. // - (very small limits) return max size as is.
  15442. //
  15443. // buf[] - utf8 bytes array
  15444. // max - length limit (mandatory);
  15445. exports.utf8border = function(buf, max) {
  15446. var pos;
  15447. max = max || buf.length;
  15448. if (max > buf.length) { max = buf.length; }
  15449. // go back from last position, until start of sequence found
  15450. pos = max-1;
  15451. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15452. // Fuckup - very small and broken sequence,
  15453. // return max, because we should return something anyway.
  15454. if (pos < 0) { return max; }
  15455. // If we came to start of buffer - that means vuffer is too small,
  15456. // return max too.
  15457. if (pos === 0) { return max; }
  15458. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15459. };
  15460. },{"./common":55}],57:[function(require,module,exports){
  15461. 'use strict';
  15462. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15463. // It doesn't worth to make additional optimizationa as in original.
  15464. // Small size is preferable.
  15465. function adler32(adler, buf, len, pos) {
  15466. var s1 = (adler & 0xffff) |0,
  15467. s2 = ((adler >>> 16) & 0xffff) |0,
  15468. n = 0;
  15469. while (len !== 0) {
  15470. // Set limit ~ twice less than 5552, to keep
  15471. // s2 in 31-bits, because we force signed ints.
  15472. // in other case %= will fail.
  15473. n = len > 2000 ? 2000 : len;
  15474. len -= n;
  15475. do {
  15476. s1 = (s1 + buf[pos++]) |0;
  15477. s2 = (s2 + s1) |0;
  15478. } while (--n);
  15479. s1 %= 65521;
  15480. s2 %= 65521;
  15481. }
  15482. return (s1 | (s2 << 16)) |0;
  15483. }
  15484. module.exports = adler32;
  15485. },{}],58:[function(require,module,exports){
  15486. module.exports = {
  15487. /* Allowed flush values; see deflate() and inflate() below for details */
  15488. Z_NO_FLUSH: 0,
  15489. Z_PARTIAL_FLUSH: 1,
  15490. Z_SYNC_FLUSH: 2,
  15491. Z_FULL_FLUSH: 3,
  15492. Z_FINISH: 4,
  15493. Z_BLOCK: 5,
  15494. Z_TREES: 6,
  15495. /* Return codes for the compression/decompression functions. Negative values
  15496. * are errors, positive values are used for special but normal events.
  15497. */
  15498. Z_OK: 0,
  15499. Z_STREAM_END: 1,
  15500. Z_NEED_DICT: 2,
  15501. Z_ERRNO: -1,
  15502. Z_STREAM_ERROR: -2,
  15503. Z_DATA_ERROR: -3,
  15504. //Z_MEM_ERROR: -4,
  15505. Z_BUF_ERROR: -5,
  15506. //Z_VERSION_ERROR: -6,
  15507. /* compression levels */
  15508. Z_NO_COMPRESSION: 0,
  15509. Z_BEST_SPEED: 1,
  15510. Z_BEST_COMPRESSION: 9,
  15511. Z_DEFAULT_COMPRESSION: -1,
  15512. Z_FILTERED: 1,
  15513. Z_HUFFMAN_ONLY: 2,
  15514. Z_RLE: 3,
  15515. Z_FIXED: 4,
  15516. Z_DEFAULT_STRATEGY: 0,
  15517. /* Possible values of the data_type field (though see inflate()) */
  15518. Z_BINARY: 0,
  15519. Z_TEXT: 1,
  15520. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15521. Z_UNKNOWN: 2,
  15522. /* The deflate compression method */
  15523. Z_DEFLATED: 8
  15524. //Z_NULL: null // Use -1 or null inline, depending on var type
  15525. };
  15526. },{}],59:[function(require,module,exports){
  15527. 'use strict';
  15528. // Note: we can't get significant speed boost here.
  15529. // So write code to minimize size - no pregenerated tables
  15530. // and array tools dependencies.
  15531. // Use ordinary array, since untyped makes no boost here
  15532. function makeTable() {
  15533. var c, table = [];
  15534. for (var n =0; n < 256; n++) {
  15535. c = n;
  15536. for (var k =0; k < 8; k++) {
  15537. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15538. }
  15539. table[n] = c;
  15540. }
  15541. return table;
  15542. }
  15543. // Create table on load. Just 255 signed longs. Not a problem.
  15544. var crcTable = makeTable();
  15545. function crc32(crc, buf, len, pos) {
  15546. var t = crcTable,
  15547. end = pos + len;
  15548. crc = crc ^ (-1);
  15549. for (var i = pos; i < end; i++) {
  15550. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15551. }
  15552. return (crc ^ (-1)); // >>> 0;
  15553. }
  15554. module.exports = crc32;
  15555. },{}],60:[function(require,module,exports){
  15556. 'use strict';
  15557. var utils = require('../utils/common');
  15558. var trees = require('./trees');
  15559. var adler32 = require('./adler32');
  15560. var crc32 = require('./crc32');
  15561. var msg = require('./messages');
  15562. /* Public constants ==========================================================*/
  15563. /* ===========================================================================*/
  15564. /* Allowed flush values; see deflate() and inflate() below for details */
  15565. var Z_NO_FLUSH = 0;
  15566. var Z_PARTIAL_FLUSH = 1;
  15567. //var Z_SYNC_FLUSH = 2;
  15568. var Z_FULL_FLUSH = 3;
  15569. var Z_FINISH = 4;
  15570. var Z_BLOCK = 5;
  15571. //var Z_TREES = 6;
  15572. /* Return codes for the compression/decompression functions. Negative values
  15573. * are errors, positive values are used for special but normal events.
  15574. */
  15575. var Z_OK = 0;
  15576. var Z_STREAM_END = 1;
  15577. //var Z_NEED_DICT = 2;
  15578. //var Z_ERRNO = -1;
  15579. var Z_STREAM_ERROR = -2;
  15580. var Z_DATA_ERROR = -3;
  15581. //var Z_MEM_ERROR = -4;
  15582. var Z_BUF_ERROR = -5;
  15583. //var Z_VERSION_ERROR = -6;
  15584. /* compression levels */
  15585. //var Z_NO_COMPRESSION = 0;
  15586. //var Z_BEST_SPEED = 1;
  15587. //var Z_BEST_COMPRESSION = 9;
  15588. var Z_DEFAULT_COMPRESSION = -1;
  15589. var Z_FILTERED = 1;
  15590. var Z_HUFFMAN_ONLY = 2;
  15591. var Z_RLE = 3;
  15592. var Z_FIXED = 4;
  15593. var Z_DEFAULT_STRATEGY = 0;
  15594. /* Possible values of the data_type field (though see inflate()) */
  15595. //var Z_BINARY = 0;
  15596. //var Z_TEXT = 1;
  15597. //var Z_ASCII = 1; // = Z_TEXT
  15598. var Z_UNKNOWN = 2;
  15599. /* The deflate compression method */
  15600. var Z_DEFLATED = 8;
  15601. /*============================================================================*/
  15602. var MAX_MEM_LEVEL = 9;
  15603. /* Maximum value for memLevel in deflateInit2 */
  15604. var MAX_WBITS = 15;
  15605. /* 32K LZ77 window */
  15606. var DEF_MEM_LEVEL = 8;
  15607. var LENGTH_CODES = 29;
  15608. /* number of length codes, not counting the special END_BLOCK code */
  15609. var LITERALS = 256;
  15610. /* number of literal bytes 0..255 */
  15611. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15612. /* number of Literal or Length codes, including the END_BLOCK code */
  15613. var D_CODES = 30;
  15614. /* number of distance codes */
  15615. var BL_CODES = 19;
  15616. /* number of codes used to transfer the bit lengths */
  15617. var HEAP_SIZE = 2*L_CODES + 1;
  15618. /* maximum heap size */
  15619. var MAX_BITS = 15;
  15620. /* All codes must not exceed MAX_BITS bits */
  15621. var MIN_MATCH = 3;
  15622. var MAX_MATCH = 258;
  15623. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15624. var PRESET_DICT = 0x20;
  15625. var INIT_STATE = 42;
  15626. var EXTRA_STATE = 69;
  15627. var NAME_STATE = 73;
  15628. var COMMENT_STATE = 91;
  15629. var HCRC_STATE = 103;
  15630. var BUSY_STATE = 113;
  15631. var FINISH_STATE = 666;
  15632. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15633. var BS_BLOCK_DONE = 2; /* block flush performed */
  15634. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15635. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15636. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15637. function err(strm, errorCode) {
  15638. strm.msg = msg[errorCode];
  15639. return errorCode;
  15640. }
  15641. function rank(f) {
  15642. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15643. }
  15644. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15645. /* =========================================================================
  15646. * Flush as much pending output as possible. All deflate() output goes
  15647. * through this function so some applications may wish to modify it
  15648. * to avoid allocating a large strm->output buffer and copying into it.
  15649. * (See also read_buf()).
  15650. */
  15651. function flush_pending(strm) {
  15652. var s = strm.state;
  15653. //_tr_flush_bits(s);
  15654. var len = s.pending;
  15655. if (len > strm.avail_out) {
  15656. len = strm.avail_out;
  15657. }
  15658. if (len === 0) { return; }
  15659. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15660. strm.next_out += len;
  15661. s.pending_out += len;
  15662. strm.total_out += len;
  15663. strm.avail_out -= len;
  15664. s.pending -= len;
  15665. if (s.pending === 0) {
  15666. s.pending_out = 0;
  15667. }
  15668. }
  15669. function flush_block_only (s, last) {
  15670. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15671. s.block_start = s.strstart;
  15672. flush_pending(s.strm);
  15673. }
  15674. function put_byte(s, b) {
  15675. s.pending_buf[s.pending++] = b;
  15676. }
  15677. /* =========================================================================
  15678. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15679. * IN assertion: the stream state is correct and there is enough room in
  15680. * pending_buf.
  15681. */
  15682. function putShortMSB(s, b) {
  15683. // put_byte(s, (Byte)(b >> 8));
  15684. // put_byte(s, (Byte)(b & 0xff));
  15685. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15686. s.pending_buf[s.pending++] = b & 0xff;
  15687. }
  15688. /* ===========================================================================
  15689. * Read a new buffer from the current input stream, update the adler32
  15690. * and total number of bytes read. All deflate() input goes through
  15691. * this function so some applications may wish to modify it to avoid
  15692. * allocating a large strm->input buffer and copying from it.
  15693. * (See also flush_pending()).
  15694. */
  15695. function read_buf(strm, buf, start, size) {
  15696. var len = strm.avail_in;
  15697. if (len > size) { len = size; }
  15698. if (len === 0) { return 0; }
  15699. strm.avail_in -= len;
  15700. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15701. if (strm.state.wrap === 1) {
  15702. strm.adler = adler32(strm.adler, buf, len, start);
  15703. }
  15704. else if (strm.state.wrap === 2) {
  15705. strm.adler = crc32(strm.adler, buf, len, start);
  15706. }
  15707. strm.next_in += len;
  15708. strm.total_in += len;
  15709. return len;
  15710. }
  15711. /* ===========================================================================
  15712. * Set match_start to the longest match starting at the given string and
  15713. * return its length. Matches shorter or equal to prev_length are discarded,
  15714. * in which case the result is equal to prev_length and match_start is
  15715. * garbage.
  15716. * IN assertions: cur_match is the head of the hash chain for the current
  15717. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15718. * OUT assertion: the match length is not greater than s->lookahead.
  15719. */
  15720. function longest_match(s, cur_match) {
  15721. var chain_length = s.max_chain_length; /* max hash chain length */
  15722. var scan = s.strstart; /* current string */
  15723. var match; /* matched string */
  15724. var len; /* length of current match */
  15725. var best_len = s.prev_length; /* best match length so far */
  15726. var nice_match = s.nice_match; /* stop if match long enough */
  15727. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15728. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15729. var _win = s.window; // shortcut
  15730. var wmask = s.w_mask;
  15731. var prev = s.prev;
  15732. /* Stop when cur_match becomes <= limit. To simplify the code,
  15733. * we prevent matches with the string of window index 0.
  15734. */
  15735. var strend = s.strstart + MAX_MATCH;
  15736. var scan_end1 = _win[scan + best_len - 1];
  15737. var scan_end = _win[scan + best_len];
  15738. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15739. * It is easy to get rid of this optimization if necessary.
  15740. */
  15741. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15742. /* Do not waste too much time if we already have a good match: */
  15743. if (s.prev_length >= s.good_match) {
  15744. chain_length >>= 2;
  15745. }
  15746. /* Do not look for matches beyond the end of the input. This is necessary
  15747. * to make deflate deterministic.
  15748. */
  15749. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15750. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15751. do {
  15752. // Assert(cur_match < s->strstart, "no future");
  15753. match = cur_match;
  15754. /* Skip to next match if the match length cannot increase
  15755. * or if the match length is less than 2. Note that the checks below
  15756. * for insufficient lookahead only occur occasionally for performance
  15757. * reasons. Therefore uninitialized memory will be accessed, and
  15758. * conditional jumps will be made that depend on those values.
  15759. * However the length of the match is limited to the lookahead, so
  15760. * the output of deflate is not affected by the uninitialized values.
  15761. */
  15762. if (_win[match + best_len] !== scan_end ||
  15763. _win[match + best_len - 1] !== scan_end1 ||
  15764. _win[match] !== _win[scan] ||
  15765. _win[++match] !== _win[scan + 1]) {
  15766. continue;
  15767. }
  15768. /* The check at best_len-1 can be removed because it will be made
  15769. * again later. (This heuristic is not always a win.)
  15770. * It is not necessary to compare scan[2] and match[2] since they
  15771. * are always equal when the other bytes match, given that
  15772. * the hash keys are equal and that HASH_BITS >= 8.
  15773. */
  15774. scan += 2;
  15775. match++;
  15776. // Assert(*scan == *match, "match[2]?");
  15777. /* We check for insufficient lookahead only every 8th comparison;
  15778. * the 256th check will be made at strstart+258.
  15779. */
  15780. do {
  15781. /*jshint noempty:false*/
  15782. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15783. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15784. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15785. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15786. scan < strend);
  15787. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15788. len = MAX_MATCH - (strend - scan);
  15789. scan = strend - MAX_MATCH;
  15790. if (len > best_len) {
  15791. s.match_start = cur_match;
  15792. best_len = len;
  15793. if (len >= nice_match) {
  15794. break;
  15795. }
  15796. scan_end1 = _win[scan + best_len - 1];
  15797. scan_end = _win[scan + best_len];
  15798. }
  15799. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15800. if (best_len <= s.lookahead) {
  15801. return best_len;
  15802. }
  15803. return s.lookahead;
  15804. }
  15805. /* ===========================================================================
  15806. * Fill the window when the lookahead becomes insufficient.
  15807. * Updates strstart and lookahead.
  15808. *
  15809. * IN assertion: lookahead < MIN_LOOKAHEAD
  15810. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15811. * At least one byte has been read, or avail_in == 0; reads are
  15812. * performed for at least two bytes (required for the zip translate_eol
  15813. * option -- not supported here).
  15814. */
  15815. function fill_window(s) {
  15816. var _w_size = s.w_size;
  15817. var p, n, m, more, str;
  15818. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15819. do {
  15820. more = s.window_size - s.lookahead - s.strstart;
  15821. // JS ints have 32 bit, block below not needed
  15822. /* Deal with !@#$% 64K limit: */
  15823. //if (sizeof(int) <= 2) {
  15824. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15825. // more = wsize;
  15826. //
  15827. // } else if (more == (unsigned)(-1)) {
  15828. // /* Very unlikely, but possible on 16 bit machine if
  15829. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15830. // */
  15831. // more--;
  15832. // }
  15833. //}
  15834. /* If the window is almost full and there is insufficient lookahead,
  15835. * move the upper half to the lower one to make room in the upper half.
  15836. */
  15837. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15838. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15839. s.match_start -= _w_size;
  15840. s.strstart -= _w_size;
  15841. /* we now have strstart >= MAX_DIST */
  15842. s.block_start -= _w_size;
  15843. /* Slide the hash table (could be avoided with 32 bit values
  15844. at the expense of memory usage). We slide even when level == 0
  15845. to keep the hash table consistent if we switch back to level > 0
  15846. later. (Using level 0 permanently is not an optimal usage of
  15847. zlib, so we don't care about this pathological case.)
  15848. */
  15849. n = s.hash_size;
  15850. p = n;
  15851. do {
  15852. m = s.head[--p];
  15853. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15854. } while (--n);
  15855. n = _w_size;
  15856. p = n;
  15857. do {
  15858. m = s.prev[--p];
  15859. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15860. /* If n is not on any hash chain, prev[n] is garbage but
  15861. * its value will never be used.
  15862. */
  15863. } while (--n);
  15864. more += _w_size;
  15865. }
  15866. if (s.strm.avail_in === 0) {
  15867. break;
  15868. }
  15869. /* If there was no sliding:
  15870. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15871. * more == window_size - lookahead - strstart
  15872. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15873. * => more >= window_size - 2*WSIZE + 2
  15874. * In the BIG_MEM or MMAP case (not yet supported),
  15875. * window_size == input_size + MIN_LOOKAHEAD &&
  15876. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15877. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15878. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15879. */
  15880. //Assert(more >= 2, "more < 2");
  15881. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15882. s.lookahead += n;
  15883. /* Initialize the hash value now that we have some input: */
  15884. if (s.lookahead + s.insert >= MIN_MATCH) {
  15885. str = s.strstart - s.insert;
  15886. s.ins_h = s.window[str];
  15887. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15888. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15889. //#if MIN_MATCH != 3
  15890. // Call update_hash() MIN_MATCH-3 more times
  15891. //#endif
  15892. while (s.insert) {
  15893. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15894. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15895. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15896. s.head[s.ins_h] = str;
  15897. str++;
  15898. s.insert--;
  15899. if (s.lookahead + s.insert < MIN_MATCH) {
  15900. break;
  15901. }
  15902. }
  15903. }
  15904. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15905. * but this is not important since only literal bytes will be emitted.
  15906. */
  15907. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15908. /* If the WIN_INIT bytes after the end of the current data have never been
  15909. * written, then zero those bytes in order to avoid memory check reports of
  15910. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15911. * the longest match routines. Update the high water mark for the next
  15912. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15913. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15914. */
  15915. // if (s.high_water < s.window_size) {
  15916. // var curr = s.strstart + s.lookahead;
  15917. // var init = 0;
  15918. //
  15919. // if (s.high_water < curr) {
  15920. // /* Previous high water mark below current data -- zero WIN_INIT
  15921. // * bytes or up to end of window, whichever is less.
  15922. // */
  15923. // init = s.window_size - curr;
  15924. // if (init > WIN_INIT)
  15925. // init = WIN_INIT;
  15926. // zmemzero(s->window + curr, (unsigned)init);
  15927. // s->high_water = curr + init;
  15928. // }
  15929. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15930. // /* High water mark at or above current data, but below current data
  15931. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15932. // * to end of window, whichever is less.
  15933. // */
  15934. // init = (ulg)curr + WIN_INIT - s->high_water;
  15935. // if (init > s->window_size - s->high_water)
  15936. // init = s->window_size - s->high_water;
  15937. // zmemzero(s->window + s->high_water, (unsigned)init);
  15938. // s->high_water += init;
  15939. // }
  15940. // }
  15941. //
  15942. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15943. // "not enough room for search");
  15944. }
  15945. /* ===========================================================================
  15946. * Copy without compression as much as possible from the input stream, return
  15947. * the current block state.
  15948. * This function does not insert new strings in the dictionary since
  15949. * uncompressible data is probably not useful. This function is used
  15950. * only for the level=0 compression option.
  15951. * NOTE: this function should be optimized to avoid extra copying from
  15952. * window to pending_buf.
  15953. */
  15954. function deflate_stored(s, flush) {
  15955. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15956. * to pending_buf_size, and each stored block has a 5 byte header:
  15957. */
  15958. var max_block_size = 0xffff;
  15959. if (max_block_size > s.pending_buf_size - 5) {
  15960. max_block_size = s.pending_buf_size - 5;
  15961. }
  15962. /* Copy as much as possible from input to output: */
  15963. for (;;) {
  15964. /* Fill the window as much as possible: */
  15965. if (s.lookahead <= 1) {
  15966. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15967. // s->block_start >= (long)s->w_size, "slide too late");
  15968. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15969. // s.block_start >= s.w_size)) {
  15970. // throw new Error("slide too late");
  15971. // }
  15972. fill_window(s);
  15973. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15974. return BS_NEED_MORE;
  15975. }
  15976. if (s.lookahead === 0) {
  15977. break;
  15978. }
  15979. /* flush the current block */
  15980. }
  15981. //Assert(s->block_start >= 0L, "block gone");
  15982. // if (s.block_start < 0) throw new Error("block gone");
  15983. s.strstart += s.lookahead;
  15984. s.lookahead = 0;
  15985. /* Emit a stored block if pending_buf will be full: */
  15986. var max_start = s.block_start + max_block_size;
  15987. if (s.strstart === 0 || s.strstart >= max_start) {
  15988. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15989. s.lookahead = s.strstart - max_start;
  15990. s.strstart = max_start;
  15991. /*** FLUSH_BLOCK(s, 0); ***/
  15992. flush_block_only(s, false);
  15993. if (s.strm.avail_out === 0) {
  15994. return BS_NEED_MORE;
  15995. }
  15996. /***/
  15997. }
  15998. /* Flush if we may have to slide, otherwise block_start may become
  15999. * negative and the data will be gone:
  16000. */
  16001. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  16002. /*** FLUSH_BLOCK(s, 0); ***/
  16003. flush_block_only(s, false);
  16004. if (s.strm.avail_out === 0) {
  16005. return BS_NEED_MORE;
  16006. }
  16007. /***/
  16008. }
  16009. }
  16010. s.insert = 0;
  16011. if (flush === Z_FINISH) {
  16012. /*** FLUSH_BLOCK(s, 1); ***/
  16013. flush_block_only(s, true);
  16014. if (s.strm.avail_out === 0) {
  16015. return BS_FINISH_STARTED;
  16016. }
  16017. /***/
  16018. return BS_FINISH_DONE;
  16019. }
  16020. if (s.strstart > s.block_start) {
  16021. /*** FLUSH_BLOCK(s, 0); ***/
  16022. flush_block_only(s, false);
  16023. if (s.strm.avail_out === 0) {
  16024. return BS_NEED_MORE;
  16025. }
  16026. /***/
  16027. }
  16028. return BS_NEED_MORE;
  16029. }
  16030. /* ===========================================================================
  16031. * Compress as much as possible from the input stream, return the current
  16032. * block state.
  16033. * This function does not perform lazy evaluation of matches and inserts
  16034. * new strings in the dictionary only for unmatched strings or for short
  16035. * matches. It is used only for the fast compression options.
  16036. */
  16037. function deflate_fast(s, flush) {
  16038. var hash_head; /* head of the hash chain */
  16039. var bflush; /* set if current block must be flushed */
  16040. for (;;) {
  16041. /* Make sure that we always have enough lookahead, except
  16042. * at the end of the input file. We need MAX_MATCH bytes
  16043. * for the next match, plus MIN_MATCH bytes to insert the
  16044. * string following the next match.
  16045. */
  16046. if (s.lookahead < MIN_LOOKAHEAD) {
  16047. fill_window(s);
  16048. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16049. return BS_NEED_MORE;
  16050. }
  16051. if (s.lookahead === 0) {
  16052. break; /* flush the current block */
  16053. }
  16054. }
  16055. /* Insert the string window[strstart .. strstart+2] in the
  16056. * dictionary, and set hash_head to the head of the hash chain:
  16057. */
  16058. hash_head = 0/*NIL*/;
  16059. if (s.lookahead >= MIN_MATCH) {
  16060. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16061. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16062. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16063. s.head[s.ins_h] = s.strstart;
  16064. /***/
  16065. }
  16066. /* Find the longest match, discarding those <= prev_length.
  16067. * At this point we have always match_length < MIN_MATCH
  16068. */
  16069. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16070. /* To simplify the code, we prevent matches with the string
  16071. * of window index 0 (in particular we have to avoid a match
  16072. * of the string with itself at the start of the input file).
  16073. */
  16074. s.match_length = longest_match(s, hash_head);
  16075. /* longest_match() sets match_start */
  16076. }
  16077. if (s.match_length >= MIN_MATCH) {
  16078. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16079. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16080. s.match_length - MIN_MATCH, bflush); ***/
  16081. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16082. s.lookahead -= s.match_length;
  16083. /* Insert new strings in the hash table only if the match length
  16084. * is not too large. This saves time but degrades compression.
  16085. */
  16086. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16087. s.match_length--; /* string at strstart already in table */
  16088. do {
  16089. s.strstart++;
  16090. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16091. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16092. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16093. s.head[s.ins_h] = s.strstart;
  16094. /***/
  16095. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16096. * always MIN_MATCH bytes ahead.
  16097. */
  16098. } while (--s.match_length !== 0);
  16099. s.strstart++;
  16100. } else
  16101. {
  16102. s.strstart += s.match_length;
  16103. s.match_length = 0;
  16104. s.ins_h = s.window[s.strstart];
  16105. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16106. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16107. //#if MIN_MATCH != 3
  16108. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16109. //#endif
  16110. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16111. * matter since it will be recomputed at next deflate call.
  16112. */
  16113. }
  16114. } else {
  16115. /* No match, output a literal byte */
  16116. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16117. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16118. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16119. s.lookahead--;
  16120. s.strstart++;
  16121. }
  16122. if (bflush) {
  16123. /*** FLUSH_BLOCK(s, 0); ***/
  16124. flush_block_only(s, false);
  16125. if (s.strm.avail_out === 0) {
  16126. return BS_NEED_MORE;
  16127. }
  16128. /***/
  16129. }
  16130. }
  16131. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  16132. if (flush === Z_FINISH) {
  16133. /*** FLUSH_BLOCK(s, 1); ***/
  16134. flush_block_only(s, true);
  16135. if (s.strm.avail_out === 0) {
  16136. return BS_FINISH_STARTED;
  16137. }
  16138. /***/
  16139. return BS_FINISH_DONE;
  16140. }
  16141. if (s.last_lit) {
  16142. /*** FLUSH_BLOCK(s, 0); ***/
  16143. flush_block_only(s, false);
  16144. if (s.strm.avail_out === 0) {
  16145. return BS_NEED_MORE;
  16146. }
  16147. /***/
  16148. }
  16149. return BS_BLOCK_DONE;
  16150. }
  16151. /* ===========================================================================
  16152. * Same as above, but achieves better compression. We use a lazy
  16153. * evaluation for matches: a match is finally adopted only if there is
  16154. * no better match at the next window position.
  16155. */
  16156. function deflate_slow(s, flush) {
  16157. var hash_head; /* head of hash chain */
  16158. var bflush; /* set if current block must be flushed */
  16159. var max_insert;
  16160. /* Process the input block. */
  16161. for (;;) {
  16162. /* Make sure that we always have enough lookahead, except
  16163. * at the end of the input file. We need MAX_MATCH bytes
  16164. * for the next match, plus MIN_MATCH bytes to insert the
  16165. * string following the next match.
  16166. */
  16167. if (s.lookahead < MIN_LOOKAHEAD) {
  16168. fill_window(s);
  16169. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16170. return BS_NEED_MORE;
  16171. }
  16172. if (s.lookahead === 0) { break; } /* flush the current block */
  16173. }
  16174. /* Insert the string window[strstart .. strstart+2] in the
  16175. * dictionary, and set hash_head to the head of the hash chain:
  16176. */
  16177. hash_head = 0/*NIL*/;
  16178. if (s.lookahead >= MIN_MATCH) {
  16179. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16180. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16181. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16182. s.head[s.ins_h] = s.strstart;
  16183. /***/
  16184. }
  16185. /* Find the longest match, discarding those <= prev_length.
  16186. */
  16187. s.prev_length = s.match_length;
  16188. s.prev_match = s.match_start;
  16189. s.match_length = MIN_MATCH-1;
  16190. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16191. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16192. /* To simplify the code, we prevent matches with the string
  16193. * of window index 0 (in particular we have to avoid a match
  16194. * of the string with itself at the start of the input file).
  16195. */
  16196. s.match_length = longest_match(s, hash_head);
  16197. /* longest_match() sets match_start */
  16198. if (s.match_length <= 5 &&
  16199. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16200. /* If prev_match is also MIN_MATCH, match_start is garbage
  16201. * but we will ignore the current match anyway.
  16202. */
  16203. s.match_length = MIN_MATCH-1;
  16204. }
  16205. }
  16206. /* If there was a match at the previous step and the current
  16207. * match is not better, output the previous match:
  16208. */
  16209. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16210. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16211. /* Do not insert strings in hash table beyond this. */
  16212. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16213. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16214. s.prev_length - MIN_MATCH, bflush);***/
  16215. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16216. /* Insert in hash table all strings up to the end of the match.
  16217. * strstart-1 and strstart are already inserted. If there is not
  16218. * enough lookahead, the last two strings are not inserted in
  16219. * the hash table.
  16220. */
  16221. s.lookahead -= s.prev_length-1;
  16222. s.prev_length -= 2;
  16223. do {
  16224. if (++s.strstart <= max_insert) {
  16225. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16226. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16227. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16228. s.head[s.ins_h] = s.strstart;
  16229. /***/
  16230. }
  16231. } while (--s.prev_length !== 0);
  16232. s.match_available = 0;
  16233. s.match_length = MIN_MATCH-1;
  16234. s.strstart++;
  16235. if (bflush) {
  16236. /*** FLUSH_BLOCK(s, 0); ***/
  16237. flush_block_only(s, false);
  16238. if (s.strm.avail_out === 0) {
  16239. return BS_NEED_MORE;
  16240. }
  16241. /***/
  16242. }
  16243. } else if (s.match_available) {
  16244. /* If there was no match at the previous position, output a
  16245. * single literal. If there was a match but the current match
  16246. * is longer, truncate the previous match to a single literal.
  16247. */
  16248. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16249. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16250. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16251. if (bflush) {
  16252. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16253. flush_block_only(s, false);
  16254. /***/
  16255. }
  16256. s.strstart++;
  16257. s.lookahead--;
  16258. if (s.strm.avail_out === 0) {
  16259. return BS_NEED_MORE;
  16260. }
  16261. } else {
  16262. /* There is no previous match to compare with, wait for
  16263. * the next step to decide.
  16264. */
  16265. s.match_available = 1;
  16266. s.strstart++;
  16267. s.lookahead--;
  16268. }
  16269. }
  16270. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16271. if (s.match_available) {
  16272. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16273. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16274. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16275. s.match_available = 0;
  16276. }
  16277. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16278. if (flush === Z_FINISH) {
  16279. /*** FLUSH_BLOCK(s, 1); ***/
  16280. flush_block_only(s, true);
  16281. if (s.strm.avail_out === 0) {
  16282. return BS_FINISH_STARTED;
  16283. }
  16284. /***/
  16285. return BS_FINISH_DONE;
  16286. }
  16287. if (s.last_lit) {
  16288. /*** FLUSH_BLOCK(s, 0); ***/
  16289. flush_block_only(s, false);
  16290. if (s.strm.avail_out === 0) {
  16291. return BS_NEED_MORE;
  16292. }
  16293. /***/
  16294. }
  16295. return BS_BLOCK_DONE;
  16296. }
  16297. /* ===========================================================================
  16298. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16299. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16300. * deflate switches away from Z_RLE.)
  16301. */
  16302. function deflate_rle(s, flush) {
  16303. var bflush; /* set if current block must be flushed */
  16304. var prev; /* byte at distance one to match */
  16305. var scan, strend; /* scan goes up to strend for length of run */
  16306. var _win = s.window;
  16307. for (;;) {
  16308. /* Make sure that we always have enough lookahead, except
  16309. * at the end of the input file. We need MAX_MATCH bytes
  16310. * for the longest run, plus one for the unrolled loop.
  16311. */
  16312. if (s.lookahead <= MAX_MATCH) {
  16313. fill_window(s);
  16314. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16315. return BS_NEED_MORE;
  16316. }
  16317. if (s.lookahead === 0) { break; } /* flush the current block */
  16318. }
  16319. /* See how many times the previous byte repeats */
  16320. s.match_length = 0;
  16321. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16322. scan = s.strstart - 1;
  16323. prev = _win[scan];
  16324. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16325. strend = s.strstart + MAX_MATCH;
  16326. do {
  16327. /*jshint noempty:false*/
  16328. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16329. prev === _win[++scan] && prev === _win[++scan] &&
  16330. prev === _win[++scan] && prev === _win[++scan] &&
  16331. prev === _win[++scan] && prev === _win[++scan] &&
  16332. scan < strend);
  16333. s.match_length = MAX_MATCH - (strend - scan);
  16334. if (s.match_length > s.lookahead) {
  16335. s.match_length = s.lookahead;
  16336. }
  16337. }
  16338. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16339. }
  16340. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16341. if (s.match_length >= MIN_MATCH) {
  16342. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16343. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16344. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16345. s.lookahead -= s.match_length;
  16346. s.strstart += s.match_length;
  16347. s.match_length = 0;
  16348. } else {
  16349. /* No match, output a literal byte */
  16350. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16351. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16352. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16353. s.lookahead--;
  16354. s.strstart++;
  16355. }
  16356. if (bflush) {
  16357. /*** FLUSH_BLOCK(s, 0); ***/
  16358. flush_block_only(s, false);
  16359. if (s.strm.avail_out === 0) {
  16360. return BS_NEED_MORE;
  16361. }
  16362. /***/
  16363. }
  16364. }
  16365. s.insert = 0;
  16366. if (flush === Z_FINISH) {
  16367. /*** FLUSH_BLOCK(s, 1); ***/
  16368. flush_block_only(s, true);
  16369. if (s.strm.avail_out === 0) {
  16370. return BS_FINISH_STARTED;
  16371. }
  16372. /***/
  16373. return BS_FINISH_DONE;
  16374. }
  16375. if (s.last_lit) {
  16376. /*** FLUSH_BLOCK(s, 0); ***/
  16377. flush_block_only(s, false);
  16378. if (s.strm.avail_out === 0) {
  16379. return BS_NEED_MORE;
  16380. }
  16381. /***/
  16382. }
  16383. return BS_BLOCK_DONE;
  16384. }
  16385. /* ===========================================================================
  16386. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16387. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16388. */
  16389. function deflate_huff(s, flush) {
  16390. var bflush; /* set if current block must be flushed */
  16391. for (;;) {
  16392. /* Make sure that we have a literal to write. */
  16393. if (s.lookahead === 0) {
  16394. fill_window(s);
  16395. if (s.lookahead === 0) {
  16396. if (flush === Z_NO_FLUSH) {
  16397. return BS_NEED_MORE;
  16398. }
  16399. break; /* flush the current block */
  16400. }
  16401. }
  16402. /* Output a literal byte */
  16403. s.match_length = 0;
  16404. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16405. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16406. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16407. s.lookahead--;
  16408. s.strstart++;
  16409. if (bflush) {
  16410. /*** FLUSH_BLOCK(s, 0); ***/
  16411. flush_block_only(s, false);
  16412. if (s.strm.avail_out === 0) {
  16413. return BS_NEED_MORE;
  16414. }
  16415. /***/
  16416. }
  16417. }
  16418. s.insert = 0;
  16419. if (flush === Z_FINISH) {
  16420. /*** FLUSH_BLOCK(s, 1); ***/
  16421. flush_block_only(s, true);
  16422. if (s.strm.avail_out === 0) {
  16423. return BS_FINISH_STARTED;
  16424. }
  16425. /***/
  16426. return BS_FINISH_DONE;
  16427. }
  16428. if (s.last_lit) {
  16429. /*** FLUSH_BLOCK(s, 0); ***/
  16430. flush_block_only(s, false);
  16431. if (s.strm.avail_out === 0) {
  16432. return BS_NEED_MORE;
  16433. }
  16434. /***/
  16435. }
  16436. return BS_BLOCK_DONE;
  16437. }
  16438. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16439. * the desired pack level (0..9). The values given below have been tuned to
  16440. * exclude worst case performance for pathological files. Better values may be
  16441. * found for specific files.
  16442. */
  16443. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16444. this.good_length = good_length;
  16445. this.max_lazy = max_lazy;
  16446. this.nice_length = nice_length;
  16447. this.max_chain = max_chain;
  16448. this.func = func;
  16449. };
  16450. var configuration_table;
  16451. configuration_table = [
  16452. /* good lazy nice chain */
  16453. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16454. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16455. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16456. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16457. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16458. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16459. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16460. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16461. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16462. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16463. ];
  16464. /* ===========================================================================
  16465. * Initialize the "longest match" routines for a new zlib stream
  16466. */
  16467. function lm_init(s) {
  16468. s.window_size = 2 * s.w_size;
  16469. /*** CLEAR_HASH(s); ***/
  16470. zero(s.head); // Fill with NIL (= 0);
  16471. /* Set the default configuration parameters:
  16472. */
  16473. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16474. s.good_match = configuration_table[s.level].good_length;
  16475. s.nice_match = configuration_table[s.level].nice_length;
  16476. s.max_chain_length = configuration_table[s.level].max_chain;
  16477. s.strstart = 0;
  16478. s.block_start = 0;
  16479. s.lookahead = 0;
  16480. s.insert = 0;
  16481. s.match_length = s.prev_length = MIN_MATCH - 1;
  16482. s.match_available = 0;
  16483. s.ins_h = 0;
  16484. }
  16485. function DeflateState() {
  16486. this.strm = null; /* pointer back to this zlib stream */
  16487. this.status = 0; /* as the name implies */
  16488. this.pending_buf = null; /* output still pending */
  16489. this.pending_buf_size = 0; /* size of pending_buf */
  16490. this.pending_out = 0; /* next pending byte to output to the stream */
  16491. this.pending = 0; /* nb of bytes in the pending buffer */
  16492. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16493. this.gzhead = null; /* gzip header information to write */
  16494. this.gzindex = 0; /* where in extra, name, or comment */
  16495. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16496. this.last_flush = -1; /* value of flush param for previous deflate call */
  16497. this.w_size = 0; /* LZ77 window size (32K by default) */
  16498. this.w_bits = 0; /* log2(w_size) (8..16) */
  16499. this.w_mask = 0; /* w_size - 1 */
  16500. this.window = null;
  16501. /* Sliding window. Input bytes are read into the second half of the window,
  16502. * and move to the first half later to keep a dictionary of at least wSize
  16503. * bytes. With this organization, matches are limited to a distance of
  16504. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16505. * performed with a length multiple of the block size.
  16506. */
  16507. this.window_size = 0;
  16508. /* Actual size of window: 2*wSize, except when the user input buffer
  16509. * is directly used as sliding window.
  16510. */
  16511. this.prev = null;
  16512. /* Link to older string with same hash index. To limit the size of this
  16513. * array to 64K, this link is maintained only for the last 32K strings.
  16514. * An index in this array is thus a window index modulo 32K.
  16515. */
  16516. this.head = null; /* Heads of the hash chains or NIL. */
  16517. this.ins_h = 0; /* hash index of string to be inserted */
  16518. this.hash_size = 0; /* number of elements in hash table */
  16519. this.hash_bits = 0; /* log2(hash_size) */
  16520. this.hash_mask = 0; /* hash_size-1 */
  16521. this.hash_shift = 0;
  16522. /* Number of bits by which ins_h must be shifted at each input
  16523. * step. It must be such that after MIN_MATCH steps, the oldest
  16524. * byte no longer takes part in the hash key, that is:
  16525. * hash_shift * MIN_MATCH >= hash_bits
  16526. */
  16527. this.block_start = 0;
  16528. /* Window position at the beginning of the current output block. Gets
  16529. * negative when the window is moved backwards.
  16530. */
  16531. this.match_length = 0; /* length of best match */
  16532. this.prev_match = 0; /* previous match */
  16533. this.match_available = 0; /* set if previous match exists */
  16534. this.strstart = 0; /* start of string to insert */
  16535. this.match_start = 0; /* start of matching string */
  16536. this.lookahead = 0; /* number of valid bytes ahead in window */
  16537. this.prev_length = 0;
  16538. /* Length of the best match at previous step. Matches not greater than this
  16539. * are discarded. This is used in the lazy match evaluation.
  16540. */
  16541. this.max_chain_length = 0;
  16542. /* To speed up deflation, hash chains are never searched beyond this
  16543. * length. A higher limit improves compression ratio but degrades the
  16544. * speed.
  16545. */
  16546. this.max_lazy_match = 0;
  16547. /* Attempt to find a better match only when the current match is strictly
  16548. * smaller than this value. This mechanism is used only for compression
  16549. * levels >= 4.
  16550. */
  16551. // That's alias to max_lazy_match, don't use directly
  16552. //this.max_insert_length = 0;
  16553. /* Insert new strings in the hash table only if the match length is not
  16554. * greater than this length. This saves time but degrades compression.
  16555. * max_insert_length is used only for compression levels <= 3.
  16556. */
  16557. this.level = 0; /* compression level (1..9) */
  16558. this.strategy = 0; /* favor or force Huffman coding*/
  16559. this.good_match = 0;
  16560. /* Use a faster search when the previous match is longer than this */
  16561. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16562. /* used by trees.c: */
  16563. /* Didn't use ct_data typedef below to suppress compiler warning */
  16564. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16565. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16566. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16567. // Use flat array of DOUBLE size, with interleaved fata,
  16568. // because JS does not support effective
  16569. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16570. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16571. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16572. zero(this.dyn_ltree);
  16573. zero(this.dyn_dtree);
  16574. zero(this.bl_tree);
  16575. this.l_desc = null; /* desc. for literal tree */
  16576. this.d_desc = null; /* desc. for distance tree */
  16577. this.bl_desc = null; /* desc. for bit length tree */
  16578. //ush bl_count[MAX_BITS+1];
  16579. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16580. /* number of codes at each bit length for an optimal tree */
  16581. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16582. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16583. zero(this.heap);
  16584. this.heap_len = 0; /* number of elements in the heap */
  16585. this.heap_max = 0; /* element of largest frequency */
  16586. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16587. * The same heap array is used to build all trees.
  16588. */
  16589. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16590. zero(this.depth);
  16591. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16592. */
  16593. this.l_buf = 0; /* buffer index for literals or lengths */
  16594. this.lit_bufsize = 0;
  16595. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16596. * limiting lit_bufsize to 64K:
  16597. * - frequencies can be kept in 16 bit counters
  16598. * - if compression is not successful for the first block, all input
  16599. * data is still in the window so we can still emit a stored block even
  16600. * when input comes from standard input. (This can also be done for
  16601. * all blocks if lit_bufsize is not greater than 32K.)
  16602. * - if compression is not successful for a file smaller than 64K, we can
  16603. * even emit a stored file instead of a stored block (saving 5 bytes).
  16604. * This is applicable only for zip (not gzip or zlib).
  16605. * - creating new Huffman trees less frequently may not provide fast
  16606. * adaptation to changes in the input data statistics. (Take for
  16607. * example a binary file with poorly compressible code followed by
  16608. * a highly compressible string table.) Smaller buffer sizes give
  16609. * fast adaptation but have of course the overhead of transmitting
  16610. * trees more frequently.
  16611. * - I can't count above 4
  16612. */
  16613. this.last_lit = 0; /* running index in l_buf */
  16614. this.d_buf = 0;
  16615. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16616. * the same number of elements. To use different lengths, an extra flag
  16617. * array would be necessary.
  16618. */
  16619. this.opt_len = 0; /* bit length of current block with optimal trees */
  16620. this.static_len = 0; /* bit length of current block with static trees */
  16621. this.matches = 0; /* number of string matches in current block */
  16622. this.insert = 0; /* bytes at end of window left to insert */
  16623. this.bi_buf = 0;
  16624. /* Output buffer. bits are inserted starting at the bottom (least
  16625. * significant bits).
  16626. */
  16627. this.bi_valid = 0;
  16628. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16629. * are always zero.
  16630. */
  16631. // Used for window memory init. We safely ignore it for JS. That makes
  16632. // sense only for pointers and memory check tools.
  16633. //this.high_water = 0;
  16634. /* High water mark offset in window for initialized bytes -- bytes above
  16635. * this are set to zero in order to avoid memory check warnings when
  16636. * longest match routines access bytes past the input. This is then
  16637. * updated to the new high water mark.
  16638. */
  16639. }
  16640. function deflateResetKeep(strm) {
  16641. var s;
  16642. if (!strm || !strm.state) {
  16643. return err(strm, Z_STREAM_ERROR);
  16644. }
  16645. strm.total_in = strm.total_out = 0;
  16646. strm.data_type = Z_UNKNOWN;
  16647. s = strm.state;
  16648. s.pending = 0;
  16649. s.pending_out = 0;
  16650. if (s.wrap < 0) {
  16651. s.wrap = -s.wrap;
  16652. /* was made negative by deflate(..., Z_FINISH); */
  16653. }
  16654. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16655. strm.adler = (s.wrap === 2) ?
  16656. 0 // crc32(0, Z_NULL, 0)
  16657. :
  16658. 1; // adler32(0, Z_NULL, 0)
  16659. s.last_flush = Z_NO_FLUSH;
  16660. trees._tr_init(s);
  16661. return Z_OK;
  16662. }
  16663. function deflateReset(strm) {
  16664. var ret = deflateResetKeep(strm);
  16665. if (ret === Z_OK) {
  16666. lm_init(strm.state);
  16667. }
  16668. return ret;
  16669. }
  16670. function deflateSetHeader(strm, head) {
  16671. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16672. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16673. strm.state.gzhead = head;
  16674. return Z_OK;
  16675. }
  16676. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16677. if (!strm) { // === Z_NULL
  16678. return Z_STREAM_ERROR;
  16679. }
  16680. var wrap = 1;
  16681. if (level === Z_DEFAULT_COMPRESSION) {
  16682. level = 6;
  16683. }
  16684. if (windowBits < 0) { /* suppress zlib wrapper */
  16685. wrap = 0;
  16686. windowBits = -windowBits;
  16687. }
  16688. else if (windowBits > 15) {
  16689. wrap = 2; /* write gzip wrapper instead */
  16690. windowBits -= 16;
  16691. }
  16692. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16693. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16694. strategy < 0 || strategy > Z_FIXED) {
  16695. return err(strm, Z_STREAM_ERROR);
  16696. }
  16697. if (windowBits === 8) {
  16698. windowBits = 9;
  16699. }
  16700. /* until 256-byte window bug fixed */
  16701. var s = new DeflateState();
  16702. strm.state = s;
  16703. s.strm = strm;
  16704. s.wrap = wrap;
  16705. s.gzhead = null;
  16706. s.w_bits = windowBits;
  16707. s.w_size = 1 << s.w_bits;
  16708. s.w_mask = s.w_size - 1;
  16709. s.hash_bits = memLevel + 7;
  16710. s.hash_size = 1 << s.hash_bits;
  16711. s.hash_mask = s.hash_size - 1;
  16712. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16713. s.window = new utils.Buf8(s.w_size * 2);
  16714. s.head = new utils.Buf16(s.hash_size);
  16715. s.prev = new utils.Buf16(s.w_size);
  16716. // Don't need mem init magic for JS.
  16717. //s.high_water = 0; /* nothing written to s->window yet */
  16718. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16719. s.pending_buf_size = s.lit_bufsize * 4;
  16720. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16721. s.d_buf = s.lit_bufsize >> 1;
  16722. s.l_buf = (1 + 2) * s.lit_bufsize;
  16723. s.level = level;
  16724. s.strategy = strategy;
  16725. s.method = method;
  16726. return deflateReset(strm);
  16727. }
  16728. function deflateInit(strm, level) {
  16729. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16730. }
  16731. function deflate(strm, flush) {
  16732. var old_flush, s;
  16733. var beg, val; // for gzip header write only
  16734. if (!strm || !strm.state ||
  16735. flush > Z_BLOCK || flush < 0) {
  16736. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16737. }
  16738. s = strm.state;
  16739. if (!strm.output ||
  16740. (!strm.input && strm.avail_in !== 0) ||
  16741. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16742. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16743. }
  16744. s.strm = strm; /* just in case */
  16745. old_flush = s.last_flush;
  16746. s.last_flush = flush;
  16747. /* Write the header */
  16748. if (s.status === INIT_STATE) {
  16749. if (s.wrap === 2) { // GZIP header
  16750. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16751. put_byte(s, 31);
  16752. put_byte(s, 139);
  16753. put_byte(s, 8);
  16754. if (!s.gzhead) { // s->gzhead == Z_NULL
  16755. put_byte(s, 0);
  16756. put_byte(s, 0);
  16757. put_byte(s, 0);
  16758. put_byte(s, 0);
  16759. put_byte(s, 0);
  16760. put_byte(s, s.level === 9 ? 2 :
  16761. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16762. 4 : 0));
  16763. put_byte(s, OS_CODE);
  16764. s.status = BUSY_STATE;
  16765. }
  16766. else {
  16767. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16768. (s.gzhead.hcrc ? 2 : 0) +
  16769. (!s.gzhead.extra ? 0 : 4) +
  16770. (!s.gzhead.name ? 0 : 8) +
  16771. (!s.gzhead.comment ? 0 : 16)
  16772. );
  16773. put_byte(s, s.gzhead.time & 0xff);
  16774. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16775. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16776. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16777. put_byte(s, s.level === 9 ? 2 :
  16778. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16779. 4 : 0));
  16780. put_byte(s, s.gzhead.os & 0xff);
  16781. if (s.gzhead.extra && s.gzhead.extra.length) {
  16782. put_byte(s, s.gzhead.extra.length & 0xff);
  16783. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16784. }
  16785. if (s.gzhead.hcrc) {
  16786. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16787. }
  16788. s.gzindex = 0;
  16789. s.status = EXTRA_STATE;
  16790. }
  16791. }
  16792. else // DEFLATE header
  16793. {
  16794. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16795. var level_flags = -1;
  16796. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16797. level_flags = 0;
  16798. } else if (s.level < 6) {
  16799. level_flags = 1;
  16800. } else if (s.level === 6) {
  16801. level_flags = 2;
  16802. } else {
  16803. level_flags = 3;
  16804. }
  16805. header |= (level_flags << 6);
  16806. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16807. header += 31 - (header % 31);
  16808. s.status = BUSY_STATE;
  16809. putShortMSB(s, header);
  16810. /* Save the adler32 of the preset dictionary: */
  16811. if (s.strstart !== 0) {
  16812. putShortMSB(s, strm.adler >>> 16);
  16813. putShortMSB(s, strm.adler & 0xffff);
  16814. }
  16815. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16816. }
  16817. }
  16818. //#ifdef GZIP
  16819. if (s.status === EXTRA_STATE) {
  16820. if (s.gzhead.extra/* != Z_NULL*/) {
  16821. beg = s.pending; /* start of bytes to update crc */
  16822. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16823. if (s.pending === s.pending_buf_size) {
  16824. if (s.gzhead.hcrc && s.pending > beg) {
  16825. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16826. }
  16827. flush_pending(strm);
  16828. beg = s.pending;
  16829. if (s.pending === s.pending_buf_size) {
  16830. break;
  16831. }
  16832. }
  16833. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16834. s.gzindex++;
  16835. }
  16836. if (s.gzhead.hcrc && s.pending > beg) {
  16837. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16838. }
  16839. if (s.gzindex === s.gzhead.extra.length) {
  16840. s.gzindex = 0;
  16841. s.status = NAME_STATE;
  16842. }
  16843. }
  16844. else {
  16845. s.status = NAME_STATE;
  16846. }
  16847. }
  16848. if (s.status === NAME_STATE) {
  16849. if (s.gzhead.name/* != Z_NULL*/) {
  16850. beg = s.pending; /* start of bytes to update crc */
  16851. //int val;
  16852. do {
  16853. if (s.pending === s.pending_buf_size) {
  16854. if (s.gzhead.hcrc && s.pending > beg) {
  16855. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16856. }
  16857. flush_pending(strm);
  16858. beg = s.pending;
  16859. if (s.pending === s.pending_buf_size) {
  16860. val = 1;
  16861. break;
  16862. }
  16863. }
  16864. // JS specific: little magic to add zero terminator to end of string
  16865. if (s.gzindex < s.gzhead.name.length) {
  16866. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16867. } else {
  16868. val = 0;
  16869. }
  16870. put_byte(s, val);
  16871. } while (val !== 0);
  16872. if (s.gzhead.hcrc && s.pending > beg) {
  16873. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16874. }
  16875. if (val === 0) {
  16876. s.gzindex = 0;
  16877. s.status = COMMENT_STATE;
  16878. }
  16879. }
  16880. else {
  16881. s.status = COMMENT_STATE;
  16882. }
  16883. }
  16884. if (s.status === COMMENT_STATE) {
  16885. if (s.gzhead.comment/* != Z_NULL*/) {
  16886. beg = s.pending; /* start of bytes to update crc */
  16887. //int val;
  16888. do {
  16889. if (s.pending === s.pending_buf_size) {
  16890. if (s.gzhead.hcrc && s.pending > beg) {
  16891. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16892. }
  16893. flush_pending(strm);
  16894. beg = s.pending;
  16895. if (s.pending === s.pending_buf_size) {
  16896. val = 1;
  16897. break;
  16898. }
  16899. }
  16900. // JS specific: little magic to add zero terminator to end of string
  16901. if (s.gzindex < s.gzhead.comment.length) {
  16902. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16903. } else {
  16904. val = 0;
  16905. }
  16906. put_byte(s, val);
  16907. } while (val !== 0);
  16908. if (s.gzhead.hcrc && s.pending > beg) {
  16909. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16910. }
  16911. if (val === 0) {
  16912. s.status = HCRC_STATE;
  16913. }
  16914. }
  16915. else {
  16916. s.status = HCRC_STATE;
  16917. }
  16918. }
  16919. if (s.status === HCRC_STATE) {
  16920. if (s.gzhead.hcrc) {
  16921. if (s.pending + 2 > s.pending_buf_size) {
  16922. flush_pending(strm);
  16923. }
  16924. if (s.pending + 2 <= s.pending_buf_size) {
  16925. put_byte(s, strm.adler & 0xff);
  16926. put_byte(s, (strm.adler >> 8) & 0xff);
  16927. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16928. s.status = BUSY_STATE;
  16929. }
  16930. }
  16931. else {
  16932. s.status = BUSY_STATE;
  16933. }
  16934. }
  16935. //#endif
  16936. /* Flush as much pending output as possible */
  16937. if (s.pending !== 0) {
  16938. flush_pending(strm);
  16939. if (strm.avail_out === 0) {
  16940. /* Since avail_out is 0, deflate will be called again with
  16941. * more output space, but possibly with both pending and
  16942. * avail_in equal to zero. There won't be anything to do,
  16943. * but this is not an error situation so make sure we
  16944. * return OK instead of BUF_ERROR at next call of deflate:
  16945. */
  16946. s.last_flush = -1;
  16947. return Z_OK;
  16948. }
  16949. /* Make sure there is something to do and avoid duplicate consecutive
  16950. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16951. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16952. */
  16953. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16954. flush !== Z_FINISH) {
  16955. return err(strm, Z_BUF_ERROR);
  16956. }
  16957. /* User must not provide more input after the first FINISH: */
  16958. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16959. return err(strm, Z_BUF_ERROR);
  16960. }
  16961. /* Start a new block or continue the current one.
  16962. */
  16963. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16964. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16965. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16966. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16967. configuration_table[s.level].func(s, flush));
  16968. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16969. s.status = FINISH_STATE;
  16970. }
  16971. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16972. if (strm.avail_out === 0) {
  16973. s.last_flush = -1;
  16974. /* avoid BUF_ERROR next call, see above */
  16975. }
  16976. return Z_OK;
  16977. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16978. * of deflate should use the same flush parameter to make sure
  16979. * that the flush is complete. So we don't have to output an
  16980. * empty block here, this will be done at next call. This also
  16981. * ensures that for a very small output buffer, we emit at most
  16982. * one empty block.
  16983. */
  16984. }
  16985. if (bstate === BS_BLOCK_DONE) {
  16986. if (flush === Z_PARTIAL_FLUSH) {
  16987. trees._tr_align(s);
  16988. }
  16989. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16990. trees._tr_stored_block(s, 0, 0, false);
  16991. /* For a full flush, this empty block will be recognized
  16992. * as a special marker by inflate_sync().
  16993. */
  16994. if (flush === Z_FULL_FLUSH) {
  16995. /*** CLEAR_HASH(s); ***/ /* forget history */
  16996. zero(s.head); // Fill with NIL (= 0);
  16997. if (s.lookahead === 0) {
  16998. s.strstart = 0;
  16999. s.block_start = 0;
  17000. s.insert = 0;
  17001. }
  17002. }
  17003. }
  17004. flush_pending(strm);
  17005. if (strm.avail_out === 0) {
  17006. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  17007. return Z_OK;
  17008. }
  17009. }
  17010. }
  17011. //Assert(strm->avail_out > 0, "bug2");
  17012. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  17013. if (flush !== Z_FINISH) { return Z_OK; }
  17014. if (s.wrap <= 0) { return Z_STREAM_END; }
  17015. /* Write the trailer */
  17016. if (s.wrap === 2) {
  17017. put_byte(s, strm.adler & 0xff);
  17018. put_byte(s, (strm.adler >> 8) & 0xff);
  17019. put_byte(s, (strm.adler >> 16) & 0xff);
  17020. put_byte(s, (strm.adler >> 24) & 0xff);
  17021. put_byte(s, strm.total_in & 0xff);
  17022. put_byte(s, (strm.total_in >> 8) & 0xff);
  17023. put_byte(s, (strm.total_in >> 16) & 0xff);
  17024. put_byte(s, (strm.total_in >> 24) & 0xff);
  17025. }
  17026. else
  17027. {
  17028. putShortMSB(s, strm.adler >>> 16);
  17029. putShortMSB(s, strm.adler & 0xffff);
  17030. }
  17031. flush_pending(strm);
  17032. /* If avail_out is zero, the application will call deflate again
  17033. * to flush the rest.
  17034. */
  17035. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17036. /* write the trailer only once! */
  17037. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17038. }
  17039. function deflateEnd(strm) {
  17040. var status;
  17041. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17042. return Z_STREAM_ERROR;
  17043. }
  17044. status = strm.state.status;
  17045. if (status !== INIT_STATE &&
  17046. status !== EXTRA_STATE &&
  17047. status !== NAME_STATE &&
  17048. status !== COMMENT_STATE &&
  17049. status !== HCRC_STATE &&
  17050. status !== BUSY_STATE &&
  17051. status !== FINISH_STATE
  17052. ) {
  17053. return err(strm, Z_STREAM_ERROR);
  17054. }
  17055. strm.state = null;
  17056. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17057. }
  17058. /* =========================================================================
  17059. * Copy the source state to the destination state
  17060. */
  17061. //function deflateCopy(dest, source) {
  17062. //
  17063. //}
  17064. exports.deflateInit = deflateInit;
  17065. exports.deflateInit2 = deflateInit2;
  17066. exports.deflateReset = deflateReset;
  17067. exports.deflateResetKeep = deflateResetKeep;
  17068. exports.deflateSetHeader = deflateSetHeader;
  17069. exports.deflate = deflate;
  17070. exports.deflateEnd = deflateEnd;
  17071. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17072. /* Not implemented
  17073. exports.deflateBound = deflateBound;
  17074. exports.deflateCopy = deflateCopy;
  17075. exports.deflateSetDictionary = deflateSetDictionary;
  17076. exports.deflateParams = deflateParams;
  17077. exports.deflatePending = deflatePending;
  17078. exports.deflatePrime = deflatePrime;
  17079. exports.deflateTune = deflateTune;
  17080. */
  17081. },{"../utils/common":55,"./adler32":57,"./crc32":59,"./messages":65,"./trees":66}],61:[function(require,module,exports){
  17082. 'use strict';
  17083. function GZheader() {
  17084. /* true if compressed data believed to be text */
  17085. this.text = 0;
  17086. /* modification time */
  17087. this.time = 0;
  17088. /* extra flags (not used when writing a gzip file) */
  17089. this.xflags = 0;
  17090. /* operating system */
  17091. this.os = 0;
  17092. /* pointer to extra field or Z_NULL if none */
  17093. this.extra = null;
  17094. /* extra field length (valid if extra != Z_NULL) */
  17095. this.extra_len = 0; // Actually, we don't need it in JS,
  17096. // but leave for few code modifications
  17097. //
  17098. // Setup limits is not necessary because in js we should not preallocate memory
  17099. // for inflate use constant limit in 65536 bytes
  17100. //
  17101. /* space at extra (only when reading header) */
  17102. // this.extra_max = 0;
  17103. /* pointer to zero-terminated file name or Z_NULL */
  17104. this.name = '';
  17105. /* space at name (only when reading header) */
  17106. // this.name_max = 0;
  17107. /* pointer to zero-terminated comment or Z_NULL */
  17108. this.comment = '';
  17109. /* space at comment (only when reading header) */
  17110. // this.comm_max = 0;
  17111. /* true if there was or will be a header crc */
  17112. this.hcrc = 0;
  17113. /* true when done reading gzip header (not used when writing a gzip file) */
  17114. this.done = false;
  17115. }
  17116. module.exports = GZheader;
  17117. },{}],62:[function(require,module,exports){
  17118. 'use strict';
  17119. // See state defs from inflate.js
  17120. var BAD = 30; /* got a data error -- remain here until reset */
  17121. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17122. /*
  17123. Decode literal, length, and distance codes and write out the resulting
  17124. literal and match bytes until either not enough input or output is
  17125. available, an end-of-block is encountered, or a data error is encountered.
  17126. When large enough input and output buffers are supplied to inflate(), for
  17127. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17128. inflate execution time is spent in this routine.
  17129. Entry assumptions:
  17130. state.mode === LEN
  17131. strm.avail_in >= 6
  17132. strm.avail_out >= 258
  17133. start >= strm.avail_out
  17134. state.bits < 8
  17135. On return, state.mode is one of:
  17136. LEN -- ran out of enough output space or enough available input
  17137. TYPE -- reached end of block code, inflate() to interpret next block
  17138. BAD -- error in block data
  17139. Notes:
  17140. - The maximum input bits used by a length/distance pair is 15 bits for the
  17141. length code, 5 bits for the length extra, 15 bits for the distance code,
  17142. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17143. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17144. checking for available input while decoding.
  17145. - The maximum bytes that a single length/distance pair can output is 258
  17146. bytes, which is the maximum length that can be coded. inflate_fast()
  17147. requires strm.avail_out >= 258 for each loop to avoid checking for
  17148. output space.
  17149. */
  17150. module.exports = function inflate_fast(strm, start) {
  17151. var state;
  17152. var _in; /* local strm.input */
  17153. var last; /* have enough input while in < last */
  17154. var _out; /* local strm.output */
  17155. var beg; /* inflate()'s initial strm.output */
  17156. var end; /* while out < end, enough space available */
  17157. //#ifdef INFLATE_STRICT
  17158. var dmax; /* maximum distance from zlib header */
  17159. //#endif
  17160. var wsize; /* window size or zero if not using window */
  17161. var whave; /* valid bytes in the window */
  17162. var wnext; /* window write index */
  17163. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  17164. var s_window; /* allocated sliding window, if wsize != 0 */
  17165. var hold; /* local strm.hold */
  17166. var bits; /* local strm.bits */
  17167. var lcode; /* local strm.lencode */
  17168. var dcode; /* local strm.distcode */
  17169. var lmask; /* mask for first level of length codes */
  17170. var dmask; /* mask for first level of distance codes */
  17171. var here; /* retrieved table entry */
  17172. var op; /* code bits, operation, extra bits, or */
  17173. /* window position, window bytes to copy */
  17174. var len; /* match length, unused bytes */
  17175. var dist; /* match distance */
  17176. var from; /* where to copy match from */
  17177. var from_source;
  17178. var input, output; // JS specific, because we have no pointers
  17179. /* copy state to local variables */
  17180. state = strm.state;
  17181. //here = state.here;
  17182. _in = strm.next_in;
  17183. input = strm.input;
  17184. last = _in + (strm.avail_in - 5);
  17185. _out = strm.next_out;
  17186. output = strm.output;
  17187. beg = _out - (start - strm.avail_out);
  17188. end = _out + (strm.avail_out - 257);
  17189. //#ifdef INFLATE_STRICT
  17190. dmax = state.dmax;
  17191. //#endif
  17192. wsize = state.wsize;
  17193. whave = state.whave;
  17194. wnext = state.wnext;
  17195. s_window = state.window;
  17196. hold = state.hold;
  17197. bits = state.bits;
  17198. lcode = state.lencode;
  17199. dcode = state.distcode;
  17200. lmask = (1 << state.lenbits) - 1;
  17201. dmask = (1 << state.distbits) - 1;
  17202. /* decode literals and length/distances until end-of-block or not enough
  17203. input data or output space */
  17204. top:
  17205. do {
  17206. if (bits < 15) {
  17207. hold += input[_in++] << bits;
  17208. bits += 8;
  17209. hold += input[_in++] << bits;
  17210. bits += 8;
  17211. }
  17212. here = lcode[hold & lmask];
  17213. dolen:
  17214. for (;;) { // Goto emulation
  17215. op = here >>> 24/*here.bits*/;
  17216. hold >>>= op;
  17217. bits -= op;
  17218. op = (here >>> 16) & 0xff/*here.op*/;
  17219. if (op === 0) { /* literal */
  17220. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17221. // "inflate: literal '%c'\n" :
  17222. // "inflate: literal 0x%02x\n", here.val));
  17223. output[_out++] = here & 0xffff/*here.val*/;
  17224. }
  17225. else if (op & 16) { /* length base */
  17226. len = here & 0xffff/*here.val*/;
  17227. op &= 15; /* number of extra bits */
  17228. if (op) {
  17229. if (bits < op) {
  17230. hold += input[_in++] << bits;
  17231. bits += 8;
  17232. }
  17233. len += hold & ((1 << op) - 1);
  17234. hold >>>= op;
  17235. bits -= op;
  17236. }
  17237. //Tracevv((stderr, "inflate: length %u\n", len));
  17238. if (bits < 15) {
  17239. hold += input[_in++] << bits;
  17240. bits += 8;
  17241. hold += input[_in++] << bits;
  17242. bits += 8;
  17243. }
  17244. here = dcode[hold & dmask];
  17245. dodist:
  17246. for (;;) { // goto emulation
  17247. op = here >>> 24/*here.bits*/;
  17248. hold >>>= op;
  17249. bits -= op;
  17250. op = (here >>> 16) & 0xff/*here.op*/;
  17251. if (op & 16) { /* distance base */
  17252. dist = here & 0xffff/*here.val*/;
  17253. op &= 15; /* number of extra bits */
  17254. if (bits < op) {
  17255. hold += input[_in++] << bits;
  17256. bits += 8;
  17257. if (bits < op) {
  17258. hold += input[_in++] << bits;
  17259. bits += 8;
  17260. }
  17261. }
  17262. dist += hold & ((1 << op) - 1);
  17263. //#ifdef INFLATE_STRICT
  17264. if (dist > dmax) {
  17265. strm.msg = 'invalid distance too far back';
  17266. state.mode = BAD;
  17267. break top;
  17268. }
  17269. //#endif
  17270. hold >>>= op;
  17271. bits -= op;
  17272. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17273. op = _out - beg; /* max distance in output */
  17274. if (dist > op) { /* see if copy from window */
  17275. op = dist - op; /* distance back in window */
  17276. if (op > whave) {
  17277. if (state.sane) {
  17278. strm.msg = 'invalid distance too far back';
  17279. state.mode = BAD;
  17280. break top;
  17281. }
  17282. // (!) This block is disabled in zlib defailts,
  17283. // don't enable it for binary compatibility
  17284. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17285. // if (len <= op - whave) {
  17286. // do {
  17287. // output[_out++] = 0;
  17288. // } while (--len);
  17289. // continue top;
  17290. // }
  17291. // len -= op - whave;
  17292. // do {
  17293. // output[_out++] = 0;
  17294. // } while (--op > whave);
  17295. // if (op === 0) {
  17296. // from = _out - dist;
  17297. // do {
  17298. // output[_out++] = output[from++];
  17299. // } while (--len);
  17300. // continue top;
  17301. // }
  17302. //#endif
  17303. }
  17304. from = 0; // window index
  17305. from_source = s_window;
  17306. if (wnext === 0) { /* very common case */
  17307. from += wsize - op;
  17308. if (op < len) { /* some from window */
  17309. len -= op;
  17310. do {
  17311. output[_out++] = s_window[from++];
  17312. } while (--op);
  17313. from = _out - dist; /* rest from output */
  17314. from_source = output;
  17315. }
  17316. }
  17317. else if (wnext < op) { /* wrap around window */
  17318. from += wsize + wnext - op;
  17319. op -= wnext;
  17320. if (op < len) { /* some from end of window */
  17321. len -= op;
  17322. do {
  17323. output[_out++] = s_window[from++];
  17324. } while (--op);
  17325. from = 0;
  17326. if (wnext < len) { /* some from start of window */
  17327. op = wnext;
  17328. len -= op;
  17329. do {
  17330. output[_out++] = s_window[from++];
  17331. } while (--op);
  17332. from = _out - dist; /* rest from output */
  17333. from_source = output;
  17334. }
  17335. }
  17336. }
  17337. else { /* contiguous in window */
  17338. from += wnext - op;
  17339. if (op < len) { /* some from window */
  17340. len -= op;
  17341. do {
  17342. output[_out++] = s_window[from++];
  17343. } while (--op);
  17344. from = _out - dist; /* rest from output */
  17345. from_source = output;
  17346. }
  17347. }
  17348. while (len > 2) {
  17349. output[_out++] = from_source[from++];
  17350. output[_out++] = from_source[from++];
  17351. output[_out++] = from_source[from++];
  17352. len -= 3;
  17353. }
  17354. if (len) {
  17355. output[_out++] = from_source[from++];
  17356. if (len > 1) {
  17357. output[_out++] = from_source[from++];
  17358. }
  17359. }
  17360. }
  17361. else {
  17362. from = _out - dist; /* copy direct from output */
  17363. do { /* minimum length is three */
  17364. output[_out++] = output[from++];
  17365. output[_out++] = output[from++];
  17366. output[_out++] = output[from++];
  17367. len -= 3;
  17368. } while (len > 2);
  17369. if (len) {
  17370. output[_out++] = output[from++];
  17371. if (len > 1) {
  17372. output[_out++] = output[from++];
  17373. }
  17374. }
  17375. }
  17376. }
  17377. else if ((op & 64) === 0) { /* 2nd level distance code */
  17378. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17379. continue dodist;
  17380. }
  17381. else {
  17382. strm.msg = 'invalid distance code';
  17383. state.mode = BAD;
  17384. break top;
  17385. }
  17386. break; // need to emulate goto via "continue"
  17387. }
  17388. }
  17389. else if ((op & 64) === 0) { /* 2nd level length code */
  17390. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17391. continue dolen;
  17392. }
  17393. else if (op & 32) { /* end-of-block */
  17394. //Tracevv((stderr, "inflate: end of block\n"));
  17395. state.mode = TYPE;
  17396. break top;
  17397. }
  17398. else {
  17399. strm.msg = 'invalid literal/length code';
  17400. state.mode = BAD;
  17401. break top;
  17402. }
  17403. break; // need to emulate goto via "continue"
  17404. }
  17405. } while (_in < last && _out < end);
  17406. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17407. len = bits >> 3;
  17408. _in -= len;
  17409. bits -= len << 3;
  17410. hold &= (1 << bits) - 1;
  17411. /* update state and return */
  17412. strm.next_in = _in;
  17413. strm.next_out = _out;
  17414. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17415. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17416. state.hold = hold;
  17417. state.bits = bits;
  17418. return;
  17419. };
  17420. },{}],63:[function(require,module,exports){
  17421. 'use strict';
  17422. var utils = require('../utils/common');
  17423. var adler32 = require('./adler32');
  17424. var crc32 = require('./crc32');
  17425. var inflate_fast = require('./inffast');
  17426. var inflate_table = require('./inftrees');
  17427. var CODES = 0;
  17428. var LENS = 1;
  17429. var DISTS = 2;
  17430. /* Public constants ==========================================================*/
  17431. /* ===========================================================================*/
  17432. /* Allowed flush values; see deflate() and inflate() below for details */
  17433. //var Z_NO_FLUSH = 0;
  17434. //var Z_PARTIAL_FLUSH = 1;
  17435. //var Z_SYNC_FLUSH = 2;
  17436. //var Z_FULL_FLUSH = 3;
  17437. var Z_FINISH = 4;
  17438. var Z_BLOCK = 5;
  17439. var Z_TREES = 6;
  17440. /* Return codes for the compression/decompression functions. Negative values
  17441. * are errors, positive values are used for special but normal events.
  17442. */
  17443. var Z_OK = 0;
  17444. var Z_STREAM_END = 1;
  17445. var Z_NEED_DICT = 2;
  17446. //var Z_ERRNO = -1;
  17447. var Z_STREAM_ERROR = -2;
  17448. var Z_DATA_ERROR = -3;
  17449. var Z_MEM_ERROR = -4;
  17450. var Z_BUF_ERROR = -5;
  17451. //var Z_VERSION_ERROR = -6;
  17452. /* The deflate compression method */
  17453. var Z_DEFLATED = 8;
  17454. /* STATES ====================================================================*/
  17455. /* ===========================================================================*/
  17456. var HEAD = 1; /* i: waiting for magic header */
  17457. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17458. var TIME = 3; /* i: waiting for modification time (gzip) */
  17459. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17460. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17461. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17462. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17463. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17464. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17465. var DICTID = 10; /* i: waiting for dictionary check value */
  17466. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17467. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17468. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17469. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17470. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17471. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17472. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17473. var LENLENS = 18; /* i: waiting for code length code lengths */
  17474. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17475. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17476. var LEN = 21; /* i: waiting for length/lit/eob code */
  17477. var LENEXT = 22; /* i: waiting for length extra bits */
  17478. var DIST = 23; /* i: waiting for distance code */
  17479. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17480. var MATCH = 25; /* o: waiting for output space to copy string */
  17481. var LIT = 26; /* o: waiting for output space to write literal */
  17482. var CHECK = 27; /* i: waiting for 32-bit check value */
  17483. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17484. var DONE = 29; /* finished check, done -- remain here until reset */
  17485. var BAD = 30; /* got a data error -- remain here until reset */
  17486. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17487. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17488. /* ===========================================================================*/
  17489. var ENOUGH_LENS = 852;
  17490. var ENOUGH_DISTS = 592;
  17491. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17492. var MAX_WBITS = 15;
  17493. /* 32K LZ77 window */
  17494. var DEF_WBITS = MAX_WBITS;
  17495. function ZSWAP32(q) {
  17496. return (((q >>> 24) & 0xff) +
  17497. ((q >>> 8) & 0xff00) +
  17498. ((q & 0xff00) << 8) +
  17499. ((q & 0xff) << 24));
  17500. }
  17501. function InflateState() {
  17502. this.mode = 0; /* current inflate mode */
  17503. this.last = false; /* true if processing last block */
  17504. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17505. this.havedict = false; /* true if dictionary provided */
  17506. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17507. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17508. this.check = 0; /* protected copy of check value */
  17509. this.total = 0; /* protected copy of output count */
  17510. // TODO: may be {}
  17511. this.head = null; /* where to save gzip header information */
  17512. /* sliding window */
  17513. this.wbits = 0; /* log base 2 of requested window size */
  17514. this.wsize = 0; /* window size or zero if not using window */
  17515. this.whave = 0; /* valid bytes in the window */
  17516. this.wnext = 0; /* window write index */
  17517. this.window = null; /* allocated sliding window, if needed */
  17518. /* bit accumulator */
  17519. this.hold = 0; /* input bit accumulator */
  17520. this.bits = 0; /* number of bits in "in" */
  17521. /* for string and stored block copying */
  17522. this.length = 0; /* literal or length of data to copy */
  17523. this.offset = 0; /* distance back to copy string from */
  17524. /* for table and code decoding */
  17525. this.extra = 0; /* extra bits needed */
  17526. /* fixed and dynamic code tables */
  17527. this.lencode = null; /* starting table for length/literal codes */
  17528. this.distcode = null; /* starting table for distance codes */
  17529. this.lenbits = 0; /* index bits for lencode */
  17530. this.distbits = 0; /* index bits for distcode */
  17531. /* dynamic table building */
  17532. this.ncode = 0; /* number of code length code lengths */
  17533. this.nlen = 0; /* number of length code lengths */
  17534. this.ndist = 0; /* number of distance code lengths */
  17535. this.have = 0; /* number of code lengths in lens[] */
  17536. this.next = null; /* next available space in codes[] */
  17537. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17538. this.work = new utils.Buf16(288); /* work area for code table building */
  17539. /*
  17540. because we don't have pointers in js, we use lencode and distcode directly
  17541. as buffers so we don't need codes
  17542. */
  17543. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17544. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17545. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17546. this.sane = 0; /* if false, allow invalid distance too far */
  17547. this.back = 0; /* bits back of last unprocessed length/lit */
  17548. this.was = 0; /* initial length of match */
  17549. }
  17550. function inflateResetKeep(strm) {
  17551. var state;
  17552. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17553. state = strm.state;
  17554. strm.total_in = strm.total_out = state.total = 0;
  17555. strm.msg = ''; /*Z_NULL*/
  17556. if (state.wrap) { /* to support ill-conceived Java test suite */
  17557. strm.adler = state.wrap & 1;
  17558. }
  17559. state.mode = HEAD;
  17560. state.last = 0;
  17561. state.havedict = 0;
  17562. state.dmax = 32768;
  17563. state.head = null/*Z_NULL*/;
  17564. state.hold = 0;
  17565. state.bits = 0;
  17566. //state.lencode = state.distcode = state.next = state.codes;
  17567. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17568. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17569. state.sane = 1;
  17570. state.back = -1;
  17571. //Tracev((stderr, "inflate: reset\n"));
  17572. return Z_OK;
  17573. }
  17574. function inflateReset(strm) {
  17575. var state;
  17576. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17577. state = strm.state;
  17578. state.wsize = 0;
  17579. state.whave = 0;
  17580. state.wnext = 0;
  17581. return inflateResetKeep(strm);
  17582. }
  17583. function inflateReset2(strm, windowBits) {
  17584. var wrap;
  17585. var state;
  17586. /* get the state */
  17587. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17588. state = strm.state;
  17589. /* extract wrap request from windowBits parameter */
  17590. if (windowBits < 0) {
  17591. wrap = 0;
  17592. windowBits = -windowBits;
  17593. }
  17594. else {
  17595. wrap = (windowBits >> 4) + 1;
  17596. if (windowBits < 48) {
  17597. windowBits &= 15;
  17598. }
  17599. }
  17600. /* set number of window bits, free window if different */
  17601. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17602. return Z_STREAM_ERROR;
  17603. }
  17604. if (state.window !== null && state.wbits !== windowBits) {
  17605. state.window = null;
  17606. }
  17607. /* update state and reset the rest of it */
  17608. state.wrap = wrap;
  17609. state.wbits = windowBits;
  17610. return inflateReset(strm);
  17611. }
  17612. function inflateInit2(strm, windowBits) {
  17613. var ret;
  17614. var state;
  17615. if (!strm) { return Z_STREAM_ERROR; }
  17616. //strm.msg = Z_NULL; /* in case we return an error */
  17617. state = new InflateState();
  17618. //if (state === Z_NULL) return Z_MEM_ERROR;
  17619. //Tracev((stderr, "inflate: allocated\n"));
  17620. strm.state = state;
  17621. state.window = null/*Z_NULL*/;
  17622. ret = inflateReset2(strm, windowBits);
  17623. if (ret !== Z_OK) {
  17624. strm.state = null/*Z_NULL*/;
  17625. }
  17626. return ret;
  17627. }
  17628. function inflateInit(strm) {
  17629. return inflateInit2(strm, DEF_WBITS);
  17630. }
  17631. /*
  17632. Return state with length and distance decoding tables and index sizes set to
  17633. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17634. If BUILDFIXED is defined, then instead this routine builds the tables the
  17635. first time it's called, and returns those tables the first time and
  17636. thereafter. This reduces the size of the code by about 2K bytes, in
  17637. exchange for a little execution time. However, BUILDFIXED should not be
  17638. used for threaded applications, since the rewriting of the tables and virgin
  17639. may not be thread-safe.
  17640. */
  17641. var virgin = true;
  17642. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17643. function fixedtables(state) {
  17644. /* build fixed huffman tables if first call (may not be thread safe) */
  17645. if (virgin) {
  17646. var sym;
  17647. lenfix = new utils.Buf32(512);
  17648. distfix = new utils.Buf32(32);
  17649. /* literal/length table */
  17650. sym = 0;
  17651. while (sym < 144) { state.lens[sym++] = 8; }
  17652. while (sym < 256) { state.lens[sym++] = 9; }
  17653. while (sym < 280) { state.lens[sym++] = 7; }
  17654. while (sym < 288) { state.lens[sym++] = 8; }
  17655. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17656. /* distance table */
  17657. sym = 0;
  17658. while (sym < 32) { state.lens[sym++] = 5; }
  17659. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17660. /* do this just once */
  17661. virgin = false;
  17662. }
  17663. state.lencode = lenfix;
  17664. state.lenbits = 9;
  17665. state.distcode = distfix;
  17666. state.distbits = 5;
  17667. }
  17668. /*
  17669. Update the window with the last wsize (normally 32K) bytes written before
  17670. returning. If window does not exist yet, create it. This is only called
  17671. when a window is already in use, or when output has been written during this
  17672. inflate call, but the end of the deflate stream has not been reached yet.
  17673. It is also called to create a window for dictionary data when a dictionary
  17674. is loaded.
  17675. Providing output buffers larger than 32K to inflate() should provide a speed
  17676. advantage, since only the last 32K of output is copied to the sliding window
  17677. upon return from inflate(), and since all distances after the first 32K of
  17678. output will fall in the output data, making match copies simpler and faster.
  17679. The advantage may be dependent on the size of the processor's data caches.
  17680. */
  17681. function updatewindow(strm, src, end, copy) {
  17682. var dist;
  17683. var state = strm.state;
  17684. /* if it hasn't been done already, allocate space for the window */
  17685. if (state.window === null) {
  17686. state.wsize = 1 << state.wbits;
  17687. state.wnext = 0;
  17688. state.whave = 0;
  17689. state.window = new utils.Buf8(state.wsize);
  17690. }
  17691. /* copy state->wsize or less output bytes into the circular window */
  17692. if (copy >= state.wsize) {
  17693. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17694. state.wnext = 0;
  17695. state.whave = state.wsize;
  17696. }
  17697. else {
  17698. dist = state.wsize - state.wnext;
  17699. if (dist > copy) {
  17700. dist = copy;
  17701. }
  17702. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17703. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17704. copy -= dist;
  17705. if (copy) {
  17706. //zmemcpy(state->window, end - copy, copy);
  17707. utils.arraySet(state.window,src, end - copy, copy, 0);
  17708. state.wnext = copy;
  17709. state.whave = state.wsize;
  17710. }
  17711. else {
  17712. state.wnext += dist;
  17713. if (state.wnext === state.wsize) { state.wnext = 0; }
  17714. if (state.whave < state.wsize) { state.whave += dist; }
  17715. }
  17716. }
  17717. return 0;
  17718. }
  17719. function inflate(strm, flush) {
  17720. var state;
  17721. var input, output; // input/output buffers
  17722. var next; /* next input INDEX */
  17723. var put; /* next output INDEX */
  17724. var have, left; /* available input and output */
  17725. var hold; /* bit buffer */
  17726. var bits; /* bits in bit buffer */
  17727. var _in, _out; /* save starting available input and output */
  17728. var copy; /* number of stored or match bytes to copy */
  17729. var from; /* where to copy match bytes from */
  17730. var from_source;
  17731. var here = 0; /* current decoding table entry */
  17732. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17733. //var last; /* parent table entry */
  17734. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17735. var len; /* length to copy for repeats, bits to drop */
  17736. var ret; /* return code */
  17737. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17738. var opts;
  17739. var n; // temporary var for NEED_BITS
  17740. var order = /* permutation of code lengths */
  17741. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17742. if (!strm || !strm.state || !strm.output ||
  17743. (!strm.input && strm.avail_in !== 0)) {
  17744. return Z_STREAM_ERROR;
  17745. }
  17746. state = strm.state;
  17747. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17748. //--- LOAD() ---
  17749. put = strm.next_out;
  17750. output = strm.output;
  17751. left = strm.avail_out;
  17752. next = strm.next_in;
  17753. input = strm.input;
  17754. have = strm.avail_in;
  17755. hold = state.hold;
  17756. bits = state.bits;
  17757. //---
  17758. _in = have;
  17759. _out = left;
  17760. ret = Z_OK;
  17761. inf_leave: // goto emulation
  17762. for (;;) {
  17763. switch (state.mode) {
  17764. case HEAD:
  17765. if (state.wrap === 0) {
  17766. state.mode = TYPEDO;
  17767. break;
  17768. }
  17769. //=== NEEDBITS(16);
  17770. while (bits < 16) {
  17771. if (have === 0) { break inf_leave; }
  17772. have--;
  17773. hold += input[next++] << bits;
  17774. bits += 8;
  17775. }
  17776. //===//
  17777. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17778. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17779. //=== CRC2(state.check, hold);
  17780. hbuf[0] = hold & 0xff;
  17781. hbuf[1] = (hold >>> 8) & 0xff;
  17782. state.check = crc32(state.check, hbuf, 2, 0);
  17783. //===//
  17784. //=== INITBITS();
  17785. hold = 0;
  17786. bits = 0;
  17787. //===//
  17788. state.mode = FLAGS;
  17789. break;
  17790. }
  17791. state.flags = 0; /* expect zlib header */
  17792. if (state.head) {
  17793. state.head.done = false;
  17794. }
  17795. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17796. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17797. strm.msg = 'incorrect header check';
  17798. state.mode = BAD;
  17799. break;
  17800. }
  17801. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17802. strm.msg = 'unknown compression method';
  17803. state.mode = BAD;
  17804. break;
  17805. }
  17806. //--- DROPBITS(4) ---//
  17807. hold >>>= 4;
  17808. bits -= 4;
  17809. //---//
  17810. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17811. if (state.wbits === 0) {
  17812. state.wbits = len;
  17813. }
  17814. else if (len > state.wbits) {
  17815. strm.msg = 'invalid window size';
  17816. state.mode = BAD;
  17817. break;
  17818. }
  17819. state.dmax = 1 << len;
  17820. //Tracev((stderr, "inflate: zlib header ok\n"));
  17821. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17822. state.mode = hold & 0x200 ? DICTID : TYPE;
  17823. //=== INITBITS();
  17824. hold = 0;
  17825. bits = 0;
  17826. //===//
  17827. break;
  17828. case FLAGS:
  17829. //=== NEEDBITS(16); */
  17830. while (bits < 16) {
  17831. if (have === 0) { break inf_leave; }
  17832. have--;
  17833. hold += input[next++] << bits;
  17834. bits += 8;
  17835. }
  17836. //===//
  17837. state.flags = hold;
  17838. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17839. strm.msg = 'unknown compression method';
  17840. state.mode = BAD;
  17841. break;
  17842. }
  17843. if (state.flags & 0xe000) {
  17844. strm.msg = 'unknown header flags set';
  17845. state.mode = BAD;
  17846. break;
  17847. }
  17848. if (state.head) {
  17849. state.head.text = ((hold >> 8) & 1);
  17850. }
  17851. if (state.flags & 0x0200) {
  17852. //=== CRC2(state.check, hold);
  17853. hbuf[0] = hold & 0xff;
  17854. hbuf[1] = (hold >>> 8) & 0xff;
  17855. state.check = crc32(state.check, hbuf, 2, 0);
  17856. //===//
  17857. }
  17858. //=== INITBITS();
  17859. hold = 0;
  17860. bits = 0;
  17861. //===//
  17862. state.mode = TIME;
  17863. /* falls through */
  17864. case TIME:
  17865. //=== NEEDBITS(32); */
  17866. while (bits < 32) {
  17867. if (have === 0) { break inf_leave; }
  17868. have--;
  17869. hold += input[next++] << bits;
  17870. bits += 8;
  17871. }
  17872. //===//
  17873. if (state.head) {
  17874. state.head.time = hold;
  17875. }
  17876. if (state.flags & 0x0200) {
  17877. //=== CRC4(state.check, hold)
  17878. hbuf[0] = hold & 0xff;
  17879. hbuf[1] = (hold >>> 8) & 0xff;
  17880. hbuf[2] = (hold >>> 16) & 0xff;
  17881. hbuf[3] = (hold >>> 24) & 0xff;
  17882. state.check = crc32(state.check, hbuf, 4, 0);
  17883. //===
  17884. }
  17885. //=== INITBITS();
  17886. hold = 0;
  17887. bits = 0;
  17888. //===//
  17889. state.mode = OS;
  17890. /* falls through */
  17891. case OS:
  17892. //=== NEEDBITS(16); */
  17893. while (bits < 16) {
  17894. if (have === 0) { break inf_leave; }
  17895. have--;
  17896. hold += input[next++] << bits;
  17897. bits += 8;
  17898. }
  17899. //===//
  17900. if (state.head) {
  17901. state.head.xflags = (hold & 0xff);
  17902. state.head.os = (hold >> 8);
  17903. }
  17904. if (state.flags & 0x0200) {
  17905. //=== CRC2(state.check, hold);
  17906. hbuf[0] = hold & 0xff;
  17907. hbuf[1] = (hold >>> 8) & 0xff;
  17908. state.check = crc32(state.check, hbuf, 2, 0);
  17909. //===//
  17910. }
  17911. //=== INITBITS();
  17912. hold = 0;
  17913. bits = 0;
  17914. //===//
  17915. state.mode = EXLEN;
  17916. /* falls through */
  17917. case EXLEN:
  17918. if (state.flags & 0x0400) {
  17919. //=== NEEDBITS(16); */
  17920. while (bits < 16) {
  17921. if (have === 0) { break inf_leave; }
  17922. have--;
  17923. hold += input[next++] << bits;
  17924. bits += 8;
  17925. }
  17926. //===//
  17927. state.length = hold;
  17928. if (state.head) {
  17929. state.head.extra_len = hold;
  17930. }
  17931. if (state.flags & 0x0200) {
  17932. //=== CRC2(state.check, hold);
  17933. hbuf[0] = hold & 0xff;
  17934. hbuf[1] = (hold >>> 8) & 0xff;
  17935. state.check = crc32(state.check, hbuf, 2, 0);
  17936. //===//
  17937. }
  17938. //=== INITBITS();
  17939. hold = 0;
  17940. bits = 0;
  17941. //===//
  17942. }
  17943. else if (state.head) {
  17944. state.head.extra = null/*Z_NULL*/;
  17945. }
  17946. state.mode = EXTRA;
  17947. /* falls through */
  17948. case EXTRA:
  17949. if (state.flags & 0x0400) {
  17950. copy = state.length;
  17951. if (copy > have) { copy = have; }
  17952. if (copy) {
  17953. if (state.head) {
  17954. len = state.head.extra_len - state.length;
  17955. if (!state.head.extra) {
  17956. // Use untyped array for more conveniend processing later
  17957. state.head.extra = new Array(state.head.extra_len);
  17958. }
  17959. utils.arraySet(
  17960. state.head.extra,
  17961. input,
  17962. next,
  17963. // extra field is limited to 65536 bytes
  17964. // - no need for additional size check
  17965. copy,
  17966. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17967. len
  17968. );
  17969. //zmemcpy(state.head.extra + len, next,
  17970. // len + copy > state.head.extra_max ?
  17971. // state.head.extra_max - len : copy);
  17972. }
  17973. if (state.flags & 0x0200) {
  17974. state.check = crc32(state.check, input, copy, next);
  17975. }
  17976. have -= copy;
  17977. next += copy;
  17978. state.length -= copy;
  17979. }
  17980. if (state.length) { break inf_leave; }
  17981. }
  17982. state.length = 0;
  17983. state.mode = NAME;
  17984. /* falls through */
  17985. case NAME:
  17986. if (state.flags & 0x0800) {
  17987. if (have === 0) { break inf_leave; }
  17988. copy = 0;
  17989. do {
  17990. // TODO: 2 or 1 bytes?
  17991. len = input[next + copy++];
  17992. /* use constant limit because in js we should not preallocate memory */
  17993. if (state.head && len &&
  17994. (state.length < 65536 /*state.head.name_max*/)) {
  17995. state.head.name += String.fromCharCode(len);
  17996. }
  17997. } while (len && copy < have);
  17998. if (state.flags & 0x0200) {
  17999. state.check = crc32(state.check, input, copy, next);
  18000. }
  18001. have -= copy;
  18002. next += copy;
  18003. if (len) { break inf_leave; }
  18004. }
  18005. else if (state.head) {
  18006. state.head.name = null;
  18007. }
  18008. state.length = 0;
  18009. state.mode = COMMENT;
  18010. /* falls through */
  18011. case COMMENT:
  18012. if (state.flags & 0x1000) {
  18013. if (have === 0) { break inf_leave; }
  18014. copy = 0;
  18015. do {
  18016. len = input[next + copy++];
  18017. /* use constant limit because in js we should not preallocate memory */
  18018. if (state.head && len &&
  18019. (state.length < 65536 /*state.head.comm_max*/)) {
  18020. state.head.comment += String.fromCharCode(len);
  18021. }
  18022. } while (len && copy < have);
  18023. if (state.flags & 0x0200) {
  18024. state.check = crc32(state.check, input, copy, next);
  18025. }
  18026. have -= copy;
  18027. next += copy;
  18028. if (len) { break inf_leave; }
  18029. }
  18030. else if (state.head) {
  18031. state.head.comment = null;
  18032. }
  18033. state.mode = HCRC;
  18034. /* falls through */
  18035. case HCRC:
  18036. if (state.flags & 0x0200) {
  18037. //=== NEEDBITS(16); */
  18038. while (bits < 16) {
  18039. if (have === 0) { break inf_leave; }
  18040. have--;
  18041. hold += input[next++] << bits;
  18042. bits += 8;
  18043. }
  18044. //===//
  18045. if (hold !== (state.check & 0xffff)) {
  18046. strm.msg = 'header crc mismatch';
  18047. state.mode = BAD;
  18048. break;
  18049. }
  18050. //=== INITBITS();
  18051. hold = 0;
  18052. bits = 0;
  18053. //===//
  18054. }
  18055. if (state.head) {
  18056. state.head.hcrc = ((state.flags >> 9) & 1);
  18057. state.head.done = true;
  18058. }
  18059. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  18060. state.mode = TYPE;
  18061. break;
  18062. case DICTID:
  18063. //=== NEEDBITS(32); */
  18064. while (bits < 32) {
  18065. if (have === 0) { break inf_leave; }
  18066. have--;
  18067. hold += input[next++] << bits;
  18068. bits += 8;
  18069. }
  18070. //===//
  18071. strm.adler = state.check = ZSWAP32(hold);
  18072. //=== INITBITS();
  18073. hold = 0;
  18074. bits = 0;
  18075. //===//
  18076. state.mode = DICT;
  18077. /* falls through */
  18078. case DICT:
  18079. if (state.havedict === 0) {
  18080. //--- RESTORE() ---
  18081. strm.next_out = put;
  18082. strm.avail_out = left;
  18083. strm.next_in = next;
  18084. strm.avail_in = have;
  18085. state.hold = hold;
  18086. state.bits = bits;
  18087. //---
  18088. return Z_NEED_DICT;
  18089. }
  18090. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18091. state.mode = TYPE;
  18092. /* falls through */
  18093. case TYPE:
  18094. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18095. /* falls through */
  18096. case TYPEDO:
  18097. if (state.last) {
  18098. //--- BYTEBITS() ---//
  18099. hold >>>= bits & 7;
  18100. bits -= bits & 7;
  18101. //---//
  18102. state.mode = CHECK;
  18103. break;
  18104. }
  18105. //=== NEEDBITS(3); */
  18106. while (bits < 3) {
  18107. if (have === 0) { break inf_leave; }
  18108. have--;
  18109. hold += input[next++] << bits;
  18110. bits += 8;
  18111. }
  18112. //===//
  18113. state.last = (hold & 0x01)/*BITS(1)*/;
  18114. //--- DROPBITS(1) ---//
  18115. hold >>>= 1;
  18116. bits -= 1;
  18117. //---//
  18118. switch ((hold & 0x03)/*BITS(2)*/) {
  18119. case 0: /* stored block */
  18120. //Tracev((stderr, "inflate: stored block%s\n",
  18121. // state.last ? " (last)" : ""));
  18122. state.mode = STORED;
  18123. break;
  18124. case 1: /* fixed block */
  18125. fixedtables(state);
  18126. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18127. // state.last ? " (last)" : ""));
  18128. state.mode = LEN_; /* decode codes */
  18129. if (flush === Z_TREES) {
  18130. //--- DROPBITS(2) ---//
  18131. hold >>>= 2;
  18132. bits -= 2;
  18133. //---//
  18134. break inf_leave;
  18135. }
  18136. break;
  18137. case 2: /* dynamic block */
  18138. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18139. // state.last ? " (last)" : ""));
  18140. state.mode = TABLE;
  18141. break;
  18142. case 3:
  18143. strm.msg = 'invalid block type';
  18144. state.mode = BAD;
  18145. }
  18146. //--- DROPBITS(2) ---//
  18147. hold >>>= 2;
  18148. bits -= 2;
  18149. //---//
  18150. break;
  18151. case STORED:
  18152. //--- BYTEBITS() ---// /* go to byte boundary */
  18153. hold >>>= bits & 7;
  18154. bits -= bits & 7;
  18155. //---//
  18156. //=== NEEDBITS(32); */
  18157. while (bits < 32) {
  18158. if (have === 0) { break inf_leave; }
  18159. have--;
  18160. hold += input[next++] << bits;
  18161. bits += 8;
  18162. }
  18163. //===//
  18164. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18165. strm.msg = 'invalid stored block lengths';
  18166. state.mode = BAD;
  18167. break;
  18168. }
  18169. state.length = hold & 0xffff;
  18170. //Tracev((stderr, "inflate: stored length %u\n",
  18171. // state.length));
  18172. //=== INITBITS();
  18173. hold = 0;
  18174. bits = 0;
  18175. //===//
  18176. state.mode = COPY_;
  18177. if (flush === Z_TREES) { break inf_leave; }
  18178. /* falls through */
  18179. case COPY_:
  18180. state.mode = COPY;
  18181. /* falls through */
  18182. case COPY:
  18183. copy = state.length;
  18184. if (copy) {
  18185. if (copy > have) { copy = have; }
  18186. if (copy > left) { copy = left; }
  18187. if (copy === 0) { break inf_leave; }
  18188. //--- zmemcpy(put, next, copy); ---
  18189. utils.arraySet(output, input, next, copy, put);
  18190. //---//
  18191. have -= copy;
  18192. next += copy;
  18193. left -= copy;
  18194. put += copy;
  18195. state.length -= copy;
  18196. break;
  18197. }
  18198. //Tracev((stderr, "inflate: stored end\n"));
  18199. state.mode = TYPE;
  18200. break;
  18201. case TABLE:
  18202. //=== NEEDBITS(14); */
  18203. while (bits < 14) {
  18204. if (have === 0) { break inf_leave; }
  18205. have--;
  18206. hold += input[next++] << bits;
  18207. bits += 8;
  18208. }
  18209. //===//
  18210. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18211. //--- DROPBITS(5) ---//
  18212. hold >>>= 5;
  18213. bits -= 5;
  18214. //---//
  18215. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18216. //--- DROPBITS(5) ---//
  18217. hold >>>= 5;
  18218. bits -= 5;
  18219. //---//
  18220. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18221. //--- DROPBITS(4) ---//
  18222. hold >>>= 4;
  18223. bits -= 4;
  18224. //---//
  18225. //#ifndef PKZIP_BUG_WORKAROUND
  18226. if (state.nlen > 286 || state.ndist > 30) {
  18227. strm.msg = 'too many length or distance symbols';
  18228. state.mode = BAD;
  18229. break;
  18230. }
  18231. //#endif
  18232. //Tracev((stderr, "inflate: table sizes ok\n"));
  18233. state.have = 0;
  18234. state.mode = LENLENS;
  18235. /* falls through */
  18236. case LENLENS:
  18237. while (state.have < state.ncode) {
  18238. //=== NEEDBITS(3);
  18239. while (bits < 3) {
  18240. if (have === 0) { break inf_leave; }
  18241. have--;
  18242. hold += input[next++] << bits;
  18243. bits += 8;
  18244. }
  18245. //===//
  18246. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18247. //--- DROPBITS(3) ---//
  18248. hold >>>= 3;
  18249. bits -= 3;
  18250. //---//
  18251. }
  18252. while (state.have < 19) {
  18253. state.lens[order[state.have++]] = 0;
  18254. }
  18255. // We have separate tables & no pointers. 2 commented lines below not needed.
  18256. //state.next = state.codes;
  18257. //state.lencode = state.next;
  18258. // Switch to use dynamic table
  18259. state.lencode = state.lendyn;
  18260. state.lenbits = 7;
  18261. opts = {bits: state.lenbits};
  18262. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18263. state.lenbits = opts.bits;
  18264. if (ret) {
  18265. strm.msg = 'invalid code lengths set';
  18266. state.mode = BAD;
  18267. break;
  18268. }
  18269. //Tracev((stderr, "inflate: code lengths ok\n"));
  18270. state.have = 0;
  18271. state.mode = CODELENS;
  18272. /* falls through */
  18273. case CODELENS:
  18274. while (state.have < state.nlen + state.ndist) {
  18275. for (;;) {
  18276. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18277. here_bits = here >>> 24;
  18278. here_op = (here >>> 16) & 0xff;
  18279. here_val = here & 0xffff;
  18280. if ((here_bits) <= bits) { break; }
  18281. //--- PULLBYTE() ---//
  18282. if (have === 0) { break inf_leave; }
  18283. have--;
  18284. hold += input[next++] << bits;
  18285. bits += 8;
  18286. //---//
  18287. }
  18288. if (here_val < 16) {
  18289. //--- DROPBITS(here.bits) ---//
  18290. hold >>>= here_bits;
  18291. bits -= here_bits;
  18292. //---//
  18293. state.lens[state.have++] = here_val;
  18294. }
  18295. else {
  18296. if (here_val === 16) {
  18297. //=== NEEDBITS(here.bits + 2);
  18298. n = here_bits + 2;
  18299. while (bits < n) {
  18300. if (have === 0) { break inf_leave; }
  18301. have--;
  18302. hold += input[next++] << bits;
  18303. bits += 8;
  18304. }
  18305. //===//
  18306. //--- DROPBITS(here.bits) ---//
  18307. hold >>>= here_bits;
  18308. bits -= here_bits;
  18309. //---//
  18310. if (state.have === 0) {
  18311. strm.msg = 'invalid bit length repeat';
  18312. state.mode = BAD;
  18313. break;
  18314. }
  18315. len = state.lens[state.have - 1];
  18316. copy = 3 + (hold & 0x03);//BITS(2);
  18317. //--- DROPBITS(2) ---//
  18318. hold >>>= 2;
  18319. bits -= 2;
  18320. //---//
  18321. }
  18322. else if (here_val === 17) {
  18323. //=== NEEDBITS(here.bits + 3);
  18324. n = here_bits + 3;
  18325. while (bits < n) {
  18326. if (have === 0) { break inf_leave; }
  18327. have--;
  18328. hold += input[next++] << bits;
  18329. bits += 8;
  18330. }
  18331. //===//
  18332. //--- DROPBITS(here.bits) ---//
  18333. hold >>>= here_bits;
  18334. bits -= here_bits;
  18335. //---//
  18336. len = 0;
  18337. copy = 3 + (hold & 0x07);//BITS(3);
  18338. //--- DROPBITS(3) ---//
  18339. hold >>>= 3;
  18340. bits -= 3;
  18341. //---//
  18342. }
  18343. else {
  18344. //=== NEEDBITS(here.bits + 7);
  18345. n = here_bits + 7;
  18346. while (bits < n) {
  18347. if (have === 0) { break inf_leave; }
  18348. have--;
  18349. hold += input[next++] << bits;
  18350. bits += 8;
  18351. }
  18352. //===//
  18353. //--- DROPBITS(here.bits) ---//
  18354. hold >>>= here_bits;
  18355. bits -= here_bits;
  18356. //---//
  18357. len = 0;
  18358. copy = 11 + (hold & 0x7f);//BITS(7);
  18359. //--- DROPBITS(7) ---//
  18360. hold >>>= 7;
  18361. bits -= 7;
  18362. //---//
  18363. }
  18364. if (state.have + copy > state.nlen + state.ndist) {
  18365. strm.msg = 'invalid bit length repeat';
  18366. state.mode = BAD;
  18367. break;
  18368. }
  18369. while (copy--) {
  18370. state.lens[state.have++] = len;
  18371. }
  18372. }
  18373. }
  18374. /* handle error breaks in while */
  18375. if (state.mode === BAD) { break; }
  18376. /* check for end-of-block code (better have one) */
  18377. if (state.lens[256] === 0) {
  18378. strm.msg = 'invalid code -- missing end-of-block';
  18379. state.mode = BAD;
  18380. break;
  18381. }
  18382. /* build code tables -- note: do not change the lenbits or distbits
  18383. values here (9 and 6) without reading the comments in inftrees.h
  18384. concerning the ENOUGH constants, which depend on those values */
  18385. state.lenbits = 9;
  18386. opts = {bits: state.lenbits};
  18387. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18388. // We have separate tables & no pointers. 2 commented lines below not needed.
  18389. // state.next_index = opts.table_index;
  18390. state.lenbits = opts.bits;
  18391. // state.lencode = state.next;
  18392. if (ret) {
  18393. strm.msg = 'invalid literal/lengths set';
  18394. state.mode = BAD;
  18395. break;
  18396. }
  18397. state.distbits = 6;
  18398. //state.distcode.copy(state.codes);
  18399. // Switch to use dynamic table
  18400. state.distcode = state.distdyn;
  18401. opts = {bits: state.distbits};
  18402. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18403. // We have separate tables & no pointers. 2 commented lines below not needed.
  18404. // state.next_index = opts.table_index;
  18405. state.distbits = opts.bits;
  18406. // state.distcode = state.next;
  18407. if (ret) {
  18408. strm.msg = 'invalid distances set';
  18409. state.mode = BAD;
  18410. break;
  18411. }
  18412. //Tracev((stderr, 'inflate: codes ok\n'));
  18413. state.mode = LEN_;
  18414. if (flush === Z_TREES) { break inf_leave; }
  18415. /* falls through */
  18416. case LEN_:
  18417. state.mode = LEN;
  18418. /* falls through */
  18419. case LEN:
  18420. if (have >= 6 && left >= 258) {
  18421. //--- RESTORE() ---
  18422. strm.next_out = put;
  18423. strm.avail_out = left;
  18424. strm.next_in = next;
  18425. strm.avail_in = have;
  18426. state.hold = hold;
  18427. state.bits = bits;
  18428. //---
  18429. inflate_fast(strm, _out);
  18430. //--- LOAD() ---
  18431. put = strm.next_out;
  18432. output = strm.output;
  18433. left = strm.avail_out;
  18434. next = strm.next_in;
  18435. input = strm.input;
  18436. have = strm.avail_in;
  18437. hold = state.hold;
  18438. bits = state.bits;
  18439. //---
  18440. if (state.mode === TYPE) {
  18441. state.back = -1;
  18442. }
  18443. break;
  18444. }
  18445. state.back = 0;
  18446. for (;;) {
  18447. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18448. here_bits = here >>> 24;
  18449. here_op = (here >>> 16) & 0xff;
  18450. here_val = here & 0xffff;
  18451. if (here_bits <= bits) { break; }
  18452. //--- PULLBYTE() ---//
  18453. if (have === 0) { break inf_leave; }
  18454. have--;
  18455. hold += input[next++] << bits;
  18456. bits += 8;
  18457. //---//
  18458. }
  18459. if (here_op && (here_op & 0xf0) === 0) {
  18460. last_bits = here_bits;
  18461. last_op = here_op;
  18462. last_val = here_val;
  18463. for (;;) {
  18464. here = state.lencode[last_val +
  18465. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18466. here_bits = here >>> 24;
  18467. here_op = (here >>> 16) & 0xff;
  18468. here_val = here & 0xffff;
  18469. if ((last_bits + here_bits) <= bits) { break; }
  18470. //--- PULLBYTE() ---//
  18471. if (have === 0) { break inf_leave; }
  18472. have--;
  18473. hold += input[next++] << bits;
  18474. bits += 8;
  18475. //---//
  18476. }
  18477. //--- DROPBITS(last.bits) ---//
  18478. hold >>>= last_bits;
  18479. bits -= last_bits;
  18480. //---//
  18481. state.back += last_bits;
  18482. }
  18483. //--- DROPBITS(here.bits) ---//
  18484. hold >>>= here_bits;
  18485. bits -= here_bits;
  18486. //---//
  18487. state.back += here_bits;
  18488. state.length = here_val;
  18489. if (here_op === 0) {
  18490. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18491. // "inflate: literal '%c'\n" :
  18492. // "inflate: literal 0x%02x\n", here.val));
  18493. state.mode = LIT;
  18494. break;
  18495. }
  18496. if (here_op & 32) {
  18497. //Tracevv((stderr, "inflate: end of block\n"));
  18498. state.back = -1;
  18499. state.mode = TYPE;
  18500. break;
  18501. }
  18502. if (here_op & 64) {
  18503. strm.msg = 'invalid literal/length code';
  18504. state.mode = BAD;
  18505. break;
  18506. }
  18507. state.extra = here_op & 15;
  18508. state.mode = LENEXT;
  18509. /* falls through */
  18510. case LENEXT:
  18511. if (state.extra) {
  18512. //=== NEEDBITS(state.extra);
  18513. n = state.extra;
  18514. while (bits < n) {
  18515. if (have === 0) { break inf_leave; }
  18516. have--;
  18517. hold += input[next++] << bits;
  18518. bits += 8;
  18519. }
  18520. //===//
  18521. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18522. //--- DROPBITS(state.extra) ---//
  18523. hold >>>= state.extra;
  18524. bits -= state.extra;
  18525. //---//
  18526. state.back += state.extra;
  18527. }
  18528. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18529. state.was = state.length;
  18530. state.mode = DIST;
  18531. /* falls through */
  18532. case DIST:
  18533. for (;;) {
  18534. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18535. here_bits = here >>> 24;
  18536. here_op = (here >>> 16) & 0xff;
  18537. here_val = here & 0xffff;
  18538. if ((here_bits) <= bits) { break; }
  18539. //--- PULLBYTE() ---//
  18540. if (have === 0) { break inf_leave; }
  18541. have--;
  18542. hold += input[next++] << bits;
  18543. bits += 8;
  18544. //---//
  18545. }
  18546. if ((here_op & 0xf0) === 0) {
  18547. last_bits = here_bits;
  18548. last_op = here_op;
  18549. last_val = here_val;
  18550. for (;;) {
  18551. here = state.distcode[last_val +
  18552. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18553. here_bits = here >>> 24;
  18554. here_op = (here >>> 16) & 0xff;
  18555. here_val = here & 0xffff;
  18556. if ((last_bits + here_bits) <= bits) { break; }
  18557. //--- PULLBYTE() ---//
  18558. if (have === 0) { break inf_leave; }
  18559. have--;
  18560. hold += input[next++] << bits;
  18561. bits += 8;
  18562. //---//
  18563. }
  18564. //--- DROPBITS(last.bits) ---//
  18565. hold >>>= last_bits;
  18566. bits -= last_bits;
  18567. //---//
  18568. state.back += last_bits;
  18569. }
  18570. //--- DROPBITS(here.bits) ---//
  18571. hold >>>= here_bits;
  18572. bits -= here_bits;
  18573. //---//
  18574. state.back += here_bits;
  18575. if (here_op & 64) {
  18576. strm.msg = 'invalid distance code';
  18577. state.mode = BAD;
  18578. break;
  18579. }
  18580. state.offset = here_val;
  18581. state.extra = (here_op) & 15;
  18582. state.mode = DISTEXT;
  18583. /* falls through */
  18584. case DISTEXT:
  18585. if (state.extra) {
  18586. //=== NEEDBITS(state.extra);
  18587. n = state.extra;
  18588. while (bits < n) {
  18589. if (have === 0) { break inf_leave; }
  18590. have--;
  18591. hold += input[next++] << bits;
  18592. bits += 8;
  18593. }
  18594. //===//
  18595. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18596. //--- DROPBITS(state.extra) ---//
  18597. hold >>>= state.extra;
  18598. bits -= state.extra;
  18599. //---//
  18600. state.back += state.extra;
  18601. }
  18602. //#ifdef INFLATE_STRICT
  18603. if (state.offset > state.dmax) {
  18604. strm.msg = 'invalid distance too far back';
  18605. state.mode = BAD;
  18606. break;
  18607. }
  18608. //#endif
  18609. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18610. state.mode = MATCH;
  18611. /* falls through */
  18612. case MATCH:
  18613. if (left === 0) { break inf_leave; }
  18614. copy = _out - left;
  18615. if (state.offset > copy) { /* copy from window */
  18616. copy = state.offset - copy;
  18617. if (copy > state.whave) {
  18618. if (state.sane) {
  18619. strm.msg = 'invalid distance too far back';
  18620. state.mode = BAD;
  18621. break;
  18622. }
  18623. // (!) This block is disabled in zlib defailts,
  18624. // don't enable it for binary compatibility
  18625. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18626. // Trace((stderr, "inflate.c too far\n"));
  18627. // copy -= state.whave;
  18628. // if (copy > state.length) { copy = state.length; }
  18629. // if (copy > left) { copy = left; }
  18630. // left -= copy;
  18631. // state.length -= copy;
  18632. // do {
  18633. // output[put++] = 0;
  18634. // } while (--copy);
  18635. // if (state.length === 0) { state.mode = LEN; }
  18636. // break;
  18637. //#endif
  18638. }
  18639. if (copy > state.wnext) {
  18640. copy -= state.wnext;
  18641. from = state.wsize - copy;
  18642. }
  18643. else {
  18644. from = state.wnext - copy;
  18645. }
  18646. if (copy > state.length) { copy = state.length; }
  18647. from_source = state.window;
  18648. }
  18649. else { /* copy from output */
  18650. from_source = output;
  18651. from = put - state.offset;
  18652. copy = state.length;
  18653. }
  18654. if (copy > left) { copy = left; }
  18655. left -= copy;
  18656. state.length -= copy;
  18657. do {
  18658. output[put++] = from_source[from++];
  18659. } while (--copy);
  18660. if (state.length === 0) { state.mode = LEN; }
  18661. break;
  18662. case LIT:
  18663. if (left === 0) { break inf_leave; }
  18664. output[put++] = state.length;
  18665. left--;
  18666. state.mode = LEN;
  18667. break;
  18668. case CHECK:
  18669. if (state.wrap) {
  18670. //=== NEEDBITS(32);
  18671. while (bits < 32) {
  18672. if (have === 0) { break inf_leave; }
  18673. have--;
  18674. // Use '|' insdead of '+' to make sure that result is signed
  18675. hold |= input[next++] << bits;
  18676. bits += 8;
  18677. }
  18678. //===//
  18679. _out -= left;
  18680. strm.total_out += _out;
  18681. state.total += _out;
  18682. if (_out) {
  18683. strm.adler = state.check =
  18684. /*UPDATE(state.check, put - _out, _out);*/
  18685. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18686. }
  18687. _out = left;
  18688. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18689. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18690. strm.msg = 'incorrect data check';
  18691. state.mode = BAD;
  18692. break;
  18693. }
  18694. //=== INITBITS();
  18695. hold = 0;
  18696. bits = 0;
  18697. //===//
  18698. //Tracev((stderr, "inflate: check matches trailer\n"));
  18699. }
  18700. state.mode = LENGTH;
  18701. /* falls through */
  18702. case LENGTH:
  18703. if (state.wrap && state.flags) {
  18704. //=== NEEDBITS(32);
  18705. while (bits < 32) {
  18706. if (have === 0) { break inf_leave; }
  18707. have--;
  18708. hold += input[next++] << bits;
  18709. bits += 8;
  18710. }
  18711. //===//
  18712. if (hold !== (state.total & 0xffffffff)) {
  18713. strm.msg = 'incorrect length check';
  18714. state.mode = BAD;
  18715. break;
  18716. }
  18717. //=== INITBITS();
  18718. hold = 0;
  18719. bits = 0;
  18720. //===//
  18721. //Tracev((stderr, "inflate: length matches trailer\n"));
  18722. }
  18723. state.mode = DONE;
  18724. /* falls through */
  18725. case DONE:
  18726. ret = Z_STREAM_END;
  18727. break inf_leave;
  18728. case BAD:
  18729. ret = Z_DATA_ERROR;
  18730. break inf_leave;
  18731. case MEM:
  18732. return Z_MEM_ERROR;
  18733. case SYNC:
  18734. /* falls through */
  18735. default:
  18736. return Z_STREAM_ERROR;
  18737. }
  18738. }
  18739. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18740. /*
  18741. Return from inflate(), updating the total counts and the check value.
  18742. If there was no progress during the inflate() call, return a buffer
  18743. error. Call updatewindow() to create and/or update the window state.
  18744. Note: a memory error from inflate() is non-recoverable.
  18745. */
  18746. //--- RESTORE() ---
  18747. strm.next_out = put;
  18748. strm.avail_out = left;
  18749. strm.next_in = next;
  18750. strm.avail_in = have;
  18751. state.hold = hold;
  18752. state.bits = bits;
  18753. //---
  18754. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18755. (state.mode < CHECK || flush !== Z_FINISH))) {
  18756. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18757. state.mode = MEM;
  18758. return Z_MEM_ERROR;
  18759. }
  18760. }
  18761. _in -= strm.avail_in;
  18762. _out -= strm.avail_out;
  18763. strm.total_in += _in;
  18764. strm.total_out += _out;
  18765. state.total += _out;
  18766. if (state.wrap && _out) {
  18767. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18768. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18769. }
  18770. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18771. (state.mode === TYPE ? 128 : 0) +
  18772. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18773. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18774. ret = Z_BUF_ERROR;
  18775. }
  18776. return ret;
  18777. }
  18778. function inflateEnd(strm) {
  18779. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18780. return Z_STREAM_ERROR;
  18781. }
  18782. var state = strm.state;
  18783. if (state.window) {
  18784. state.window = null;
  18785. }
  18786. strm.state = null;
  18787. return Z_OK;
  18788. }
  18789. function inflateGetHeader(strm, head) {
  18790. var state;
  18791. /* check state */
  18792. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18793. state = strm.state;
  18794. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18795. /* save header structure */
  18796. state.head = head;
  18797. head.done = false;
  18798. return Z_OK;
  18799. }
  18800. exports.inflateReset = inflateReset;
  18801. exports.inflateReset2 = inflateReset2;
  18802. exports.inflateResetKeep = inflateResetKeep;
  18803. exports.inflateInit = inflateInit;
  18804. exports.inflateInit2 = inflateInit2;
  18805. exports.inflate = inflate;
  18806. exports.inflateEnd = inflateEnd;
  18807. exports.inflateGetHeader = inflateGetHeader;
  18808. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18809. /* Not implemented
  18810. exports.inflateCopy = inflateCopy;
  18811. exports.inflateGetDictionary = inflateGetDictionary;
  18812. exports.inflateMark = inflateMark;
  18813. exports.inflatePrime = inflatePrime;
  18814. exports.inflateSetDictionary = inflateSetDictionary;
  18815. exports.inflateSync = inflateSync;
  18816. exports.inflateSyncPoint = inflateSyncPoint;
  18817. exports.inflateUndermine = inflateUndermine;
  18818. */
  18819. },{"../utils/common":55,"./adler32":57,"./crc32":59,"./inffast":62,"./inftrees":64}],64:[function(require,module,exports){
  18820. 'use strict';
  18821. var utils = require('../utils/common');
  18822. var MAXBITS = 15;
  18823. var ENOUGH_LENS = 852;
  18824. var ENOUGH_DISTS = 592;
  18825. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18826. var CODES = 0;
  18827. var LENS = 1;
  18828. var DISTS = 2;
  18829. var lbase = [ /* Length codes 257..285 base */
  18830. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18831. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18832. ];
  18833. var lext = [ /* Length codes 257..285 extra */
  18834. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18835. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18836. ];
  18837. var dbase = [ /* Distance codes 0..29 base */
  18838. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18839. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18840. 8193, 12289, 16385, 24577, 0, 0
  18841. ];
  18842. var dext = [ /* Distance codes 0..29 extra */
  18843. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18844. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18845. 28, 28, 29, 29, 64, 64
  18846. ];
  18847. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18848. {
  18849. var bits = opts.bits;
  18850. //here = opts.here; /* table entry for duplication */
  18851. var len = 0; /* a code's length in bits */
  18852. var sym = 0; /* index of code symbols */
  18853. var min = 0, max = 0; /* minimum and maximum code lengths */
  18854. var root = 0; /* number of index bits for root table */
  18855. var curr = 0; /* number of index bits for current table */
  18856. var drop = 0; /* code bits to drop for sub-table */
  18857. var left = 0; /* number of prefix codes available */
  18858. var used = 0; /* code entries in table used */
  18859. var huff = 0; /* Huffman code */
  18860. var incr; /* for incrementing code, index */
  18861. var fill; /* index for replicating entries */
  18862. var low; /* low bits for current root entry */
  18863. var mask; /* mask for low root bits */
  18864. var next; /* next available space in table */
  18865. var base = null; /* base value table to use */
  18866. var base_index = 0;
  18867. // var shoextra; /* extra bits table to use */
  18868. var end; /* use base and extra for symbol > end */
  18869. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18870. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18871. var extra = null;
  18872. var extra_index = 0;
  18873. var here_bits, here_op, here_val;
  18874. /*
  18875. Process a set of code lengths to create a canonical Huffman code. The
  18876. code lengths are lens[0..codes-1]. Each length corresponds to the
  18877. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18878. symbols by length from short to long, and retaining the symbol order
  18879. for codes with equal lengths. Then the code starts with all zero bits
  18880. for the first code of the shortest length, and the codes are integer
  18881. increments for the same length, and zeros are appended as the length
  18882. increases. For the deflate format, these bits are stored backwards
  18883. from their more natural integer increment ordering, and so when the
  18884. decoding tables are built in the large loop below, the integer codes
  18885. are incremented backwards.
  18886. This routine assumes, but does not check, that all of the entries in
  18887. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18888. 1..MAXBITS is interpreted as that code length. zero means that that
  18889. symbol does not occur in this code.
  18890. The codes are sorted by computing a count of codes for each length,
  18891. creating from that a table of starting indices for each length in the
  18892. sorted table, and then entering the symbols in order in the sorted
  18893. table. The sorted table is work[], with that space being provided by
  18894. the caller.
  18895. The length counts are used for other purposes as well, i.e. finding
  18896. the minimum and maximum length codes, determining if there are any
  18897. codes at all, checking for a valid set of lengths, and looking ahead
  18898. at length counts to determine sub-table sizes when building the
  18899. decoding tables.
  18900. */
  18901. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18902. for (len = 0; len <= MAXBITS; len++) {
  18903. count[len] = 0;
  18904. }
  18905. for (sym = 0; sym < codes; sym++) {
  18906. count[lens[lens_index + sym]]++;
  18907. }
  18908. /* bound code lengths, force root to be within code lengths */
  18909. root = bits;
  18910. for (max = MAXBITS; max >= 1; max--) {
  18911. if (count[max] !== 0) { break; }
  18912. }
  18913. if (root > max) {
  18914. root = max;
  18915. }
  18916. if (max === 0) { /* no symbols to code at all */
  18917. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18918. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18919. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18920. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18921. //table.op[opts.table_index] = 64;
  18922. //table.bits[opts.table_index] = 1;
  18923. //table.val[opts.table_index++] = 0;
  18924. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18925. opts.bits = 1;
  18926. return 0; /* no symbols, but wait for decoding to report error */
  18927. }
  18928. for (min = 1; min < max; min++) {
  18929. if (count[min] !== 0) { break; }
  18930. }
  18931. if (root < min) {
  18932. root = min;
  18933. }
  18934. /* check for an over-subscribed or incomplete set of lengths */
  18935. left = 1;
  18936. for (len = 1; len <= MAXBITS; len++) {
  18937. left <<= 1;
  18938. left -= count[len];
  18939. if (left < 0) {
  18940. return -1;
  18941. } /* over-subscribed */
  18942. }
  18943. if (left > 0 && (type === CODES || max !== 1)) {
  18944. return -1; /* incomplete set */
  18945. }
  18946. /* generate offsets into symbol table for each length for sorting */
  18947. offs[1] = 0;
  18948. for (len = 1; len < MAXBITS; len++) {
  18949. offs[len + 1] = offs[len] + count[len];
  18950. }
  18951. /* sort symbols by length, by symbol order within each length */
  18952. for (sym = 0; sym < codes; sym++) {
  18953. if (lens[lens_index + sym] !== 0) {
  18954. work[offs[lens[lens_index + sym]]++] = sym;
  18955. }
  18956. }
  18957. /*
  18958. Create and fill in decoding tables. In this loop, the table being
  18959. filled is at next and has curr index bits. The code being used is huff
  18960. with length len. That code is converted to an index by dropping drop
  18961. bits off of the bottom. For codes where len is less than drop + curr,
  18962. those top drop + curr - len bits are incremented through all values to
  18963. fill the table with replicated entries.
  18964. root is the number of index bits for the root table. When len exceeds
  18965. root, sub-tables are created pointed to by the root entry with an index
  18966. of the low root bits of huff. This is saved in low to check for when a
  18967. new sub-table should be started. drop is zero when the root table is
  18968. being filled, and drop is root when sub-tables are being filled.
  18969. When a new sub-table is needed, it is necessary to look ahead in the
  18970. code lengths to determine what size sub-table is needed. The length
  18971. counts are used for this, and so count[] is decremented as codes are
  18972. entered in the tables.
  18973. used keeps track of how many table entries have been allocated from the
  18974. provided *table space. It is checked for LENS and DIST tables against
  18975. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18976. the initial root table size constants. See the comments in inftrees.h
  18977. for more information.
  18978. sym increments through all symbols, and the loop terminates when
  18979. all codes of length max, i.e. all codes, have been processed. This
  18980. routine permits incomplete codes, so another loop after this one fills
  18981. in the rest of the decoding tables with invalid code markers.
  18982. */
  18983. /* set up for code type */
  18984. // poor man optimization - use if-else instead of switch,
  18985. // to avoid deopts in old v8
  18986. if (type === CODES) {
  18987. base = extra = work; /* dummy value--not used */
  18988. end = 19;
  18989. } else if (type === LENS) {
  18990. base = lbase;
  18991. base_index -= 257;
  18992. extra = lext;
  18993. extra_index -= 257;
  18994. end = 256;
  18995. } else { /* DISTS */
  18996. base = dbase;
  18997. extra = dext;
  18998. end = -1;
  18999. }
  19000. /* initialize opts for loop */
  19001. huff = 0; /* starting code */
  19002. sym = 0; /* starting code symbol */
  19003. len = min; /* starting code length */
  19004. next = table_index; /* current table to fill in */
  19005. curr = root; /* current table index bits */
  19006. drop = 0; /* current bits to drop from code for index */
  19007. low = -1; /* trigger new sub-table when len > root */
  19008. used = 1 << root; /* use root table entries */
  19009. mask = used - 1; /* mask for comparing low */
  19010. /* check available table space */
  19011. if ((type === LENS && used > ENOUGH_LENS) ||
  19012. (type === DISTS && used > ENOUGH_DISTS)) {
  19013. return 1;
  19014. }
  19015. var i=0;
  19016. /* process all codes and make table entries */
  19017. for (;;) {
  19018. i++;
  19019. /* create table entry */
  19020. here_bits = len - drop;
  19021. if (work[sym] < end) {
  19022. here_op = 0;
  19023. here_val = work[sym];
  19024. }
  19025. else if (work[sym] > end) {
  19026. here_op = extra[extra_index + work[sym]];
  19027. here_val = base[base_index + work[sym]];
  19028. }
  19029. else {
  19030. here_op = 32 + 64; /* end of block */
  19031. here_val = 0;
  19032. }
  19033. /* replicate for those indices with low len bits equal to huff */
  19034. incr = 1 << (len - drop);
  19035. fill = 1 << curr;
  19036. min = fill; /* save offset to next table */
  19037. do {
  19038. fill -= incr;
  19039. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19040. } while (fill !== 0);
  19041. /* backwards increment the len-bit code huff */
  19042. incr = 1 << (len - 1);
  19043. while (huff & incr) {
  19044. incr >>= 1;
  19045. }
  19046. if (incr !== 0) {
  19047. huff &= incr - 1;
  19048. huff += incr;
  19049. } else {
  19050. huff = 0;
  19051. }
  19052. /* go to next symbol, update count, len */
  19053. sym++;
  19054. if (--count[len] === 0) {
  19055. if (len === max) { break; }
  19056. len = lens[lens_index + work[sym]];
  19057. }
  19058. /* create new sub-table if needed */
  19059. if (len > root && (huff & mask) !== low) {
  19060. /* if first time, transition to sub-tables */
  19061. if (drop === 0) {
  19062. drop = root;
  19063. }
  19064. /* increment past last table */
  19065. next += min; /* here min is 1 << curr */
  19066. /* determine length of next table */
  19067. curr = len - drop;
  19068. left = 1 << curr;
  19069. while (curr + drop < max) {
  19070. left -= count[curr + drop];
  19071. if (left <= 0) { break; }
  19072. curr++;
  19073. left <<= 1;
  19074. }
  19075. /* check for enough space */
  19076. used += 1 << curr;
  19077. if ((type === LENS && used > ENOUGH_LENS) ||
  19078. (type === DISTS && used > ENOUGH_DISTS)) {
  19079. return 1;
  19080. }
  19081. /* point entry in root table to sub-table */
  19082. low = huff & mask;
  19083. /*table.op[low] = curr;
  19084. table.bits[low] = root;
  19085. table.val[low] = next - opts.table_index;*/
  19086. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19087. }
  19088. }
  19089. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19090. at most one remaining entry, since if the code is incomplete, the
  19091. maximum code length that was allowed to get this far is one bit) */
  19092. if (huff !== 0) {
  19093. //table.op[next + huff] = 64; /* invalid code marker */
  19094. //table.bits[next + huff] = len - drop;
  19095. //table.val[next + huff] = 0;
  19096. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19097. }
  19098. /* set return parameters */
  19099. //opts.table_index += used;
  19100. opts.bits = root;
  19101. return 0;
  19102. };
  19103. },{"../utils/common":55}],65:[function(require,module,exports){
  19104. 'use strict';
  19105. module.exports = {
  19106. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  19107. '1': 'stream end', /* Z_STREAM_END 1 */
  19108. '0': '', /* Z_OK 0 */
  19109. '-1': 'file error', /* Z_ERRNO (-1) */
  19110. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19111. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19112. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19113. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19114. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19115. };
  19116. },{}],66:[function(require,module,exports){
  19117. 'use strict';
  19118. var utils = require('../utils/common');
  19119. /* Public constants ==========================================================*/
  19120. /* ===========================================================================*/
  19121. //var Z_FILTERED = 1;
  19122. //var Z_HUFFMAN_ONLY = 2;
  19123. //var Z_RLE = 3;
  19124. var Z_FIXED = 4;
  19125. //var Z_DEFAULT_STRATEGY = 0;
  19126. /* Possible values of the data_type field (though see inflate()) */
  19127. var Z_BINARY = 0;
  19128. var Z_TEXT = 1;
  19129. //var Z_ASCII = 1; // = Z_TEXT
  19130. var Z_UNKNOWN = 2;
  19131. /*============================================================================*/
  19132. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19133. // From zutil.h
  19134. var STORED_BLOCK = 0;
  19135. var STATIC_TREES = 1;
  19136. var DYN_TREES = 2;
  19137. /* The three kinds of block type */
  19138. var MIN_MATCH = 3;
  19139. var MAX_MATCH = 258;
  19140. /* The minimum and maximum match lengths */
  19141. // From deflate.h
  19142. /* ===========================================================================
  19143. * Internal compression state.
  19144. */
  19145. var LENGTH_CODES = 29;
  19146. /* number of length codes, not counting the special END_BLOCK code */
  19147. var LITERALS = 256;
  19148. /* number of literal bytes 0..255 */
  19149. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19150. /* number of Literal or Length codes, including the END_BLOCK code */
  19151. var D_CODES = 30;
  19152. /* number of distance codes */
  19153. var BL_CODES = 19;
  19154. /* number of codes used to transfer the bit lengths */
  19155. var HEAP_SIZE = 2*L_CODES + 1;
  19156. /* maximum heap size */
  19157. var MAX_BITS = 15;
  19158. /* All codes must not exceed MAX_BITS bits */
  19159. var Buf_size = 16;
  19160. /* size of bit buffer in bi_buf */
  19161. /* ===========================================================================
  19162. * Constants
  19163. */
  19164. var MAX_BL_BITS = 7;
  19165. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19166. var END_BLOCK = 256;
  19167. /* end of block literal code */
  19168. var REP_3_6 = 16;
  19169. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19170. var REPZ_3_10 = 17;
  19171. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19172. var REPZ_11_138 = 18;
  19173. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19174. var extra_lbits = /* extra bits for each length code */
  19175. [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];
  19176. var extra_dbits = /* extra bits for each distance code */
  19177. [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];
  19178. var extra_blbits = /* extra bits for each bit length code */
  19179. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19180. var bl_order =
  19181. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19182. /* The lengths of the bit length codes are sent in order of decreasing
  19183. * probability, to avoid transmitting the lengths for unused bit length codes.
  19184. */
  19185. /* ===========================================================================
  19186. * Local data. These are initialized only once.
  19187. */
  19188. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19189. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19190. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19191. var static_ltree = new Array((L_CODES+2) * 2);
  19192. zero(static_ltree);
  19193. /* The static literal tree. Since the bit lengths are imposed, there is no
  19194. * need for the L_CODES extra codes used during heap construction. However
  19195. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19196. * below).
  19197. */
  19198. var static_dtree = new Array(D_CODES * 2);
  19199. zero(static_dtree);
  19200. /* The static distance tree. (Actually a trivial tree since all codes use
  19201. * 5 bits.)
  19202. */
  19203. var _dist_code = new Array(DIST_CODE_LEN);
  19204. zero(_dist_code);
  19205. /* Distance codes. The first 256 values correspond to the distances
  19206. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19207. * the 15 bit distances.
  19208. */
  19209. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  19210. zero(_length_code);
  19211. /* length code for each normalized match length (0 == MIN_MATCH) */
  19212. var base_length = new Array(LENGTH_CODES);
  19213. zero(base_length);
  19214. /* First normalized length for each code (0 = MIN_MATCH) */
  19215. var base_dist = new Array(D_CODES);
  19216. zero(base_dist);
  19217. /* First normalized distance for each code (0 = distance of 1) */
  19218. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19219. this.static_tree = static_tree; /* static tree or NULL */
  19220. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19221. this.extra_base = extra_base; /* base index for extra_bits */
  19222. this.elems = elems; /* max number of elements in the tree */
  19223. this.max_length = max_length; /* max bit length for the codes */
  19224. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19225. this.has_stree = static_tree && static_tree.length;
  19226. };
  19227. var static_l_desc;
  19228. var static_d_desc;
  19229. var static_bl_desc;
  19230. var TreeDesc = function(dyn_tree, stat_desc) {
  19231. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19232. this.max_code = 0; /* largest code with non zero frequency */
  19233. this.stat_desc = stat_desc; /* the corresponding static tree */
  19234. };
  19235. function d_code(dist) {
  19236. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19237. }
  19238. /* ===========================================================================
  19239. * Output a short LSB first on the stream.
  19240. * IN assertion: there is enough room in pendingBuf.
  19241. */
  19242. function put_short (s, w) {
  19243. // put_byte(s, (uch)((w) & 0xff));
  19244. // put_byte(s, (uch)((ush)(w) >> 8));
  19245. s.pending_buf[s.pending++] = (w) & 0xff;
  19246. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19247. }
  19248. /* ===========================================================================
  19249. * Send a value on a given number of bits.
  19250. * IN assertion: length <= 16 and value fits in length bits.
  19251. */
  19252. function send_bits(s, value, length) {
  19253. if (s.bi_valid > (Buf_size - length)) {
  19254. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19255. put_short(s, s.bi_buf);
  19256. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19257. s.bi_valid += length - Buf_size;
  19258. } else {
  19259. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19260. s.bi_valid += length;
  19261. }
  19262. }
  19263. function send_code(s, c, tree) {
  19264. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19265. }
  19266. /* ===========================================================================
  19267. * Reverse the first len bits of a code, using straightforward code (a faster
  19268. * method would use a table)
  19269. * IN assertion: 1 <= len <= 15
  19270. */
  19271. function bi_reverse(code, len) {
  19272. var res = 0;
  19273. do {
  19274. res |= code & 1;
  19275. code >>>= 1;
  19276. res <<= 1;
  19277. } while (--len > 0);
  19278. return res >>> 1;
  19279. }
  19280. /* ===========================================================================
  19281. * Flush the bit buffer, keeping at most 7 bits in it.
  19282. */
  19283. function bi_flush(s) {
  19284. if (s.bi_valid === 16) {
  19285. put_short(s, s.bi_buf);
  19286. s.bi_buf = 0;
  19287. s.bi_valid = 0;
  19288. } else if (s.bi_valid >= 8) {
  19289. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19290. s.bi_buf >>= 8;
  19291. s.bi_valid -= 8;
  19292. }
  19293. }
  19294. /* ===========================================================================
  19295. * Compute the optimal bit lengths for a tree and update the total bit length
  19296. * for the current block.
  19297. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19298. * above are the tree nodes sorted by increasing frequency.
  19299. * OUT assertions: the field len is set to the optimal bit length, the
  19300. * array bl_count contains the frequencies for each bit length.
  19301. * The length opt_len is updated; static_len is also updated if stree is
  19302. * not null.
  19303. */
  19304. function gen_bitlen(s, desc)
  19305. // deflate_state *s;
  19306. // tree_desc *desc; /* the tree descriptor */
  19307. {
  19308. var tree = desc.dyn_tree;
  19309. var max_code = desc.max_code;
  19310. var stree = desc.stat_desc.static_tree;
  19311. var has_stree = desc.stat_desc.has_stree;
  19312. var extra = desc.stat_desc.extra_bits;
  19313. var base = desc.stat_desc.extra_base;
  19314. var max_length = desc.stat_desc.max_length;
  19315. var h; /* heap index */
  19316. var n, m; /* iterate over the tree elements */
  19317. var bits; /* bit length */
  19318. var xbits; /* extra bits */
  19319. var f; /* frequency */
  19320. var overflow = 0; /* number of elements with bit length too large */
  19321. for (bits = 0; bits <= MAX_BITS; bits++) {
  19322. s.bl_count[bits] = 0;
  19323. }
  19324. /* In a first pass, compute the optimal bit lengths (which may
  19325. * overflow in the case of the bit length tree).
  19326. */
  19327. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19328. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19329. n = s.heap[h];
  19330. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19331. if (bits > max_length) {
  19332. bits = max_length;
  19333. overflow++;
  19334. }
  19335. tree[n*2 + 1]/*.Len*/ = bits;
  19336. /* We overwrite tree[n].Dad which is no longer needed */
  19337. if (n > max_code) { continue; } /* not a leaf node */
  19338. s.bl_count[bits]++;
  19339. xbits = 0;
  19340. if (n >= base) {
  19341. xbits = extra[n-base];
  19342. }
  19343. f = tree[n * 2]/*.Freq*/;
  19344. s.opt_len += f * (bits + xbits);
  19345. if (has_stree) {
  19346. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19347. }
  19348. }
  19349. if (overflow === 0) { return; }
  19350. // Trace((stderr,"\nbit length overflow\n"));
  19351. /* This happens for example on obj2 and pic of the Calgary corpus */
  19352. /* Find the first bit length which could increase: */
  19353. do {
  19354. bits = max_length-1;
  19355. while (s.bl_count[bits] === 0) { bits--; }
  19356. s.bl_count[bits]--; /* move one leaf down the tree */
  19357. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19358. s.bl_count[max_length]--;
  19359. /* The brother of the overflow item also moves one step up,
  19360. * but this does not affect bl_count[max_length]
  19361. */
  19362. overflow -= 2;
  19363. } while (overflow > 0);
  19364. /* Now recompute all bit lengths, scanning in increasing frequency.
  19365. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19366. * lengths instead of fixing only the wrong ones. This idea is taken
  19367. * from 'ar' written by Haruhiko Okumura.)
  19368. */
  19369. for (bits = max_length; bits !== 0; bits--) {
  19370. n = s.bl_count[bits];
  19371. while (n !== 0) {
  19372. m = s.heap[--h];
  19373. if (m > max_code) { continue; }
  19374. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19375. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19376. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19377. tree[m*2 + 1]/*.Len*/ = bits;
  19378. }
  19379. n--;
  19380. }
  19381. }
  19382. }
  19383. /* ===========================================================================
  19384. * Generate the codes for a given tree and bit counts (which need not be
  19385. * optimal).
  19386. * IN assertion: the array bl_count contains the bit length statistics for
  19387. * the given tree and the field len is set for all tree elements.
  19388. * OUT assertion: the field code is set for all tree elements of non
  19389. * zero code length.
  19390. */
  19391. function gen_codes(tree, max_code, bl_count)
  19392. // ct_data *tree; /* the tree to decorate */
  19393. // int max_code; /* largest code with non zero frequency */
  19394. // ushf *bl_count; /* number of codes at each bit length */
  19395. {
  19396. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19397. var code = 0; /* running code value */
  19398. var bits; /* bit index */
  19399. var n; /* code index */
  19400. /* The distribution counts are first used to generate the code values
  19401. * without bit reversal.
  19402. */
  19403. for (bits = 1; bits <= MAX_BITS; bits++) {
  19404. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19405. }
  19406. /* Check that the bit counts in bl_count are consistent. The last code
  19407. * must be all ones.
  19408. */
  19409. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19410. // "inconsistent bit counts");
  19411. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19412. for (n = 0; n <= max_code; n++) {
  19413. var len = tree[n*2 + 1]/*.Len*/;
  19414. if (len === 0) { continue; }
  19415. /* Now reverse the bits */
  19416. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19417. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19418. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19419. }
  19420. }
  19421. /* ===========================================================================
  19422. * Initialize the various 'constant' tables.
  19423. */
  19424. function tr_static_init() {
  19425. var n; /* iterates over tree elements */
  19426. var bits; /* bit counter */
  19427. var length; /* length value */
  19428. var code; /* code value */
  19429. var dist; /* distance index */
  19430. var bl_count = new Array(MAX_BITS+1);
  19431. /* number of codes at each bit length for an optimal tree */
  19432. // do check in _tr_init()
  19433. //if (static_init_done) return;
  19434. /* For some embedded targets, global variables are not initialized: */
  19435. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19436. static_l_desc.static_tree = static_ltree;
  19437. static_l_desc.extra_bits = extra_lbits;
  19438. static_d_desc.static_tree = static_dtree;
  19439. static_d_desc.extra_bits = extra_dbits;
  19440. static_bl_desc.extra_bits = extra_blbits;
  19441. #endif*/
  19442. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19443. length = 0;
  19444. for (code = 0; code < LENGTH_CODES-1; code++) {
  19445. base_length[code] = length;
  19446. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19447. _length_code[length++] = code;
  19448. }
  19449. }
  19450. //Assert (length == 256, "tr_static_init: length != 256");
  19451. /* Note that the length 255 (match length 258) can be represented
  19452. * in two different ways: code 284 + 5 bits or code 285, so we
  19453. * overwrite length_code[255] to use the best encoding:
  19454. */
  19455. _length_code[length-1] = code;
  19456. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19457. dist = 0;
  19458. for (code = 0 ; code < 16; code++) {
  19459. base_dist[code] = dist;
  19460. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19461. _dist_code[dist++] = code;
  19462. }
  19463. }
  19464. //Assert (dist == 256, "tr_static_init: dist != 256");
  19465. dist >>= 7; /* from now on, all distances are divided by 128 */
  19466. for (; code < D_CODES; code++) {
  19467. base_dist[code] = dist << 7;
  19468. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19469. _dist_code[256 + dist++] = code;
  19470. }
  19471. }
  19472. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19473. /* Construct the codes of the static literal tree */
  19474. for (bits = 0; bits <= MAX_BITS; bits++) {
  19475. bl_count[bits] = 0;
  19476. }
  19477. n = 0;
  19478. while (n <= 143) {
  19479. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19480. n++;
  19481. bl_count[8]++;
  19482. }
  19483. while (n <= 255) {
  19484. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19485. n++;
  19486. bl_count[9]++;
  19487. }
  19488. while (n <= 279) {
  19489. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19490. n++;
  19491. bl_count[7]++;
  19492. }
  19493. while (n <= 287) {
  19494. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19495. n++;
  19496. bl_count[8]++;
  19497. }
  19498. /* Codes 286 and 287 do not exist, but we must include them in the
  19499. * tree construction to get a canonical Huffman tree (longest code
  19500. * all ones)
  19501. */
  19502. gen_codes(static_ltree, L_CODES+1, bl_count);
  19503. /* The static distance tree is trivial: */
  19504. for (n = 0; n < D_CODES; n++) {
  19505. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19506. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19507. }
  19508. // Now data ready and we can init static trees
  19509. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19510. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19511. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19512. //static_init_done = true;
  19513. }
  19514. /* ===========================================================================
  19515. * Initialize a new block.
  19516. */
  19517. function init_block(s) {
  19518. var n; /* iterates over tree elements */
  19519. /* Initialize the trees. */
  19520. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19521. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19522. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19523. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19524. s.opt_len = s.static_len = 0;
  19525. s.last_lit = s.matches = 0;
  19526. }
  19527. /* ===========================================================================
  19528. * Flush the bit buffer and align the output on a byte boundary
  19529. */
  19530. function bi_windup(s)
  19531. {
  19532. if (s.bi_valid > 8) {
  19533. put_short(s, s.bi_buf);
  19534. } else if (s.bi_valid > 0) {
  19535. //put_byte(s, (Byte)s->bi_buf);
  19536. s.pending_buf[s.pending++] = s.bi_buf;
  19537. }
  19538. s.bi_buf = 0;
  19539. s.bi_valid = 0;
  19540. }
  19541. /* ===========================================================================
  19542. * Copy a stored block, storing first the length and its
  19543. * one's complement if requested.
  19544. */
  19545. function copy_block(s, buf, len, header)
  19546. //DeflateState *s;
  19547. //charf *buf; /* the input data */
  19548. //unsigned len; /* its length */
  19549. //int header; /* true if block header must be written */
  19550. {
  19551. bi_windup(s); /* align on byte boundary */
  19552. if (header) {
  19553. put_short(s, len);
  19554. put_short(s, ~len);
  19555. }
  19556. // while (len--) {
  19557. // put_byte(s, *buf++);
  19558. // }
  19559. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19560. s.pending += len;
  19561. }
  19562. /* ===========================================================================
  19563. * Compares to subtrees, using the tree depth as tie breaker when
  19564. * the subtrees have equal frequency. This minimizes the worst case length.
  19565. */
  19566. function smaller(tree, n, m, depth) {
  19567. var _n2 = n*2;
  19568. var _m2 = m*2;
  19569. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19570. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19571. }
  19572. /* ===========================================================================
  19573. * Restore the heap property by moving down the tree starting at node k,
  19574. * exchanging a node with the smallest of its two sons if necessary, stopping
  19575. * when the heap property is re-established (each father smaller than its
  19576. * two sons).
  19577. */
  19578. function pqdownheap(s, tree, k)
  19579. // deflate_state *s;
  19580. // ct_data *tree; /* the tree to restore */
  19581. // int k; /* node to move down */
  19582. {
  19583. var v = s.heap[k];
  19584. var j = k << 1; /* left son of k */
  19585. while (j <= s.heap_len) {
  19586. /* Set j to the smallest of the two sons: */
  19587. if (j < s.heap_len &&
  19588. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19589. j++;
  19590. }
  19591. /* Exit if v is smaller than both sons */
  19592. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19593. /* Exchange v with the smallest son */
  19594. s.heap[k] = s.heap[j];
  19595. k = j;
  19596. /* And continue down the tree, setting j to the left son of k */
  19597. j <<= 1;
  19598. }
  19599. s.heap[k] = v;
  19600. }
  19601. // inlined manually
  19602. // var SMALLEST = 1;
  19603. /* ===========================================================================
  19604. * Send the block data compressed using the given Huffman trees
  19605. */
  19606. function compress_block(s, ltree, dtree)
  19607. // deflate_state *s;
  19608. // const ct_data *ltree; /* literal tree */
  19609. // const ct_data *dtree; /* distance tree */
  19610. {
  19611. var dist; /* distance of matched string */
  19612. var lc; /* match length or unmatched char (if dist == 0) */
  19613. var lx = 0; /* running index in l_buf */
  19614. var code; /* the code to send */
  19615. var extra; /* number of extra bits to send */
  19616. if (s.last_lit !== 0) {
  19617. do {
  19618. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19619. lc = s.pending_buf[s.l_buf + lx];
  19620. lx++;
  19621. if (dist === 0) {
  19622. send_code(s, lc, ltree); /* send a literal byte */
  19623. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19624. } else {
  19625. /* Here, lc is the match length - MIN_MATCH */
  19626. code = _length_code[lc];
  19627. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19628. extra = extra_lbits[code];
  19629. if (extra !== 0) {
  19630. lc -= base_length[code];
  19631. send_bits(s, lc, extra); /* send the extra length bits */
  19632. }
  19633. dist--; /* dist is now the match distance - 1 */
  19634. code = d_code(dist);
  19635. //Assert (code < D_CODES, "bad d_code");
  19636. send_code(s, code, dtree); /* send the distance code */
  19637. extra = extra_dbits[code];
  19638. if (extra !== 0) {
  19639. dist -= base_dist[code];
  19640. send_bits(s, dist, extra); /* send the extra distance bits */
  19641. }
  19642. } /* literal or match pair ? */
  19643. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19644. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19645. // "pendingBuf overflow");
  19646. } while (lx < s.last_lit);
  19647. }
  19648. send_code(s, END_BLOCK, ltree);
  19649. }
  19650. /* ===========================================================================
  19651. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19652. * Update the total bit length for the current block.
  19653. * IN assertion: the field freq is set for all tree elements.
  19654. * OUT assertions: the fields len and code are set to the optimal bit length
  19655. * and corresponding code. The length opt_len is updated; static_len is
  19656. * also updated if stree is not null. The field max_code is set.
  19657. */
  19658. function build_tree(s, desc)
  19659. // deflate_state *s;
  19660. // tree_desc *desc; /* the tree descriptor */
  19661. {
  19662. var tree = desc.dyn_tree;
  19663. var stree = desc.stat_desc.static_tree;
  19664. var has_stree = desc.stat_desc.has_stree;
  19665. var elems = desc.stat_desc.elems;
  19666. var n, m; /* iterate over heap elements */
  19667. var max_code = -1; /* largest code with non zero frequency */
  19668. var node; /* new node being created */
  19669. /* Construct the initial heap, with least frequent element in
  19670. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19671. * heap[0] is not used.
  19672. */
  19673. s.heap_len = 0;
  19674. s.heap_max = HEAP_SIZE;
  19675. for (n = 0; n < elems; n++) {
  19676. if (tree[n * 2]/*.Freq*/ !== 0) {
  19677. s.heap[++s.heap_len] = max_code = n;
  19678. s.depth[n] = 0;
  19679. } else {
  19680. tree[n*2 + 1]/*.Len*/ = 0;
  19681. }
  19682. }
  19683. /* The pkzip format requires that at least one distance code exists,
  19684. * and that at least one bit should be sent even if there is only one
  19685. * possible code. So to avoid special checks later on we force at least
  19686. * two codes of non zero frequency.
  19687. */
  19688. while (s.heap_len < 2) {
  19689. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19690. tree[node * 2]/*.Freq*/ = 1;
  19691. s.depth[node] = 0;
  19692. s.opt_len--;
  19693. if (has_stree) {
  19694. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19695. }
  19696. /* node is 0 or 1 so it does not have extra bits */
  19697. }
  19698. desc.max_code = max_code;
  19699. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19700. * establish sub-heaps of increasing lengths:
  19701. */
  19702. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19703. /* Construct the Huffman tree by repeatedly combining the least two
  19704. * frequent nodes.
  19705. */
  19706. node = elems; /* next internal node of the tree */
  19707. do {
  19708. //pqremove(s, tree, n); /* n = node of least frequency */
  19709. /*** pqremove ***/
  19710. n = s.heap[1/*SMALLEST*/];
  19711. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19712. pqdownheap(s, tree, 1/*SMALLEST*/);
  19713. /***/
  19714. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19715. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19716. s.heap[--s.heap_max] = m;
  19717. /* Create a new node father of n and m */
  19718. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19719. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19720. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19721. /* and insert the new node in the heap */
  19722. s.heap[1/*SMALLEST*/] = node++;
  19723. pqdownheap(s, tree, 1/*SMALLEST*/);
  19724. } while (s.heap_len >= 2);
  19725. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19726. /* At this point, the fields freq and dad are set. We can now
  19727. * generate the bit lengths.
  19728. */
  19729. gen_bitlen(s, desc);
  19730. /* The field len is now set, we can generate the bit codes */
  19731. gen_codes(tree, max_code, s.bl_count);
  19732. }
  19733. /* ===========================================================================
  19734. * Scan a literal or distance tree to determine the frequencies of the codes
  19735. * in the bit length tree.
  19736. */
  19737. function scan_tree(s, tree, max_code)
  19738. // deflate_state *s;
  19739. // ct_data *tree; /* the tree to be scanned */
  19740. // int max_code; /* and its largest code of non zero frequency */
  19741. {
  19742. var n; /* iterates over all tree elements */
  19743. var prevlen = -1; /* last emitted length */
  19744. var curlen; /* length of current code */
  19745. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19746. var count = 0; /* repeat count of the current code */
  19747. var max_count = 7; /* max repeat count */
  19748. var min_count = 4; /* min repeat count */
  19749. if (nextlen === 0) {
  19750. max_count = 138;
  19751. min_count = 3;
  19752. }
  19753. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19754. for (n = 0; n <= max_code; n++) {
  19755. curlen = nextlen;
  19756. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19757. if (++count < max_count && curlen === nextlen) {
  19758. continue;
  19759. } else if (count < min_count) {
  19760. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19761. } else if (curlen !== 0) {
  19762. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19763. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19764. } else if (count <= 10) {
  19765. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19766. } else {
  19767. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19768. }
  19769. count = 0;
  19770. prevlen = curlen;
  19771. if (nextlen === 0) {
  19772. max_count = 138;
  19773. min_count = 3;
  19774. } else if (curlen === nextlen) {
  19775. max_count = 6;
  19776. min_count = 3;
  19777. } else {
  19778. max_count = 7;
  19779. min_count = 4;
  19780. }
  19781. }
  19782. }
  19783. /* ===========================================================================
  19784. * Send a literal or distance tree in compressed form, using the codes in
  19785. * bl_tree.
  19786. */
  19787. function send_tree(s, tree, max_code)
  19788. // deflate_state *s;
  19789. // ct_data *tree; /* the tree to be scanned */
  19790. // int max_code; /* and its largest code of non zero frequency */
  19791. {
  19792. var n; /* iterates over all tree elements */
  19793. var prevlen = -1; /* last emitted length */
  19794. var curlen; /* length of current code */
  19795. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19796. var count = 0; /* repeat count of the current code */
  19797. var max_count = 7; /* max repeat count */
  19798. var min_count = 4; /* min repeat count */
  19799. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19800. if (nextlen === 0) {
  19801. max_count = 138;
  19802. min_count = 3;
  19803. }
  19804. for (n = 0; n <= max_code; n++) {
  19805. curlen = nextlen;
  19806. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19807. if (++count < max_count && curlen === nextlen) {
  19808. continue;
  19809. } else if (count < min_count) {
  19810. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19811. } else if (curlen !== 0) {
  19812. if (curlen !== prevlen) {
  19813. send_code(s, curlen, s.bl_tree);
  19814. count--;
  19815. }
  19816. //Assert(count >= 3 && count <= 6, " 3_6?");
  19817. send_code(s, REP_3_6, s.bl_tree);
  19818. send_bits(s, count-3, 2);
  19819. } else if (count <= 10) {
  19820. send_code(s, REPZ_3_10, s.bl_tree);
  19821. send_bits(s, count-3, 3);
  19822. } else {
  19823. send_code(s, REPZ_11_138, s.bl_tree);
  19824. send_bits(s, count-11, 7);
  19825. }
  19826. count = 0;
  19827. prevlen = curlen;
  19828. if (nextlen === 0) {
  19829. max_count = 138;
  19830. min_count = 3;
  19831. } else if (curlen === nextlen) {
  19832. max_count = 6;
  19833. min_count = 3;
  19834. } else {
  19835. max_count = 7;
  19836. min_count = 4;
  19837. }
  19838. }
  19839. }
  19840. /* ===========================================================================
  19841. * Construct the Huffman tree for the bit lengths and return the index in
  19842. * bl_order of the last bit length code to send.
  19843. */
  19844. function build_bl_tree(s) {
  19845. var max_blindex; /* index of last bit length code of non zero freq */
  19846. /* Determine the bit length frequencies for literal and distance trees */
  19847. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19848. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19849. /* Build the bit length tree: */
  19850. build_tree(s, s.bl_desc);
  19851. /* opt_len now includes the length of the tree representations, except
  19852. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19853. */
  19854. /* Determine the number of bit length codes to send. The pkzip format
  19855. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19856. * 3 but the actual value used is 4.)
  19857. */
  19858. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19859. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19860. break;
  19861. }
  19862. }
  19863. /* Update opt_len to include the bit length tree and counts */
  19864. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19865. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19866. // s->opt_len, s->static_len));
  19867. return max_blindex;
  19868. }
  19869. /* ===========================================================================
  19870. * Send the header for a block using dynamic Huffman trees: the counts, the
  19871. * lengths of the bit length codes, the literal tree and the distance tree.
  19872. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19873. */
  19874. function send_all_trees(s, lcodes, dcodes, blcodes)
  19875. // deflate_state *s;
  19876. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19877. {
  19878. var rank; /* index in bl_order */
  19879. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19880. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19881. // "too many codes");
  19882. //Tracev((stderr, "\nbl counts: "));
  19883. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19884. send_bits(s, dcodes-1, 5);
  19885. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19886. for (rank = 0; rank < blcodes; rank++) {
  19887. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19888. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19889. }
  19890. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19891. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19892. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19893. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19894. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19895. }
  19896. /* ===========================================================================
  19897. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19898. * - TEXT if the two conditions below are satisfied:
  19899. * a) There are no non-portable control characters belonging to the
  19900. * "black list" (0..6, 14..25, 28..31).
  19901. * b) There is at least one printable character belonging to the
  19902. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19903. * - BINARY otherwise.
  19904. * - The following partially-portable control characters form a
  19905. * "gray list" that is ignored in this detection algorithm:
  19906. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19907. * IN assertion: the fields Freq of dyn_ltree are set.
  19908. */
  19909. function detect_data_type(s) {
  19910. /* black_mask is the bit mask of black-listed bytes
  19911. * set bits 0..6, 14..25, and 28..31
  19912. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19913. */
  19914. var black_mask = 0xf3ffc07f;
  19915. var n;
  19916. /* Check for non-textual ("black-listed") bytes. */
  19917. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19918. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19919. return Z_BINARY;
  19920. }
  19921. }
  19922. /* Check for textual ("white-listed") bytes. */
  19923. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19924. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19925. return Z_TEXT;
  19926. }
  19927. for (n = 32; n < LITERALS; n++) {
  19928. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19929. return Z_TEXT;
  19930. }
  19931. }
  19932. /* There are no "black-listed" or "white-listed" bytes:
  19933. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19934. */
  19935. return Z_BINARY;
  19936. }
  19937. var static_init_done = false;
  19938. /* ===========================================================================
  19939. * Initialize the tree data structures for a new zlib stream.
  19940. */
  19941. function _tr_init(s)
  19942. {
  19943. if (!static_init_done) {
  19944. tr_static_init();
  19945. static_init_done = true;
  19946. }
  19947. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19948. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19949. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19950. s.bi_buf = 0;
  19951. s.bi_valid = 0;
  19952. /* Initialize the first block of the first file: */
  19953. init_block(s);
  19954. }
  19955. /* ===========================================================================
  19956. * Send a stored block
  19957. */
  19958. function _tr_stored_block(s, buf, stored_len, last)
  19959. //DeflateState *s;
  19960. //charf *buf; /* input block */
  19961. //ulg stored_len; /* length of input block */
  19962. //int last; /* one if this is the last block for a file */
  19963. {
  19964. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19965. copy_block(s, buf, stored_len, true); /* with header */
  19966. }
  19967. /* ===========================================================================
  19968. * Send one empty static block to give enough lookahead for inflate.
  19969. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19970. */
  19971. function _tr_align(s) {
  19972. send_bits(s, STATIC_TREES<<1, 3);
  19973. send_code(s, END_BLOCK, static_ltree);
  19974. bi_flush(s);
  19975. }
  19976. /* ===========================================================================
  19977. * Determine the best encoding for the current block: dynamic trees, static
  19978. * trees or store, and output the encoded block to the zip file.
  19979. */
  19980. function _tr_flush_block(s, buf, stored_len, last)
  19981. //DeflateState *s;
  19982. //charf *buf; /* input block, or NULL if too old */
  19983. //ulg stored_len; /* length of input block */
  19984. //int last; /* one if this is the last block for a file */
  19985. {
  19986. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19987. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19988. /* Build the Huffman trees unless a stored block is forced */
  19989. if (s.level > 0) {
  19990. /* Check if the file is binary or text */
  19991. if (s.strm.data_type === Z_UNKNOWN) {
  19992. s.strm.data_type = detect_data_type(s);
  19993. }
  19994. /* Construct the literal and distance trees */
  19995. build_tree(s, s.l_desc);
  19996. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19997. // s->static_len));
  19998. build_tree(s, s.d_desc);
  19999. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  20000. // s->static_len));
  20001. /* At this point, opt_len and static_len are the total bit lengths of
  20002. * the compressed block data, excluding the tree representations.
  20003. */
  20004. /* Build the bit length tree for the above two trees, and get the index
  20005. * in bl_order of the last bit length code to send.
  20006. */
  20007. max_blindex = build_bl_tree(s);
  20008. /* Determine the best encoding. Compute the block lengths in bytes. */
  20009. opt_lenb = (s.opt_len+3+7) >>> 3;
  20010. static_lenb = (s.static_len+3+7) >>> 3;
  20011. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  20012. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  20013. // s->last_lit));
  20014. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  20015. } else {
  20016. // Assert(buf != (char*)0, "lost buf");
  20017. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20018. }
  20019. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  20020. /* 4: two words for the lengths */
  20021. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20022. * Otherwise we can't have processed more than WSIZE input bytes since
  20023. * the last block flush, because compression would have been
  20024. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20025. * transform a block into a stored block.
  20026. */
  20027. _tr_stored_block(s, buf, stored_len, last);
  20028. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20029. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  20030. compress_block(s, static_ltree, static_dtree);
  20031. } else {
  20032. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  20033. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  20034. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20035. }
  20036. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20037. /* The above check is made mod 2^32, for files larger than 512 MB
  20038. * and uLong implemented on 32 bits.
  20039. */
  20040. init_block(s);
  20041. if (last) {
  20042. bi_windup(s);
  20043. }
  20044. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20045. // s->compressed_len-7*last));
  20046. }
  20047. /* ===========================================================================
  20048. * Save the match info and tally the frequency counts. Return true if
  20049. * the current block must be flushed.
  20050. */
  20051. function _tr_tally(s, dist, lc)
  20052. // deflate_state *s;
  20053. // unsigned dist; /* distance of matched string */
  20054. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20055. {
  20056. //var out_length, in_length, dcode;
  20057. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20058. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20059. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20060. s.last_lit++;
  20061. if (dist === 0) {
  20062. /* lc is the unmatched char */
  20063. s.dyn_ltree[lc*2]/*.Freq*/++;
  20064. } else {
  20065. s.matches++;
  20066. /* Here, lc is the match length - MIN_MATCH */
  20067. dist--; /* dist = match distance - 1 */
  20068. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20069. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20070. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20071. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  20072. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20073. }
  20074. // (!) This block is disabled in zlib defailts,
  20075. // don't enable it for binary compatibility
  20076. //#ifdef TRUNCATE_BLOCK
  20077. // /* Try to guess if it is profitable to stop the current block here */
  20078. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20079. // /* Compute an upper bound for the compressed length */
  20080. // out_length = s.last_lit*8;
  20081. // in_length = s.strstart - s.block_start;
  20082. //
  20083. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20084. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20085. // }
  20086. // out_length >>>= 3;
  20087. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20088. // // s->last_lit, in_length, out_length,
  20089. // // 100L - out_length*100L/in_length));
  20090. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20091. // return true;
  20092. // }
  20093. // }
  20094. //#endif
  20095. return (s.last_lit === s.lit_bufsize-1);
  20096. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20097. * on 16 bit machines and because stored blocks are restricted to
  20098. * 64K-1 bytes.
  20099. */
  20100. }
  20101. exports._tr_init = _tr_init;
  20102. exports._tr_stored_block = _tr_stored_block;
  20103. exports._tr_flush_block = _tr_flush_block;
  20104. exports._tr_tally = _tr_tally;
  20105. exports._tr_align = _tr_align;
  20106. },{"../utils/common":55}],67:[function(require,module,exports){
  20107. 'use strict';
  20108. function ZStream() {
  20109. /* next input byte */
  20110. this.input = null; // JS specific, because we have no pointers
  20111. this.next_in = 0;
  20112. /* number of bytes available at input */
  20113. this.avail_in = 0;
  20114. /* total number of input bytes read so far */
  20115. this.total_in = 0;
  20116. /* next output byte should be put there */
  20117. this.output = null; // JS specific, because we have no pointers
  20118. this.next_out = 0;
  20119. /* remaining free space at output */
  20120. this.avail_out = 0;
  20121. /* total number of bytes output so far */
  20122. this.total_out = 0;
  20123. /* last error message, NULL if no error */
  20124. this.msg = ''/*Z_NULL*/;
  20125. /* not visible by applications */
  20126. this.state = null;
  20127. /* best guess about the data type: binary or text */
  20128. this.data_type = 2/*Z_UNKNOWN*/;
  20129. /* adler32 value of the uncompressed data */
  20130. this.adler = 0;
  20131. }
  20132. module.exports = ZStream;
  20133. },{}],68:[function(require,module,exports){
  20134. /* Copyright @ 2015 Atlassian Pty Ltd
  20135. *
  20136. * Licensed under the Apache License, Version 2.0 (the "License");
  20137. * you may not use this file except in compliance with the License.
  20138. * You may obtain a copy of the License at
  20139. *
  20140. * http://www.apache.org/licenses/LICENSE-2.0
  20141. *
  20142. * Unless required by applicable law or agreed to in writing, software
  20143. * distributed under the License is distributed on an "AS IS" BASIS,
  20144. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20145. * See the License for the specific language governing permissions and
  20146. * limitations under the License.
  20147. */
  20148. module.exports = function arrayEquals(array) {
  20149. // if the other array is a falsy value, return
  20150. if (!array)
  20151. return false;
  20152. // compare lengths - can save a lot of time
  20153. if (this.length != array.length)
  20154. return false;
  20155. for (var i = 0, l = this.length; i < l; i++) {
  20156. // Check if we have nested arrays
  20157. if (this[i] instanceof Array && array[i] instanceof Array) {
  20158. // recurse into the nested arrays
  20159. if (!arrayEquals.apply(this[i], [array[i]]))
  20160. return false;
  20161. } else if (this[i] != array[i]) {
  20162. // Warning - two different object instances will never be equal:
  20163. // {x:20} != {x:20}
  20164. return false;
  20165. }
  20166. }
  20167. return true;
  20168. };
  20169. },{}],69:[function(require,module,exports){
  20170. /* Copyright @ 2015 Atlassian Pty Ltd
  20171. *
  20172. * Licensed under the Apache License, Version 2.0 (the "License");
  20173. * you may not use this file except in compliance with the License.
  20174. * You may obtain a copy of the License at
  20175. *
  20176. * http://www.apache.org/licenses/LICENSE-2.0
  20177. *
  20178. * Unless required by applicable law or agreed to in writing, software
  20179. * distributed under the License is distributed on an "AS IS" BASIS,
  20180. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20181. * See the License for the specific language governing permissions and
  20182. * limitations under the License.
  20183. */
  20184. exports.Interop = require('./interop');
  20185. },{"./interop":70}],70:[function(require,module,exports){
  20186. /* Copyright @ 2015 Atlassian Pty Ltd
  20187. *
  20188. * Licensed under the Apache License, Version 2.0 (the "License");
  20189. * you may not use this file except in compliance with the License.
  20190. * You may obtain a copy of the License at
  20191. *
  20192. * http://www.apache.org/licenses/LICENSE-2.0
  20193. *
  20194. * Unless required by applicable law or agreed to in writing, software
  20195. * distributed under the License is distributed on an "AS IS" BASIS,
  20196. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20197. * See the License for the specific language governing permissions and
  20198. * limitations under the License.
  20199. */
  20200. /* global RTCSessionDescription */
  20201. /* jshint -W097 */
  20202. "use strict";
  20203. var transform = require('./transform');
  20204. var arrayEquals = require('./array-equals');
  20205. function Interop() {
  20206. /**
  20207. * This map holds the most recent Unified Plan offer/answer SDP that was
  20208. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  20209. * the SDP string as values.
  20210. *
  20211. * @type {{}}
  20212. */
  20213. this.cache = {};
  20214. }
  20215. module.exports = Interop;
  20216. /**
  20217. * Returns the index of the first m-line with the given media type and with a
  20218. * direction which allows sending, in the last Unified Plan description with
  20219. * type "answer" converted to Plan B. Returns {null} if there is no saved
  20220. * answer, or if none of its m-lines with the given type allow sending.
  20221. * @param type the media type ("audio" or "video").
  20222. * @returns {*}
  20223. */
  20224. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  20225. if (!this.cache.answer) {
  20226. return null;
  20227. }
  20228. var session = transform.parse(this.cache.answer);
  20229. if (session && session.media && Array.isArray(session.media)){
  20230. for (var i = 0; i < session.media.length; i++) {
  20231. if (session.media[i].type == type &&
  20232. (!session.media[i].direction /* default to sendrecv */ ||
  20233. session.media[i].direction === 'sendrecv' ||
  20234. session.media[i].direction === 'sendonly')){
  20235. return i;
  20236. }
  20237. }
  20238. }
  20239. return null;
  20240. };
  20241. /**
  20242. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  20243. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  20244. * application.
  20245. *
  20246. * @param desc
  20247. * @returns {*}
  20248. */
  20249. Interop.prototype.toPlanB = function(desc) {
  20250. var self = this;
  20251. //#region Preliminary input validation.
  20252. if (typeof desc !== 'object' || desc === null ||
  20253. typeof desc.sdp !== 'string') {
  20254. console.warn('An empty description was passed as an argument.');
  20255. return desc;
  20256. }
  20257. // Objectify the SDP for easier manipulation.
  20258. var session = transform.parse(desc.sdp);
  20259. // If the SDP contains no media, there's nothing to transform.
  20260. if (typeof session.media === 'undefined' ||
  20261. !Array.isArray(session.media) || session.media.length === 0) {
  20262. console.warn('The description has no media.');
  20263. return desc;
  20264. }
  20265. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  20266. // SDP has a video, an audio and a data "channel" at most.
  20267. if (session.media.length <= 3 && session.media.every(function(m) {
  20268. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20269. })) {
  20270. console.warn('This description does not look like Unified Plan.');
  20271. return desc;
  20272. }
  20273. //#endregion
  20274. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  20275. var sdp = desc.sdp;
  20276. var rewrite = false;
  20277. for (var i = 0; i < session.media.length; i++) {
  20278. var uLine = session.media[i];
  20279. uLine.rtp.forEach(function(rtp) {
  20280. if (rtp.codec === 'NULL')
  20281. {
  20282. rewrite = true;
  20283. var offer = transform.parse(self.cache['offer']);
  20284. rtp.codec = offer.media[i].rtp[0].codec;
  20285. }
  20286. });
  20287. };
  20288. if (rewrite) {
  20289. sdp = transform.write(session);
  20290. }
  20291. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  20292. // -> Unified Plan transformation.
  20293. this.cache[desc.type] = sdp;
  20294. //#region Convert from Unified Plan to Plan B.
  20295. // We rebuild the session.media array.
  20296. var media = session.media;
  20297. session.media = [];
  20298. // Associative array that maps channel types to channel objects for fast
  20299. // access to channel objects by their type, e.g. type2bl['audio']->channel
  20300. // obj.
  20301. var type2bl = {};
  20302. // Used to build the group:BUNDLE value after the channels construction
  20303. // loop.
  20304. var types = [];
  20305. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  20306. media.forEach(function(uLine) {
  20307. // rtcp-mux is required in the Plan B SDP.
  20308. if ((typeof uLine.rtcpMux !== 'string' ||
  20309. uLine.rtcpMux !== 'rtcp-mux') &&
  20310. uLine.direction !== 'inactive') {
  20311. throw new Error('Cannot convert to Plan B because m-lines ' +
  20312. 'without the rtcp-mux attribute were found.');
  20313. }
  20314. if (uLine.type === 'application') {
  20315. session.media.push(uLine);
  20316. types.push(uLine.mid);
  20317. return;
  20318. }
  20319. // If we don't have a channel for this uLine.type, then use this
  20320. // uLine as the channel basis.
  20321. if (typeof type2bl[uLine.type] === 'undefined') {
  20322. type2bl[uLine.type] = uLine;
  20323. }
  20324. // Add sources to the channel and handle a=msid.
  20325. if (typeof uLine.sources === 'object') {
  20326. Object.keys(uLine.sources).forEach(function(ssrc) {
  20327. if (typeof type2bl[uLine.type].sources !== 'object')
  20328. type2bl[uLine.type].sources = {};
  20329. // Assign the sources to the channel.
  20330. type2bl[uLine.type].sources[ssrc] =
  20331. uLine.sources[ssrc];
  20332. if (typeof uLine.msid !== 'undefined') {
  20333. // In Plan B the msid is an SSRC attribute. Also, we don't
  20334. // care about the obsolete label and mslabel attributes.
  20335. //
  20336. // Note that it is not guaranteed that the uLine will
  20337. // have an msid. recvonly channels in particular don't have
  20338. // one.
  20339. type2bl[uLine.type].sources[ssrc].msid =
  20340. uLine.msid;
  20341. }
  20342. // NOTE ssrcs in ssrc groups will share msids, as
  20343. // draft-uberti-rtcweb-plan-00 mandates.
  20344. });
  20345. }
  20346. // Add ssrc groups to the channel.
  20347. if (typeof uLine.ssrcGroups !== 'undefined' &&
  20348. Array.isArray(uLine.ssrcGroups)) {
  20349. // Create the ssrcGroups array, if it's not defined.
  20350. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  20351. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  20352. type2bl[uLine.type].ssrcGroups = [];
  20353. }
  20354. type2bl[uLine.type].ssrcGroups =
  20355. type2bl[uLine.type].ssrcGroups.concat(
  20356. uLine.ssrcGroups);
  20357. }
  20358. if (type2bl[uLine.type] === uLine) {
  20359. // Copy ICE related stuff from the principal media line.
  20360. uLine.candidates = media[0].candidates;
  20361. uLine.iceUfrag = media[0].iceUfrag;
  20362. uLine.icePwd = media[0].icePwd;
  20363. uLine.fingerprint = media[0].fingerprint;
  20364. // Plan B mids are in ['audio', 'video', 'data']
  20365. uLine.mid = uLine.type;
  20366. // Plan B doesn't support/need the bundle-only attribute.
  20367. delete uLine.bundleOnly;
  20368. // In Plan B the msid is an SSRC attribute.
  20369. delete uLine.msid;
  20370. // Used to build the group:BUNDLE value after this loop.
  20371. types.push(uLine.type);
  20372. // Add the channel to the new media array.
  20373. session.media.push(uLine);
  20374. }
  20375. });
  20376. // We regenerate the BUNDLE group with the new mids.
  20377. session.groups.some(function(group) {
  20378. if (group.type === 'BUNDLE') {
  20379. group.mids = types.join(' ');
  20380. return true;
  20381. }
  20382. });
  20383. // msid semantic
  20384. session.msidSemantic = {
  20385. semantic: 'WMS',
  20386. token: '*'
  20387. };
  20388. var resStr = transform.write(session);
  20389. return new RTCSessionDescription({
  20390. type: desc.type,
  20391. sdp: resStr
  20392. });
  20393. //#endregion
  20394. };
  20395. /**
  20396. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  20397. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  20398. * to FF.
  20399. *
  20400. * @param desc
  20401. * @returns {*}
  20402. */
  20403. Interop.prototype.toUnifiedPlan = function(desc) {
  20404. var self = this;
  20405. //#region Preliminary input validation.
  20406. if (typeof desc !== 'object' || desc === null ||
  20407. typeof desc.sdp !== 'string') {
  20408. console.warn('An empty description was passed as an argument.');
  20409. return desc;
  20410. }
  20411. var session = transform.parse(desc.sdp);
  20412. // If the SDP contains no media, there's nothing to transform.
  20413. if (typeof session.media === 'undefined' ||
  20414. !Array.isArray(session.media) || session.media.length === 0) {
  20415. console.warn('The description has no media.');
  20416. return desc;
  20417. }
  20418. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  20419. // a video, an audio and a data "channel" at most.
  20420. if (session.media.length > 3 || !session.media.every(function(m) {
  20421. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20422. })) {
  20423. console.warn('This description does not look like Plan B.');
  20424. return desc;
  20425. }
  20426. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  20427. var mids = [];
  20428. session.media.forEach(function(m) {
  20429. mids.push(m.mid);
  20430. });
  20431. var hasBundle = false;
  20432. if (typeof session.groups !== 'undefined' &&
  20433. Array.isArray(session.groups)) {
  20434. hasBundle = session.groups.every(function(g) {
  20435. return g.type !== 'BUNDLE' ||
  20436. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  20437. });
  20438. }
  20439. if (!hasBundle) {
  20440. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  20441. " are not bundled were found.");
  20442. }
  20443. //#endregion
  20444. //#region Convert from Plan B to Unified Plan.
  20445. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  20446. // rebuild an equivalent Unified Plan offer/answer.
  20447. //
  20448. // For example, if this is a local answer (in Unified Plan style) that we
  20449. // convert to Plan B prior to handing it over to the application (the
  20450. // PeerConnection wrapper called us, for instance, after a successful
  20451. // createAnswer), we want to remember the m-line at which we've seen the
  20452. // (local) SSRC. That's because when the application wants to do call the
  20453. // SLD method, forcing us to do the inverse transformation (from Plan B to
  20454. // Unified Plan), we need to know to which m-line to assign the (local)
  20455. // SSRC. We also need to know all the other m-lines that the original
  20456. // answer had and include them in the transformed answer as well.
  20457. //
  20458. // Another example is if this is a remote offer that we convert to Plan B
  20459. // prior to giving it to the application, we want to remember the mid at
  20460. // which we've seen the (remote) SSRC.
  20461. //
  20462. // In the iteration that follows, we use the cached Unified Plan (if it
  20463. // exists) to assign mids to ssrcs.
  20464. var cached;
  20465. if (typeof this.cache[desc.type] !== 'undefined') {
  20466. cached = transform.parse(this.cache[desc.type]);
  20467. }
  20468. var recvonlySsrcs = {
  20469. audio: {},
  20470. video: {}
  20471. };
  20472. // A helper map that sends mids to m-line objects. We use it later to
  20473. // rebuild the Unified Plan style session.media array.
  20474. var mid2ul = {};
  20475. session.media.forEach(function(bLine) {
  20476. if ((typeof bLine.rtcpMux !== 'string' ||
  20477. bLine.rtcpMux !== 'rtcp-mux') &&
  20478. bLine.direction !== 'inactive') {
  20479. throw new Error("Cannot convert to Unified Plan because m-lines " +
  20480. "without the rtcp-mux attribute were found.");
  20481. }
  20482. if (bLine.type === 'application') {
  20483. mid2ul[bLine.mid] = bLine;
  20484. return;
  20485. }
  20486. // With rtcp-mux and bundle all the channels should have the same ICE
  20487. // stuff.
  20488. var sources = bLine.sources;
  20489. var ssrcGroups = bLine.ssrcGroups;
  20490. var candidates = bLine.candidates;
  20491. var iceUfrag = bLine.iceUfrag;
  20492. var icePwd = bLine.icePwd;
  20493. var fingerprint = bLine.fingerprint;
  20494. var port = bLine.port;
  20495. // We'll use the "bLine" object as a prototype for each new "mLine"
  20496. // that we create, but first we need to clean it up a bit.
  20497. delete bLine.sources;
  20498. delete bLine.ssrcGroups;
  20499. delete bLine.candidates;
  20500. delete bLine.iceUfrag;
  20501. delete bLine.icePwd;
  20502. delete bLine.fingerprint;
  20503. delete bLine.port;
  20504. delete bLine.mid;
  20505. // inverted ssrc group map
  20506. var ssrc2group = {};
  20507. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  20508. ssrcGroups.forEach(function (ssrcGroup) {
  20509. // TODO(gp) find out how to receive simulcast with FF. For the
  20510. // time being, hide it.
  20511. if (ssrcGroup.semantics === 'SIM') {
  20512. return;
  20513. }
  20514. // XXX This might brake if an SSRC is in more than one group
  20515. // for some reason.
  20516. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20517. Array.isArray(ssrcGroup.ssrcs)) {
  20518. ssrcGroup.ssrcs.forEach(function (ssrc) {
  20519. if (typeof ssrc2group[ssrc] === 'undefined') {
  20520. ssrc2group[ssrc] = [];
  20521. }
  20522. ssrc2group[ssrc].push(ssrcGroup);
  20523. });
  20524. }
  20525. });
  20526. }
  20527. // ssrc to m-line index.
  20528. var ssrc2ml = {};
  20529. if (typeof sources === 'object') {
  20530. // Explode the Plan B channel sources with one m-line per source.
  20531. Object.keys(sources).forEach(function(ssrc) {
  20532. // The (unified) m-line for this SSRC. We either create it from
  20533. // scratch or, if it's a grouped SSRC, we re-use a related
  20534. // mline. In other words, if the source is grouped with another
  20535. // source, put the two together in the same m-line.
  20536. var uLine;
  20537. // We assume here that we are the answerer in the O/A, so any
  20538. // offers which we translate come from the remote side, while
  20539. // answers are local. So the check below is to make that we
  20540. // handle receive-only SSRCs in a special way only if they come
  20541. // from the remote side.
  20542. if (desc.type==='offer') {
  20543. // We want to detect SSRCs which are used by a remote peer
  20544. // in an m-line with direction=recvonly (i.e. they are
  20545. // being used for RTCP only).
  20546. // This information would have gotten lost if the remote
  20547. // peer used Unified Plan and their local description was
  20548. // translated to Plan B. So we use the lack of an MSID
  20549. // attribute to deduce a "receive only" SSRC.
  20550. if (!sources[ssrc].msid) {
  20551. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  20552. // Receive-only SSRCs must not create new m-lines. We
  20553. // will assign them to an existing m-line later.
  20554. return;
  20555. }
  20556. }
  20557. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  20558. Array.isArray(ssrc2group[ssrc])) {
  20559. ssrc2group[ssrc].some(function (ssrcGroup) {
  20560. // ssrcGroup.ssrcs *is* an Array, no need to check
  20561. // again here.
  20562. return ssrcGroup.ssrcs.some(function (related) {
  20563. if (typeof ssrc2ml[related] === 'object') {
  20564. uLine = ssrc2ml[related];
  20565. return true;
  20566. }
  20567. });
  20568. });
  20569. }
  20570. if (typeof uLine === 'object') {
  20571. // the m-line already exists. Just add the source.
  20572. uLine.sources[ssrc] = sources[ssrc];
  20573. delete sources[ssrc].msid;
  20574. } else {
  20575. // Use the "bLine" as a prototype for the "uLine".
  20576. uLine = Object.create(bLine);
  20577. ssrc2ml[ssrc] = uLine;
  20578. if (typeof sources[ssrc].msid !== 'undefined') {
  20579. // Assign the msid of the source to the m-line. Note
  20580. // that it is not guaranteed that the source will have
  20581. // msid. In particular "recvonly" sources don't have an
  20582. // msid. Note that "recvonly" is a term only defined
  20583. // for m-lines.
  20584. uLine.msid = sources[ssrc].msid;
  20585. uLine.direction = 'sendrecv';
  20586. delete sources[ssrc].msid;
  20587. }
  20588. // We assign one SSRC per media line.
  20589. uLine.sources = {};
  20590. uLine.sources[ssrc] = sources[ssrc];
  20591. uLine.ssrcGroups = ssrc2group[ssrc];
  20592. // Use the cached Unified Plan SDP (if it exists) to assign
  20593. // SSRCs to mids.
  20594. if (typeof cached !== 'undefined' &&
  20595. typeof cached.media !== 'undefined' &&
  20596. Array.isArray(cached.media)) {
  20597. cached.media.forEach(function (m) {
  20598. if (typeof m.sources === 'object') {
  20599. Object.keys(m.sources).forEach(function (s) {
  20600. if (s === ssrc) {
  20601. uLine.mid = m.mid;
  20602. }
  20603. });
  20604. }
  20605. });
  20606. }
  20607. if (typeof uLine.mid === 'undefined') {
  20608. // If this is an SSRC that we see for the first time
  20609. // assign it a new mid. This is typically the case when
  20610. // this method is called to transform a remote
  20611. // description for the first time or when there is a
  20612. // new SSRC in the remote description because a new
  20613. // peer has joined the conference. Local SSRCs should
  20614. // have already been added to the map in the toPlanB
  20615. // method.
  20616. //
  20617. // Because FF generates answers in Unified Plan style,
  20618. // we MUST already have a cached answer with all the
  20619. // local SSRCs mapped to some m-line/mid.
  20620. if (desc.type === 'answer') {
  20621. throw new Error("An unmapped SSRC was found.");
  20622. }
  20623. uLine.mid = [bLine.type, '-', ssrc].join('');
  20624. }
  20625. // Include the candidates in the 1st media line.
  20626. uLine.candidates = candidates;
  20627. uLine.iceUfrag = iceUfrag;
  20628. uLine.icePwd = icePwd;
  20629. uLine.fingerprint = fingerprint;
  20630. uLine.port = port;
  20631. mid2ul[uLine.mid] = uLine;
  20632. }
  20633. });
  20634. }
  20635. });
  20636. // Rebuild the media array in the right order and add the missing mLines
  20637. // (missing from the Plan B SDP).
  20638. session.media = [];
  20639. mids = []; // reuse
  20640. if (desc.type === 'answer') {
  20641. // The media lines in the answer must match the media lines in the
  20642. // offer. The order is important too. Here we assume that Firefox is
  20643. // the answerer, so we merely have to use the reconstructed (unified)
  20644. // answer to update the cached (unified) answer accordingly.
  20645. //
  20646. // In the general case, one would have to use the cached (unified)
  20647. // offer to find the m-lines that are missing from the reconstructed
  20648. // answer, potentially grabbing them from the cached (unified) answer.
  20649. // One has to be careful with this approach because inactive m-lines do
  20650. // not always have an mid, making it tricky (impossible?) to find where
  20651. // exactly and which m-lines are missing from the reconstructed answer.
  20652. for (var i = 0; i < cached.media.length; i++) {
  20653. var uLine = cached.media[i];
  20654. if (typeof mid2ul[uLine.mid] === 'undefined') {
  20655. // The mid isn't in the reconstructed (unified) answer.
  20656. // This is either a (unified) m-line containing a remote
  20657. // track only, or a (unified) m-line containing a remote
  20658. // track and a local track that has been removed.
  20659. // In either case, it MUST exist in the cached
  20660. // (unified) answer.
  20661. //
  20662. // In case this is a removed local track, clean-up
  20663. // the (unified) m-line and make sure it's 'recvonly' or
  20664. // 'inactive'.
  20665. delete uLine.msid;
  20666. delete uLine.sources;
  20667. delete uLine.ssrcGroups;
  20668. if (!uLine.direction
  20669. || uLine.direction === 'sendrecv')
  20670. uLine.direction = 'recvonly';
  20671. else if (uLine.direction === 'sendonly')
  20672. uLine.direction = 'inactive';
  20673. } else {
  20674. // This is an (unified) m-line/channel that contains a local
  20675. // track (sendrecv or sendonly channel) or it's a unified
  20676. // recvonly m-line/channel. In either case, since we're
  20677. // going from PlanB -> Unified Plan this m-line MUST
  20678. // exist in the cached answer.
  20679. }
  20680. session.media.push(uLine);
  20681. if (typeof uLine.mid === 'string') {
  20682. // inactive lines don't/may not have an mid.
  20683. mids.push(uLine.mid);
  20684. }
  20685. }
  20686. } else {
  20687. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  20688. // under any circumstances. If we are no longer interested in sending a
  20689. // track, we just remove the msid and ssrc attributes and set it to
  20690. // either a=recvonly (as the reofferer, we must use recvonly if the
  20691. // other side was previously sending on the m-section, but we can also
  20692. // leave the possibility open if it wasn't previously in use), or
  20693. // a=inactive.
  20694. if (typeof cached !== 'undefined' &&
  20695. typeof cached.media !== 'undefined' &&
  20696. Array.isArray(cached.media)) {
  20697. cached.media.forEach(function(uLine) {
  20698. mids.push(uLine.mid);
  20699. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  20700. session.media.push(mid2ul[uLine.mid]);
  20701. } else {
  20702. delete uLine.msid;
  20703. delete uLine.sources;
  20704. delete uLine.ssrcGroups;
  20705. if (!uLine.direction
  20706. || uLine.direction === 'sendrecv')
  20707. uLine.direction = 'recvonly';
  20708. if (!uLine.direction
  20709. || uLine.direction === 'sendonly')
  20710. uLine.direction = 'inactive';
  20711. session.media.push(uLine);
  20712. }
  20713. });
  20714. }
  20715. // Add all the remaining (new) m-lines of the transformed SDP.
  20716. Object.keys(mid2ul).forEach(function(mid) {
  20717. if (mids.indexOf(mid) === -1) {
  20718. mids.push(mid);
  20719. if (mid2ul[mid].direction === 'recvonly') {
  20720. // This is a remote recvonly channel. Add its SSRC to the
  20721. // appropriate sendrecv or sendonly channel.
  20722. // TODO(gp) what if we don't have sendrecv/sendonly
  20723. // channel?
  20724. session.media.some(function (uLine) {
  20725. if ((uLine.direction === 'sendrecv' ||
  20726. uLine.direction === 'sendonly') &&
  20727. uLine.type === mid2ul[mid].type) {
  20728. // mid2ul[mid] shouldn't have any ssrc-groups
  20729. Object.keys(mid2ul[mid].sources).forEach(
  20730. function (ssrc) {
  20731. uLine.sources[ssrc] =
  20732. mid2ul[mid].sources[ssrc];
  20733. });
  20734. return true;
  20735. }
  20736. });
  20737. } else {
  20738. session.media.push(mid2ul[mid]);
  20739. }
  20740. }
  20741. });
  20742. }
  20743. // After we have constructed the Plan Unified m-lines we can figure out
  20744. // where (in which m-line) to place the 'recvonly SSRCs'.
  20745. // Note: we assume here that we are the answerer in the O/A, so any offers
  20746. // which we translate come from the remote side, while answers are local
  20747. // (and so our last local description is cached as an 'answer').
  20748. ["audio", "video"].forEach(function (type) {
  20749. if (!session || !session.media || !Array.isArray(session.media))
  20750. return;
  20751. var idx = null;
  20752. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  20753. idx = self.getFirstSendingIndexFromAnswer(type);
  20754. if (idx === null){
  20755. // If this is the first offer we receive, we don't have a
  20756. // cached answer. Assume that we will be sending media using
  20757. // the first m-line for each media type.
  20758. for (var i = 0; i < session.media.length; i++) {
  20759. if (session.media[i].type === type) {
  20760. idx = i;
  20761. break;
  20762. }
  20763. }
  20764. }
  20765. }
  20766. if (idx && session.media.length > idx) {
  20767. var mLine = session.media[idx];
  20768. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  20769. if (mLine.sources && mLine.sources[ssrc]) {
  20770. console.warn("Replacing an existing SSRC.");
  20771. }
  20772. if (!mLine.sources) {
  20773. mLine.sources = {};
  20774. }
  20775. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  20776. });
  20777. }
  20778. });
  20779. // We regenerate the BUNDLE group (since we regenerated the mids)
  20780. session.groups.some(function(group) {
  20781. if (group.type === 'BUNDLE') {
  20782. group.mids = mids.join(' ');
  20783. return true;
  20784. }
  20785. });
  20786. // msid semantic
  20787. session.msidSemantic = {
  20788. semantic: 'WMS',
  20789. token: '*'
  20790. };
  20791. var resStr = transform.write(session);
  20792. // Cache the transformed SDP (Unified Plan) for later re-use in this
  20793. // function.
  20794. this.cache[desc.type] = resStr;
  20795. return new RTCSessionDescription({
  20796. type: desc.type,
  20797. sdp: resStr
  20798. });
  20799. //#endregion
  20800. };
  20801. },{"./array-equals":68,"./transform":71}],71:[function(require,module,exports){
  20802. /* Copyright @ 2015 Atlassian Pty Ltd
  20803. *
  20804. * Licensed under the Apache License, Version 2.0 (the "License");
  20805. * you may not use this file except in compliance with the License.
  20806. * You may obtain a copy of the License at
  20807. *
  20808. * http://www.apache.org/licenses/LICENSE-2.0
  20809. *
  20810. * Unless required by applicable law or agreed to in writing, software
  20811. * distributed under the License is distributed on an "AS IS" BASIS,
  20812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20813. * See the License for the specific language governing permissions and
  20814. * limitations under the License.
  20815. */
  20816. var transform = require('sdp-transform');
  20817. exports.write = function(session, opts) {
  20818. if (typeof session !== 'undefined' &&
  20819. typeof session.media !== 'undefined' &&
  20820. Array.isArray(session.media)) {
  20821. session.media.forEach(function (mLine) {
  20822. // expand sources to ssrcs
  20823. if (typeof mLine.sources !== 'undefined' &&
  20824. Object.keys(mLine.sources).length !== 0) {
  20825. mLine.ssrcs = [];
  20826. Object.keys(mLine.sources).forEach(function (ssrc) {
  20827. var source = mLine.sources[ssrc];
  20828. Object.keys(source).forEach(function (attribute) {
  20829. mLine.ssrcs.push({
  20830. id: ssrc,
  20831. attribute: attribute,
  20832. value: source[attribute]
  20833. });
  20834. });
  20835. });
  20836. delete mLine.sources;
  20837. }
  20838. // join ssrcs in ssrc groups
  20839. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20840. Array.isArray(mLine.ssrcGroups)) {
  20841. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20842. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20843. Array.isArray(ssrcGroup.ssrcs)) {
  20844. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  20845. }
  20846. });
  20847. }
  20848. });
  20849. }
  20850. // join group mids
  20851. if (typeof session !== 'undefined' &&
  20852. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20853. session.groups.forEach(function (g) {
  20854. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  20855. g.mids = g.mids.join(' ');
  20856. }
  20857. });
  20858. }
  20859. return transform.write(session, opts);
  20860. };
  20861. exports.parse = function(sdp) {
  20862. var session = transform.parse(sdp);
  20863. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  20864. Array.isArray(session.media)) {
  20865. session.media.forEach(function (mLine) {
  20866. // group sources attributes by ssrc
  20867. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20868. mLine.sources = {};
  20869. mLine.ssrcs.forEach(function (ssrc) {
  20870. if (!mLine.sources[ssrc.id])
  20871. mLine.sources[ssrc.id] = {};
  20872. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20873. });
  20874. delete mLine.ssrcs;
  20875. }
  20876. // split ssrcs in ssrc groups
  20877. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20878. Array.isArray(mLine.ssrcGroups)) {
  20879. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20880. if (typeof ssrcGroup.ssrcs === 'string') {
  20881. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  20882. }
  20883. });
  20884. }
  20885. });
  20886. }
  20887. // split group mids
  20888. if (typeof session !== 'undefined' &&
  20889. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20890. session.groups.forEach(function (g) {
  20891. if (typeof g.mids === 'string') {
  20892. g.mids = g.mids.split(' ');
  20893. }
  20894. });
  20895. }
  20896. return session;
  20897. };
  20898. },{"sdp-transform":73}],72:[function(require,module,exports){
  20899. var grammar = module.exports = {
  20900. v: [{
  20901. name: 'version',
  20902. reg: /^(\d*)$/
  20903. }],
  20904. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20905. // NB: sessionId will be a String in most cases because it is huge
  20906. name: 'origin',
  20907. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20908. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20909. format: "%s %s %d %s IP%d %s"
  20910. }],
  20911. // default parsing of these only (though some of these feel outdated)
  20912. s: [{ name: 'name' }],
  20913. i: [{ name: 'description' }],
  20914. u: [{ name: 'uri' }],
  20915. e: [{ name: 'email' }],
  20916. p: [{ name: 'phone' }],
  20917. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20918. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20919. //k: [{}], // outdated thing ignored
  20920. t: [{ //t=0 0
  20921. name: 'timing',
  20922. reg: /^(\d*) (\d*)/,
  20923. names: ['start', 'stop'],
  20924. format: "%d %d"
  20925. }],
  20926. c: [{ //c=IN IP4 10.47.197.26
  20927. name: 'connection',
  20928. reg: /^IN IP(\d) (\S*)/,
  20929. names: ['version', 'ip'],
  20930. format: "IN IP%d %s"
  20931. }],
  20932. b: [{ //b=AS:4000
  20933. push: 'bandwidth',
  20934. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20935. names: ['type', 'limit'],
  20936. format: "%s:%s"
  20937. }],
  20938. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20939. // NB: special - pushes to session
  20940. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20941. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20942. names: ['type', 'port', 'protocol', 'payloads'],
  20943. format: "%s %d %s %s"
  20944. }],
  20945. a: [
  20946. { //a=rtpmap:110 opus/48000/2
  20947. push: 'rtp',
  20948. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  20949. names: ['payload', 'codec', 'rate', 'encoding'],
  20950. format: function (o) {
  20951. return (o.encoding) ?
  20952. "rtpmap:%d %s/%s/%s":
  20953. o.rate ?
  20954. "rtpmap:%d %s/%s":
  20955. "rtpmap:%d %s";
  20956. }
  20957. },
  20958. {
  20959. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20960. //a=fmtp:111 minptime=10; useinbandfec=1
  20961. push: 'fmtp',
  20962. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20963. names: ['payload', 'config'],
  20964. format: "fmtp:%d %s"
  20965. },
  20966. { //a=control:streamid=0
  20967. name: 'control',
  20968. reg: /^control:(.*)/,
  20969. format: "control:%s"
  20970. },
  20971. { //a=rtcp:65179 IN IP4 193.84.77.194
  20972. name: 'rtcp',
  20973. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20974. names: ['port', 'netType', 'ipVer', 'address'],
  20975. format: function (o) {
  20976. return (o.address != null) ?
  20977. "rtcp:%d %s IP%d %s":
  20978. "rtcp:%d";
  20979. }
  20980. },
  20981. { //a=rtcp-fb:98 trr-int 100
  20982. push: 'rtcpFbTrrInt',
  20983. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20984. names: ['payload', 'value'],
  20985. format: "rtcp-fb:%d trr-int %d"
  20986. },
  20987. { //a=rtcp-fb:98 nack rpsi
  20988. push: 'rtcpFb',
  20989. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20990. names: ['payload', 'type', 'subtype'],
  20991. format: function (o) {
  20992. return (o.subtype != null) ?
  20993. "rtcp-fb:%s %s %s":
  20994. "rtcp-fb:%s %s";
  20995. }
  20996. },
  20997. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20998. //a=extmap:1/recvonly URI-gps-string
  20999. push: 'ext',
  21000. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  21001. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  21002. format: function (o) {
  21003. return (o.config != null) ?
  21004. "extmap:%s %s %s":
  21005. "extmap:%s %s";
  21006. }
  21007. },
  21008. {
  21009. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  21010. push: 'crypto',
  21011. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  21012. names: ['id', 'suite', 'config', 'sessionConfig'],
  21013. format: function (o) {
  21014. return (o.sessionConfig != null) ?
  21015. "crypto:%d %s %s %s":
  21016. "crypto:%d %s %s";
  21017. }
  21018. },
  21019. { //a=setup:actpass
  21020. name: 'setup',
  21021. reg: /^setup:(\w*)/,
  21022. format: "setup:%s"
  21023. },
  21024. { //a=mid:1
  21025. name: 'mid',
  21026. reg: /^mid:([^\s]*)/,
  21027. format: "mid:%s"
  21028. },
  21029. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  21030. name: 'msid',
  21031. reg: /^msid:(.*)/,
  21032. format: "msid:%s"
  21033. },
  21034. { //a=ptime:20
  21035. name: 'ptime',
  21036. reg: /^ptime:(\d*)/,
  21037. format: "ptime:%d"
  21038. },
  21039. { //a=maxptime:60
  21040. name: 'maxptime',
  21041. reg: /^maxptime:(\d*)/,
  21042. format: "maxptime:%d"
  21043. },
  21044. { //a=sendrecv
  21045. name: 'direction',
  21046. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  21047. },
  21048. { //a=ice-lite
  21049. name: 'icelite',
  21050. reg: /^(ice-lite)/
  21051. },
  21052. { //a=ice-ufrag:F7gI
  21053. name: 'iceUfrag',
  21054. reg: /^ice-ufrag:(\S*)/,
  21055. format: "ice-ufrag:%s"
  21056. },
  21057. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  21058. name: 'icePwd',
  21059. reg: /^ice-pwd:(\S*)/,
  21060. format: "ice-pwd:%s"
  21061. },
  21062. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  21063. name: 'fingerprint',
  21064. reg: /^fingerprint:(\S*) (\S*)/,
  21065. names: ['type', 'hash'],
  21066. format: "fingerprint:%s %s"
  21067. },
  21068. {
  21069. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  21070. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  21071. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  21072. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  21073. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  21074. push:'candidates',
  21075. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  21076. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  21077. format: function (o) {
  21078. var str = "candidate:%s %d %s %d %s %d typ %s";
  21079. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  21080. // NB: candidate has three optional chunks, so %void middles one if it's missing
  21081. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  21082. if (o.generation != null) {
  21083. str += " generation %d";
  21084. }
  21085. return str;
  21086. }
  21087. },
  21088. { //a=end-of-candidates (keep after the candidates line for readability)
  21089. name: 'endOfCandidates',
  21090. reg: /^(end-of-candidates)/
  21091. },
  21092. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  21093. name: 'remoteCandidates',
  21094. reg: /^remote-candidates:(.*)/,
  21095. format: "remote-candidates:%s"
  21096. },
  21097. { //a=ice-options:google-ice
  21098. name: 'iceOptions',
  21099. reg: /^ice-options:(\S*)/,
  21100. format: "ice-options:%s"
  21101. },
  21102. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  21103. push: "ssrcs",
  21104. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  21105. names: ['id', 'attribute', 'value'],
  21106. format: "ssrc:%d %s:%s"
  21107. },
  21108. { //a=ssrc-group:FEC 1 2
  21109. push: "ssrcGroups",
  21110. reg: /^ssrc-group:(\w*) (.*)/,
  21111. names: ['semantics', 'ssrcs'],
  21112. format: "ssrc-group:%s %s"
  21113. },
  21114. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  21115. name: "msidSemantic",
  21116. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  21117. names: ['semantic', 'token'],
  21118. format: "msid-semantic: %s %s" // space after ":" is not accidental
  21119. },
  21120. { //a=group:BUNDLE audio video
  21121. push: 'groups',
  21122. reg: /^group:(\w*) (.*)/,
  21123. names: ['type', 'mids'],
  21124. format: "group:%s %s"
  21125. },
  21126. { //a=rtcp-mux
  21127. name: 'rtcpMux',
  21128. reg: /^(rtcp-mux)/
  21129. },
  21130. { //a=rtcp-rsize
  21131. name: 'rtcpRsize',
  21132. reg: /^(rtcp-rsize)/
  21133. },
  21134. { // any a= that we don't understand is kepts verbatim on media.invalid
  21135. push: 'invalid',
  21136. names: ["value"]
  21137. }
  21138. ]
  21139. };
  21140. // set sensible defaults to avoid polluting the grammar with boring details
  21141. Object.keys(grammar).forEach(function (key) {
  21142. var objs = grammar[key];
  21143. objs.forEach(function (obj) {
  21144. if (!obj.reg) {
  21145. obj.reg = /(.*)/;
  21146. }
  21147. if (!obj.format) {
  21148. obj.format = "%s";
  21149. }
  21150. });
  21151. });
  21152. },{}],73:[function(require,module,exports){
  21153. var parser = require('./parser');
  21154. var writer = require('./writer');
  21155. exports.write = writer;
  21156. exports.parse = parser.parse;
  21157. exports.parseFmtpConfig = parser.parseFmtpConfig;
  21158. exports.parsePayloads = parser.parsePayloads;
  21159. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  21160. },{"./parser":74,"./writer":75}],74:[function(require,module,exports){
  21161. var toIntIfInt = function (v) {
  21162. return String(Number(v)) === v ? Number(v) : v;
  21163. };
  21164. var attachProperties = function (match, location, names, rawName) {
  21165. if (rawName && !names) {
  21166. location[rawName] = toIntIfInt(match[1]);
  21167. }
  21168. else {
  21169. for (var i = 0; i < names.length; i += 1) {
  21170. if (match[i+1] != null) {
  21171. location[names[i]] = toIntIfInt(match[i+1]);
  21172. }
  21173. }
  21174. }
  21175. };
  21176. var parseReg = function (obj, location, content) {
  21177. var needsBlank = obj.name && obj.names;
  21178. if (obj.push && !location[obj.push]) {
  21179. location[obj.push] = [];
  21180. }
  21181. else if (needsBlank && !location[obj.name]) {
  21182. location[obj.name] = {};
  21183. }
  21184. var keyLocation = obj.push ?
  21185. {} : // blank object that will be pushed
  21186. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21187. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21188. if (obj.push) {
  21189. location[obj.push].push(keyLocation);
  21190. }
  21191. };
  21192. var grammar = require('./grammar');
  21193. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21194. exports.parse = function (sdp) {
  21195. var session = {}
  21196. , media = []
  21197. , location = session; // points at where properties go under (one of the above)
  21198. // parse lines we understand
  21199. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21200. var type = l[0];
  21201. var content = l.slice(2);
  21202. if (type === 'm') {
  21203. media.push({rtp: [], fmtp: []});
  21204. location = media[media.length-1]; // point at latest media line
  21205. }
  21206. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21207. var obj = grammar[type][j];
  21208. if (obj.reg.test(content)) {
  21209. return parseReg(obj, location, content);
  21210. }
  21211. }
  21212. });
  21213. session.media = media; // link it up
  21214. return session;
  21215. };
  21216. var fmtpReducer = function (acc, expr) {
  21217. var s = expr.split('=');
  21218. if (s.length === 2) {
  21219. acc[s[0]] = toIntIfInt(s[1]);
  21220. }
  21221. return acc;
  21222. };
  21223. exports.parseFmtpConfig = function (str) {
  21224. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21225. };
  21226. exports.parsePayloads = function (str) {
  21227. return str.split(' ').map(Number);
  21228. };
  21229. exports.parseRemoteCandidates = function (str) {
  21230. var candidates = [];
  21231. var parts = str.split(' ').map(toIntIfInt);
  21232. for (var i = 0; i < parts.length; i += 3) {
  21233. candidates.push({
  21234. component: parts[i],
  21235. ip: parts[i + 1],
  21236. port: parts[i + 2]
  21237. });
  21238. }
  21239. return candidates;
  21240. };
  21241. },{"./grammar":72}],75:[function(require,module,exports){
  21242. var grammar = require('./grammar');
  21243. // customized util.format - discards excess arguments and can void middle ones
  21244. var formatRegExp = /%[sdv%]/g;
  21245. var format = function (formatStr) {
  21246. var i = 1;
  21247. var args = arguments;
  21248. var len = args.length;
  21249. return formatStr.replace(formatRegExp, function (x) {
  21250. if (i >= len) {
  21251. return x; // missing argument
  21252. }
  21253. var arg = args[i];
  21254. i += 1;
  21255. switch (x) {
  21256. case '%%':
  21257. return '%';
  21258. case '%s':
  21259. return String(arg);
  21260. case '%d':
  21261. return Number(arg);
  21262. case '%v':
  21263. return '';
  21264. }
  21265. });
  21266. // NB: we discard excess arguments - they are typically undefined from makeLine
  21267. };
  21268. var makeLine = function (type, obj, location) {
  21269. var str = obj.format instanceof Function ?
  21270. (obj.format(obj.push ? location : location[obj.name])) :
  21271. obj.format;
  21272. var args = [type + '=' + str];
  21273. if (obj.names) {
  21274. for (var i = 0; i < obj.names.length; i += 1) {
  21275. var n = obj.names[i];
  21276. if (obj.name) {
  21277. args.push(location[obj.name][n]);
  21278. }
  21279. else { // for mLine and push attributes
  21280. args.push(location[obj.names[i]]);
  21281. }
  21282. }
  21283. }
  21284. else {
  21285. args.push(location[obj.name]);
  21286. }
  21287. return format.apply(null, args);
  21288. };
  21289. // RFC specified order
  21290. // TODO: extend this with all the rest
  21291. var defaultOuterOrder = [
  21292. 'v', 'o', 's', 'i',
  21293. 'u', 'e', 'p', 'c',
  21294. 'b', 't', 'r', 'z', 'a'
  21295. ];
  21296. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  21297. module.exports = function (session, opts) {
  21298. opts = opts || {};
  21299. // ensure certain properties exist
  21300. if (session.version == null) {
  21301. session.version = 0; // "v=0" must be there (only defined version atm)
  21302. }
  21303. if (session.name == null) {
  21304. session.name = " "; // "s= " must be there if no meaningful name set
  21305. }
  21306. session.media.forEach(function (mLine) {
  21307. if (mLine.payloads == null) {
  21308. mLine.payloads = "";
  21309. }
  21310. });
  21311. var outerOrder = opts.outerOrder || defaultOuterOrder;
  21312. var innerOrder = opts.innerOrder || defaultInnerOrder;
  21313. var sdp = [];
  21314. // loop through outerOrder for matching properties on session
  21315. outerOrder.forEach(function (type) {
  21316. grammar[type].forEach(function (obj) {
  21317. if (obj.name in session && session[obj.name] != null) {
  21318. sdp.push(makeLine(type, obj, session));
  21319. }
  21320. else if (obj.push in session && session[obj.push] != null) {
  21321. session[obj.push].forEach(function (el) {
  21322. sdp.push(makeLine(type, obj, el));
  21323. });
  21324. }
  21325. });
  21326. });
  21327. // then for each media line, follow the innerOrder
  21328. session.media.forEach(function (mLine) {
  21329. sdp.push(makeLine('m', grammar.m[0], mLine));
  21330. innerOrder.forEach(function (type) {
  21331. grammar[type].forEach(function (obj) {
  21332. if (obj.name in mLine && mLine[obj.name] != null) {
  21333. sdp.push(makeLine(type, obj, mLine));
  21334. }
  21335. else if (obj.push in mLine && mLine[obj.push] != null) {
  21336. mLine[obj.push].forEach(function (el) {
  21337. sdp.push(makeLine(type, obj, el));
  21338. });
  21339. }
  21340. });
  21341. });
  21342. });
  21343. return sdp.join('\r\n') + '\r\n';
  21344. };
  21345. },{"./grammar":72}],76:[function(require,module,exports){
  21346. /* Copyright @ 2015 Atlassian Pty Ltd
  21347. *
  21348. * Licensed under the Apache License, Version 2.0 (the "License");
  21349. * you may not use this file except in compliance with the License.
  21350. * You may obtain a copy of the License at
  21351. *
  21352. * http://www.apache.org/licenses/LICENSE-2.0
  21353. *
  21354. * Unless required by applicable law or agreed to in writing, software
  21355. * distributed under the License is distributed on an "AS IS" BASIS,
  21356. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21357. * See the License for the specific language governing permissions and
  21358. * limitations under the License.
  21359. */
  21360. var transform = require('sdp-transform');
  21361. var transformUtils = require('./transform-utils');
  21362. var parseSsrcs = transformUtils.parseSsrcs;
  21363. var writeSsrcs = transformUtils.writeSsrcs;
  21364. //region Constants
  21365. var DEFAULT_NUM_OF_LAYERS = 3;
  21366. //endregion
  21367. //region Ctor
  21368. function Simulcast(options) {
  21369. this.options = options ? options : {};
  21370. if (!this.options.numOfLayers) {
  21371. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  21372. }
  21373. this.layers = [];
  21374. }
  21375. //endregion
  21376. //region Stateless private utility functions
  21377. /**
  21378. * Returns a random integer between min (included) and max (excluded)
  21379. * Using Math.round() gives a non-uniform distribution!
  21380. * @returns {number}
  21381. */
  21382. function generateSSRC() {
  21383. var min = 0, max = 0xffffffff;
  21384. return Math.floor(Math.random() * (max - min)) + min;
  21385. };
  21386. function processVideo(session, action) {
  21387. if (session == null || !Array.isArray(session.media)) {
  21388. return;
  21389. }
  21390. session.media.forEach(function (mLine) {
  21391. if (mLine.type === 'video') {
  21392. action(mLine);
  21393. }
  21394. });
  21395. }
  21396. function validateDescription(desc)
  21397. {
  21398. return desc && desc != null
  21399. && desc.type && desc.type != ''
  21400. && desc.sdp && desc.sdp != '';
  21401. }
  21402. function explodeRemoteSimulcast(mLine) {
  21403. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21404. return;
  21405. }
  21406. var sources = parseSsrcs(mLine);
  21407. var order = [];
  21408. // Find the SIM group and explode its sources.
  21409. var j = mLine.ssrcGroups.length;
  21410. while (j--) {
  21411. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  21412. continue;
  21413. }
  21414. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  21415. for (var i = 0; i < simulcastSsrcs.length; i++) {
  21416. var ssrc = simulcastSsrcs[i];
  21417. order.push(ssrc);
  21418. var parts = sources[ssrc].msid.split(' ');
  21419. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  21420. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  21421. // Remove all the groups that this SSRC participates in.
  21422. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21423. if (relatedGroup.semantics === 'SIM') {
  21424. return;
  21425. }
  21426. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21427. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21428. return;
  21429. }
  21430. // Nuke all the related SSRCs.
  21431. relatedSsrcs.forEach(function (relatedSSRC) {
  21432. sources[relatedSSRC].msid = sources[ssrc].msid;
  21433. sources[relatedSSRC].cname = sources[ssrc].cname;
  21434. if (relatedSSRC !== ssrc) {
  21435. order.push(relatedSSRC);
  21436. }
  21437. });
  21438. // Schedule the related group for nuking.
  21439. })
  21440. }
  21441. mLine.ssrcs = writeSsrcs(sources, order);
  21442. mLine.ssrcGroups.splice(j, 1);
  21443. };
  21444. }
  21445. function implodeRemoteSimulcast(mLine) {
  21446. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21447. console.info('Halt: There are no SSRC groups in the remote ' +
  21448. 'description.');
  21449. return;
  21450. }
  21451. var sources = parseSsrcs(mLine);
  21452. // Find the SIM group and nuke it.
  21453. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  21454. if (simulcastGroup.semantics !== 'SIM') {
  21455. return;
  21456. }
  21457. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  21458. // Schedule the SIM group for nuking.
  21459. simulcastGroup.nuke = true;
  21460. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  21461. // Nuke all the higher layer SSRCs.
  21462. for (var i = 1; i < simulcastSsrcs.length; i++) {
  21463. var ssrc = simulcastSsrcs[i];
  21464. delete sources[ssrc];
  21465. // Remove all the groups that this SSRC participates in.
  21466. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21467. if (relatedGroup.semantics === 'SIM') {
  21468. return;
  21469. }
  21470. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21471. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21472. return;
  21473. }
  21474. // Nuke all the related SSRCs.
  21475. relatedSsrcs.forEach(function (relatedSSRC) {
  21476. delete sources[relatedSSRC];
  21477. });
  21478. // Schedule the related group for nuking.
  21479. relatedGroup.nuke = true;
  21480. })
  21481. }
  21482. return;
  21483. });
  21484. mLine.ssrcs = writeSsrcs(sources);
  21485. // Nuke all the scheduled groups.
  21486. var i = mLine.ssrcGroups.length;
  21487. while (i--) {
  21488. if (mLine.ssrcGroups[i].nuke) {
  21489. mLine.ssrcGroups.splice(i, 1);
  21490. }
  21491. }
  21492. }
  21493. function removeGoogConference(mLine) {
  21494. if (!mLine || !Array.isArray(mLine.invalid)) {
  21495. return;
  21496. }
  21497. var i = mLine.invalid.length;
  21498. while (i--) {
  21499. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  21500. mLine.invalid.splice(i, 1);
  21501. }
  21502. }
  21503. }
  21504. function assertGoogConference(mLine) {
  21505. if (!mLine) {
  21506. return;
  21507. }
  21508. if (!Array.isArray(mLine.invalid)) {
  21509. mLine.invalid = [];
  21510. }
  21511. if (!mLine.invalid.some(
  21512. function (i) { return i.value === 'x-google-flag:conference' })) {
  21513. mLine.invalid.push({'value': 'x-google-flag:conference'});
  21514. }
  21515. }
  21516. //endregion
  21517. //region "Private" functions
  21518. /**
  21519. *
  21520. * @param mLine
  21521. * @private
  21522. */
  21523. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  21524. if (!mLine || mLine.type !== 'video') {
  21525. return;
  21526. }
  21527. var sources = parseSsrcs(mLine);
  21528. if (Object.keys(sources).length === 0) {
  21529. // no sources, disable simulcast.
  21530. if (this.layers.length !== 0) {
  21531. this.layers = [];
  21532. }
  21533. return;
  21534. }
  21535. // find the base layer (we'll reuse its msid and cname).
  21536. var baseLayerSSRC = Object.keys(sources)[0];
  21537. var baseLayer = sources[baseLayerSSRC];
  21538. // todo(gp) handle screen sharing.
  21539. // check if base CNAME has changed and reinitialise layers.
  21540. if (this.layers.length > 0
  21541. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  21542. this.layers = [];
  21543. }
  21544. // (re)initialise layers
  21545. if (this.layers.length < 1) {
  21546. // first push the base layer.
  21547. this.layers.push({
  21548. ssrc: baseLayerSSRC,
  21549. msid: baseLayer.msid,
  21550. cname: baseLayer.cname
  21551. });
  21552. var rtx = false; // RFC 4588
  21553. if (Array.isArray(mLine.rtp)) {
  21554. rtx = mLine.rtp.some(
  21555. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  21556. }
  21557. if (rtx) {
  21558. this.layers[0].rtx = generateSSRC();
  21559. }
  21560. // now push additional layers.
  21561. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  21562. var layer = { ssrc: generateSSRC() };
  21563. if (rtx) {
  21564. layer.rtx = generateSSRC();
  21565. }
  21566. this.layers.push(layer);
  21567. }
  21568. }
  21569. };
  21570. /**
  21571. *
  21572. * @param mLine
  21573. * @private
  21574. */
  21575. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  21576. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  21577. var sources = {};
  21578. var msid = this.layers[0].msid;
  21579. var cname = this.layers[0].cname;
  21580. var simulcastSsrcs = [];
  21581. var ssrcGroups = [];
  21582. for (var i = 0; i < this.layers.length; i++) {
  21583. var layer = this.layers[i];
  21584. sources[layer.ssrc] = { msid: msid, cname: cname };
  21585. simulcastSsrcs.push(layer.ssrc);
  21586. if (layer.rtx) {
  21587. sources[layer.rtx] = {
  21588. msid: msid,
  21589. cname: cname
  21590. }
  21591. ssrcGroups.push({
  21592. semantics: 'FID',
  21593. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  21594. });
  21595. }
  21596. }
  21597. ssrcGroups.push({
  21598. semantics: 'SIM',
  21599. ssrcs: simulcastSsrcs.join(' ')
  21600. });
  21601. mLine.ssrcGroups = ssrcGroups;
  21602. mLine.ssrcs = writeSsrcs(sources);
  21603. }
  21604. }
  21605. //endregion
  21606. //region "Public" functions
  21607. Simulcast.prototype.isSupported = function () {
  21608. return window.chrome;
  21609. // TODO this needs improvements. For example I doubt that Chrome in Android
  21610. // has simulcast support. Also, only recent versions of Chromium have native
  21611. // simulcast support.
  21612. }
  21613. /**
  21614. *
  21615. * @param desc
  21616. * @returns {RTCSessionDescription}
  21617. */
  21618. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  21619. if (!validateDescription(desc)) {
  21620. return desc;
  21621. }
  21622. var session = transform.parse(desc.sdp);
  21623. var self = this;
  21624. processVideo(session, function (mLine) {
  21625. // Handle simulcast reception.
  21626. if (self.options.explodeRemoteSimulcast) {
  21627. explodeRemoteSimulcast(mLine);
  21628. } else {
  21629. implodeRemoteSimulcast(mLine);
  21630. }
  21631. // If native simulcast is enabled, we must append the x-goog-conference
  21632. // attribute to the SDP.
  21633. if (self.layers.length < 1) {
  21634. removeGoogConference(mLine);
  21635. } else {
  21636. assertGoogConference(mLine);
  21637. }
  21638. });
  21639. return new RTCSessionDescription({
  21640. type: desc.type,
  21641. sdp: transform.write(session)
  21642. });
  21643. };
  21644. /**
  21645. *
  21646. * @param desc
  21647. * @returns {RTCSessionDescription}
  21648. */
  21649. Simulcast.prototype.mungeLocalDescription = function (desc) {
  21650. if (!validateDescription(desc) || !this.isSupported()) {
  21651. return desc;
  21652. }
  21653. var session = transform.parse(desc.sdp);
  21654. var self = this;
  21655. processVideo(session, function (mLine) {
  21656. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  21657. {
  21658. return;
  21659. }
  21660. // Initialize native simulcast layers, if not already done.
  21661. self._maybeInitializeLayers(mLine);
  21662. // Update the SDP with the simulcast layers.
  21663. self._restoreSimulcastView(mLine);
  21664. });
  21665. return new RTCSessionDescription({
  21666. type: desc.type,
  21667. sdp: transform.write(session)
  21668. });
  21669. };
  21670. //endregion
  21671. module.exports = Simulcast;
  21672. },{"./transform-utils":77,"sdp-transform":79}],77:[function(require,module,exports){
  21673. /* Copyright @ 2015 Atlassian Pty Ltd
  21674. *
  21675. * Licensed under the Apache License, Version 2.0 (the "License");
  21676. * you may not use this file except in compliance with the License.
  21677. * You may obtain a copy of the License at
  21678. *
  21679. * http://www.apache.org/licenses/LICENSE-2.0
  21680. *
  21681. * Unless required by applicable law or agreed to in writing, software
  21682. * distributed under the License is distributed on an "AS IS" BASIS,
  21683. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21684. * See the License for the specific language governing permissions and
  21685. * limitations under the License.
  21686. */
  21687. exports.writeSsrcs = function(sources, order) {
  21688. var ssrcs = [];
  21689. // expand sources to ssrcs
  21690. if (typeof sources !== 'undefined' &&
  21691. Object.keys(sources).length !== 0) {
  21692. if (Array.isArray(order)) {
  21693. for (var i = 0; i < order.length; i++) {
  21694. var ssrc = order[i];
  21695. var source = sources[ssrc];
  21696. Object.keys(source).forEach(function (attribute) {
  21697. ssrcs.push({
  21698. id: ssrc,
  21699. attribute: attribute,
  21700. value: source[attribute]
  21701. });
  21702. });
  21703. }
  21704. } else {
  21705. Object.keys(sources).forEach(function (ssrc) {
  21706. var source = sources[ssrc];
  21707. Object.keys(source).forEach(function (attribute) {
  21708. ssrcs.push({
  21709. id: ssrc,
  21710. attribute: attribute,
  21711. value: source[attribute]
  21712. });
  21713. });
  21714. });
  21715. }
  21716. }
  21717. return ssrcs;
  21718. };
  21719. exports.parseSsrcs = function (mLine) {
  21720. var sources = {};
  21721. // group sources attributes by ssrc.
  21722. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  21723. mLine.ssrcs.forEach(function (ssrc) {
  21724. if (!sources[ssrc.id])
  21725. sources[ssrc.id] = {};
  21726. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  21727. });
  21728. }
  21729. return sources;
  21730. };
  21731. },{}],78:[function(require,module,exports){
  21732. arguments[4][72][0].apply(exports,arguments)
  21733. },{"dup":72}],79:[function(require,module,exports){
  21734. arguments[4][73][0].apply(exports,arguments)
  21735. },{"./parser":80,"./writer":81,"dup":73}],80:[function(require,module,exports){
  21736. arguments[4][74][0].apply(exports,arguments)
  21737. },{"./grammar":78,"dup":74}],81:[function(require,module,exports){
  21738. arguments[4][75][0].apply(exports,arguments)
  21739. },{"./grammar":78,"dup":75}],82:[function(require,module,exports){
  21740. arguments[4][72][0].apply(exports,arguments)
  21741. },{"dup":72}],83:[function(require,module,exports){
  21742. arguments[4][73][0].apply(exports,arguments)
  21743. },{"./parser":84,"./writer":85,"dup":73}],84:[function(require,module,exports){
  21744. arguments[4][74][0].apply(exports,arguments)
  21745. },{"./grammar":82,"dup":74}],85:[function(require,module,exports){
  21746. arguments[4][75][0].apply(exports,arguments)
  21747. },{"./grammar":82,"dup":75}],86:[function(require,module,exports){
  21748. module.exports = require('./lib/');
  21749. },{"./lib/":87}],87:[function(require,module,exports){
  21750. /**
  21751. * Module dependencies.
  21752. */
  21753. var url = require('./url');
  21754. var parser = require('socket.io-parser');
  21755. var Manager = require('./manager');
  21756. var debug = require('debug')('socket.io-client');
  21757. /**
  21758. * Module exports.
  21759. */
  21760. module.exports = exports = lookup;
  21761. /**
  21762. * Managers cache.
  21763. */
  21764. var cache = exports.managers = {};
  21765. /**
  21766. * Looks up an existing `Manager` for multiplexing.
  21767. * If the user summons:
  21768. *
  21769. * `io('http://localhost/a');`
  21770. * `io('http://localhost/b');`
  21771. *
  21772. * We reuse the existing instance based on same scheme/port/host,
  21773. * and we initialize sockets for each namespace.
  21774. *
  21775. * @api public
  21776. */
  21777. function lookup(uri, opts) {
  21778. if (typeof uri == 'object') {
  21779. opts = uri;
  21780. uri = undefined;
  21781. }
  21782. opts = opts || {};
  21783. var parsed = url(uri);
  21784. var source = parsed.source;
  21785. var id = parsed.id;
  21786. var io;
  21787. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  21788. debug('ignoring socket cache for %s', source);
  21789. io = Manager(source, opts);
  21790. } else {
  21791. if (!cache[id]) {
  21792. debug('new io instance for %s', source);
  21793. cache[id] = Manager(source, opts);
  21794. }
  21795. io = cache[id];
  21796. }
  21797. return io.socket(parsed.path);
  21798. }
  21799. /**
  21800. * Protocol version.
  21801. *
  21802. * @api public
  21803. */
  21804. exports.protocol = parser.protocol;
  21805. /**
  21806. * `connect`.
  21807. *
  21808. * @param {String} uri
  21809. * @api public
  21810. */
  21811. exports.connect = lookup;
  21812. /**
  21813. * Expose constructors for standalone build.
  21814. *
  21815. * @api public
  21816. */
  21817. exports.Manager = require('./manager');
  21818. exports.Socket = require('./socket');
  21819. },{"./manager":88,"./socket":90,"./url":91,"debug":95,"socket.io-parser":131}],88:[function(require,module,exports){
  21820. /**
  21821. * Module dependencies.
  21822. */
  21823. var url = require('./url');
  21824. var eio = require('engine.io-client');
  21825. var Socket = require('./socket');
  21826. var Emitter = require('component-emitter');
  21827. var parser = require('socket.io-parser');
  21828. var on = require('./on');
  21829. var bind = require('component-bind');
  21830. var object = require('object-component');
  21831. var debug = require('debug')('socket.io-client:manager');
  21832. var indexOf = require('indexof');
  21833. var Backoff = require('backo2');
  21834. /**
  21835. * Module exports
  21836. */
  21837. module.exports = Manager;
  21838. /**
  21839. * `Manager` constructor.
  21840. *
  21841. * @param {String} engine instance or engine uri/opts
  21842. * @param {Object} options
  21843. * @api public
  21844. */
  21845. function Manager(uri, opts){
  21846. if (!(this instanceof Manager)) return new Manager(uri, opts);
  21847. if (uri && ('object' == typeof uri)) {
  21848. opts = uri;
  21849. uri = undefined;
  21850. }
  21851. opts = opts || {};
  21852. opts.path = opts.path || '/socket.io';
  21853. this.nsps = {};
  21854. this.subs = [];
  21855. this.opts = opts;
  21856. this.reconnection(opts.reconnection !== false);
  21857. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  21858. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  21859. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  21860. this.randomizationFactor(opts.randomizationFactor || 0.5);
  21861. this.backoff = new Backoff({
  21862. min: this.reconnectionDelay(),
  21863. max: this.reconnectionDelayMax(),
  21864. jitter: this.randomizationFactor()
  21865. });
  21866. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  21867. this.readyState = 'closed';
  21868. this.uri = uri;
  21869. this.connected = [];
  21870. this.encoding = false;
  21871. this.packetBuffer = [];
  21872. this.encoder = new parser.Encoder();
  21873. this.decoder = new parser.Decoder();
  21874. this.autoConnect = opts.autoConnect !== false;
  21875. if (this.autoConnect) this.open();
  21876. }
  21877. /**
  21878. * Propagate given event to sockets and emit on `this`
  21879. *
  21880. * @api private
  21881. */
  21882. Manager.prototype.emitAll = function() {
  21883. this.emit.apply(this, arguments);
  21884. for (var nsp in this.nsps) {
  21885. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  21886. }
  21887. };
  21888. /**
  21889. * Update `socket.id` of all sockets
  21890. *
  21891. * @api private
  21892. */
  21893. Manager.prototype.updateSocketIds = function(){
  21894. for (var nsp in this.nsps) {
  21895. this.nsps[nsp].id = this.engine.id;
  21896. }
  21897. };
  21898. /**
  21899. * Mix in `Emitter`.
  21900. */
  21901. Emitter(Manager.prototype);
  21902. /**
  21903. * Sets the `reconnection` config.
  21904. *
  21905. * @param {Boolean} true/false if it should automatically reconnect
  21906. * @return {Manager} self or value
  21907. * @api public
  21908. */
  21909. Manager.prototype.reconnection = function(v){
  21910. if (!arguments.length) return this._reconnection;
  21911. this._reconnection = !!v;
  21912. return this;
  21913. };
  21914. /**
  21915. * Sets the reconnection attempts config.
  21916. *
  21917. * @param {Number} max reconnection attempts before giving up
  21918. * @return {Manager} self or value
  21919. * @api public
  21920. */
  21921. Manager.prototype.reconnectionAttempts = function(v){
  21922. if (!arguments.length) return this._reconnectionAttempts;
  21923. this._reconnectionAttempts = v;
  21924. return this;
  21925. };
  21926. /**
  21927. * Sets the delay between reconnections.
  21928. *
  21929. * @param {Number} delay
  21930. * @return {Manager} self or value
  21931. * @api public
  21932. */
  21933. Manager.prototype.reconnectionDelay = function(v){
  21934. if (!arguments.length) return this._reconnectionDelay;
  21935. this._reconnectionDelay = v;
  21936. this.backoff && this.backoff.setMin(v);
  21937. return this;
  21938. };
  21939. Manager.prototype.randomizationFactor = function(v){
  21940. if (!arguments.length) return this._randomizationFactor;
  21941. this._randomizationFactor = v;
  21942. this.backoff && this.backoff.setJitter(v);
  21943. return this;
  21944. };
  21945. /**
  21946. * Sets the maximum delay between reconnections.
  21947. *
  21948. * @param {Number} delay
  21949. * @return {Manager} self or value
  21950. * @api public
  21951. */
  21952. Manager.prototype.reconnectionDelayMax = function(v){
  21953. if (!arguments.length) return this._reconnectionDelayMax;
  21954. this._reconnectionDelayMax = v;
  21955. this.backoff && this.backoff.setMax(v);
  21956. return this;
  21957. };
  21958. /**
  21959. * Sets the connection timeout. `false` to disable
  21960. *
  21961. * @return {Manager} self or value
  21962. * @api public
  21963. */
  21964. Manager.prototype.timeout = function(v){
  21965. if (!arguments.length) return this._timeout;
  21966. this._timeout = v;
  21967. return this;
  21968. };
  21969. /**
  21970. * Starts trying to reconnect if reconnection is enabled and we have not
  21971. * started reconnecting yet
  21972. *
  21973. * @api private
  21974. */
  21975. Manager.prototype.maybeReconnectOnOpen = function() {
  21976. // Only try to reconnect if it's the first time we're connecting
  21977. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  21978. // keeps reconnection from firing twice for the same reconnection loop
  21979. this.reconnect();
  21980. }
  21981. };
  21982. /**
  21983. * Sets the current transport `socket`.
  21984. *
  21985. * @param {Function} optional, callback
  21986. * @return {Manager} self
  21987. * @api public
  21988. */
  21989. Manager.prototype.open =
  21990. Manager.prototype.connect = function(fn){
  21991. debug('readyState %s', this.readyState);
  21992. if (~this.readyState.indexOf('open')) return this;
  21993. debug('opening %s', this.uri);
  21994. this.engine = eio(this.uri, this.opts);
  21995. var socket = this.engine;
  21996. var self = this;
  21997. this.readyState = 'opening';
  21998. this.skipReconnect = false;
  21999. // emit `open`
  22000. var openSub = on(socket, 'open', function() {
  22001. self.onopen();
  22002. fn && fn();
  22003. });
  22004. // emit `connect_error`
  22005. var errorSub = on(socket, 'error', function(data){
  22006. debug('connect_error');
  22007. self.cleanup();
  22008. self.readyState = 'closed';
  22009. self.emitAll('connect_error', data);
  22010. if (fn) {
  22011. var err = new Error('Connection error');
  22012. err.data = data;
  22013. fn(err);
  22014. } else {
  22015. // Only do this if there is no fn to handle the error
  22016. self.maybeReconnectOnOpen();
  22017. }
  22018. });
  22019. // emit `connect_timeout`
  22020. if (false !== this._timeout) {
  22021. var timeout = this._timeout;
  22022. debug('connect attempt will timeout after %d', timeout);
  22023. // set timer
  22024. var timer = setTimeout(function(){
  22025. debug('connect attempt timed out after %d', timeout);
  22026. openSub.destroy();
  22027. socket.close();
  22028. socket.emit('error', 'timeout');
  22029. self.emitAll('connect_timeout', timeout);
  22030. }, timeout);
  22031. this.subs.push({
  22032. destroy: function(){
  22033. clearTimeout(timer);
  22034. }
  22035. });
  22036. }
  22037. this.subs.push(openSub);
  22038. this.subs.push(errorSub);
  22039. return this;
  22040. };
  22041. /**
  22042. * Called upon transport open.
  22043. *
  22044. * @api private
  22045. */
  22046. Manager.prototype.onopen = function(){
  22047. debug('open');
  22048. // clear old subs
  22049. this.cleanup();
  22050. // mark as open
  22051. this.readyState = 'open';
  22052. this.emit('open');
  22053. // add new subs
  22054. var socket = this.engine;
  22055. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  22056. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  22057. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  22058. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  22059. };
  22060. /**
  22061. * Called with data.
  22062. *
  22063. * @api private
  22064. */
  22065. Manager.prototype.ondata = function(data){
  22066. this.decoder.add(data);
  22067. };
  22068. /**
  22069. * Called when parser fully decodes a packet.
  22070. *
  22071. * @api private
  22072. */
  22073. Manager.prototype.ondecoded = function(packet) {
  22074. this.emit('packet', packet);
  22075. };
  22076. /**
  22077. * Called upon socket error.
  22078. *
  22079. * @api private
  22080. */
  22081. Manager.prototype.onerror = function(err){
  22082. debug('error', err);
  22083. this.emitAll('error', err);
  22084. };
  22085. /**
  22086. * Creates a new socket for the given `nsp`.
  22087. *
  22088. * @return {Socket}
  22089. * @api public
  22090. */
  22091. Manager.prototype.socket = function(nsp){
  22092. var socket = this.nsps[nsp];
  22093. if (!socket) {
  22094. socket = new Socket(this, nsp);
  22095. this.nsps[nsp] = socket;
  22096. var self = this;
  22097. socket.on('connect', function(){
  22098. socket.id = self.engine.id;
  22099. if (!~indexOf(self.connected, socket)) {
  22100. self.connected.push(socket);
  22101. }
  22102. });
  22103. }
  22104. return socket;
  22105. };
  22106. /**
  22107. * Called upon a socket close.
  22108. *
  22109. * @param {Socket} socket
  22110. */
  22111. Manager.prototype.destroy = function(socket){
  22112. var index = indexOf(this.connected, socket);
  22113. if (~index) this.connected.splice(index, 1);
  22114. if (this.connected.length) return;
  22115. this.close();
  22116. };
  22117. /**
  22118. * Writes a packet.
  22119. *
  22120. * @param {Object} packet
  22121. * @api private
  22122. */
  22123. Manager.prototype.packet = function(packet){
  22124. debug('writing packet %j', packet);
  22125. var self = this;
  22126. if (!self.encoding) {
  22127. // encode, then write to engine with result
  22128. self.encoding = true;
  22129. this.encoder.encode(packet, function(encodedPackets) {
  22130. for (var i = 0; i < encodedPackets.length; i++) {
  22131. self.engine.write(encodedPackets[i]);
  22132. }
  22133. self.encoding = false;
  22134. self.processPacketQueue();
  22135. });
  22136. } else { // add packet to the queue
  22137. self.packetBuffer.push(packet);
  22138. }
  22139. };
  22140. /**
  22141. * If packet buffer is non-empty, begins encoding the
  22142. * next packet in line.
  22143. *
  22144. * @api private
  22145. */
  22146. Manager.prototype.processPacketQueue = function() {
  22147. if (this.packetBuffer.length > 0 && !this.encoding) {
  22148. var pack = this.packetBuffer.shift();
  22149. this.packet(pack);
  22150. }
  22151. };
  22152. /**
  22153. * Clean up transport subscriptions and packet buffer.
  22154. *
  22155. * @api private
  22156. */
  22157. Manager.prototype.cleanup = function(){
  22158. var sub;
  22159. while (sub = this.subs.shift()) sub.destroy();
  22160. this.packetBuffer = [];
  22161. this.encoding = false;
  22162. this.decoder.destroy();
  22163. };
  22164. /**
  22165. * Close the current socket.
  22166. *
  22167. * @api private
  22168. */
  22169. Manager.prototype.close =
  22170. Manager.prototype.disconnect = function(){
  22171. this.skipReconnect = true;
  22172. this.backoff.reset();
  22173. this.readyState = 'closed';
  22174. this.engine && this.engine.close();
  22175. };
  22176. /**
  22177. * Called upon engine close.
  22178. *
  22179. * @api private
  22180. */
  22181. Manager.prototype.onclose = function(reason){
  22182. debug('close');
  22183. this.cleanup();
  22184. this.backoff.reset();
  22185. this.readyState = 'closed';
  22186. this.emit('close', reason);
  22187. if (this._reconnection && !this.skipReconnect) {
  22188. this.reconnect();
  22189. }
  22190. };
  22191. /**
  22192. * Attempt a reconnection.
  22193. *
  22194. * @api private
  22195. */
  22196. Manager.prototype.reconnect = function(){
  22197. if (this.reconnecting || this.skipReconnect) return this;
  22198. var self = this;
  22199. if (this.backoff.attempts >= this._reconnectionAttempts) {
  22200. debug('reconnect failed');
  22201. this.backoff.reset();
  22202. this.emitAll('reconnect_failed');
  22203. this.reconnecting = false;
  22204. } else {
  22205. var delay = this.backoff.duration();
  22206. debug('will wait %dms before reconnect attempt', delay);
  22207. this.reconnecting = true;
  22208. var timer = setTimeout(function(){
  22209. if (self.skipReconnect) return;
  22210. debug('attempting reconnect');
  22211. self.emitAll('reconnect_attempt', self.backoff.attempts);
  22212. self.emitAll('reconnecting', self.backoff.attempts);
  22213. // check again for the case socket closed in above events
  22214. if (self.skipReconnect) return;
  22215. self.open(function(err){
  22216. if (err) {
  22217. debug('reconnect attempt error');
  22218. self.reconnecting = false;
  22219. self.reconnect();
  22220. self.emitAll('reconnect_error', err.data);
  22221. } else {
  22222. debug('reconnect success');
  22223. self.onreconnect();
  22224. }
  22225. });
  22226. }, delay);
  22227. this.subs.push({
  22228. destroy: function(){
  22229. clearTimeout(timer);
  22230. }
  22231. });
  22232. }
  22233. };
  22234. /**
  22235. * Called upon successful reconnect.
  22236. *
  22237. * @api private
  22238. */
  22239. Manager.prototype.onreconnect = function(){
  22240. var attempt = this.backoff.attempts;
  22241. this.reconnecting = false;
  22242. this.backoff.reset();
  22243. this.updateSocketIds();
  22244. this.emitAll('reconnect', attempt);
  22245. };
  22246. },{"./on":89,"./socket":90,"./url":91,"backo2":92,"component-bind":93,"component-emitter":94,"debug":95,"engine.io-client":96,"indexof":127,"object-component":128,"socket.io-parser":131}],89:[function(require,module,exports){
  22247. /**
  22248. * Module exports.
  22249. */
  22250. module.exports = on;
  22251. /**
  22252. * Helper for subscriptions.
  22253. *
  22254. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  22255. * @param {String} event name
  22256. * @param {Function} callback
  22257. * @api public
  22258. */
  22259. function on(obj, ev, fn) {
  22260. obj.on(ev, fn);
  22261. return {
  22262. destroy: function(){
  22263. obj.removeListener(ev, fn);
  22264. }
  22265. };
  22266. }
  22267. },{}],90:[function(require,module,exports){
  22268. /**
  22269. * Module dependencies.
  22270. */
  22271. var parser = require('socket.io-parser');
  22272. var Emitter = require('component-emitter');
  22273. var toArray = require('to-array');
  22274. var on = require('./on');
  22275. var bind = require('component-bind');
  22276. var debug = require('debug')('socket.io-client:socket');
  22277. var hasBin = require('has-binary');
  22278. /**
  22279. * Module exports.
  22280. */
  22281. module.exports = exports = Socket;
  22282. /**
  22283. * Internal events (blacklisted).
  22284. * These events can't be emitted by the user.
  22285. *
  22286. * @api private
  22287. */
  22288. var events = {
  22289. connect: 1,
  22290. connect_error: 1,
  22291. connect_timeout: 1,
  22292. disconnect: 1,
  22293. error: 1,
  22294. reconnect: 1,
  22295. reconnect_attempt: 1,
  22296. reconnect_failed: 1,
  22297. reconnect_error: 1,
  22298. reconnecting: 1
  22299. };
  22300. /**
  22301. * Shortcut to `Emitter#emit`.
  22302. */
  22303. var emit = Emitter.prototype.emit;
  22304. /**
  22305. * `Socket` constructor.
  22306. *
  22307. * @api public
  22308. */
  22309. function Socket(io, nsp){
  22310. this.io = io;
  22311. this.nsp = nsp;
  22312. this.json = this; // compat
  22313. this.ids = 0;
  22314. this.acks = {};
  22315. if (this.io.autoConnect) this.open();
  22316. this.receiveBuffer = [];
  22317. this.sendBuffer = [];
  22318. this.connected = false;
  22319. this.disconnected = true;
  22320. }
  22321. /**
  22322. * Mix in `Emitter`.
  22323. */
  22324. Emitter(Socket.prototype);
  22325. /**
  22326. * Subscribe to open, close and packet events
  22327. *
  22328. * @api private
  22329. */
  22330. Socket.prototype.subEvents = function() {
  22331. if (this.subs) return;
  22332. var io = this.io;
  22333. this.subs = [
  22334. on(io, 'open', bind(this, 'onopen')),
  22335. on(io, 'packet', bind(this, 'onpacket')),
  22336. on(io, 'close', bind(this, 'onclose'))
  22337. ];
  22338. };
  22339. /**
  22340. * "Opens" the socket.
  22341. *
  22342. * @api public
  22343. */
  22344. Socket.prototype.open =
  22345. Socket.prototype.connect = function(){
  22346. if (this.connected) return this;
  22347. this.subEvents();
  22348. this.io.open(); // ensure open
  22349. if ('open' == this.io.readyState) this.onopen();
  22350. return this;
  22351. };
  22352. /**
  22353. * Sends a `message` event.
  22354. *
  22355. * @return {Socket} self
  22356. * @api public
  22357. */
  22358. Socket.prototype.send = function(){
  22359. var args = toArray(arguments);
  22360. args.unshift('message');
  22361. this.emit.apply(this, args);
  22362. return this;
  22363. };
  22364. /**
  22365. * Override `emit`.
  22366. * If the event is in `events`, it's emitted normally.
  22367. *
  22368. * @param {String} event name
  22369. * @return {Socket} self
  22370. * @api public
  22371. */
  22372. Socket.prototype.emit = function(ev){
  22373. if (events.hasOwnProperty(ev)) {
  22374. emit.apply(this, arguments);
  22375. return this;
  22376. }
  22377. var args = toArray(arguments);
  22378. var parserType = parser.EVENT; // default
  22379. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  22380. var packet = { type: parserType, data: args };
  22381. // event ack callback
  22382. if ('function' == typeof args[args.length - 1]) {
  22383. debug('emitting packet with ack id %d', this.ids);
  22384. this.acks[this.ids] = args.pop();
  22385. packet.id = this.ids++;
  22386. }
  22387. if (this.connected) {
  22388. this.packet(packet);
  22389. } else {
  22390. this.sendBuffer.push(packet);
  22391. }
  22392. return this;
  22393. };
  22394. /**
  22395. * Sends a packet.
  22396. *
  22397. * @param {Object} packet
  22398. * @api private
  22399. */
  22400. Socket.prototype.packet = function(packet){
  22401. packet.nsp = this.nsp;
  22402. this.io.packet(packet);
  22403. };
  22404. /**
  22405. * Called upon engine `open`.
  22406. *
  22407. * @api private
  22408. */
  22409. Socket.prototype.onopen = function(){
  22410. debug('transport is open - connecting');
  22411. // write connect packet if necessary
  22412. if ('/' != this.nsp) {
  22413. this.packet({ type: parser.CONNECT });
  22414. }
  22415. };
  22416. /**
  22417. * Called upon engine `close`.
  22418. *
  22419. * @param {String} reason
  22420. * @api private
  22421. */
  22422. Socket.prototype.onclose = function(reason){
  22423. debug('close (%s)', reason);
  22424. this.connected = false;
  22425. this.disconnected = true;
  22426. delete this.id;
  22427. this.emit('disconnect', reason);
  22428. };
  22429. /**
  22430. * Called with socket packet.
  22431. *
  22432. * @param {Object} packet
  22433. * @api private
  22434. */
  22435. Socket.prototype.onpacket = function(packet){
  22436. if (packet.nsp != this.nsp) return;
  22437. switch (packet.type) {
  22438. case parser.CONNECT:
  22439. this.onconnect();
  22440. break;
  22441. case parser.EVENT:
  22442. this.onevent(packet);
  22443. break;
  22444. case parser.BINARY_EVENT:
  22445. this.onevent(packet);
  22446. break;
  22447. case parser.ACK:
  22448. this.onack(packet);
  22449. break;
  22450. case parser.BINARY_ACK:
  22451. this.onack(packet);
  22452. break;
  22453. case parser.DISCONNECT:
  22454. this.ondisconnect();
  22455. break;
  22456. case parser.ERROR:
  22457. this.emit('error', packet.data);
  22458. break;
  22459. }
  22460. };
  22461. /**
  22462. * Called upon a server event.
  22463. *
  22464. * @param {Object} packet
  22465. * @api private
  22466. */
  22467. Socket.prototype.onevent = function(packet){
  22468. var args = packet.data || [];
  22469. debug('emitting event %j', args);
  22470. if (null != packet.id) {
  22471. debug('attaching ack callback to event');
  22472. args.push(this.ack(packet.id));
  22473. }
  22474. if (this.connected) {
  22475. emit.apply(this, args);
  22476. } else {
  22477. this.receiveBuffer.push(args);
  22478. }
  22479. };
  22480. /**
  22481. * Produces an ack callback to emit with an event.
  22482. *
  22483. * @api private
  22484. */
  22485. Socket.prototype.ack = function(id){
  22486. var self = this;
  22487. var sent = false;
  22488. return function(){
  22489. // prevent double callbacks
  22490. if (sent) return;
  22491. sent = true;
  22492. var args = toArray(arguments);
  22493. debug('sending ack %j', args);
  22494. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  22495. self.packet({
  22496. type: type,
  22497. id: id,
  22498. data: args
  22499. });
  22500. };
  22501. };
  22502. /**
  22503. * Called upon a server acknowlegement.
  22504. *
  22505. * @param {Object} packet
  22506. * @api private
  22507. */
  22508. Socket.prototype.onack = function(packet){
  22509. debug('calling ack %s with %j', packet.id, packet.data);
  22510. var fn = this.acks[packet.id];
  22511. fn.apply(this, packet.data);
  22512. delete this.acks[packet.id];
  22513. };
  22514. /**
  22515. * Called upon server connect.
  22516. *
  22517. * @api private
  22518. */
  22519. Socket.prototype.onconnect = function(){
  22520. this.connected = true;
  22521. this.disconnected = false;
  22522. this.emit('connect');
  22523. this.emitBuffered();
  22524. };
  22525. /**
  22526. * Emit buffered events (received and emitted).
  22527. *
  22528. * @api private
  22529. */
  22530. Socket.prototype.emitBuffered = function(){
  22531. var i;
  22532. for (i = 0; i < this.receiveBuffer.length; i++) {
  22533. emit.apply(this, this.receiveBuffer[i]);
  22534. }
  22535. this.receiveBuffer = [];
  22536. for (i = 0; i < this.sendBuffer.length; i++) {
  22537. this.packet(this.sendBuffer[i]);
  22538. }
  22539. this.sendBuffer = [];
  22540. };
  22541. /**
  22542. * Called upon server disconnect.
  22543. *
  22544. * @api private
  22545. */
  22546. Socket.prototype.ondisconnect = function(){
  22547. debug('server disconnect (%s)', this.nsp);
  22548. this.destroy();
  22549. this.onclose('io server disconnect');
  22550. };
  22551. /**
  22552. * Called upon forced client/server side disconnections,
  22553. * this method ensures the manager stops tracking us and
  22554. * that reconnections don't get triggered for this.
  22555. *
  22556. * @api private.
  22557. */
  22558. Socket.prototype.destroy = function(){
  22559. if (this.subs) {
  22560. // clean subscriptions to avoid reconnections
  22561. for (var i = 0; i < this.subs.length; i++) {
  22562. this.subs[i].destroy();
  22563. }
  22564. this.subs = null;
  22565. }
  22566. this.io.destroy(this);
  22567. };
  22568. /**
  22569. * Disconnects the socket manually.
  22570. *
  22571. * @return {Socket} self
  22572. * @api public
  22573. */
  22574. Socket.prototype.close =
  22575. Socket.prototype.disconnect = function(){
  22576. if (this.connected) {
  22577. debug('performing disconnect (%s)', this.nsp);
  22578. this.packet({ type: parser.DISCONNECT });
  22579. }
  22580. // remove socket from pool
  22581. this.destroy();
  22582. if (this.connected) {
  22583. // fire events
  22584. this.onclose('io client disconnect');
  22585. }
  22586. return this;
  22587. };
  22588. },{"./on":89,"component-bind":93,"component-emitter":94,"debug":95,"has-binary":125,"socket.io-parser":131,"to-array":135}],91:[function(require,module,exports){
  22589. (function (global){
  22590. /**
  22591. * Module dependencies.
  22592. */
  22593. var parseuri = require('parseuri');
  22594. var debug = require('debug')('socket.io-client:url');
  22595. /**
  22596. * Module exports.
  22597. */
  22598. module.exports = url;
  22599. /**
  22600. * URL parser.
  22601. *
  22602. * @param {String} url
  22603. * @param {Object} An object meant to mimic window.location.
  22604. * Defaults to window.location.
  22605. * @api public
  22606. */
  22607. function url(uri, loc){
  22608. var obj = uri;
  22609. // default to window.location
  22610. var loc = loc || global.location;
  22611. if (null == uri) uri = loc.protocol + '//' + loc.host;
  22612. // relative path support
  22613. if ('string' == typeof uri) {
  22614. if ('/' == uri.charAt(0)) {
  22615. if ('/' == uri.charAt(1)) {
  22616. uri = loc.protocol + uri;
  22617. } else {
  22618. uri = loc.hostname + uri;
  22619. }
  22620. }
  22621. if (!/^(https?|wss?):\/\//.test(uri)) {
  22622. debug('protocol-less url %s', uri);
  22623. if ('undefined' != typeof loc) {
  22624. uri = loc.protocol + '//' + uri;
  22625. } else {
  22626. uri = 'https://' + uri;
  22627. }
  22628. }
  22629. // parse
  22630. debug('parse %s', uri);
  22631. obj = parseuri(uri);
  22632. }
  22633. // make sure we treat `localhost:80` and `localhost` equally
  22634. if (!obj.port) {
  22635. if (/^(http|ws)$/.test(obj.protocol)) {
  22636. obj.port = '80';
  22637. }
  22638. else if (/^(http|ws)s$/.test(obj.protocol)) {
  22639. obj.port = '443';
  22640. }
  22641. }
  22642. obj.path = obj.path || '/';
  22643. // define unique id
  22644. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  22645. // define href
  22646. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  22647. return obj;
  22648. }
  22649. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22650. },{"debug":95,"parseuri":129}],92:[function(require,module,exports){
  22651. /**
  22652. * Expose `Backoff`.
  22653. */
  22654. module.exports = Backoff;
  22655. /**
  22656. * Initialize backoff timer with `opts`.
  22657. *
  22658. * - `min` initial timeout in milliseconds [100]
  22659. * - `max` max timeout [10000]
  22660. * - `jitter` [0]
  22661. * - `factor` [2]
  22662. *
  22663. * @param {Object} opts
  22664. * @api public
  22665. */
  22666. function Backoff(opts) {
  22667. opts = opts || {};
  22668. this.ms = opts.min || 100;
  22669. this.max = opts.max || 10000;
  22670. this.factor = opts.factor || 2;
  22671. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  22672. this.attempts = 0;
  22673. }
  22674. /**
  22675. * Return the backoff duration.
  22676. *
  22677. * @return {Number}
  22678. * @api public
  22679. */
  22680. Backoff.prototype.duration = function(){
  22681. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  22682. if (this.jitter) {
  22683. var rand = Math.random();
  22684. var deviation = Math.floor(rand * this.jitter * ms);
  22685. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  22686. }
  22687. return Math.min(ms, this.max) | 0;
  22688. };
  22689. /**
  22690. * Reset the number of attempts.
  22691. *
  22692. * @api public
  22693. */
  22694. Backoff.prototype.reset = function(){
  22695. this.attempts = 0;
  22696. };
  22697. /**
  22698. * Set the minimum duration
  22699. *
  22700. * @api public
  22701. */
  22702. Backoff.prototype.setMin = function(min){
  22703. this.ms = min;
  22704. };
  22705. /**
  22706. * Set the maximum duration
  22707. *
  22708. * @api public
  22709. */
  22710. Backoff.prototype.setMax = function(max){
  22711. this.max = max;
  22712. };
  22713. /**
  22714. * Set the jitter
  22715. *
  22716. * @api public
  22717. */
  22718. Backoff.prototype.setJitter = function(jitter){
  22719. this.jitter = jitter;
  22720. };
  22721. },{}],93:[function(require,module,exports){
  22722. /**
  22723. * Slice reference.
  22724. */
  22725. var slice = [].slice;
  22726. /**
  22727. * Bind `obj` to `fn`.
  22728. *
  22729. * @param {Object} obj
  22730. * @param {Function|String} fn or string
  22731. * @return {Function}
  22732. * @api public
  22733. */
  22734. module.exports = function(obj, fn){
  22735. if ('string' == typeof fn) fn = obj[fn];
  22736. if ('function' != typeof fn) throw new Error('bind() requires a function');
  22737. var args = slice.call(arguments, 2);
  22738. return function(){
  22739. return fn.apply(obj, args.concat(slice.call(arguments)));
  22740. }
  22741. };
  22742. },{}],94:[function(require,module,exports){
  22743. /**
  22744. * Expose `Emitter`.
  22745. */
  22746. module.exports = Emitter;
  22747. /**
  22748. * Initialize a new `Emitter`.
  22749. *
  22750. * @api public
  22751. */
  22752. function Emitter(obj) {
  22753. if (obj) return mixin(obj);
  22754. };
  22755. /**
  22756. * Mixin the emitter properties.
  22757. *
  22758. * @param {Object} obj
  22759. * @return {Object}
  22760. * @api private
  22761. */
  22762. function mixin(obj) {
  22763. for (var key in Emitter.prototype) {
  22764. obj[key] = Emitter.prototype[key];
  22765. }
  22766. return obj;
  22767. }
  22768. /**
  22769. * Listen on the given `event` with `fn`.
  22770. *
  22771. * @param {String} event
  22772. * @param {Function} fn
  22773. * @return {Emitter}
  22774. * @api public
  22775. */
  22776. Emitter.prototype.on =
  22777. Emitter.prototype.addEventListener = function(event, fn){
  22778. this._callbacks = this._callbacks || {};
  22779. (this._callbacks[event] = this._callbacks[event] || [])
  22780. .push(fn);
  22781. return this;
  22782. };
  22783. /**
  22784. * Adds an `event` listener that will be invoked a single
  22785. * time then automatically removed.
  22786. *
  22787. * @param {String} event
  22788. * @param {Function} fn
  22789. * @return {Emitter}
  22790. * @api public
  22791. */
  22792. Emitter.prototype.once = function(event, fn){
  22793. var self = this;
  22794. this._callbacks = this._callbacks || {};
  22795. function on() {
  22796. self.off(event, on);
  22797. fn.apply(this, arguments);
  22798. }
  22799. on.fn = fn;
  22800. this.on(event, on);
  22801. return this;
  22802. };
  22803. /**
  22804. * Remove the given callback for `event` or all
  22805. * registered callbacks.
  22806. *
  22807. * @param {String} event
  22808. * @param {Function} fn
  22809. * @return {Emitter}
  22810. * @api public
  22811. */
  22812. Emitter.prototype.off =
  22813. Emitter.prototype.removeListener =
  22814. Emitter.prototype.removeAllListeners =
  22815. Emitter.prototype.removeEventListener = function(event, fn){
  22816. this._callbacks = this._callbacks || {};
  22817. // all
  22818. if (0 == arguments.length) {
  22819. this._callbacks = {};
  22820. return this;
  22821. }
  22822. // specific event
  22823. var callbacks = this._callbacks[event];
  22824. if (!callbacks) return this;
  22825. // remove all handlers
  22826. if (1 == arguments.length) {
  22827. delete this._callbacks[event];
  22828. return this;
  22829. }
  22830. // remove specific handler
  22831. var cb;
  22832. for (var i = 0; i < callbacks.length; i++) {
  22833. cb = callbacks[i];
  22834. if (cb === fn || cb.fn === fn) {
  22835. callbacks.splice(i, 1);
  22836. break;
  22837. }
  22838. }
  22839. return this;
  22840. };
  22841. /**
  22842. * Emit `event` with the given args.
  22843. *
  22844. * @param {String} event
  22845. * @param {Mixed} ...
  22846. * @return {Emitter}
  22847. */
  22848. Emitter.prototype.emit = function(event){
  22849. this._callbacks = this._callbacks || {};
  22850. var args = [].slice.call(arguments, 1)
  22851. , callbacks = this._callbacks[event];
  22852. if (callbacks) {
  22853. callbacks = callbacks.slice(0);
  22854. for (var i = 0, len = callbacks.length; i < len; ++i) {
  22855. callbacks[i].apply(this, args);
  22856. }
  22857. }
  22858. return this;
  22859. };
  22860. /**
  22861. * Return array of callbacks for `event`.
  22862. *
  22863. * @param {String} event
  22864. * @return {Array}
  22865. * @api public
  22866. */
  22867. Emitter.prototype.listeners = function(event){
  22868. this._callbacks = this._callbacks || {};
  22869. return this._callbacks[event] || [];
  22870. };
  22871. /**
  22872. * Check if this emitter has `event` handlers.
  22873. *
  22874. * @param {String} event
  22875. * @return {Boolean}
  22876. * @api public
  22877. */
  22878. Emitter.prototype.hasListeners = function(event){
  22879. return !! this.listeners(event).length;
  22880. };
  22881. },{}],95:[function(require,module,exports){
  22882. /**
  22883. * Expose `debug()` as the module.
  22884. */
  22885. module.exports = debug;
  22886. /**
  22887. * Create a debugger with the given `name`.
  22888. *
  22889. * @param {String} name
  22890. * @return {Type}
  22891. * @api public
  22892. */
  22893. function debug(name) {
  22894. if (!debug.enabled(name)) return function(){};
  22895. return function(fmt){
  22896. fmt = coerce(fmt);
  22897. var curr = new Date;
  22898. var ms = curr - (debug[name] || curr);
  22899. debug[name] = curr;
  22900. fmt = name
  22901. + ' '
  22902. + fmt
  22903. + ' +' + debug.humanize(ms);
  22904. // This hackery is required for IE8
  22905. // where `console.log` doesn't have 'apply'
  22906. window.console
  22907. && console.log
  22908. && Function.prototype.apply.call(console.log, console, arguments);
  22909. }
  22910. }
  22911. /**
  22912. * The currently active debug mode names.
  22913. */
  22914. debug.names = [];
  22915. debug.skips = [];
  22916. /**
  22917. * Enables a debug mode by name. This can include modes
  22918. * separated by a colon and wildcards.
  22919. *
  22920. * @param {String} name
  22921. * @api public
  22922. */
  22923. debug.enable = function(name) {
  22924. try {
  22925. localStorage.debug = name;
  22926. } catch(e){}
  22927. var split = (name || '').split(/[\s,]+/)
  22928. , len = split.length;
  22929. for (var i = 0; i < len; i++) {
  22930. name = split[i].replace('*', '.*?');
  22931. if (name[0] === '-') {
  22932. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  22933. }
  22934. else {
  22935. debug.names.push(new RegExp('^' + name + '$'));
  22936. }
  22937. }
  22938. };
  22939. /**
  22940. * Disable debug output.
  22941. *
  22942. * @api public
  22943. */
  22944. debug.disable = function(){
  22945. debug.enable('');
  22946. };
  22947. /**
  22948. * Humanize the given `ms`.
  22949. *
  22950. * @param {Number} m
  22951. * @return {String}
  22952. * @api private
  22953. */
  22954. debug.humanize = function(ms) {
  22955. var sec = 1000
  22956. , min = 60 * 1000
  22957. , hour = 60 * min;
  22958. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  22959. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  22960. if (ms >= sec) return (ms / sec | 0) + 's';
  22961. return ms + 'ms';
  22962. };
  22963. /**
  22964. * Returns true if the given mode name is enabled, false otherwise.
  22965. *
  22966. * @param {String} name
  22967. * @return {Boolean}
  22968. * @api public
  22969. */
  22970. debug.enabled = function(name) {
  22971. for (var i = 0, len = debug.skips.length; i < len; i++) {
  22972. if (debug.skips[i].test(name)) {
  22973. return false;
  22974. }
  22975. }
  22976. for (var i = 0, len = debug.names.length; i < len; i++) {
  22977. if (debug.names[i].test(name)) {
  22978. return true;
  22979. }
  22980. }
  22981. return false;
  22982. };
  22983. /**
  22984. * Coerce `val`.
  22985. */
  22986. function coerce(val) {
  22987. if (val instanceof Error) return val.stack || val.message;
  22988. return val;
  22989. }
  22990. // persist
  22991. try {
  22992. if (window.localStorage) debug.enable(localStorage.debug);
  22993. } catch(e){}
  22994. },{}],96:[function(require,module,exports){
  22995. module.exports = require('./lib/');
  22996. },{"./lib/":97}],97:[function(require,module,exports){
  22997. module.exports = require('./socket');
  22998. /**
  22999. * Exports parser
  23000. *
  23001. * @api public
  23002. *
  23003. */
  23004. module.exports.parser = require('engine.io-parser');
  23005. },{"./socket":98,"engine.io-parser":110}],98:[function(require,module,exports){
  23006. (function (global){
  23007. /**
  23008. * Module dependencies.
  23009. */
  23010. var transports = require('./transports');
  23011. var Emitter = require('component-emitter');
  23012. var debug = require('debug')('engine.io-client:socket');
  23013. var index = require('indexof');
  23014. var parser = require('engine.io-parser');
  23015. var parseuri = require('parseuri');
  23016. var parsejson = require('parsejson');
  23017. var parseqs = require('parseqs');
  23018. /**
  23019. * Module exports.
  23020. */
  23021. module.exports = Socket;
  23022. /**
  23023. * Noop function.
  23024. *
  23025. * @api private
  23026. */
  23027. function noop(){}
  23028. /**
  23029. * Socket constructor.
  23030. *
  23031. * @param {String|Object} uri or options
  23032. * @param {Object} options
  23033. * @api public
  23034. */
  23035. function Socket(uri, opts){
  23036. if (!(this instanceof Socket)) return new Socket(uri, opts);
  23037. opts = opts || {};
  23038. if (uri && 'object' == typeof uri) {
  23039. opts = uri;
  23040. uri = null;
  23041. }
  23042. if (uri) {
  23043. uri = parseuri(uri);
  23044. opts.host = uri.host;
  23045. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  23046. opts.port = uri.port;
  23047. if (uri.query) opts.query = uri.query;
  23048. }
  23049. this.secure = null != opts.secure ? opts.secure :
  23050. (global.location && 'https:' == location.protocol);
  23051. if (opts.host) {
  23052. var pieces = opts.host.split(':');
  23053. opts.hostname = pieces.shift();
  23054. if (pieces.length) {
  23055. opts.port = pieces.pop();
  23056. } else if (!opts.port) {
  23057. // if no port is specified manually, use the protocol default
  23058. opts.port = this.secure ? '443' : '80';
  23059. }
  23060. }
  23061. this.agent = opts.agent || false;
  23062. this.hostname = opts.hostname ||
  23063. (global.location ? location.hostname : 'localhost');
  23064. this.port = opts.port || (global.location && location.port ?
  23065. location.port :
  23066. (this.secure ? 443 : 80));
  23067. this.query = opts.query || {};
  23068. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  23069. this.upgrade = false !== opts.upgrade;
  23070. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  23071. this.forceJSONP = !!opts.forceJSONP;
  23072. this.jsonp = false !== opts.jsonp;
  23073. this.forceBase64 = !!opts.forceBase64;
  23074. this.enablesXDR = !!opts.enablesXDR;
  23075. this.timestampParam = opts.timestampParam || 't';
  23076. this.timestampRequests = opts.timestampRequests;
  23077. this.transports = opts.transports || ['polling', 'websocket'];
  23078. this.readyState = '';
  23079. this.writeBuffer = [];
  23080. this.callbackBuffer = [];
  23081. this.policyPort = opts.policyPort || 843;
  23082. this.rememberUpgrade = opts.rememberUpgrade || false;
  23083. this.binaryType = null;
  23084. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  23085. // SSL options for Node.js client
  23086. this.pfx = opts.pfx || null;
  23087. this.key = opts.key || null;
  23088. this.passphrase = opts.passphrase || null;
  23089. this.cert = opts.cert || null;
  23090. this.ca = opts.ca || null;
  23091. this.ciphers = opts.ciphers || null;
  23092. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  23093. this.open();
  23094. }
  23095. Socket.priorWebsocketSuccess = false;
  23096. /**
  23097. * Mix in `Emitter`.
  23098. */
  23099. Emitter(Socket.prototype);
  23100. /**
  23101. * Protocol version.
  23102. *
  23103. * @api public
  23104. */
  23105. Socket.protocol = parser.protocol; // this is an int
  23106. /**
  23107. * Expose deps for legacy compatibility
  23108. * and standalone browser access.
  23109. */
  23110. Socket.Socket = Socket;
  23111. Socket.Transport = require('./transport');
  23112. Socket.transports = require('./transports');
  23113. Socket.parser = require('engine.io-parser');
  23114. /**
  23115. * Creates transport of the given type.
  23116. *
  23117. * @param {String} transport name
  23118. * @return {Transport}
  23119. * @api private
  23120. */
  23121. Socket.prototype.createTransport = function (name) {
  23122. debug('creating transport "%s"', name);
  23123. var query = clone(this.query);
  23124. // append engine.io protocol identifier
  23125. query.EIO = parser.protocol;
  23126. // transport name
  23127. query.transport = name;
  23128. // session id if we already have one
  23129. if (this.id) query.sid = this.id;
  23130. var transport = new transports[name]({
  23131. agent: this.agent,
  23132. hostname: this.hostname,
  23133. port: this.port,
  23134. secure: this.secure,
  23135. path: this.path,
  23136. query: query,
  23137. forceJSONP: this.forceJSONP,
  23138. jsonp: this.jsonp,
  23139. forceBase64: this.forceBase64,
  23140. enablesXDR: this.enablesXDR,
  23141. timestampRequests: this.timestampRequests,
  23142. timestampParam: this.timestampParam,
  23143. policyPort: this.policyPort,
  23144. socket: this,
  23145. pfx: this.pfx,
  23146. key: this.key,
  23147. passphrase: this.passphrase,
  23148. cert: this.cert,
  23149. ca: this.ca,
  23150. ciphers: this.ciphers,
  23151. rejectUnauthorized: this.rejectUnauthorized
  23152. });
  23153. return transport;
  23154. };
  23155. function clone (obj) {
  23156. var o = {};
  23157. for (var i in obj) {
  23158. if (obj.hasOwnProperty(i)) {
  23159. o[i] = obj[i];
  23160. }
  23161. }
  23162. return o;
  23163. }
  23164. /**
  23165. * Initializes transport to use and starts probe.
  23166. *
  23167. * @api private
  23168. */
  23169. Socket.prototype.open = function () {
  23170. var transport;
  23171. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  23172. transport = 'websocket';
  23173. } else if (0 == this.transports.length) {
  23174. // Emit error on next tick so it can be listened to
  23175. var self = this;
  23176. setTimeout(function() {
  23177. self.emit('error', 'No transports available');
  23178. }, 0);
  23179. return;
  23180. } else {
  23181. transport = this.transports[0];
  23182. }
  23183. this.readyState = 'opening';
  23184. // Retry with the next transport if the transport is disabled (jsonp: false)
  23185. var transport;
  23186. try {
  23187. transport = this.createTransport(transport);
  23188. } catch (e) {
  23189. this.transports.shift();
  23190. this.open();
  23191. return;
  23192. }
  23193. transport.open();
  23194. this.setTransport(transport);
  23195. };
  23196. /**
  23197. * Sets the current transport. Disables the existing one (if any).
  23198. *
  23199. * @api private
  23200. */
  23201. Socket.prototype.setTransport = function(transport){
  23202. debug('setting transport %s', transport.name);
  23203. var self = this;
  23204. if (this.transport) {
  23205. debug('clearing existing transport %s', this.transport.name);
  23206. this.transport.removeAllListeners();
  23207. }
  23208. // set up transport
  23209. this.transport = transport;
  23210. // set up transport listeners
  23211. transport
  23212. .on('drain', function(){
  23213. self.onDrain();
  23214. })
  23215. .on('packet', function(packet){
  23216. self.onPacket(packet);
  23217. })
  23218. .on('error', function(e){
  23219. self.onError(e);
  23220. })
  23221. .on('close', function(){
  23222. self.onClose('transport close');
  23223. });
  23224. };
  23225. /**
  23226. * Probes a transport.
  23227. *
  23228. * @param {String} transport name
  23229. * @api private
  23230. */
  23231. Socket.prototype.probe = function (name) {
  23232. debug('probing transport "%s"', name);
  23233. var transport = this.createTransport(name, { probe: 1 })
  23234. , failed = false
  23235. , self = this;
  23236. Socket.priorWebsocketSuccess = false;
  23237. function onTransportOpen(){
  23238. if (self.onlyBinaryUpgrades) {
  23239. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  23240. failed = failed || upgradeLosesBinary;
  23241. }
  23242. if (failed) return;
  23243. debug('probe transport "%s" opened', name);
  23244. transport.send([{ type: 'ping', data: 'probe' }]);
  23245. transport.once('packet', function (msg) {
  23246. if (failed) return;
  23247. if ('pong' == msg.type && 'probe' == msg.data) {
  23248. debug('probe transport "%s" pong', name);
  23249. self.upgrading = true;
  23250. self.emit('upgrading', transport);
  23251. if (!transport) return;
  23252. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  23253. debug('pausing current transport "%s"', self.transport.name);
  23254. self.transport.pause(function () {
  23255. if (failed) return;
  23256. if ('closed' == self.readyState) return;
  23257. debug('changing transport and sending upgrade packet');
  23258. cleanup();
  23259. self.setTransport(transport);
  23260. transport.send([{ type: 'upgrade' }]);
  23261. self.emit('upgrade', transport);
  23262. transport = null;
  23263. self.upgrading = false;
  23264. self.flush();
  23265. });
  23266. } else {
  23267. debug('probe transport "%s" failed', name);
  23268. var err = new Error('probe error');
  23269. err.transport = transport.name;
  23270. self.emit('upgradeError', err);
  23271. }
  23272. });
  23273. }
  23274. function freezeTransport() {
  23275. if (failed) return;
  23276. // Any callback called by transport should be ignored since now
  23277. failed = true;
  23278. cleanup();
  23279. transport.close();
  23280. transport = null;
  23281. }
  23282. //Handle any error that happens while probing
  23283. function onerror(err) {
  23284. var error = new Error('probe error: ' + err);
  23285. error.transport = transport.name;
  23286. freezeTransport();
  23287. debug('probe transport "%s" failed because of error: %s', name, err);
  23288. self.emit('upgradeError', error);
  23289. }
  23290. function onTransportClose(){
  23291. onerror("transport closed");
  23292. }
  23293. //When the socket is closed while we're probing
  23294. function onclose(){
  23295. onerror("socket closed");
  23296. }
  23297. //When the socket is upgraded while we're probing
  23298. function onupgrade(to){
  23299. if (transport && to.name != transport.name) {
  23300. debug('"%s" works - aborting "%s"', to.name, transport.name);
  23301. freezeTransport();
  23302. }
  23303. }
  23304. //Remove all listeners on the transport and on self
  23305. function cleanup(){
  23306. transport.removeListener('open', onTransportOpen);
  23307. transport.removeListener('error', onerror);
  23308. transport.removeListener('close', onTransportClose);
  23309. self.removeListener('close', onclose);
  23310. self.removeListener('upgrading', onupgrade);
  23311. }
  23312. transport.once('open', onTransportOpen);
  23313. transport.once('error', onerror);
  23314. transport.once('close', onTransportClose);
  23315. this.once('close', onclose);
  23316. this.once('upgrading', onupgrade);
  23317. transport.open();
  23318. };
  23319. /**
  23320. * Called when connection is deemed open.
  23321. *
  23322. * @api public
  23323. */
  23324. Socket.prototype.onOpen = function () {
  23325. debug('socket open');
  23326. this.readyState = 'open';
  23327. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  23328. this.emit('open');
  23329. this.flush();
  23330. // we check for `readyState` in case an `open`
  23331. // listener already closed the socket
  23332. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  23333. debug('starting upgrade probes');
  23334. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  23335. this.probe(this.upgrades[i]);
  23336. }
  23337. }
  23338. };
  23339. /**
  23340. * Handles a packet.
  23341. *
  23342. * @api private
  23343. */
  23344. Socket.prototype.onPacket = function (packet) {
  23345. if ('opening' == this.readyState || 'open' == this.readyState) {
  23346. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  23347. this.emit('packet', packet);
  23348. // Socket is live - any packet counts
  23349. this.emit('heartbeat');
  23350. switch (packet.type) {
  23351. case 'open':
  23352. this.onHandshake(parsejson(packet.data));
  23353. break;
  23354. case 'pong':
  23355. this.setPing();
  23356. break;
  23357. case 'error':
  23358. var err = new Error('server error');
  23359. err.code = packet.data;
  23360. this.emit('error', err);
  23361. break;
  23362. case 'message':
  23363. this.emit('data', packet.data);
  23364. this.emit('message', packet.data);
  23365. break;
  23366. }
  23367. } else {
  23368. debug('packet received with socket readyState "%s"', this.readyState);
  23369. }
  23370. };
  23371. /**
  23372. * Called upon handshake completion.
  23373. *
  23374. * @param {Object} handshake obj
  23375. * @api private
  23376. */
  23377. Socket.prototype.onHandshake = function (data) {
  23378. this.emit('handshake', data);
  23379. this.id = data.sid;
  23380. this.transport.query.sid = data.sid;
  23381. this.upgrades = this.filterUpgrades(data.upgrades);
  23382. this.pingInterval = data.pingInterval;
  23383. this.pingTimeout = data.pingTimeout;
  23384. this.onOpen();
  23385. // In case open handler closes socket
  23386. if ('closed' == this.readyState) return;
  23387. this.setPing();
  23388. // Prolong liveness of socket on heartbeat
  23389. this.removeListener('heartbeat', this.onHeartbeat);
  23390. this.on('heartbeat', this.onHeartbeat);
  23391. };
  23392. /**
  23393. * Resets ping timeout.
  23394. *
  23395. * @api private
  23396. */
  23397. Socket.prototype.onHeartbeat = function (timeout) {
  23398. clearTimeout(this.pingTimeoutTimer);
  23399. var self = this;
  23400. self.pingTimeoutTimer = setTimeout(function () {
  23401. if ('closed' == self.readyState) return;
  23402. self.onClose('ping timeout');
  23403. }, timeout || (self.pingInterval + self.pingTimeout));
  23404. };
  23405. /**
  23406. * Pings server every `this.pingInterval` and expects response
  23407. * within `this.pingTimeout` or closes connection.
  23408. *
  23409. * @api private
  23410. */
  23411. Socket.prototype.setPing = function () {
  23412. var self = this;
  23413. clearTimeout(self.pingIntervalTimer);
  23414. self.pingIntervalTimer = setTimeout(function () {
  23415. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  23416. self.ping();
  23417. self.onHeartbeat(self.pingTimeout);
  23418. }, self.pingInterval);
  23419. };
  23420. /**
  23421. * Sends a ping packet.
  23422. *
  23423. * @api public
  23424. */
  23425. Socket.prototype.ping = function () {
  23426. this.sendPacket('ping');
  23427. };
  23428. /**
  23429. * Called on `drain` event
  23430. *
  23431. * @api private
  23432. */
  23433. Socket.prototype.onDrain = function() {
  23434. for (var i = 0; i < this.prevBufferLen; i++) {
  23435. if (this.callbackBuffer[i]) {
  23436. this.callbackBuffer[i]();
  23437. }
  23438. }
  23439. this.writeBuffer.splice(0, this.prevBufferLen);
  23440. this.callbackBuffer.splice(0, this.prevBufferLen);
  23441. // setting prevBufferLen = 0 is very important
  23442. // for example, when upgrading, upgrade packet is sent over,
  23443. // and a nonzero prevBufferLen could cause problems on `drain`
  23444. this.prevBufferLen = 0;
  23445. if (this.writeBuffer.length == 0) {
  23446. this.emit('drain');
  23447. } else {
  23448. this.flush();
  23449. }
  23450. };
  23451. /**
  23452. * Flush write buffers.
  23453. *
  23454. * @api private
  23455. */
  23456. Socket.prototype.flush = function () {
  23457. if ('closed' != this.readyState && this.transport.writable &&
  23458. !this.upgrading && this.writeBuffer.length) {
  23459. debug('flushing %d packets in socket', this.writeBuffer.length);
  23460. this.transport.send(this.writeBuffer);
  23461. // keep track of current length of writeBuffer
  23462. // splice writeBuffer and callbackBuffer on `drain`
  23463. this.prevBufferLen = this.writeBuffer.length;
  23464. this.emit('flush');
  23465. }
  23466. };
  23467. /**
  23468. * Sends a message.
  23469. *
  23470. * @param {String} message.
  23471. * @param {Function} callback function.
  23472. * @return {Socket} for chaining.
  23473. * @api public
  23474. */
  23475. Socket.prototype.write =
  23476. Socket.prototype.send = function (msg, fn) {
  23477. this.sendPacket('message', msg, fn);
  23478. return this;
  23479. };
  23480. /**
  23481. * Sends a packet.
  23482. *
  23483. * @param {String} packet type.
  23484. * @param {String} data.
  23485. * @param {Function} callback function.
  23486. * @api private
  23487. */
  23488. Socket.prototype.sendPacket = function (type, data, fn) {
  23489. if ('closing' == this.readyState || 'closed' == this.readyState) {
  23490. return;
  23491. }
  23492. var packet = { type: type, data: data };
  23493. this.emit('packetCreate', packet);
  23494. this.writeBuffer.push(packet);
  23495. this.callbackBuffer.push(fn);
  23496. this.flush();
  23497. };
  23498. /**
  23499. * Closes the connection.
  23500. *
  23501. * @api private
  23502. */
  23503. Socket.prototype.close = function () {
  23504. if ('opening' == this.readyState || 'open' == this.readyState) {
  23505. this.readyState = 'closing';
  23506. var self = this;
  23507. function close() {
  23508. self.onClose('forced close');
  23509. debug('socket closing - telling transport to close');
  23510. self.transport.close();
  23511. }
  23512. function cleanupAndClose() {
  23513. self.removeListener('upgrade', cleanupAndClose);
  23514. self.removeListener('upgradeError', cleanupAndClose);
  23515. close();
  23516. }
  23517. function waitForUpgrade() {
  23518. // wait for upgrade to finish since we can't send packets while pausing a transport
  23519. self.once('upgrade', cleanupAndClose);
  23520. self.once('upgradeError', cleanupAndClose);
  23521. }
  23522. if (this.writeBuffer.length) {
  23523. this.once('drain', function() {
  23524. if (this.upgrading) {
  23525. waitForUpgrade();
  23526. } else {
  23527. close();
  23528. }
  23529. });
  23530. } else if (this.upgrading) {
  23531. waitForUpgrade();
  23532. } else {
  23533. close();
  23534. }
  23535. }
  23536. return this;
  23537. };
  23538. /**
  23539. * Called upon transport error
  23540. *
  23541. * @api private
  23542. */
  23543. Socket.prototype.onError = function (err) {
  23544. debug('socket error %j', err);
  23545. Socket.priorWebsocketSuccess = false;
  23546. this.emit('error', err);
  23547. this.onClose('transport error', err);
  23548. };
  23549. /**
  23550. * Called upon transport close.
  23551. *
  23552. * @api private
  23553. */
  23554. Socket.prototype.onClose = function (reason, desc) {
  23555. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  23556. debug('socket close with reason: "%s"', reason);
  23557. var self = this;
  23558. // clear timers
  23559. clearTimeout(this.pingIntervalTimer);
  23560. clearTimeout(this.pingTimeoutTimer);
  23561. // clean buffers in next tick, so developers can still
  23562. // grab the buffers on `close` event
  23563. setTimeout(function() {
  23564. self.writeBuffer = [];
  23565. self.callbackBuffer = [];
  23566. self.prevBufferLen = 0;
  23567. }, 0);
  23568. // stop event from firing again for transport
  23569. this.transport.removeAllListeners('close');
  23570. // ensure transport won't stay open
  23571. this.transport.close();
  23572. // ignore further transport communication
  23573. this.transport.removeAllListeners();
  23574. // set ready state
  23575. this.readyState = 'closed';
  23576. // clear session id
  23577. this.id = null;
  23578. // emit close event
  23579. this.emit('close', reason, desc);
  23580. }
  23581. };
  23582. /**
  23583. * Filters upgrades, returning only those matching client transports.
  23584. *
  23585. * @param {Array} server upgrades
  23586. * @api private
  23587. *
  23588. */
  23589. Socket.prototype.filterUpgrades = function (upgrades) {
  23590. var filteredUpgrades = [];
  23591. for (var i = 0, j = upgrades.length; i<j; i++) {
  23592. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  23593. }
  23594. return filteredUpgrades;
  23595. };
  23596. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23597. },{"./transport":99,"./transports":100,"component-emitter":94,"debug":107,"engine.io-parser":110,"indexof":127,"parsejson":121,"parseqs":122,"parseuri":123}],99:[function(require,module,exports){
  23598. /**
  23599. * Module dependencies.
  23600. */
  23601. var parser = require('engine.io-parser');
  23602. var Emitter = require('component-emitter');
  23603. /**
  23604. * Module exports.
  23605. */
  23606. module.exports = Transport;
  23607. /**
  23608. * Transport abstract constructor.
  23609. *
  23610. * @param {Object} options.
  23611. * @api private
  23612. */
  23613. function Transport (opts) {
  23614. this.path = opts.path;
  23615. this.hostname = opts.hostname;
  23616. this.port = opts.port;
  23617. this.secure = opts.secure;
  23618. this.query = opts.query;
  23619. this.timestampParam = opts.timestampParam;
  23620. this.timestampRequests = opts.timestampRequests;
  23621. this.readyState = '';
  23622. this.agent = opts.agent || false;
  23623. this.socket = opts.socket;
  23624. this.enablesXDR = opts.enablesXDR;
  23625. // SSL options for Node.js client
  23626. this.pfx = opts.pfx;
  23627. this.key = opts.key;
  23628. this.passphrase = opts.passphrase;
  23629. this.cert = opts.cert;
  23630. this.ca = opts.ca;
  23631. this.ciphers = opts.ciphers;
  23632. this.rejectUnauthorized = opts.rejectUnauthorized;
  23633. }
  23634. /**
  23635. * Mix in `Emitter`.
  23636. */
  23637. Emitter(Transport.prototype);
  23638. /**
  23639. * A counter used to prevent collisions in the timestamps used
  23640. * for cache busting.
  23641. */
  23642. Transport.timestamps = 0;
  23643. /**
  23644. * Emits an error.
  23645. *
  23646. * @param {String} str
  23647. * @return {Transport} for chaining
  23648. * @api public
  23649. */
  23650. Transport.prototype.onError = function (msg, desc) {
  23651. var err = new Error(msg);
  23652. err.type = 'TransportError';
  23653. err.description = desc;
  23654. this.emit('error', err);
  23655. return this;
  23656. };
  23657. /**
  23658. * Opens the transport.
  23659. *
  23660. * @api public
  23661. */
  23662. Transport.prototype.open = function () {
  23663. if ('closed' == this.readyState || '' == this.readyState) {
  23664. this.readyState = 'opening';
  23665. this.doOpen();
  23666. }
  23667. return this;
  23668. };
  23669. /**
  23670. * Closes the transport.
  23671. *
  23672. * @api private
  23673. */
  23674. Transport.prototype.close = function () {
  23675. if ('opening' == this.readyState || 'open' == this.readyState) {
  23676. this.doClose();
  23677. this.onClose();
  23678. }
  23679. return this;
  23680. };
  23681. /**
  23682. * Sends multiple packets.
  23683. *
  23684. * @param {Array} packets
  23685. * @api private
  23686. */
  23687. Transport.prototype.send = function(packets){
  23688. if ('open' == this.readyState) {
  23689. this.write(packets);
  23690. } else {
  23691. throw new Error('Transport not open');
  23692. }
  23693. };
  23694. /**
  23695. * Called upon open
  23696. *
  23697. * @api private
  23698. */
  23699. Transport.prototype.onOpen = function () {
  23700. this.readyState = 'open';
  23701. this.writable = true;
  23702. this.emit('open');
  23703. };
  23704. /**
  23705. * Called with data.
  23706. *
  23707. * @param {String} data
  23708. * @api private
  23709. */
  23710. Transport.prototype.onData = function(data){
  23711. var packet = parser.decodePacket(data, this.socket.binaryType);
  23712. this.onPacket(packet);
  23713. };
  23714. /**
  23715. * Called with a decoded packet.
  23716. */
  23717. Transport.prototype.onPacket = function (packet) {
  23718. this.emit('packet', packet);
  23719. };
  23720. /**
  23721. * Called upon close.
  23722. *
  23723. * @api private
  23724. */
  23725. Transport.prototype.onClose = function () {
  23726. this.readyState = 'closed';
  23727. this.emit('close');
  23728. };
  23729. },{"component-emitter":94,"engine.io-parser":110}],100:[function(require,module,exports){
  23730. (function (global){
  23731. /**
  23732. * Module dependencies
  23733. */
  23734. var XMLHttpRequest = require('xmlhttprequest');
  23735. var XHR = require('./polling-xhr');
  23736. var JSONP = require('./polling-jsonp');
  23737. var websocket = require('./websocket');
  23738. /**
  23739. * Export transports.
  23740. */
  23741. exports.polling = polling;
  23742. exports.websocket = websocket;
  23743. /**
  23744. * Polling transport polymorphic constructor.
  23745. * Decides on xhr vs jsonp based on feature detection.
  23746. *
  23747. * @api private
  23748. */
  23749. function polling(opts){
  23750. var xhr;
  23751. var xd = false;
  23752. var xs = false;
  23753. var jsonp = false !== opts.jsonp;
  23754. if (global.location) {
  23755. var isSSL = 'https:' == location.protocol;
  23756. var port = location.port;
  23757. // some user agents have empty `location.port`
  23758. if (!port) {
  23759. port = isSSL ? 443 : 80;
  23760. }
  23761. xd = opts.hostname != location.hostname || port != opts.port;
  23762. xs = opts.secure != isSSL;
  23763. }
  23764. opts.xdomain = xd;
  23765. opts.xscheme = xs;
  23766. xhr = new XMLHttpRequest(opts);
  23767. if ('open' in xhr && !opts.forceJSONP) {
  23768. return new XHR(opts);
  23769. } else {
  23770. if (!jsonp) throw new Error('JSONP disabled');
  23771. return new JSONP(opts);
  23772. }
  23773. }
  23774. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23775. },{"./polling-jsonp":101,"./polling-xhr":102,"./websocket":104,"xmlhttprequest":105}],101:[function(require,module,exports){
  23776. (function (global){
  23777. /**
  23778. * Module requirements.
  23779. */
  23780. var Polling = require('./polling');
  23781. var inherit = require('component-inherit');
  23782. /**
  23783. * Module exports.
  23784. */
  23785. module.exports = JSONPPolling;
  23786. /**
  23787. * Cached regular expressions.
  23788. */
  23789. var rNewline = /\n/g;
  23790. var rEscapedNewline = /\\n/g;
  23791. /**
  23792. * Global JSONP callbacks.
  23793. */
  23794. var callbacks;
  23795. /**
  23796. * Callbacks count.
  23797. */
  23798. var index = 0;
  23799. /**
  23800. * Noop.
  23801. */
  23802. function empty () { }
  23803. /**
  23804. * JSONP Polling constructor.
  23805. *
  23806. * @param {Object} opts.
  23807. * @api public
  23808. */
  23809. function JSONPPolling (opts) {
  23810. Polling.call(this, opts);
  23811. this.query = this.query || {};
  23812. // define global callbacks array if not present
  23813. // we do this here (lazily) to avoid unneeded global pollution
  23814. if (!callbacks) {
  23815. // we need to consider multiple engines in the same page
  23816. if (!global.___eio) global.___eio = [];
  23817. callbacks = global.___eio;
  23818. }
  23819. // callback identifier
  23820. this.index = callbacks.length;
  23821. // add callback to jsonp global
  23822. var self = this;
  23823. callbacks.push(function (msg) {
  23824. self.onData(msg);
  23825. });
  23826. // append to query string
  23827. this.query.j = this.index;
  23828. // prevent spurious errors from being emitted when the window is unloaded
  23829. if (global.document && global.addEventListener) {
  23830. global.addEventListener('beforeunload', function () {
  23831. if (self.script) self.script.onerror = empty;
  23832. }, false);
  23833. }
  23834. }
  23835. /**
  23836. * Inherits from Polling.
  23837. */
  23838. inherit(JSONPPolling, Polling);
  23839. /*
  23840. * JSONP only supports binary as base64 encoded strings
  23841. */
  23842. JSONPPolling.prototype.supportsBinary = false;
  23843. /**
  23844. * Closes the socket.
  23845. *
  23846. * @api private
  23847. */
  23848. JSONPPolling.prototype.doClose = function () {
  23849. if (this.script) {
  23850. this.script.parentNode.removeChild(this.script);
  23851. this.script = null;
  23852. }
  23853. if (this.form) {
  23854. this.form.parentNode.removeChild(this.form);
  23855. this.form = null;
  23856. this.iframe = null;
  23857. }
  23858. Polling.prototype.doClose.call(this);
  23859. };
  23860. /**
  23861. * Starts a poll cycle.
  23862. *
  23863. * @api private
  23864. */
  23865. JSONPPolling.prototype.doPoll = function () {
  23866. var self = this;
  23867. var script = document.createElement('script');
  23868. if (this.script) {
  23869. this.script.parentNode.removeChild(this.script);
  23870. this.script = null;
  23871. }
  23872. script.async = true;
  23873. script.src = this.uri();
  23874. script.onerror = function(e){
  23875. self.onError('jsonp poll error',e);
  23876. };
  23877. var insertAt = document.getElementsByTagName('script')[0];
  23878. insertAt.parentNode.insertBefore(script, insertAt);
  23879. this.script = script;
  23880. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  23881. if (isUAgecko) {
  23882. setTimeout(function () {
  23883. var iframe = document.createElement('iframe');
  23884. document.body.appendChild(iframe);
  23885. document.body.removeChild(iframe);
  23886. }, 100);
  23887. }
  23888. };
  23889. /**
  23890. * Writes with a hidden iframe.
  23891. *
  23892. * @param {String} data to send
  23893. * @param {Function} called upon flush.
  23894. * @api private
  23895. */
  23896. JSONPPolling.prototype.doWrite = function (data, fn) {
  23897. var self = this;
  23898. if (!this.form) {
  23899. var form = document.createElement('form');
  23900. var area = document.createElement('textarea');
  23901. var id = this.iframeId = 'eio_iframe_' + this.index;
  23902. var iframe;
  23903. form.className = 'socketio';
  23904. form.style.position = 'absolute';
  23905. form.style.top = '-1000px';
  23906. form.style.left = '-1000px';
  23907. form.target = id;
  23908. form.method = 'POST';
  23909. form.setAttribute('accept-charset', 'utf-8');
  23910. area.name = 'd';
  23911. form.appendChild(area);
  23912. document.body.appendChild(form);
  23913. this.form = form;
  23914. this.area = area;
  23915. }
  23916. this.form.action = this.uri();
  23917. function complete () {
  23918. initIframe();
  23919. fn();
  23920. }
  23921. function initIframe () {
  23922. if (self.iframe) {
  23923. try {
  23924. self.form.removeChild(self.iframe);
  23925. } catch (e) {
  23926. self.onError('jsonp polling iframe removal error', e);
  23927. }
  23928. }
  23929. try {
  23930. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  23931. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  23932. iframe = document.createElement(html);
  23933. } catch (e) {
  23934. iframe = document.createElement('iframe');
  23935. iframe.name = self.iframeId;
  23936. iframe.src = 'javascript:0';
  23937. }
  23938. iframe.id = self.iframeId;
  23939. self.form.appendChild(iframe);
  23940. self.iframe = iframe;
  23941. }
  23942. initIframe();
  23943. // escape \n to prevent it from being converted into \r\n by some UAs
  23944. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  23945. data = data.replace(rEscapedNewline, '\\\n');
  23946. this.area.value = data.replace(rNewline, '\\n');
  23947. try {
  23948. this.form.submit();
  23949. } catch(e) {}
  23950. if (this.iframe.attachEvent) {
  23951. this.iframe.onreadystatechange = function(){
  23952. if (self.iframe.readyState == 'complete') {
  23953. complete();
  23954. }
  23955. };
  23956. } else {
  23957. this.iframe.onload = complete;
  23958. }
  23959. };
  23960. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23961. },{"./polling":103,"component-inherit":106}],102:[function(require,module,exports){
  23962. (function (global){
  23963. /**
  23964. * Module requirements.
  23965. */
  23966. var XMLHttpRequest = require('xmlhttprequest');
  23967. var Polling = require('./polling');
  23968. var Emitter = require('component-emitter');
  23969. var inherit = require('component-inherit');
  23970. var debug = require('debug')('engine.io-client:polling-xhr');
  23971. /**
  23972. * Module exports.
  23973. */
  23974. module.exports = XHR;
  23975. module.exports.Request = Request;
  23976. /**
  23977. * Empty function
  23978. */
  23979. function empty(){}
  23980. /**
  23981. * XHR Polling constructor.
  23982. *
  23983. * @param {Object} opts
  23984. * @api public
  23985. */
  23986. function XHR(opts){
  23987. Polling.call(this, opts);
  23988. if (global.location) {
  23989. var isSSL = 'https:' == location.protocol;
  23990. var port = location.port;
  23991. // some user agents have empty `location.port`
  23992. if (!port) {
  23993. port = isSSL ? 443 : 80;
  23994. }
  23995. this.xd = opts.hostname != global.location.hostname ||
  23996. port != opts.port;
  23997. this.xs = opts.secure != isSSL;
  23998. }
  23999. }
  24000. /**
  24001. * Inherits from Polling.
  24002. */
  24003. inherit(XHR, Polling);
  24004. /**
  24005. * XHR supports binary
  24006. */
  24007. XHR.prototype.supportsBinary = true;
  24008. /**
  24009. * Creates a request.
  24010. *
  24011. * @param {String} method
  24012. * @api private
  24013. */
  24014. XHR.prototype.request = function(opts){
  24015. opts = opts || {};
  24016. opts.uri = this.uri();
  24017. opts.xd = this.xd;
  24018. opts.xs = this.xs;
  24019. opts.agent = this.agent || false;
  24020. opts.supportsBinary = this.supportsBinary;
  24021. opts.enablesXDR = this.enablesXDR;
  24022. // SSL options for Node.js client
  24023. opts.pfx = this.pfx;
  24024. opts.key = this.key;
  24025. opts.passphrase = this.passphrase;
  24026. opts.cert = this.cert;
  24027. opts.ca = this.ca;
  24028. opts.ciphers = this.ciphers;
  24029. opts.rejectUnauthorized = this.rejectUnauthorized;
  24030. return new Request(opts);
  24031. };
  24032. /**
  24033. * Sends data.
  24034. *
  24035. * @param {String} data to send.
  24036. * @param {Function} called upon flush.
  24037. * @api private
  24038. */
  24039. XHR.prototype.doWrite = function(data, fn){
  24040. var isBinary = typeof data !== 'string' && data !== undefined;
  24041. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  24042. var self = this;
  24043. req.on('success', fn);
  24044. req.on('error', function(err){
  24045. self.onError('xhr post error', err);
  24046. });
  24047. this.sendXhr = req;
  24048. };
  24049. /**
  24050. * Starts a poll cycle.
  24051. *
  24052. * @api private
  24053. */
  24054. XHR.prototype.doPoll = function(){
  24055. debug('xhr poll');
  24056. var req = this.request();
  24057. var self = this;
  24058. req.on('data', function(data){
  24059. self.onData(data);
  24060. });
  24061. req.on('error', function(err){
  24062. self.onError('xhr poll error', err);
  24063. });
  24064. this.pollXhr = req;
  24065. };
  24066. /**
  24067. * Request constructor
  24068. *
  24069. * @param {Object} options
  24070. * @api public
  24071. */
  24072. function Request(opts){
  24073. this.method = opts.method || 'GET';
  24074. this.uri = opts.uri;
  24075. this.xd = !!opts.xd;
  24076. this.xs = !!opts.xs;
  24077. this.async = false !== opts.async;
  24078. this.data = undefined != opts.data ? opts.data : null;
  24079. this.agent = opts.agent;
  24080. this.isBinary = opts.isBinary;
  24081. this.supportsBinary = opts.supportsBinary;
  24082. this.enablesXDR = opts.enablesXDR;
  24083. // SSL options for Node.js client
  24084. this.pfx = opts.pfx;
  24085. this.key = opts.key;
  24086. this.passphrase = opts.passphrase;
  24087. this.cert = opts.cert;
  24088. this.ca = opts.ca;
  24089. this.ciphers = opts.ciphers;
  24090. this.rejectUnauthorized = opts.rejectUnauthorized;
  24091. this.create();
  24092. }
  24093. /**
  24094. * Mix in `Emitter`.
  24095. */
  24096. Emitter(Request.prototype);
  24097. /**
  24098. * Creates the XHR object and sends the request.
  24099. *
  24100. * @api private
  24101. */
  24102. Request.prototype.create = function(){
  24103. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  24104. // SSL options for Node.js client
  24105. opts.pfx = this.pfx;
  24106. opts.key = this.key;
  24107. opts.passphrase = this.passphrase;
  24108. opts.cert = this.cert;
  24109. opts.ca = this.ca;
  24110. opts.ciphers = this.ciphers;
  24111. opts.rejectUnauthorized = this.rejectUnauthorized;
  24112. var xhr = this.xhr = new XMLHttpRequest(opts);
  24113. var self = this;
  24114. try {
  24115. debug('xhr open %s: %s', this.method, this.uri);
  24116. xhr.open(this.method, this.uri, this.async);
  24117. if (this.supportsBinary) {
  24118. // This has to be done after open because Firefox is stupid
  24119. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  24120. xhr.responseType = 'arraybuffer';
  24121. }
  24122. if ('POST' == this.method) {
  24123. try {
  24124. if (this.isBinary) {
  24125. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  24126. } else {
  24127. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  24128. }
  24129. } catch (e) {}
  24130. }
  24131. // ie6 check
  24132. if ('withCredentials' in xhr) {
  24133. xhr.withCredentials = true;
  24134. }
  24135. if (this.hasXDR()) {
  24136. xhr.onload = function(){
  24137. self.onLoad();
  24138. };
  24139. xhr.onerror = function(){
  24140. self.onError(xhr.responseText);
  24141. };
  24142. } else {
  24143. xhr.onreadystatechange = function(){
  24144. if (4 != xhr.readyState) return;
  24145. if (200 == xhr.status || 1223 == xhr.status) {
  24146. self.onLoad();
  24147. } else {
  24148. // make sure the `error` event handler that's user-set
  24149. // does not throw in the same tick and gets caught here
  24150. setTimeout(function(){
  24151. self.onError(xhr.status);
  24152. }, 0);
  24153. }
  24154. };
  24155. }
  24156. debug('xhr data %s', this.data);
  24157. xhr.send(this.data);
  24158. } catch (e) {
  24159. // Need to defer since .create() is called directly fhrom the constructor
  24160. // and thus the 'error' event can only be only bound *after* this exception
  24161. // occurs. Therefore, also, we cannot throw here at all.
  24162. setTimeout(function() {
  24163. self.onError(e);
  24164. }, 0);
  24165. return;
  24166. }
  24167. if (global.document) {
  24168. this.index = Request.requestsCount++;
  24169. Request.requests[this.index] = this;
  24170. }
  24171. };
  24172. /**
  24173. * Called upon successful response.
  24174. *
  24175. * @api private
  24176. */
  24177. Request.prototype.onSuccess = function(){
  24178. this.emit('success');
  24179. this.cleanup();
  24180. };
  24181. /**
  24182. * Called if we have data.
  24183. *
  24184. * @api private
  24185. */
  24186. Request.prototype.onData = function(data){
  24187. this.emit('data', data);
  24188. this.onSuccess();
  24189. };
  24190. /**
  24191. * Called upon error.
  24192. *
  24193. * @api private
  24194. */
  24195. Request.prototype.onError = function(err){
  24196. this.emit('error', err);
  24197. this.cleanup(true);
  24198. };
  24199. /**
  24200. * Cleans up house.
  24201. *
  24202. * @api private
  24203. */
  24204. Request.prototype.cleanup = function(fromError){
  24205. if ('undefined' == typeof this.xhr || null === this.xhr) {
  24206. return;
  24207. }
  24208. // xmlhttprequest
  24209. if (this.hasXDR()) {
  24210. this.xhr.onload = this.xhr.onerror = empty;
  24211. } else {
  24212. this.xhr.onreadystatechange = empty;
  24213. }
  24214. if (fromError) {
  24215. try {
  24216. this.xhr.abort();
  24217. } catch(e) {}
  24218. }
  24219. if (global.document) {
  24220. delete Request.requests[this.index];
  24221. }
  24222. this.xhr = null;
  24223. };
  24224. /**
  24225. * Called upon load.
  24226. *
  24227. * @api private
  24228. */
  24229. Request.prototype.onLoad = function(){
  24230. var data;
  24231. try {
  24232. var contentType;
  24233. try {
  24234. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  24235. } catch (e) {}
  24236. if (contentType === 'application/octet-stream') {
  24237. data = this.xhr.response;
  24238. } else {
  24239. if (!this.supportsBinary) {
  24240. data = this.xhr.responseText;
  24241. } else {
  24242. data = 'ok';
  24243. }
  24244. }
  24245. } catch (e) {
  24246. this.onError(e);
  24247. }
  24248. if (null != data) {
  24249. this.onData(data);
  24250. }
  24251. };
  24252. /**
  24253. * Check if it has XDomainRequest.
  24254. *
  24255. * @api private
  24256. */
  24257. Request.prototype.hasXDR = function(){
  24258. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  24259. };
  24260. /**
  24261. * Aborts the request.
  24262. *
  24263. * @api public
  24264. */
  24265. Request.prototype.abort = function(){
  24266. this.cleanup();
  24267. };
  24268. /**
  24269. * Aborts pending requests when unloading the window. This is needed to prevent
  24270. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  24271. * emitted.
  24272. */
  24273. if (global.document) {
  24274. Request.requestsCount = 0;
  24275. Request.requests = {};
  24276. if (global.attachEvent) {
  24277. global.attachEvent('onunload', unloadHandler);
  24278. } else if (global.addEventListener) {
  24279. global.addEventListener('beforeunload', unloadHandler, false);
  24280. }
  24281. }
  24282. function unloadHandler() {
  24283. for (var i in Request.requests) {
  24284. if (Request.requests.hasOwnProperty(i)) {
  24285. Request.requests[i].abort();
  24286. }
  24287. }
  24288. }
  24289. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24290. },{"./polling":103,"component-emitter":94,"component-inherit":106,"debug":107,"xmlhttprequest":105}],103:[function(require,module,exports){
  24291. /**
  24292. * Module dependencies.
  24293. */
  24294. var Transport = require('../transport');
  24295. var parseqs = require('parseqs');
  24296. var parser = require('engine.io-parser');
  24297. var inherit = require('component-inherit');
  24298. var debug = require('debug')('engine.io-client:polling');
  24299. /**
  24300. * Module exports.
  24301. */
  24302. module.exports = Polling;
  24303. /**
  24304. * Is XHR2 supported?
  24305. */
  24306. var hasXHR2 = (function() {
  24307. var XMLHttpRequest = require('xmlhttprequest');
  24308. var xhr = new XMLHttpRequest({ xdomain: false });
  24309. return null != xhr.responseType;
  24310. })();
  24311. /**
  24312. * Polling interface.
  24313. *
  24314. * @param {Object} opts
  24315. * @api private
  24316. */
  24317. function Polling(opts){
  24318. var forceBase64 = (opts && opts.forceBase64);
  24319. if (!hasXHR2 || forceBase64) {
  24320. this.supportsBinary = false;
  24321. }
  24322. Transport.call(this, opts);
  24323. }
  24324. /**
  24325. * Inherits from Transport.
  24326. */
  24327. inherit(Polling, Transport);
  24328. /**
  24329. * Transport name.
  24330. */
  24331. Polling.prototype.name = 'polling';
  24332. /**
  24333. * Opens the socket (triggers polling). We write a PING message to determine
  24334. * when the transport is open.
  24335. *
  24336. * @api private
  24337. */
  24338. Polling.prototype.doOpen = function(){
  24339. this.poll();
  24340. };
  24341. /**
  24342. * Pauses polling.
  24343. *
  24344. * @param {Function} callback upon buffers are flushed and transport is paused
  24345. * @api private
  24346. */
  24347. Polling.prototype.pause = function(onPause){
  24348. var pending = 0;
  24349. var self = this;
  24350. this.readyState = 'pausing';
  24351. function pause(){
  24352. debug('paused');
  24353. self.readyState = 'paused';
  24354. onPause();
  24355. }
  24356. if (this.polling || !this.writable) {
  24357. var total = 0;
  24358. if (this.polling) {
  24359. debug('we are currently polling - waiting to pause');
  24360. total++;
  24361. this.once('pollComplete', function(){
  24362. debug('pre-pause polling complete');
  24363. --total || pause();
  24364. });
  24365. }
  24366. if (!this.writable) {
  24367. debug('we are currently writing - waiting to pause');
  24368. total++;
  24369. this.once('drain', function(){
  24370. debug('pre-pause writing complete');
  24371. --total || pause();
  24372. });
  24373. }
  24374. } else {
  24375. pause();
  24376. }
  24377. };
  24378. /**
  24379. * Starts polling cycle.
  24380. *
  24381. * @api public
  24382. */
  24383. Polling.prototype.poll = function(){
  24384. debug('polling');
  24385. this.polling = true;
  24386. this.doPoll();
  24387. this.emit('poll');
  24388. };
  24389. /**
  24390. * Overloads onData to detect payloads.
  24391. *
  24392. * @api private
  24393. */
  24394. Polling.prototype.onData = function(data){
  24395. var self = this;
  24396. debug('polling got data %s', data);
  24397. var callback = function(packet, index, total) {
  24398. // if its the first message we consider the transport open
  24399. if ('opening' == self.readyState) {
  24400. self.onOpen();
  24401. }
  24402. // if its a close packet, we close the ongoing requests
  24403. if ('close' == packet.type) {
  24404. self.onClose();
  24405. return false;
  24406. }
  24407. // otherwise bypass onData and handle the message
  24408. self.onPacket(packet);
  24409. };
  24410. // decode payload
  24411. parser.decodePayload(data, this.socket.binaryType, callback);
  24412. // if an event did not trigger closing
  24413. if ('closed' != this.readyState) {
  24414. // if we got data we're not polling
  24415. this.polling = false;
  24416. this.emit('pollComplete');
  24417. if ('open' == this.readyState) {
  24418. this.poll();
  24419. } else {
  24420. debug('ignoring poll - transport state "%s"', this.readyState);
  24421. }
  24422. }
  24423. };
  24424. /**
  24425. * For polling, send a close packet.
  24426. *
  24427. * @api private
  24428. */
  24429. Polling.prototype.doClose = function(){
  24430. var self = this;
  24431. function close(){
  24432. debug('writing close packet');
  24433. self.write([{ type: 'close' }]);
  24434. }
  24435. if ('open' == this.readyState) {
  24436. debug('transport open - closing');
  24437. close();
  24438. } else {
  24439. // in case we're trying to close while
  24440. // handshaking is in progress (GH-164)
  24441. debug('transport not open - deferring close');
  24442. this.once('open', close);
  24443. }
  24444. };
  24445. /**
  24446. * Writes a packets payload.
  24447. *
  24448. * @param {Array} data packets
  24449. * @param {Function} drain callback
  24450. * @api private
  24451. */
  24452. Polling.prototype.write = function(packets){
  24453. var self = this;
  24454. this.writable = false;
  24455. var callbackfn = function() {
  24456. self.writable = true;
  24457. self.emit('drain');
  24458. };
  24459. var self = this;
  24460. parser.encodePayload(packets, this.supportsBinary, function(data) {
  24461. self.doWrite(data, callbackfn);
  24462. });
  24463. };
  24464. /**
  24465. * Generates uri for connection.
  24466. *
  24467. * @api private
  24468. */
  24469. Polling.prototype.uri = function(){
  24470. var query = this.query || {};
  24471. var schema = this.secure ? 'https' : 'http';
  24472. var port = '';
  24473. // cache busting is forced
  24474. if (false !== this.timestampRequests) {
  24475. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  24476. }
  24477. if (!this.supportsBinary && !query.sid) {
  24478. query.b64 = 1;
  24479. }
  24480. query = parseqs.encode(query);
  24481. // avoid port if default for schema
  24482. if (this.port && (('https' == schema && this.port != 443) ||
  24483. ('http' == schema && this.port != 80))) {
  24484. port = ':' + this.port;
  24485. }
  24486. // prepend ? to query
  24487. if (query.length) {
  24488. query = '?' + query;
  24489. }
  24490. return schema + '://' + this.hostname + port + this.path + query;
  24491. };
  24492. },{"../transport":99,"component-inherit":106,"debug":107,"engine.io-parser":110,"parseqs":122,"xmlhttprequest":105}],104:[function(require,module,exports){
  24493. /**
  24494. * Module dependencies.
  24495. */
  24496. var Transport = require('../transport');
  24497. var parser = require('engine.io-parser');
  24498. var parseqs = require('parseqs');
  24499. var inherit = require('component-inherit');
  24500. var debug = require('debug')('engine.io-client:websocket');
  24501. /**
  24502. * `ws` exposes a WebSocket-compatible interface in
  24503. * Node, or the `WebSocket` or `MozWebSocket` globals
  24504. * in the browser.
  24505. */
  24506. var WebSocket = require('ws');
  24507. /**
  24508. * Module exports.
  24509. */
  24510. module.exports = WS;
  24511. /**
  24512. * WebSocket transport constructor.
  24513. *
  24514. * @api {Object} connection options
  24515. * @api public
  24516. */
  24517. function WS(opts){
  24518. var forceBase64 = (opts && opts.forceBase64);
  24519. if (forceBase64) {
  24520. this.supportsBinary = false;
  24521. }
  24522. Transport.call(this, opts);
  24523. }
  24524. /**
  24525. * Inherits from Transport.
  24526. */
  24527. inherit(WS, Transport);
  24528. /**
  24529. * Transport name.
  24530. *
  24531. * @api public
  24532. */
  24533. WS.prototype.name = 'websocket';
  24534. /*
  24535. * WebSockets support binary
  24536. */
  24537. WS.prototype.supportsBinary = true;
  24538. /**
  24539. * Opens socket.
  24540. *
  24541. * @api private
  24542. */
  24543. WS.prototype.doOpen = function(){
  24544. if (!this.check()) {
  24545. // let probe timeout
  24546. return;
  24547. }
  24548. var self = this;
  24549. var uri = this.uri();
  24550. var protocols = void(0);
  24551. var opts = { agent: this.agent };
  24552. // SSL options for Node.js client
  24553. opts.pfx = this.pfx;
  24554. opts.key = this.key;
  24555. opts.passphrase = this.passphrase;
  24556. opts.cert = this.cert;
  24557. opts.ca = this.ca;
  24558. opts.ciphers = this.ciphers;
  24559. opts.rejectUnauthorized = this.rejectUnauthorized;
  24560. this.ws = new WebSocket(uri, protocols, opts);
  24561. if (this.ws.binaryType === undefined) {
  24562. this.supportsBinary = false;
  24563. }
  24564. this.ws.binaryType = 'arraybuffer';
  24565. this.addEventListeners();
  24566. };
  24567. /**
  24568. * Adds event listeners to the socket
  24569. *
  24570. * @api private
  24571. */
  24572. WS.prototype.addEventListeners = function(){
  24573. var self = this;
  24574. this.ws.onopen = function(){
  24575. self.onOpen();
  24576. };
  24577. this.ws.onclose = function(){
  24578. self.onClose();
  24579. };
  24580. this.ws.onmessage = function(ev){
  24581. self.onData(ev.data);
  24582. };
  24583. this.ws.onerror = function(e){
  24584. self.onError('websocket error', e);
  24585. };
  24586. };
  24587. /**
  24588. * Override `onData` to use a timer on iOS.
  24589. * See: https://gist.github.com/mloughran/2052006
  24590. *
  24591. * @api private
  24592. */
  24593. if ('undefined' != typeof navigator
  24594. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  24595. WS.prototype.onData = function(data){
  24596. var self = this;
  24597. setTimeout(function(){
  24598. Transport.prototype.onData.call(self, data);
  24599. }, 0);
  24600. };
  24601. }
  24602. /**
  24603. * Writes data to socket.
  24604. *
  24605. * @param {Array} array of packets.
  24606. * @api private
  24607. */
  24608. WS.prototype.write = function(packets){
  24609. var self = this;
  24610. this.writable = false;
  24611. // encodePacket efficient as it uses WS framing
  24612. // no need for encodePayload
  24613. for (var i = 0, l = packets.length; i < l; i++) {
  24614. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  24615. //Sometimes the websocket has already been closed but the browser didn't
  24616. //have a chance of informing us about it yet, in that case send will
  24617. //throw an error
  24618. try {
  24619. self.ws.send(data);
  24620. } catch (e){
  24621. debug('websocket closed before onclose event');
  24622. }
  24623. });
  24624. }
  24625. function ondrain() {
  24626. self.writable = true;
  24627. self.emit('drain');
  24628. }
  24629. // fake drain
  24630. // defer to next tick to allow Socket to clear writeBuffer
  24631. setTimeout(ondrain, 0);
  24632. };
  24633. /**
  24634. * Called upon close
  24635. *
  24636. * @api private
  24637. */
  24638. WS.prototype.onClose = function(){
  24639. Transport.prototype.onClose.call(this);
  24640. };
  24641. /**
  24642. * Closes socket.
  24643. *
  24644. * @api private
  24645. */
  24646. WS.prototype.doClose = function(){
  24647. if (typeof this.ws !== 'undefined') {
  24648. this.ws.close();
  24649. }
  24650. };
  24651. /**
  24652. * Generates uri for connection.
  24653. *
  24654. * @api private
  24655. */
  24656. WS.prototype.uri = function(){
  24657. var query = this.query || {};
  24658. var schema = this.secure ? 'wss' : 'ws';
  24659. var port = '';
  24660. // avoid port if default for schema
  24661. if (this.port && (('wss' == schema && this.port != 443)
  24662. || ('ws' == schema && this.port != 80))) {
  24663. port = ':' + this.port;
  24664. }
  24665. // append timestamp to URI
  24666. if (this.timestampRequests) {
  24667. query[this.timestampParam] = +new Date;
  24668. }
  24669. // communicate binary support capabilities
  24670. if (!this.supportsBinary) {
  24671. query.b64 = 1;
  24672. }
  24673. query = parseqs.encode(query);
  24674. // prepend ? to query
  24675. if (query.length) {
  24676. query = '?' + query;
  24677. }
  24678. return schema + '://' + this.hostname + port + this.path + query;
  24679. };
  24680. /**
  24681. * Feature detection for WebSocket.
  24682. *
  24683. * @return {Boolean} whether this transport is available.
  24684. * @api public
  24685. */
  24686. WS.prototype.check = function(){
  24687. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  24688. };
  24689. },{"../transport":99,"component-inherit":106,"debug":107,"engine.io-parser":110,"parseqs":122,"ws":124}],105:[function(require,module,exports){
  24690. // browser shim for xmlhttprequest module
  24691. var hasCORS = require('has-cors');
  24692. module.exports = function(opts) {
  24693. var xdomain = opts.xdomain;
  24694. // scheme must be same when usign XDomainRequest
  24695. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  24696. var xscheme = opts.xscheme;
  24697. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  24698. // https://github.com/Automattic/engine.io-client/pull/217
  24699. var enablesXDR = opts.enablesXDR;
  24700. // XMLHttpRequest can be disabled on IE
  24701. try {
  24702. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  24703. return new XMLHttpRequest();
  24704. }
  24705. } catch (e) { }
  24706. // Use XDomainRequest for IE8 if enablesXDR is true
  24707. // because loading bar keeps flashing when using jsonp-polling
  24708. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  24709. try {
  24710. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  24711. return new XDomainRequest();
  24712. }
  24713. } catch (e) { }
  24714. if (!xdomain) {
  24715. try {
  24716. return new ActiveXObject('Microsoft.XMLHTTP');
  24717. } catch(e) { }
  24718. }
  24719. }
  24720. },{"has-cors":119}],106:[function(require,module,exports){
  24721. module.exports = function(a, b){
  24722. var fn = function(){};
  24723. fn.prototype = b.prototype;
  24724. a.prototype = new fn;
  24725. a.prototype.constructor = a;
  24726. };
  24727. },{}],107:[function(require,module,exports){
  24728. /**
  24729. * This is the web browser implementation of `debug()`.
  24730. *
  24731. * Expose `debug()` as the module.
  24732. */
  24733. exports = module.exports = require('./debug');
  24734. exports.log = log;
  24735. exports.formatArgs = formatArgs;
  24736. exports.save = save;
  24737. exports.load = load;
  24738. exports.useColors = useColors;
  24739. /**
  24740. * Colors.
  24741. */
  24742. exports.colors = [
  24743. 'lightseagreen',
  24744. 'forestgreen',
  24745. 'goldenrod',
  24746. 'dodgerblue',
  24747. 'darkorchid',
  24748. 'crimson'
  24749. ];
  24750. /**
  24751. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  24752. * and the Firebug extension (any Firefox version) are known
  24753. * to support "%c" CSS customizations.
  24754. *
  24755. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  24756. */
  24757. function useColors() {
  24758. // is webkit? http://stackoverflow.com/a/16459606/376773
  24759. return ('WebkitAppearance' in document.documentElement.style) ||
  24760. // is firebug? http://stackoverflow.com/a/398120/376773
  24761. (window.console && (console.firebug || (console.exception && console.table))) ||
  24762. // is firefox >= v31?
  24763. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  24764. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  24765. }
  24766. /**
  24767. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  24768. */
  24769. exports.formatters.j = function(v) {
  24770. return JSON.stringify(v);
  24771. };
  24772. /**
  24773. * Colorize log arguments if enabled.
  24774. *
  24775. * @api public
  24776. */
  24777. function formatArgs() {
  24778. var args = arguments;
  24779. var useColors = this.useColors;
  24780. args[0] = (useColors ? '%c' : '')
  24781. + this.namespace
  24782. + (useColors ? ' %c' : ' ')
  24783. + args[0]
  24784. + (useColors ? '%c ' : ' ')
  24785. + '+' + exports.humanize(this.diff);
  24786. if (!useColors) return args;
  24787. var c = 'color: ' + this.color;
  24788. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  24789. // the final "%c" is somewhat tricky, because there could be other
  24790. // arguments passed either before or after the %c, so we need to
  24791. // figure out the correct index to insert the CSS into
  24792. var index = 0;
  24793. var lastC = 0;
  24794. args[0].replace(/%[a-z%]/g, function(match) {
  24795. if ('%%' === match) return;
  24796. index++;
  24797. if ('%c' === match) {
  24798. // we only are interested in the *last* %c
  24799. // (the user may have provided their own)
  24800. lastC = index;
  24801. }
  24802. });
  24803. args.splice(lastC, 0, c);
  24804. return args;
  24805. }
  24806. /**
  24807. * Invokes `console.log()` when available.
  24808. * No-op when `console.log` is not a "function".
  24809. *
  24810. * @api public
  24811. */
  24812. function log() {
  24813. // This hackery is required for IE8,
  24814. // where the `console.log` function doesn't have 'apply'
  24815. return 'object' == typeof console
  24816. && 'function' == typeof console.log
  24817. && Function.prototype.apply.call(console.log, console, arguments);
  24818. }
  24819. /**
  24820. * Save `namespaces`.
  24821. *
  24822. * @param {String} namespaces
  24823. * @api private
  24824. */
  24825. function save(namespaces) {
  24826. try {
  24827. if (null == namespaces) {
  24828. localStorage.removeItem('debug');
  24829. } else {
  24830. localStorage.debug = namespaces;
  24831. }
  24832. } catch(e) {}
  24833. }
  24834. /**
  24835. * Load `namespaces`.
  24836. *
  24837. * @return {String} returns the previously persisted debug modes
  24838. * @api private
  24839. */
  24840. function load() {
  24841. var r;
  24842. try {
  24843. r = localStorage.debug;
  24844. } catch(e) {}
  24845. return r;
  24846. }
  24847. /**
  24848. * Enable namespaces listed in `localStorage.debug` initially.
  24849. */
  24850. exports.enable(load());
  24851. },{"./debug":108}],108:[function(require,module,exports){
  24852. /**
  24853. * This is the common logic for both the Node.js and web browser
  24854. * implementations of `debug()`.
  24855. *
  24856. * Expose `debug()` as the module.
  24857. */
  24858. exports = module.exports = debug;
  24859. exports.coerce = coerce;
  24860. exports.disable = disable;
  24861. exports.enable = enable;
  24862. exports.enabled = enabled;
  24863. exports.humanize = require('ms');
  24864. /**
  24865. * The currently active debug mode names, and names to skip.
  24866. */
  24867. exports.names = [];
  24868. exports.skips = [];
  24869. /**
  24870. * Map of special "%n" handling functions, for the debug "format" argument.
  24871. *
  24872. * Valid key names are a single, lowercased letter, i.e. "n".
  24873. */
  24874. exports.formatters = {};
  24875. /**
  24876. * Previously assigned color.
  24877. */
  24878. var prevColor = 0;
  24879. /**
  24880. * Previous log timestamp.
  24881. */
  24882. var prevTime;
  24883. /**
  24884. * Select a color.
  24885. *
  24886. * @return {Number}
  24887. * @api private
  24888. */
  24889. function selectColor() {
  24890. return exports.colors[prevColor++ % exports.colors.length];
  24891. }
  24892. /**
  24893. * Create a debugger with the given `namespace`.
  24894. *
  24895. * @param {String} namespace
  24896. * @return {Function}
  24897. * @api public
  24898. */
  24899. function debug(namespace) {
  24900. // define the `disabled` version
  24901. function disabled() {
  24902. }
  24903. disabled.enabled = false;
  24904. // define the `enabled` version
  24905. function enabled() {
  24906. var self = enabled;
  24907. // set `diff` timestamp
  24908. var curr = +new Date();
  24909. var ms = curr - (prevTime || curr);
  24910. self.diff = ms;
  24911. self.prev = prevTime;
  24912. self.curr = curr;
  24913. prevTime = curr;
  24914. // add the `color` if not set
  24915. if (null == self.useColors) self.useColors = exports.useColors();
  24916. if (null == self.color && self.useColors) self.color = selectColor();
  24917. var args = Array.prototype.slice.call(arguments);
  24918. args[0] = exports.coerce(args[0]);
  24919. if ('string' !== typeof args[0]) {
  24920. // anything else let's inspect with %o
  24921. args = ['%o'].concat(args);
  24922. }
  24923. // apply any `formatters` transformations
  24924. var index = 0;
  24925. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  24926. // if we encounter an escaped % then don't increase the array index
  24927. if (match === '%%') return match;
  24928. index++;
  24929. var formatter = exports.formatters[format];
  24930. if ('function' === typeof formatter) {
  24931. var val = args[index];
  24932. match = formatter.call(self, val);
  24933. // now we need to remove `args[index]` since it's inlined in the `format`
  24934. args.splice(index, 1);
  24935. index--;
  24936. }
  24937. return match;
  24938. });
  24939. if ('function' === typeof exports.formatArgs) {
  24940. args = exports.formatArgs.apply(self, args);
  24941. }
  24942. var logFn = enabled.log || exports.log || console.log.bind(console);
  24943. logFn.apply(self, args);
  24944. }
  24945. enabled.enabled = true;
  24946. var fn = exports.enabled(namespace) ? enabled : disabled;
  24947. fn.namespace = namespace;
  24948. return fn;
  24949. }
  24950. /**
  24951. * Enables a debug mode by namespaces. This can include modes
  24952. * separated by a colon and wildcards.
  24953. *
  24954. * @param {String} namespaces
  24955. * @api public
  24956. */
  24957. function enable(namespaces) {
  24958. exports.save(namespaces);
  24959. var split = (namespaces || '').split(/[\s,]+/);
  24960. var len = split.length;
  24961. for (var i = 0; i < len; i++) {
  24962. if (!split[i]) continue; // ignore empty strings
  24963. namespaces = split[i].replace(/\*/g, '.*?');
  24964. if (namespaces[0] === '-') {
  24965. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  24966. } else {
  24967. exports.names.push(new RegExp('^' + namespaces + '$'));
  24968. }
  24969. }
  24970. }
  24971. /**
  24972. * Disable debug output.
  24973. *
  24974. * @api public
  24975. */
  24976. function disable() {
  24977. exports.enable('');
  24978. }
  24979. /**
  24980. * Returns true if the given mode name is enabled, false otherwise.
  24981. *
  24982. * @param {String} name
  24983. * @return {Boolean}
  24984. * @api public
  24985. */
  24986. function enabled(name) {
  24987. var i, len;
  24988. for (i = 0, len = exports.skips.length; i < len; i++) {
  24989. if (exports.skips[i].test(name)) {
  24990. return false;
  24991. }
  24992. }
  24993. for (i = 0, len = exports.names.length; i < len; i++) {
  24994. if (exports.names[i].test(name)) {
  24995. return true;
  24996. }
  24997. }
  24998. return false;
  24999. }
  25000. /**
  25001. * Coerce `val`.
  25002. *
  25003. * @param {Mixed} val
  25004. * @return {Mixed}
  25005. * @api private
  25006. */
  25007. function coerce(val) {
  25008. if (val instanceof Error) return val.stack || val.message;
  25009. return val;
  25010. }
  25011. },{"ms":109}],109:[function(require,module,exports){
  25012. /**
  25013. * Helpers.
  25014. */
  25015. var s = 1000;
  25016. var m = s * 60;
  25017. var h = m * 60;
  25018. var d = h * 24;
  25019. var y = d * 365.25;
  25020. /**
  25021. * Parse or format the given `val`.
  25022. *
  25023. * Options:
  25024. *
  25025. * - `long` verbose formatting [false]
  25026. *
  25027. * @param {String|Number} val
  25028. * @param {Object} options
  25029. * @return {String|Number}
  25030. * @api public
  25031. */
  25032. module.exports = function(val, options){
  25033. options = options || {};
  25034. if ('string' == typeof val) return parse(val);
  25035. return options.long
  25036. ? long(val)
  25037. : short(val);
  25038. };
  25039. /**
  25040. * Parse the given `str` and return milliseconds.
  25041. *
  25042. * @param {String} str
  25043. * @return {Number}
  25044. * @api private
  25045. */
  25046. function parse(str) {
  25047. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  25048. if (!match) return;
  25049. var n = parseFloat(match[1]);
  25050. var type = (match[2] || 'ms').toLowerCase();
  25051. switch (type) {
  25052. case 'years':
  25053. case 'year':
  25054. case 'y':
  25055. return n * y;
  25056. case 'days':
  25057. case 'day':
  25058. case 'd':
  25059. return n * d;
  25060. case 'hours':
  25061. case 'hour':
  25062. case 'h':
  25063. return n * h;
  25064. case 'minutes':
  25065. case 'minute':
  25066. case 'm':
  25067. return n * m;
  25068. case 'seconds':
  25069. case 'second':
  25070. case 's':
  25071. return n * s;
  25072. case 'ms':
  25073. return n;
  25074. }
  25075. }
  25076. /**
  25077. * Short format for `ms`.
  25078. *
  25079. * @param {Number} ms
  25080. * @return {String}
  25081. * @api private
  25082. */
  25083. function short(ms) {
  25084. if (ms >= d) return Math.round(ms / d) + 'd';
  25085. if (ms >= h) return Math.round(ms / h) + 'h';
  25086. if (ms >= m) return Math.round(ms / m) + 'm';
  25087. if (ms >= s) return Math.round(ms / s) + 's';
  25088. return ms + 'ms';
  25089. }
  25090. /**
  25091. * Long format for `ms`.
  25092. *
  25093. * @param {Number} ms
  25094. * @return {String}
  25095. * @api private
  25096. */
  25097. function long(ms) {
  25098. return plural(ms, d, 'day')
  25099. || plural(ms, h, 'hour')
  25100. || plural(ms, m, 'minute')
  25101. || plural(ms, s, 'second')
  25102. || ms + ' ms';
  25103. }
  25104. /**
  25105. * Pluralization helper.
  25106. */
  25107. function plural(ms, n, name) {
  25108. if (ms < n) return;
  25109. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  25110. return Math.ceil(ms / n) + ' ' + name + 's';
  25111. }
  25112. },{}],110:[function(require,module,exports){
  25113. (function (global){
  25114. /**
  25115. * Module dependencies.
  25116. */
  25117. var keys = require('./keys');
  25118. var hasBinary = require('has-binary');
  25119. var sliceBuffer = require('arraybuffer.slice');
  25120. var base64encoder = require('base64-arraybuffer');
  25121. var after = require('after');
  25122. var utf8 = require('utf8');
  25123. /**
  25124. * Check if we are running an android browser. That requires us to use
  25125. * ArrayBuffer with polling transports...
  25126. *
  25127. * http://ghinda.net/jpeg-blob-ajax-android/
  25128. */
  25129. var isAndroid = navigator.userAgent.match(/Android/i);
  25130. /**
  25131. * Check if we are running in PhantomJS.
  25132. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  25133. * https://github.com/ariya/phantomjs/issues/11395
  25134. * @type boolean
  25135. */
  25136. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  25137. /**
  25138. * When true, avoids using Blobs to encode payloads.
  25139. * @type boolean
  25140. */
  25141. var dontSendBlobs = isAndroid || isPhantomJS;
  25142. /**
  25143. * Current protocol version.
  25144. */
  25145. exports.protocol = 3;
  25146. /**
  25147. * Packet types.
  25148. */
  25149. var packets = exports.packets = {
  25150. open: 0 // non-ws
  25151. , close: 1 // non-ws
  25152. , ping: 2
  25153. , pong: 3
  25154. , message: 4
  25155. , upgrade: 5
  25156. , noop: 6
  25157. };
  25158. var packetslist = keys(packets);
  25159. /**
  25160. * Premade error packet.
  25161. */
  25162. var err = { type: 'error', data: 'parser error' };
  25163. /**
  25164. * Create a blob api even for blob builder when vendor prefixes exist
  25165. */
  25166. var Blob = require('blob');
  25167. /**
  25168. * Encodes a packet.
  25169. *
  25170. * <packet type id> [ <data> ]
  25171. *
  25172. * Example:
  25173. *
  25174. * 5hello world
  25175. * 3
  25176. * 4
  25177. *
  25178. * Binary is encoded in an identical principle
  25179. *
  25180. * @api private
  25181. */
  25182. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  25183. if ('function' == typeof supportsBinary) {
  25184. callback = supportsBinary;
  25185. supportsBinary = false;
  25186. }
  25187. if ('function' == typeof utf8encode) {
  25188. callback = utf8encode;
  25189. utf8encode = null;
  25190. }
  25191. var data = (packet.data === undefined)
  25192. ? undefined
  25193. : packet.data.buffer || packet.data;
  25194. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  25195. return encodeArrayBuffer(packet, supportsBinary, callback);
  25196. } else if (Blob && data instanceof global.Blob) {
  25197. return encodeBlob(packet, supportsBinary, callback);
  25198. }
  25199. // might be an object with { base64: true, data: dataAsBase64String }
  25200. if (data && data.base64) {
  25201. return encodeBase64Object(packet, callback);
  25202. }
  25203. // Sending data as a utf-8 string
  25204. var encoded = packets[packet.type];
  25205. // data fragment is optional
  25206. if (undefined !== packet.data) {
  25207. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  25208. }
  25209. return callback('' + encoded);
  25210. };
  25211. function encodeBase64Object(packet, callback) {
  25212. // packet data is an object { base64: true, data: dataAsBase64String }
  25213. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  25214. return callback(message);
  25215. }
  25216. /**
  25217. * Encode packet helpers for binary types
  25218. */
  25219. function encodeArrayBuffer(packet, supportsBinary, callback) {
  25220. if (!supportsBinary) {
  25221. return exports.encodeBase64Packet(packet, callback);
  25222. }
  25223. var data = packet.data;
  25224. var contentArray = new Uint8Array(data);
  25225. var resultBuffer = new Uint8Array(1 + data.byteLength);
  25226. resultBuffer[0] = packets[packet.type];
  25227. for (var i = 0; i < contentArray.length; i++) {
  25228. resultBuffer[i+1] = contentArray[i];
  25229. }
  25230. return callback(resultBuffer.buffer);
  25231. }
  25232. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  25233. if (!supportsBinary) {
  25234. return exports.encodeBase64Packet(packet, callback);
  25235. }
  25236. var fr = new FileReader();
  25237. fr.onload = function() {
  25238. packet.data = fr.result;
  25239. exports.encodePacket(packet, supportsBinary, true, callback);
  25240. };
  25241. return fr.readAsArrayBuffer(packet.data);
  25242. }
  25243. function encodeBlob(packet, supportsBinary, callback) {
  25244. if (!supportsBinary) {
  25245. return exports.encodeBase64Packet(packet, callback);
  25246. }
  25247. if (dontSendBlobs) {
  25248. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  25249. }
  25250. var length = new Uint8Array(1);
  25251. length[0] = packets[packet.type];
  25252. var blob = new Blob([length.buffer, packet.data]);
  25253. return callback(blob);
  25254. }
  25255. /**
  25256. * Encodes a packet with binary data in a base64 string
  25257. *
  25258. * @param {Object} packet, has `type` and `data`
  25259. * @return {String} base64 encoded message
  25260. */
  25261. exports.encodeBase64Packet = function(packet, callback) {
  25262. var message = 'b' + exports.packets[packet.type];
  25263. if (Blob && packet.data instanceof Blob) {
  25264. var fr = new FileReader();
  25265. fr.onload = function() {
  25266. var b64 = fr.result.split(',')[1];
  25267. callback(message + b64);
  25268. };
  25269. return fr.readAsDataURL(packet.data);
  25270. }
  25271. var b64data;
  25272. try {
  25273. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  25274. } catch (e) {
  25275. // iPhone Safari doesn't let you apply with typed arrays
  25276. var typed = new Uint8Array(packet.data);
  25277. var basic = new Array(typed.length);
  25278. for (var i = 0; i < typed.length; i++) {
  25279. basic[i] = typed[i];
  25280. }
  25281. b64data = String.fromCharCode.apply(null, basic);
  25282. }
  25283. message += global.btoa(b64data);
  25284. return callback(message);
  25285. };
  25286. /**
  25287. * Decodes a packet. Changes format to Blob if requested.
  25288. *
  25289. * @return {Object} with `type` and `data` (if any)
  25290. * @api private
  25291. */
  25292. exports.decodePacket = function (data, binaryType, utf8decode) {
  25293. // String data
  25294. if (typeof data == 'string' || data === undefined) {
  25295. if (data.charAt(0) == 'b') {
  25296. return exports.decodeBase64Packet(data.substr(1), binaryType);
  25297. }
  25298. if (utf8decode) {
  25299. try {
  25300. data = utf8.decode(data);
  25301. } catch (e) {
  25302. return err;
  25303. }
  25304. }
  25305. var type = data.charAt(0);
  25306. if (Number(type) != type || !packetslist[type]) {
  25307. return err;
  25308. }
  25309. if (data.length > 1) {
  25310. return { type: packetslist[type], data: data.substring(1) };
  25311. } else {
  25312. return { type: packetslist[type] };
  25313. }
  25314. }
  25315. var asArray = new Uint8Array(data);
  25316. var type = asArray[0];
  25317. var rest = sliceBuffer(data, 1);
  25318. if (Blob && binaryType === 'blob') {
  25319. rest = new Blob([rest]);
  25320. }
  25321. return { type: packetslist[type], data: rest };
  25322. };
  25323. /**
  25324. * Decodes a packet encoded in a base64 string
  25325. *
  25326. * @param {String} base64 encoded message
  25327. * @return {Object} with `type` and `data` (if any)
  25328. */
  25329. exports.decodeBase64Packet = function(msg, binaryType) {
  25330. var type = packetslist[msg.charAt(0)];
  25331. if (!global.ArrayBuffer) {
  25332. return { type: type, data: { base64: true, data: msg.substr(1) } };
  25333. }
  25334. var data = base64encoder.decode(msg.substr(1));
  25335. if (binaryType === 'blob' && Blob) {
  25336. data = new Blob([data]);
  25337. }
  25338. return { type: type, data: data };
  25339. };
  25340. /**
  25341. * Encodes multiple messages (payload).
  25342. *
  25343. * <length>:data
  25344. *
  25345. * Example:
  25346. *
  25347. * 11:hello world2:hi
  25348. *
  25349. * If any contents are binary, they will be encoded as base64 strings. Base64
  25350. * encoded strings are marked with a b before the length specifier
  25351. *
  25352. * @param {Array} packets
  25353. * @api private
  25354. */
  25355. exports.encodePayload = function (packets, supportsBinary, callback) {
  25356. if (typeof supportsBinary == 'function') {
  25357. callback = supportsBinary;
  25358. supportsBinary = null;
  25359. }
  25360. var isBinary = hasBinary(packets);
  25361. if (supportsBinary && isBinary) {
  25362. if (Blob && !dontSendBlobs) {
  25363. return exports.encodePayloadAsBlob(packets, callback);
  25364. }
  25365. return exports.encodePayloadAsArrayBuffer(packets, callback);
  25366. }
  25367. if (!packets.length) {
  25368. return callback('0:');
  25369. }
  25370. function setLengthHeader(message) {
  25371. return message.length + ':' + message;
  25372. }
  25373. function encodeOne(packet, doneCallback) {
  25374. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  25375. doneCallback(null, setLengthHeader(message));
  25376. });
  25377. }
  25378. map(packets, encodeOne, function(err, results) {
  25379. return callback(results.join(''));
  25380. });
  25381. };
  25382. /**
  25383. * Async array map using after
  25384. */
  25385. function map(ary, each, done) {
  25386. var result = new Array(ary.length);
  25387. var next = after(ary.length, done);
  25388. var eachWithIndex = function(i, el, cb) {
  25389. each(el, function(error, msg) {
  25390. result[i] = msg;
  25391. cb(error, result);
  25392. });
  25393. };
  25394. for (var i = 0; i < ary.length; i++) {
  25395. eachWithIndex(i, ary[i], next);
  25396. }
  25397. }
  25398. /*
  25399. * Decodes data when a payload is maybe expected. Possible binary contents are
  25400. * decoded from their base64 representation
  25401. *
  25402. * @param {String} data, callback method
  25403. * @api public
  25404. */
  25405. exports.decodePayload = function (data, binaryType, callback) {
  25406. if (typeof data != 'string') {
  25407. return exports.decodePayloadAsBinary(data, binaryType, callback);
  25408. }
  25409. if (typeof binaryType === 'function') {
  25410. callback = binaryType;
  25411. binaryType = null;
  25412. }
  25413. var packet;
  25414. if (data == '') {
  25415. // parser error - ignoring payload
  25416. return callback(err, 0, 1);
  25417. }
  25418. var length = ''
  25419. , n, msg;
  25420. for (var i = 0, l = data.length; i < l; i++) {
  25421. var chr = data.charAt(i);
  25422. if (':' != chr) {
  25423. length += chr;
  25424. } else {
  25425. if ('' == length || (length != (n = Number(length)))) {
  25426. // parser error - ignoring payload
  25427. return callback(err, 0, 1);
  25428. }
  25429. msg = data.substr(i + 1, n);
  25430. if (length != msg.length) {
  25431. // parser error - ignoring payload
  25432. return callback(err, 0, 1);
  25433. }
  25434. if (msg.length) {
  25435. packet = exports.decodePacket(msg, binaryType, true);
  25436. if (err.type == packet.type && err.data == packet.data) {
  25437. // parser error in individual packet - ignoring payload
  25438. return callback(err, 0, 1);
  25439. }
  25440. var ret = callback(packet, i + n, l);
  25441. if (false === ret) return;
  25442. }
  25443. // advance cursor
  25444. i += n;
  25445. length = '';
  25446. }
  25447. }
  25448. if (length != '') {
  25449. // parser error - ignoring payload
  25450. return callback(err, 0, 1);
  25451. }
  25452. };
  25453. /**
  25454. * Encodes multiple messages (payload) as binary.
  25455. *
  25456. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  25457. * 255><data>
  25458. *
  25459. * Example:
  25460. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  25461. *
  25462. * @param {Array} packets
  25463. * @return {ArrayBuffer} encoded payload
  25464. * @api private
  25465. */
  25466. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  25467. if (!packets.length) {
  25468. return callback(new ArrayBuffer(0));
  25469. }
  25470. function encodeOne(packet, doneCallback) {
  25471. exports.encodePacket(packet, true, true, function(data) {
  25472. return doneCallback(null, data);
  25473. });
  25474. }
  25475. map(packets, encodeOne, function(err, encodedPackets) {
  25476. var totalLength = encodedPackets.reduce(function(acc, p) {
  25477. var len;
  25478. if (typeof p === 'string'){
  25479. len = p.length;
  25480. } else {
  25481. len = p.byteLength;
  25482. }
  25483. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  25484. }, 0);
  25485. var resultArray = new Uint8Array(totalLength);
  25486. var bufferIndex = 0;
  25487. encodedPackets.forEach(function(p) {
  25488. var isString = typeof p === 'string';
  25489. var ab = p;
  25490. if (isString) {
  25491. var view = new Uint8Array(p.length);
  25492. for (var i = 0; i < p.length; i++) {
  25493. view[i] = p.charCodeAt(i);
  25494. }
  25495. ab = view.buffer;
  25496. }
  25497. if (isString) { // not true binary
  25498. resultArray[bufferIndex++] = 0;
  25499. } else { // true binary
  25500. resultArray[bufferIndex++] = 1;
  25501. }
  25502. var lenStr = ab.byteLength.toString();
  25503. for (var i = 0; i < lenStr.length; i++) {
  25504. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  25505. }
  25506. resultArray[bufferIndex++] = 255;
  25507. var view = new Uint8Array(ab);
  25508. for (var i = 0; i < view.length; i++) {
  25509. resultArray[bufferIndex++] = view[i];
  25510. }
  25511. });
  25512. return callback(resultArray.buffer);
  25513. });
  25514. };
  25515. /**
  25516. * Encode as Blob
  25517. */
  25518. exports.encodePayloadAsBlob = function(packets, callback) {
  25519. function encodeOne(packet, doneCallback) {
  25520. exports.encodePacket(packet, true, true, function(encoded) {
  25521. var binaryIdentifier = new Uint8Array(1);
  25522. binaryIdentifier[0] = 1;
  25523. if (typeof encoded === 'string') {
  25524. var view = new Uint8Array(encoded.length);
  25525. for (var i = 0; i < encoded.length; i++) {
  25526. view[i] = encoded.charCodeAt(i);
  25527. }
  25528. encoded = view.buffer;
  25529. binaryIdentifier[0] = 0;
  25530. }
  25531. var len = (encoded instanceof ArrayBuffer)
  25532. ? encoded.byteLength
  25533. : encoded.size;
  25534. var lenStr = len.toString();
  25535. var lengthAry = new Uint8Array(lenStr.length + 1);
  25536. for (var i = 0; i < lenStr.length; i++) {
  25537. lengthAry[i] = parseInt(lenStr[i]);
  25538. }
  25539. lengthAry[lenStr.length] = 255;
  25540. if (Blob) {
  25541. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  25542. doneCallback(null, blob);
  25543. }
  25544. });
  25545. }
  25546. map(packets, encodeOne, function(err, results) {
  25547. return callback(new Blob(results));
  25548. });
  25549. };
  25550. /*
  25551. * Decodes data when a payload is maybe expected. Strings are decoded by
  25552. * interpreting each byte as a key code for entries marked to start with 0. See
  25553. * description of encodePayloadAsBinary
  25554. *
  25555. * @param {ArrayBuffer} data, callback method
  25556. * @api public
  25557. */
  25558. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  25559. if (typeof binaryType === 'function') {
  25560. callback = binaryType;
  25561. binaryType = null;
  25562. }
  25563. var bufferTail = data;
  25564. var buffers = [];
  25565. var numberTooLong = false;
  25566. while (bufferTail.byteLength > 0) {
  25567. var tailArray = new Uint8Array(bufferTail);
  25568. var isString = tailArray[0] === 0;
  25569. var msgLength = '';
  25570. for (var i = 1; ; i++) {
  25571. if (tailArray[i] == 255) break;
  25572. if (msgLength.length > 310) {
  25573. numberTooLong = true;
  25574. break;
  25575. }
  25576. msgLength += tailArray[i];
  25577. }
  25578. if(numberTooLong) return callback(err, 0, 1);
  25579. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  25580. msgLength = parseInt(msgLength);
  25581. var msg = sliceBuffer(bufferTail, 0, msgLength);
  25582. if (isString) {
  25583. try {
  25584. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  25585. } catch (e) {
  25586. // iPhone Safari doesn't let you apply to typed arrays
  25587. var typed = new Uint8Array(msg);
  25588. msg = '';
  25589. for (var i = 0; i < typed.length; i++) {
  25590. msg += String.fromCharCode(typed[i]);
  25591. }
  25592. }
  25593. }
  25594. buffers.push(msg);
  25595. bufferTail = sliceBuffer(bufferTail, msgLength);
  25596. }
  25597. var total = buffers.length;
  25598. buffers.forEach(function(buffer, i) {
  25599. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  25600. });
  25601. };
  25602. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25603. },{"./keys":111,"after":112,"arraybuffer.slice":113,"base64-arraybuffer":114,"blob":115,"has-binary":116,"utf8":118}],111:[function(require,module,exports){
  25604. /**
  25605. * Gets the keys for an object.
  25606. *
  25607. * @return {Array} keys
  25608. * @api private
  25609. */
  25610. module.exports = Object.keys || function keys (obj){
  25611. var arr = [];
  25612. var has = Object.prototype.hasOwnProperty;
  25613. for (var i in obj) {
  25614. if (has.call(obj, i)) {
  25615. arr.push(i);
  25616. }
  25617. }
  25618. return arr;
  25619. };
  25620. },{}],112:[function(require,module,exports){
  25621. module.exports = after
  25622. function after(count, callback, err_cb) {
  25623. var bail = false
  25624. err_cb = err_cb || noop
  25625. proxy.count = count
  25626. return (count === 0) ? callback() : proxy
  25627. function proxy(err, result) {
  25628. if (proxy.count <= 0) {
  25629. throw new Error('after called too many times')
  25630. }
  25631. --proxy.count
  25632. // after first error, rest are passed to err_cb
  25633. if (err) {
  25634. bail = true
  25635. callback(err)
  25636. // future error callbacks will go to error handler
  25637. callback = err_cb
  25638. } else if (proxy.count === 0 && !bail) {
  25639. callback(null, result)
  25640. }
  25641. }
  25642. }
  25643. function noop() {}
  25644. },{}],113:[function(require,module,exports){
  25645. /**
  25646. * An abstraction for slicing an arraybuffer even when
  25647. * ArrayBuffer.prototype.slice is not supported
  25648. *
  25649. * @api public
  25650. */
  25651. module.exports = function(arraybuffer, start, end) {
  25652. var bytes = arraybuffer.byteLength;
  25653. start = start || 0;
  25654. end = end || bytes;
  25655. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  25656. if (start < 0) { start += bytes; }
  25657. if (end < 0) { end += bytes; }
  25658. if (end > bytes) { end = bytes; }
  25659. if (start >= bytes || start >= end || bytes === 0) {
  25660. return new ArrayBuffer(0);
  25661. }
  25662. var abv = new Uint8Array(arraybuffer);
  25663. var result = new Uint8Array(end - start);
  25664. for (var i = start, ii = 0; i < end; i++, ii++) {
  25665. result[ii] = abv[i];
  25666. }
  25667. return result.buffer;
  25668. };
  25669. },{}],114:[function(require,module,exports){
  25670. /*
  25671. * base64-arraybuffer
  25672. * https://github.com/niklasvh/base64-arraybuffer
  25673. *
  25674. * Copyright (c) 2012 Niklas von Hertzen
  25675. * Licensed under the MIT license.
  25676. */
  25677. (function(chars){
  25678. "use strict";
  25679. exports.encode = function(arraybuffer) {
  25680. var bytes = new Uint8Array(arraybuffer),
  25681. i, len = bytes.length, base64 = "";
  25682. for (i = 0; i < len; i+=3) {
  25683. base64 += chars[bytes[i] >> 2];
  25684. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  25685. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  25686. base64 += chars[bytes[i + 2] & 63];
  25687. }
  25688. if ((len % 3) === 2) {
  25689. base64 = base64.substring(0, base64.length - 1) + "=";
  25690. } else if (len % 3 === 1) {
  25691. base64 = base64.substring(0, base64.length - 2) + "==";
  25692. }
  25693. return base64;
  25694. };
  25695. exports.decode = function(base64) {
  25696. var bufferLength = base64.length * 0.75,
  25697. len = base64.length, i, p = 0,
  25698. encoded1, encoded2, encoded3, encoded4;
  25699. if (base64[base64.length - 1] === "=") {
  25700. bufferLength--;
  25701. if (base64[base64.length - 2] === "=") {
  25702. bufferLength--;
  25703. }
  25704. }
  25705. var arraybuffer = new ArrayBuffer(bufferLength),
  25706. bytes = new Uint8Array(arraybuffer);
  25707. for (i = 0; i < len; i+=4) {
  25708. encoded1 = chars.indexOf(base64[i]);
  25709. encoded2 = chars.indexOf(base64[i+1]);
  25710. encoded3 = chars.indexOf(base64[i+2]);
  25711. encoded4 = chars.indexOf(base64[i+3]);
  25712. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  25713. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  25714. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  25715. }
  25716. return arraybuffer;
  25717. };
  25718. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  25719. },{}],115:[function(require,module,exports){
  25720. (function (global){
  25721. /**
  25722. * Create a blob builder even when vendor prefixes exist
  25723. */
  25724. var BlobBuilder = global.BlobBuilder
  25725. || global.WebKitBlobBuilder
  25726. || global.MSBlobBuilder
  25727. || global.MozBlobBuilder;
  25728. /**
  25729. * Check if Blob constructor is supported
  25730. */
  25731. var blobSupported = (function() {
  25732. try {
  25733. var b = new Blob(['hi']);
  25734. return b.size == 2;
  25735. } catch(e) {
  25736. return false;
  25737. }
  25738. })();
  25739. /**
  25740. * Check if BlobBuilder is supported
  25741. */
  25742. var blobBuilderSupported = BlobBuilder
  25743. && BlobBuilder.prototype.append
  25744. && BlobBuilder.prototype.getBlob;
  25745. function BlobBuilderConstructor(ary, options) {
  25746. options = options || {};
  25747. var bb = new BlobBuilder();
  25748. for (var i = 0; i < ary.length; i++) {
  25749. bb.append(ary[i]);
  25750. }
  25751. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  25752. };
  25753. module.exports = (function() {
  25754. if (blobSupported) {
  25755. return global.Blob;
  25756. } else if (blobBuilderSupported) {
  25757. return BlobBuilderConstructor;
  25758. } else {
  25759. return undefined;
  25760. }
  25761. })();
  25762. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25763. },{}],116:[function(require,module,exports){
  25764. (function (global){
  25765. /*
  25766. * Module requirements.
  25767. */
  25768. var isArray = require('isarray');
  25769. /**
  25770. * Module exports.
  25771. */
  25772. module.exports = hasBinary;
  25773. /**
  25774. * Checks for binary data.
  25775. *
  25776. * Right now only Buffer and ArrayBuffer are supported..
  25777. *
  25778. * @param {Object} anything
  25779. * @api public
  25780. */
  25781. function hasBinary(data) {
  25782. function _hasBinary(obj) {
  25783. if (!obj) return false;
  25784. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  25785. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  25786. (global.Blob && obj instanceof Blob) ||
  25787. (global.File && obj instanceof File)
  25788. ) {
  25789. return true;
  25790. }
  25791. if (isArray(obj)) {
  25792. for (var i = 0; i < obj.length; i++) {
  25793. if (_hasBinary(obj[i])) {
  25794. return true;
  25795. }
  25796. }
  25797. } else if (obj && 'object' == typeof obj) {
  25798. if (obj.toJSON) {
  25799. obj = obj.toJSON();
  25800. }
  25801. for (var key in obj) {
  25802. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  25803. return true;
  25804. }
  25805. }
  25806. }
  25807. return false;
  25808. }
  25809. return _hasBinary(data);
  25810. }
  25811. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25812. },{"isarray":117}],117:[function(require,module,exports){
  25813. module.exports = Array.isArray || function (arr) {
  25814. return Object.prototype.toString.call(arr) == '[object Array]';
  25815. };
  25816. },{}],118:[function(require,module,exports){
  25817. (function (global){
  25818. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  25819. ;(function(root) {
  25820. // Detect free variables `exports`
  25821. var freeExports = typeof exports == 'object' && exports;
  25822. // Detect free variable `module`
  25823. var freeModule = typeof module == 'object' && module &&
  25824. module.exports == freeExports && module;
  25825. // Detect free variable `global`, from Node.js or Browserified code,
  25826. // and use it as `root`
  25827. var freeGlobal = typeof global == 'object' && global;
  25828. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  25829. root = freeGlobal;
  25830. }
  25831. /*--------------------------------------------------------------------------*/
  25832. var stringFromCharCode = String.fromCharCode;
  25833. // Taken from http://mths.be/punycode
  25834. function ucs2decode(string) {
  25835. var output = [];
  25836. var counter = 0;
  25837. var length = string.length;
  25838. var value;
  25839. var extra;
  25840. while (counter < length) {
  25841. value = string.charCodeAt(counter++);
  25842. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  25843. // high surrogate, and there is a next character
  25844. extra = string.charCodeAt(counter++);
  25845. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  25846. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  25847. } else {
  25848. // unmatched surrogate; only append this code unit, in case the next
  25849. // code unit is the high surrogate of a surrogate pair
  25850. output.push(value);
  25851. counter--;
  25852. }
  25853. } else {
  25854. output.push(value);
  25855. }
  25856. }
  25857. return output;
  25858. }
  25859. // Taken from http://mths.be/punycode
  25860. function ucs2encode(array) {
  25861. var length = array.length;
  25862. var index = -1;
  25863. var value;
  25864. var output = '';
  25865. while (++index < length) {
  25866. value = array[index];
  25867. if (value > 0xFFFF) {
  25868. value -= 0x10000;
  25869. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  25870. value = 0xDC00 | value & 0x3FF;
  25871. }
  25872. output += stringFromCharCode(value);
  25873. }
  25874. return output;
  25875. }
  25876. /*--------------------------------------------------------------------------*/
  25877. function createByte(codePoint, shift) {
  25878. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  25879. }
  25880. function encodeCodePoint(codePoint) {
  25881. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  25882. return stringFromCharCode(codePoint);
  25883. }
  25884. var symbol = '';
  25885. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  25886. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  25887. }
  25888. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  25889. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  25890. symbol += createByte(codePoint, 6);
  25891. }
  25892. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  25893. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  25894. symbol += createByte(codePoint, 12);
  25895. symbol += createByte(codePoint, 6);
  25896. }
  25897. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  25898. return symbol;
  25899. }
  25900. function utf8encode(string) {
  25901. var codePoints = ucs2decode(string);
  25902. // console.log(JSON.stringify(codePoints.map(function(x) {
  25903. // return 'U+' + x.toString(16).toUpperCase();
  25904. // })));
  25905. var length = codePoints.length;
  25906. var index = -1;
  25907. var codePoint;
  25908. var byteString = '';
  25909. while (++index < length) {
  25910. codePoint = codePoints[index];
  25911. byteString += encodeCodePoint(codePoint);
  25912. }
  25913. return byteString;
  25914. }
  25915. /*--------------------------------------------------------------------------*/
  25916. function readContinuationByte() {
  25917. if (byteIndex >= byteCount) {
  25918. throw Error('Invalid byte index');
  25919. }
  25920. var continuationByte = byteArray[byteIndex] & 0xFF;
  25921. byteIndex++;
  25922. if ((continuationByte & 0xC0) == 0x80) {
  25923. return continuationByte & 0x3F;
  25924. }
  25925. // If we end up here, it’s not a continuation byte
  25926. throw Error('Invalid continuation byte');
  25927. }
  25928. function decodeSymbol() {
  25929. var byte1;
  25930. var byte2;
  25931. var byte3;
  25932. var byte4;
  25933. var codePoint;
  25934. if (byteIndex > byteCount) {
  25935. throw Error('Invalid byte index');
  25936. }
  25937. if (byteIndex == byteCount) {
  25938. return false;
  25939. }
  25940. // Read first byte
  25941. byte1 = byteArray[byteIndex] & 0xFF;
  25942. byteIndex++;
  25943. // 1-byte sequence (no continuation bytes)
  25944. if ((byte1 & 0x80) == 0) {
  25945. return byte1;
  25946. }
  25947. // 2-byte sequence
  25948. if ((byte1 & 0xE0) == 0xC0) {
  25949. var byte2 = readContinuationByte();
  25950. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  25951. if (codePoint >= 0x80) {
  25952. return codePoint;
  25953. } else {
  25954. throw Error('Invalid continuation byte');
  25955. }
  25956. }
  25957. // 3-byte sequence (may include unpaired surrogates)
  25958. if ((byte1 & 0xF0) == 0xE0) {
  25959. byte2 = readContinuationByte();
  25960. byte3 = readContinuationByte();
  25961. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  25962. if (codePoint >= 0x0800) {
  25963. return codePoint;
  25964. } else {
  25965. throw Error('Invalid continuation byte');
  25966. }
  25967. }
  25968. // 4-byte sequence
  25969. if ((byte1 & 0xF8) == 0xF0) {
  25970. byte2 = readContinuationByte();
  25971. byte3 = readContinuationByte();
  25972. byte4 = readContinuationByte();
  25973. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  25974. (byte3 << 0x06) | byte4;
  25975. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  25976. return codePoint;
  25977. }
  25978. }
  25979. throw Error('Invalid UTF-8 detected');
  25980. }
  25981. var byteArray;
  25982. var byteCount;
  25983. var byteIndex;
  25984. function utf8decode(byteString) {
  25985. byteArray = ucs2decode(byteString);
  25986. byteCount = byteArray.length;
  25987. byteIndex = 0;
  25988. var codePoints = [];
  25989. var tmp;
  25990. while ((tmp = decodeSymbol()) !== false) {
  25991. codePoints.push(tmp);
  25992. }
  25993. return ucs2encode(codePoints);
  25994. }
  25995. /*--------------------------------------------------------------------------*/
  25996. var utf8 = {
  25997. 'version': '2.0.0',
  25998. 'encode': utf8encode,
  25999. 'decode': utf8decode
  26000. };
  26001. // Some AMD build optimizers, like r.js, check for specific condition patterns
  26002. // like the following:
  26003. if (
  26004. typeof define == 'function' &&
  26005. typeof define.amd == 'object' &&
  26006. define.amd
  26007. ) {
  26008. define(function() {
  26009. return utf8;
  26010. });
  26011. } else if (freeExports && !freeExports.nodeType) {
  26012. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  26013. freeModule.exports = utf8;
  26014. } else { // in Narwhal or RingoJS v0.7.0-
  26015. var object = {};
  26016. var hasOwnProperty = object.hasOwnProperty;
  26017. for (var key in utf8) {
  26018. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  26019. }
  26020. }
  26021. } else { // in Rhino or a web browser
  26022. root.utf8 = utf8;
  26023. }
  26024. }(this));
  26025. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26026. },{}],119:[function(require,module,exports){
  26027. /**
  26028. * Module dependencies.
  26029. */
  26030. var global = require('global');
  26031. /**
  26032. * Module exports.
  26033. *
  26034. * Logic borrowed from Modernizr:
  26035. *
  26036. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  26037. */
  26038. try {
  26039. module.exports = 'XMLHttpRequest' in global &&
  26040. 'withCredentials' in new global.XMLHttpRequest();
  26041. } catch (err) {
  26042. // if XMLHttp support is disabled in IE then it will throw
  26043. // when trying to create
  26044. module.exports = false;
  26045. }
  26046. },{"global":120}],120:[function(require,module,exports){
  26047. /**
  26048. * Returns `this`. Execute this without a "context" (i.e. without it being
  26049. * attached to an object of the left-hand side), and `this` points to the
  26050. * "global" scope of the current JS execution.
  26051. */
  26052. module.exports = (function () { return this; })();
  26053. },{}],121:[function(require,module,exports){
  26054. (function (global){
  26055. /**
  26056. * JSON parse.
  26057. *
  26058. * @see Based on jQuery#parseJSON (MIT) and JSON2
  26059. * @api private
  26060. */
  26061. var rvalidchars = /^[\],:{}\s]*$/;
  26062. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  26063. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  26064. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  26065. var rtrimLeft = /^\s+/;
  26066. var rtrimRight = /\s+$/;
  26067. module.exports = function parsejson(data) {
  26068. if ('string' != typeof data || !data) {
  26069. return null;
  26070. }
  26071. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  26072. // Attempt to parse using the native JSON parser first
  26073. if (global.JSON && JSON.parse) {
  26074. return JSON.parse(data);
  26075. }
  26076. if (rvalidchars.test(data.replace(rvalidescape, '@')
  26077. .replace(rvalidtokens, ']')
  26078. .replace(rvalidbraces, ''))) {
  26079. return (new Function('return ' + data))();
  26080. }
  26081. };
  26082. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26083. },{}],122:[function(require,module,exports){
  26084. /**
  26085. * Compiles a querystring
  26086. * Returns string representation of the object
  26087. *
  26088. * @param {Object}
  26089. * @api private
  26090. */
  26091. exports.encode = function (obj) {
  26092. var str = '';
  26093. for (var i in obj) {
  26094. if (obj.hasOwnProperty(i)) {
  26095. if (str.length) str += '&';
  26096. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  26097. }
  26098. }
  26099. return str;
  26100. };
  26101. /**
  26102. * Parses a simple querystring into an object
  26103. *
  26104. * @param {String} qs
  26105. * @api private
  26106. */
  26107. exports.decode = function(qs){
  26108. var qry = {};
  26109. var pairs = qs.split('&');
  26110. for (var i = 0, l = pairs.length; i < l; i++) {
  26111. var pair = pairs[i].split('=');
  26112. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  26113. }
  26114. return qry;
  26115. };
  26116. },{}],123:[function(require,module,exports){
  26117. /**
  26118. * Parses an URI
  26119. *
  26120. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26121. * @api private
  26122. */
  26123. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26124. var parts = [
  26125. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26126. ];
  26127. module.exports = function parseuri(str) {
  26128. var src = str,
  26129. b = str.indexOf('['),
  26130. e = str.indexOf(']');
  26131. if (b != -1 && e != -1) {
  26132. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  26133. }
  26134. var m = re.exec(str || ''),
  26135. uri = {},
  26136. i = 14;
  26137. while (i--) {
  26138. uri[parts[i]] = m[i] || '';
  26139. }
  26140. if (b != -1 && e != -1) {
  26141. uri.source = src;
  26142. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  26143. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  26144. uri.ipv6uri = true;
  26145. }
  26146. return uri;
  26147. };
  26148. },{}],124:[function(require,module,exports){
  26149. /**
  26150. * Module dependencies.
  26151. */
  26152. var global = (function() { return this; })();
  26153. /**
  26154. * WebSocket constructor.
  26155. */
  26156. var WebSocket = global.WebSocket || global.MozWebSocket;
  26157. /**
  26158. * Module exports.
  26159. */
  26160. module.exports = WebSocket ? ws : null;
  26161. /**
  26162. * WebSocket constructor.
  26163. *
  26164. * The third `opts` options object gets ignored in web browsers, since it's
  26165. * non-standard, and throws a TypeError if passed to the constructor.
  26166. * See: https://github.com/einaros/ws/issues/227
  26167. *
  26168. * @param {String} uri
  26169. * @param {Array} protocols (optional)
  26170. * @param {Object) opts (optional)
  26171. * @api public
  26172. */
  26173. function ws(uri, protocols, opts) {
  26174. var instance;
  26175. if (protocols) {
  26176. instance = new WebSocket(uri, protocols);
  26177. } else {
  26178. instance = new WebSocket(uri);
  26179. }
  26180. return instance;
  26181. }
  26182. if (WebSocket) ws.prototype = WebSocket.prototype;
  26183. },{}],125:[function(require,module,exports){
  26184. (function (global){
  26185. /*
  26186. * Module requirements.
  26187. */
  26188. var isArray = require('isarray');
  26189. /**
  26190. * Module exports.
  26191. */
  26192. module.exports = hasBinary;
  26193. /**
  26194. * Checks for binary data.
  26195. *
  26196. * Right now only Buffer and ArrayBuffer are supported..
  26197. *
  26198. * @param {Object} anything
  26199. * @api public
  26200. */
  26201. function hasBinary(data) {
  26202. function _hasBinary(obj) {
  26203. if (!obj) return false;
  26204. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26205. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  26206. (global.Blob && obj instanceof Blob) ||
  26207. (global.File && obj instanceof File)
  26208. ) {
  26209. return true;
  26210. }
  26211. if (isArray(obj)) {
  26212. for (var i = 0; i < obj.length; i++) {
  26213. if (_hasBinary(obj[i])) {
  26214. return true;
  26215. }
  26216. }
  26217. } else if (obj && 'object' == typeof obj) {
  26218. if (obj.toJSON) {
  26219. obj = obj.toJSON();
  26220. }
  26221. for (var key in obj) {
  26222. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26223. return true;
  26224. }
  26225. }
  26226. }
  26227. return false;
  26228. }
  26229. return _hasBinary(data);
  26230. }
  26231. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26232. },{"isarray":126}],126:[function(require,module,exports){
  26233. arguments[4][117][0].apply(exports,arguments)
  26234. },{"dup":117}],127:[function(require,module,exports){
  26235. var indexOf = [].indexOf;
  26236. module.exports = function(arr, obj){
  26237. if (indexOf) return arr.indexOf(obj);
  26238. for (var i = 0; i < arr.length; ++i) {
  26239. if (arr[i] === obj) return i;
  26240. }
  26241. return -1;
  26242. };
  26243. },{}],128:[function(require,module,exports){
  26244. /**
  26245. * HOP ref.
  26246. */
  26247. var has = Object.prototype.hasOwnProperty;
  26248. /**
  26249. * Return own keys in `obj`.
  26250. *
  26251. * @param {Object} obj
  26252. * @return {Array}
  26253. * @api public
  26254. */
  26255. exports.keys = Object.keys || function(obj){
  26256. var keys = [];
  26257. for (var key in obj) {
  26258. if (has.call(obj, key)) {
  26259. keys.push(key);
  26260. }
  26261. }
  26262. return keys;
  26263. };
  26264. /**
  26265. * Return own values in `obj`.
  26266. *
  26267. * @param {Object} obj
  26268. * @return {Array}
  26269. * @api public
  26270. */
  26271. exports.values = function(obj){
  26272. var vals = [];
  26273. for (var key in obj) {
  26274. if (has.call(obj, key)) {
  26275. vals.push(obj[key]);
  26276. }
  26277. }
  26278. return vals;
  26279. };
  26280. /**
  26281. * Merge `b` into `a`.
  26282. *
  26283. * @param {Object} a
  26284. * @param {Object} b
  26285. * @return {Object} a
  26286. * @api public
  26287. */
  26288. exports.merge = function(a, b){
  26289. for (var key in b) {
  26290. if (has.call(b, key)) {
  26291. a[key] = b[key];
  26292. }
  26293. }
  26294. return a;
  26295. };
  26296. /**
  26297. * Return length of `obj`.
  26298. *
  26299. * @param {Object} obj
  26300. * @return {Number}
  26301. * @api public
  26302. */
  26303. exports.length = function(obj){
  26304. return exports.keys(obj).length;
  26305. };
  26306. /**
  26307. * Check if `obj` is empty.
  26308. *
  26309. * @param {Object} obj
  26310. * @return {Boolean}
  26311. * @api public
  26312. */
  26313. exports.isEmpty = function(obj){
  26314. return 0 == exports.length(obj);
  26315. };
  26316. },{}],129:[function(require,module,exports){
  26317. /**
  26318. * Parses an URI
  26319. *
  26320. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26321. * @api private
  26322. */
  26323. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26324. var parts = [
  26325. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  26326. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26327. ];
  26328. module.exports = function parseuri(str) {
  26329. var m = re.exec(str || '')
  26330. , uri = {}
  26331. , i = 14;
  26332. while (i--) {
  26333. uri[parts[i]] = m[i] || '';
  26334. }
  26335. return uri;
  26336. };
  26337. },{}],130:[function(require,module,exports){
  26338. (function (global){
  26339. /*global Blob,File*/
  26340. /**
  26341. * Module requirements
  26342. */
  26343. var isArray = require('isarray');
  26344. var isBuf = require('./is-buffer');
  26345. /**
  26346. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26347. * Anything with blobs or files should be fed through removeBlobs before coming
  26348. * here.
  26349. *
  26350. * @param {Object} packet - socket.io event packet
  26351. * @return {Object} with deconstructed packet and list of buffers
  26352. * @api public
  26353. */
  26354. exports.deconstructPacket = function(packet){
  26355. var buffers = [];
  26356. var packetData = packet.data;
  26357. function _deconstructPacket(data) {
  26358. if (!data) return data;
  26359. if (isBuf(data)) {
  26360. var placeholder = { _placeholder: true, num: buffers.length };
  26361. buffers.push(data);
  26362. return placeholder;
  26363. } else if (isArray(data)) {
  26364. var newData = new Array(data.length);
  26365. for (var i = 0; i < data.length; i++) {
  26366. newData[i] = _deconstructPacket(data[i]);
  26367. }
  26368. return newData;
  26369. } else if ('object' == typeof data && !(data instanceof Date)) {
  26370. var newData = {};
  26371. for (var key in data) {
  26372. newData[key] = _deconstructPacket(data[key]);
  26373. }
  26374. return newData;
  26375. }
  26376. return data;
  26377. }
  26378. var pack = packet;
  26379. pack.data = _deconstructPacket(packetData);
  26380. pack.attachments = buffers.length; // number of binary 'attachments'
  26381. return {packet: pack, buffers: buffers};
  26382. };
  26383. /**
  26384. * Reconstructs a binary packet from its placeholder packet and buffers
  26385. *
  26386. * @param {Object} packet - event packet with placeholders
  26387. * @param {Array} buffers - binary buffers to put in placeholder positions
  26388. * @return {Object} reconstructed packet
  26389. * @api public
  26390. */
  26391. exports.reconstructPacket = function(packet, buffers) {
  26392. var curPlaceHolder = 0;
  26393. function _reconstructPacket(data) {
  26394. if (data && data._placeholder) {
  26395. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26396. return buf;
  26397. } else if (isArray(data)) {
  26398. for (var i = 0; i < data.length; i++) {
  26399. data[i] = _reconstructPacket(data[i]);
  26400. }
  26401. return data;
  26402. } else if (data && 'object' == typeof data) {
  26403. for (var key in data) {
  26404. data[key] = _reconstructPacket(data[key]);
  26405. }
  26406. return data;
  26407. }
  26408. return data;
  26409. }
  26410. packet.data = _reconstructPacket(packet.data);
  26411. packet.attachments = undefined; // no longer useful
  26412. return packet;
  26413. };
  26414. /**
  26415. * Asynchronously removes Blobs or Files from data via
  26416. * FileReader's readAsArrayBuffer method. Used before encoding
  26417. * data as msgpack. Calls callback with the blobless data.
  26418. *
  26419. * @param {Object} data
  26420. * @param {Function} callback
  26421. * @api private
  26422. */
  26423. exports.removeBlobs = function(data, callback) {
  26424. function _removeBlobs(obj, curKey, containingObject) {
  26425. if (!obj) return obj;
  26426. // convert any blob
  26427. if ((global.Blob && obj instanceof Blob) ||
  26428. (global.File && obj instanceof File)) {
  26429. pendingBlobs++;
  26430. // async filereader
  26431. var fileReader = new FileReader();
  26432. fileReader.onload = function() { // this.result == arraybuffer
  26433. if (containingObject) {
  26434. containingObject[curKey] = this.result;
  26435. }
  26436. else {
  26437. bloblessData = this.result;
  26438. }
  26439. // if nothing pending its callback time
  26440. if(! --pendingBlobs) {
  26441. callback(bloblessData);
  26442. }
  26443. };
  26444. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26445. } else if (isArray(obj)) { // handle array
  26446. for (var i = 0; i < obj.length; i++) {
  26447. _removeBlobs(obj[i], i, obj);
  26448. }
  26449. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26450. for (var key in obj) {
  26451. _removeBlobs(obj[key], key, obj);
  26452. }
  26453. }
  26454. }
  26455. var pendingBlobs = 0;
  26456. var bloblessData = data;
  26457. _removeBlobs(bloblessData);
  26458. if (!pendingBlobs) {
  26459. callback(bloblessData);
  26460. }
  26461. };
  26462. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26463. },{"./is-buffer":132,"isarray":133}],131:[function(require,module,exports){
  26464. /**
  26465. * Module dependencies.
  26466. */
  26467. var debug = require('debug')('socket.io-parser');
  26468. var json = require('json3');
  26469. var isArray = require('isarray');
  26470. var Emitter = require('component-emitter');
  26471. var binary = require('./binary');
  26472. var isBuf = require('./is-buffer');
  26473. /**
  26474. * Protocol version.
  26475. *
  26476. * @api public
  26477. */
  26478. exports.protocol = 4;
  26479. /**
  26480. * Packet types.
  26481. *
  26482. * @api public
  26483. */
  26484. exports.types = [
  26485. 'CONNECT',
  26486. 'DISCONNECT',
  26487. 'EVENT',
  26488. 'BINARY_EVENT',
  26489. 'ACK',
  26490. 'BINARY_ACK',
  26491. 'ERROR'
  26492. ];
  26493. /**
  26494. * Packet type `connect`.
  26495. *
  26496. * @api public
  26497. */
  26498. exports.CONNECT = 0;
  26499. /**
  26500. * Packet type `disconnect`.
  26501. *
  26502. * @api public
  26503. */
  26504. exports.DISCONNECT = 1;
  26505. /**
  26506. * Packet type `event`.
  26507. *
  26508. * @api public
  26509. */
  26510. exports.EVENT = 2;
  26511. /**
  26512. * Packet type `ack`.
  26513. *
  26514. * @api public
  26515. */
  26516. exports.ACK = 3;
  26517. /**
  26518. * Packet type `error`.
  26519. *
  26520. * @api public
  26521. */
  26522. exports.ERROR = 4;
  26523. /**
  26524. * Packet type 'binary event'
  26525. *
  26526. * @api public
  26527. */
  26528. exports.BINARY_EVENT = 5;
  26529. /**
  26530. * Packet type `binary ack`. For acks with binary arguments.
  26531. *
  26532. * @api public
  26533. */
  26534. exports.BINARY_ACK = 6;
  26535. /**
  26536. * Encoder constructor.
  26537. *
  26538. * @api public
  26539. */
  26540. exports.Encoder = Encoder;
  26541. /**
  26542. * Decoder constructor.
  26543. *
  26544. * @api public
  26545. */
  26546. exports.Decoder = Decoder;
  26547. /**
  26548. * A socket.io Encoder instance
  26549. *
  26550. * @api public
  26551. */
  26552. function Encoder() {}
  26553. /**
  26554. * Encode a packet as a single string if non-binary, or as a
  26555. * buffer sequence, depending on packet type.
  26556. *
  26557. * @param {Object} obj - packet object
  26558. * @param {Function} callback - function to handle encodings (likely engine.write)
  26559. * @return Calls callback with Array of encodings
  26560. * @api public
  26561. */
  26562. Encoder.prototype.encode = function(obj, callback){
  26563. debug('encoding packet %j', obj);
  26564. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26565. encodeAsBinary(obj, callback);
  26566. }
  26567. else {
  26568. var encoding = encodeAsString(obj);
  26569. callback([encoding]);
  26570. }
  26571. };
  26572. /**
  26573. * Encode packet as string.
  26574. *
  26575. * @param {Object} packet
  26576. * @return {String} encoded
  26577. * @api private
  26578. */
  26579. function encodeAsString(obj) {
  26580. var str = '';
  26581. var nsp = false;
  26582. // first is type
  26583. str += obj.type;
  26584. // attachments if we have them
  26585. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26586. str += obj.attachments;
  26587. str += '-';
  26588. }
  26589. // if we have a namespace other than `/`
  26590. // we append it followed by a comma `,`
  26591. if (obj.nsp && '/' != obj.nsp) {
  26592. nsp = true;
  26593. str += obj.nsp;
  26594. }
  26595. // immediately followed by the id
  26596. if (null != obj.id) {
  26597. if (nsp) {
  26598. str += ',';
  26599. nsp = false;
  26600. }
  26601. str += obj.id;
  26602. }
  26603. // json data
  26604. if (null != obj.data) {
  26605. if (nsp) str += ',';
  26606. str += json.stringify(obj.data);
  26607. }
  26608. debug('encoded %j as %s', obj, str);
  26609. return str;
  26610. }
  26611. /**
  26612. * Encode packet as 'buffer sequence' by removing blobs, and
  26613. * deconstructing packet into object with placeholders and
  26614. * a list of buffers.
  26615. *
  26616. * @param {Object} packet
  26617. * @return {Buffer} encoded
  26618. * @api private
  26619. */
  26620. function encodeAsBinary(obj, callback) {
  26621. function writeEncoding(bloblessData) {
  26622. var deconstruction = binary.deconstructPacket(bloblessData);
  26623. var pack = encodeAsString(deconstruction.packet);
  26624. var buffers = deconstruction.buffers;
  26625. buffers.unshift(pack); // add packet info to beginning of data list
  26626. callback(buffers); // write all the buffers
  26627. }
  26628. binary.removeBlobs(obj, writeEncoding);
  26629. }
  26630. /**
  26631. * A socket.io Decoder instance
  26632. *
  26633. * @return {Object} decoder
  26634. * @api public
  26635. */
  26636. function Decoder() {
  26637. this.reconstructor = null;
  26638. }
  26639. /**
  26640. * Mix in `Emitter` with Decoder.
  26641. */
  26642. Emitter(Decoder.prototype);
  26643. /**
  26644. * Decodes an ecoded packet string into packet JSON.
  26645. *
  26646. * @param {String} obj - encoded packet
  26647. * @return {Object} packet
  26648. * @api public
  26649. */
  26650. Decoder.prototype.add = function(obj) {
  26651. var packet;
  26652. if ('string' == typeof obj) {
  26653. packet = decodeString(obj);
  26654. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  26655. this.reconstructor = new BinaryReconstructor(packet);
  26656. // no attachments, labeled binary but no binary data to follow
  26657. if (this.reconstructor.reconPack.attachments === 0) {
  26658. this.emit('decoded', packet);
  26659. }
  26660. } else { // non-binary full packet
  26661. this.emit('decoded', packet);
  26662. }
  26663. }
  26664. else if (isBuf(obj) || obj.base64) { // raw binary data
  26665. if (!this.reconstructor) {
  26666. throw new Error('got binary data when not reconstructing a packet');
  26667. } else {
  26668. packet = this.reconstructor.takeBinaryData(obj);
  26669. if (packet) { // received final buffer
  26670. this.reconstructor = null;
  26671. this.emit('decoded', packet);
  26672. }
  26673. }
  26674. }
  26675. else {
  26676. throw new Error('Unknown type: ' + obj);
  26677. }
  26678. };
  26679. /**
  26680. * Decode a packet String (JSON data)
  26681. *
  26682. * @param {String} str
  26683. * @return {Object} packet
  26684. * @api private
  26685. */
  26686. function decodeString(str) {
  26687. var p = {};
  26688. var i = 0;
  26689. // look up type
  26690. p.type = Number(str.charAt(0));
  26691. if (null == exports.types[p.type]) return error();
  26692. // look up attachments if type binary
  26693. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  26694. var buf = '';
  26695. while (str.charAt(++i) != '-') {
  26696. buf += str.charAt(i);
  26697. if (i == str.length) break;
  26698. }
  26699. if (buf != Number(buf) || str.charAt(i) != '-') {
  26700. throw new Error('Illegal attachments');
  26701. }
  26702. p.attachments = Number(buf);
  26703. }
  26704. // look up namespace (if any)
  26705. if ('/' == str.charAt(i + 1)) {
  26706. p.nsp = '';
  26707. while (++i) {
  26708. var c = str.charAt(i);
  26709. if (',' == c) break;
  26710. p.nsp += c;
  26711. if (i == str.length) break;
  26712. }
  26713. } else {
  26714. p.nsp = '/';
  26715. }
  26716. // look up id
  26717. var next = str.charAt(i + 1);
  26718. if ('' !== next && Number(next) == next) {
  26719. p.id = '';
  26720. while (++i) {
  26721. var c = str.charAt(i);
  26722. if (null == c || Number(c) != c) {
  26723. --i;
  26724. break;
  26725. }
  26726. p.id += str.charAt(i);
  26727. if (i == str.length) break;
  26728. }
  26729. p.id = Number(p.id);
  26730. }
  26731. // look up json data
  26732. if (str.charAt(++i)) {
  26733. try {
  26734. p.data = json.parse(str.substr(i));
  26735. } catch(e){
  26736. return error();
  26737. }
  26738. }
  26739. debug('decoded %s as %j', str, p);
  26740. return p;
  26741. }
  26742. /**
  26743. * Deallocates a parser's resources
  26744. *
  26745. * @api public
  26746. */
  26747. Decoder.prototype.destroy = function() {
  26748. if (this.reconstructor) {
  26749. this.reconstructor.finishedReconstruction();
  26750. }
  26751. };
  26752. /**
  26753. * A manager of a binary event's 'buffer sequence'. Should
  26754. * be constructed whenever a packet of type BINARY_EVENT is
  26755. * decoded.
  26756. *
  26757. * @param {Object} packet
  26758. * @return {BinaryReconstructor} initialized reconstructor
  26759. * @api private
  26760. */
  26761. function BinaryReconstructor(packet) {
  26762. this.reconPack = packet;
  26763. this.buffers = [];
  26764. }
  26765. /**
  26766. * Method to be called when binary data received from connection
  26767. * after a BINARY_EVENT packet.
  26768. *
  26769. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  26770. * @return {null | Object} returns null if more binary data is expected or
  26771. * a reconstructed packet object if all buffers have been received.
  26772. * @api private
  26773. */
  26774. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  26775. this.buffers.push(binData);
  26776. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  26777. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  26778. this.finishedReconstruction();
  26779. return packet;
  26780. }
  26781. return null;
  26782. };
  26783. /**
  26784. * Cleans up binary packet reconstruction variables.
  26785. *
  26786. * @api private
  26787. */
  26788. BinaryReconstructor.prototype.finishedReconstruction = function() {
  26789. this.reconPack = null;
  26790. this.buffers = [];
  26791. };
  26792. function error(data){
  26793. return {
  26794. type: exports.ERROR,
  26795. data: 'parser error'
  26796. };
  26797. }
  26798. },{"./binary":130,"./is-buffer":132,"component-emitter":94,"debug":95,"isarray":133,"json3":134}],132:[function(require,module,exports){
  26799. (function (global){
  26800. module.exports = isBuf;
  26801. /**
  26802. * Returns true if obj is a buffer or an arraybuffer.
  26803. *
  26804. * @api private
  26805. */
  26806. function isBuf(obj) {
  26807. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26808. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  26809. }
  26810. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26811. },{}],133:[function(require,module,exports){
  26812. arguments[4][117][0].apply(exports,arguments)
  26813. },{"dup":117}],134:[function(require,module,exports){
  26814. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  26815. ;(function (window) {
  26816. // Convenience aliases.
  26817. var getClass = {}.toString, isProperty, forEach, undef;
  26818. // Detect the `define` function exposed by asynchronous module loaders. The
  26819. // strict `define` check is necessary for compatibility with `r.js`.
  26820. var isLoader = typeof define === "function" && define.amd;
  26821. // Detect native implementations.
  26822. var nativeJSON = typeof JSON == "object" && JSON;
  26823. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  26824. // available.
  26825. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  26826. if (JSON3 && nativeJSON) {
  26827. // Explicitly delegate to the native `stringify` and `parse`
  26828. // implementations in CommonJS environments.
  26829. JSON3.stringify = nativeJSON.stringify;
  26830. JSON3.parse = nativeJSON.parse;
  26831. } else {
  26832. // Export for web browsers, JavaScript engines, and asynchronous module
  26833. // loaders, using the global `JSON` object if available.
  26834. JSON3 = window.JSON = nativeJSON || {};
  26835. }
  26836. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  26837. var isExtended = new Date(-3509827334573292);
  26838. try {
  26839. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  26840. // results for certain dates in Opera >= 10.53.
  26841. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  26842. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  26843. // but clips the values returned by the date methods to the range of
  26844. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  26845. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  26846. } catch (exception) {}
  26847. // Internal: Determines whether the native `JSON.stringify` and `parse`
  26848. // implementations are spec-compliant. Based on work by Ken Snyder.
  26849. function has(name) {
  26850. if (has[name] !== undef) {
  26851. // Return cached feature test result.
  26852. return has[name];
  26853. }
  26854. var isSupported;
  26855. if (name == "bug-string-char-index") {
  26856. // IE <= 7 doesn't support accessing string characters using square
  26857. // bracket notation. IE 8 only supports this for primitives.
  26858. isSupported = "a"[0] != "a";
  26859. } else if (name == "json") {
  26860. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  26861. // supported.
  26862. isSupported = has("json-stringify") && has("json-parse");
  26863. } else {
  26864. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  26865. // Test `JSON.stringify`.
  26866. if (name == "json-stringify") {
  26867. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  26868. if (stringifySupported) {
  26869. // A test function object with a custom `toJSON` method.
  26870. (value = function () {
  26871. return 1;
  26872. }).toJSON = value;
  26873. try {
  26874. stringifySupported =
  26875. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  26876. // primitives as object literals.
  26877. stringify(0) === "0" &&
  26878. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  26879. // literals.
  26880. stringify(new Number()) === "0" &&
  26881. stringify(new String()) == '""' &&
  26882. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  26883. // does not define a canonical JSON representation (this applies to
  26884. // objects with `toJSON` properties as well, *unless* they are nested
  26885. // within an object or array).
  26886. stringify(getClass) === undef &&
  26887. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  26888. // FF 3.1b3 pass this test.
  26889. stringify(undef) === undef &&
  26890. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  26891. // respectively, if the value is omitted entirely.
  26892. stringify() === undef &&
  26893. // FF 3.1b1, 2 throw an error if the given value is not a number,
  26894. // string, array, object, Boolean, or `null` literal. This applies to
  26895. // objects with custom `toJSON` methods as well, unless they are nested
  26896. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  26897. // methods entirely.
  26898. stringify(value) === "1" &&
  26899. stringify([value]) == "[1]" &&
  26900. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  26901. // `"[null]"`.
  26902. stringify([undef]) == "[null]" &&
  26903. // YUI 3.0.0b1 fails to serialize `null` literals.
  26904. stringify(null) == "null" &&
  26905. // FF 3.1b1, 2 halts serialization if an array contains a function:
  26906. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  26907. // elides non-JSON values from objects and arrays, unless they
  26908. // define custom `toJSON` methods.
  26909. stringify([undef, getClass, null]) == "[null,null,null]" &&
  26910. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  26911. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  26912. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  26913. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  26914. stringify(null, value) === "1" &&
  26915. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  26916. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  26917. // serialize extended years.
  26918. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  26919. // The milliseconds are optional in ES 5, but required in 5.1.
  26920. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  26921. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  26922. // four-digit years instead of six-digit years. Credits: @Yaffle.
  26923. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  26924. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  26925. // values less than 1000. Credits: @Yaffle.
  26926. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  26927. } catch (exception) {
  26928. stringifySupported = false;
  26929. }
  26930. }
  26931. isSupported = stringifySupported;
  26932. }
  26933. // Test `JSON.parse`.
  26934. if (name == "json-parse") {
  26935. var parse = JSON3.parse;
  26936. if (typeof parse == "function") {
  26937. try {
  26938. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  26939. // Conforming implementations should also coerce the initial argument to
  26940. // a string prior to parsing.
  26941. if (parse("0") === 0 && !parse(false)) {
  26942. // Simple parsing test.
  26943. value = parse(serialized);
  26944. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  26945. if (parseSupported) {
  26946. try {
  26947. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  26948. parseSupported = !parse('"\t"');
  26949. } catch (exception) {}
  26950. if (parseSupported) {
  26951. try {
  26952. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  26953. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  26954. // certain octal literals.
  26955. parseSupported = parse("01") !== 1;
  26956. } catch (exception) {}
  26957. }
  26958. if (parseSupported) {
  26959. try {
  26960. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  26961. // points. These environments, along with FF 3.1b1 and 2,
  26962. // also allow trailing commas in JSON objects and arrays.
  26963. parseSupported = parse("1.") !== 1;
  26964. } catch (exception) {}
  26965. }
  26966. }
  26967. }
  26968. } catch (exception) {
  26969. parseSupported = false;
  26970. }
  26971. }
  26972. isSupported = parseSupported;
  26973. }
  26974. }
  26975. return has[name] = !!isSupported;
  26976. }
  26977. if (!has("json")) {
  26978. // Common `[[Class]]` name aliases.
  26979. var functionClass = "[object Function]";
  26980. var dateClass = "[object Date]";
  26981. var numberClass = "[object Number]";
  26982. var stringClass = "[object String]";
  26983. var arrayClass = "[object Array]";
  26984. var booleanClass = "[object Boolean]";
  26985. // Detect incomplete support for accessing string characters by index.
  26986. var charIndexBuggy = has("bug-string-char-index");
  26987. // Define additional utility methods if the `Date` methods are buggy.
  26988. if (!isExtended) {
  26989. var floor = Math.floor;
  26990. // A mapping between the months of the year and the number of days between
  26991. // January 1st and the first of the respective month.
  26992. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  26993. // Internal: Calculates the number of days between the Unix epoch and the
  26994. // first day of the given month.
  26995. var getDay = function (year, month) {
  26996. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  26997. };
  26998. }
  26999. // Internal: Determines if a property is a direct property of the given
  27000. // object. Delegates to the native `Object#hasOwnProperty` method.
  27001. if (!(isProperty = {}.hasOwnProperty)) {
  27002. isProperty = function (property) {
  27003. var members = {}, constructor;
  27004. if ((members.__proto__ = null, members.__proto__ = {
  27005. // The *proto* property cannot be set multiple times in recent
  27006. // versions of Firefox and SeaMonkey.
  27007. "toString": 1
  27008. }, members).toString != getClass) {
  27009. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  27010. // supports the mutable *proto* property.
  27011. isProperty = function (property) {
  27012. // Capture and break the object's prototype chain (see section 8.6.2
  27013. // of the ES 5.1 spec). The parenthesized expression prevents an
  27014. // unsafe transformation by the Closure Compiler.
  27015. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  27016. // Restore the original prototype chain.
  27017. this.__proto__ = original;
  27018. return result;
  27019. };
  27020. } else {
  27021. // Capture a reference to the top-level `Object` constructor.
  27022. constructor = members.constructor;
  27023. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  27024. // other environments.
  27025. isProperty = function (property) {
  27026. var parent = (this.constructor || constructor).prototype;
  27027. return property in this && !(property in parent && this[property] === parent[property]);
  27028. };
  27029. }
  27030. members = null;
  27031. return isProperty.call(this, property);
  27032. };
  27033. }
  27034. // Internal: A set of primitive types used by `isHostType`.
  27035. var PrimitiveTypes = {
  27036. 'boolean': 1,
  27037. 'number': 1,
  27038. 'string': 1,
  27039. 'undefined': 1
  27040. };
  27041. // Internal: Determines if the given object `property` value is a
  27042. // non-primitive.
  27043. var isHostType = function (object, property) {
  27044. var type = typeof object[property];
  27045. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  27046. };
  27047. // Internal: Normalizes the `for...in` iteration algorithm across
  27048. // environments. Each enumerated key is yielded to a `callback` function.
  27049. forEach = function (object, callback) {
  27050. var size = 0, Properties, members, property;
  27051. // Tests for bugs in the current environment's `for...in` algorithm. The
  27052. // `valueOf` property inherits the non-enumerable flag from
  27053. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  27054. (Properties = function () {
  27055. this.valueOf = 0;
  27056. }).prototype.valueOf = 0;
  27057. // Iterate over a new instance of the `Properties` class.
  27058. members = new Properties();
  27059. for (property in members) {
  27060. // Ignore all properties inherited from `Object.prototype`.
  27061. if (isProperty.call(members, property)) {
  27062. size++;
  27063. }
  27064. }
  27065. Properties = members = null;
  27066. // Normalize the iteration algorithm.
  27067. if (!size) {
  27068. // A list of non-enumerable properties inherited from `Object.prototype`.
  27069. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  27070. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  27071. // properties.
  27072. forEach = function (object, callback) {
  27073. var isFunction = getClass.call(object) == functionClass, property, length;
  27074. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  27075. for (property in object) {
  27076. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  27077. // certain conditions; IE does not.
  27078. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  27079. callback(property);
  27080. }
  27081. }
  27082. // Manually invoke the callback for each non-enumerable property.
  27083. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  27084. };
  27085. } else if (size == 2) {
  27086. // Safari <= 2.0.4 enumerates shadowed properties twice.
  27087. forEach = function (object, callback) {
  27088. // Create a set of iterated properties.
  27089. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  27090. for (property in object) {
  27091. // Store each property name to prevent double enumeration. The
  27092. // `prototype` property of functions is not enumerated due to cross-
  27093. // environment inconsistencies.
  27094. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  27095. callback(property);
  27096. }
  27097. }
  27098. };
  27099. } else {
  27100. // No bugs detected; use the standard `for...in` algorithm.
  27101. forEach = function (object, callback) {
  27102. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  27103. for (property in object) {
  27104. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  27105. callback(property);
  27106. }
  27107. }
  27108. // Manually invoke the callback for the `constructor` property due to
  27109. // cross-environment inconsistencies.
  27110. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  27111. callback(property);
  27112. }
  27113. };
  27114. }
  27115. return forEach(object, callback);
  27116. };
  27117. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  27118. // `filter` argument may specify either a function that alters how object and
  27119. // array members are serialized, or an array of strings and numbers that
  27120. // indicates which properties should be serialized. The optional `width`
  27121. // argument may be either a string or number that specifies the indentation
  27122. // level of the output.
  27123. if (!has("json-stringify")) {
  27124. // Internal: A map of control characters and their escaped equivalents.
  27125. var Escapes = {
  27126. 92: "\\\\",
  27127. 34: '\\"',
  27128. 8: "\\b",
  27129. 12: "\\f",
  27130. 10: "\\n",
  27131. 13: "\\r",
  27132. 9: "\\t"
  27133. };
  27134. // Internal: Converts `value` into a zero-padded string such that its
  27135. // length is at least equal to `width`. The `width` must be <= 6.
  27136. var leadingZeroes = "000000";
  27137. var toPaddedString = function (width, value) {
  27138. // The `|| 0` expression is necessary to work around a bug in
  27139. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  27140. return (leadingZeroes + (value || 0)).slice(-width);
  27141. };
  27142. // Internal: Double-quotes a string `value`, replacing all ASCII control
  27143. // characters (characters with code unit values between 0 and 31) with
  27144. // their escaped equivalents. This is an implementation of the
  27145. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  27146. var unicodePrefix = "\\u00";
  27147. var quote = function (value) {
  27148. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  27149. if (isLarge) {
  27150. symbols = value.split("");
  27151. }
  27152. for (; index < length; index++) {
  27153. var charCode = value.charCodeAt(index);
  27154. // If the character is a control character, append its Unicode or
  27155. // shorthand escape sequence; otherwise, append the character as-is.
  27156. switch (charCode) {
  27157. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  27158. result += Escapes[charCode];
  27159. break;
  27160. default:
  27161. if (charCode < 32) {
  27162. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  27163. break;
  27164. }
  27165. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  27166. }
  27167. }
  27168. return result + '"';
  27169. };
  27170. // Internal: Recursively serializes an object. Implements the
  27171. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  27172. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  27173. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  27174. try {
  27175. // Necessary for host object support.
  27176. value = object[property];
  27177. } catch (exception) {}
  27178. if (typeof value == "object" && value) {
  27179. className = getClass.call(value);
  27180. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  27181. if (value > -1 / 0 && value < 1 / 0) {
  27182. // Dates are serialized according to the `Date#toJSON` method
  27183. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  27184. // for the ISO 8601 date time string format.
  27185. if (getDay) {
  27186. // Manually compute the year, month, date, hours, minutes,
  27187. // seconds, and milliseconds if the `getUTC*` methods are
  27188. // buggy. Adapted from @Yaffle's `date-shim` project.
  27189. date = floor(value / 864e5);
  27190. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  27191. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  27192. date = 1 + date - getDay(year, month);
  27193. // The `time` value specifies the time within the day (see ES
  27194. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  27195. // to compute `A modulo B`, as the `%` operator does not
  27196. // correspond to the `modulo` operation for negative numbers.
  27197. time = (value % 864e5 + 864e5) % 864e5;
  27198. // The hours, minutes, seconds, and milliseconds are obtained by
  27199. // decomposing the time within the day. See section 15.9.1.10.
  27200. hours = floor(time / 36e5) % 24;
  27201. minutes = floor(time / 6e4) % 60;
  27202. seconds = floor(time / 1e3) % 60;
  27203. milliseconds = time % 1e3;
  27204. } else {
  27205. year = value.getUTCFullYear();
  27206. month = value.getUTCMonth();
  27207. date = value.getUTCDate();
  27208. hours = value.getUTCHours();
  27209. minutes = value.getUTCMinutes();
  27210. seconds = value.getUTCSeconds();
  27211. milliseconds = value.getUTCMilliseconds();
  27212. }
  27213. // Serialize extended years correctly.
  27214. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  27215. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  27216. // Months, dates, hours, minutes, and seconds should have two
  27217. // digits; milliseconds should have three.
  27218. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  27219. // Milliseconds are optional in ES 5.0, but required in 5.1.
  27220. "." + toPaddedString(3, milliseconds) + "Z";
  27221. } else {
  27222. value = null;
  27223. }
  27224. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  27225. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  27226. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  27227. // ignores all `toJSON` methods on these objects unless they are
  27228. // defined directly on an instance.
  27229. value = value.toJSON(property);
  27230. }
  27231. }
  27232. if (callback) {
  27233. // If a replacement function was provided, call it to obtain the value
  27234. // for serialization.
  27235. value = callback.call(object, property, value);
  27236. }
  27237. if (value === null) {
  27238. return "null";
  27239. }
  27240. className = getClass.call(value);
  27241. if (className == booleanClass) {
  27242. // Booleans are represented literally.
  27243. return "" + value;
  27244. } else if (className == numberClass) {
  27245. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  27246. // `"null"`.
  27247. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  27248. } else if (className == stringClass) {
  27249. // Strings are double-quoted and escaped.
  27250. return quote("" + value);
  27251. }
  27252. // Recursively serialize objects and arrays.
  27253. if (typeof value == "object") {
  27254. // Check for cyclic structures. This is a linear search; performance
  27255. // is inversely proportional to the number of unique nested objects.
  27256. for (length = stack.length; length--;) {
  27257. if (stack[length] === value) {
  27258. // Cyclic structures cannot be serialized by `JSON.stringify`.
  27259. throw TypeError();
  27260. }
  27261. }
  27262. // Add the object to the stack of traversed objects.
  27263. stack.push(value);
  27264. results = [];
  27265. // Save the current indentation level and indent one additional level.
  27266. prefix = indentation;
  27267. indentation += whitespace;
  27268. if (className == arrayClass) {
  27269. // Recursively serialize array elements.
  27270. for (index = 0, length = value.length; index < length; index++) {
  27271. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  27272. results.push(element === undef ? "null" : element);
  27273. }
  27274. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  27275. } else {
  27276. // Recursively serialize object members. Members are selected from
  27277. // either a user-specified list of property names, or the object
  27278. // itself.
  27279. forEach(properties || value, function (property) {
  27280. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  27281. if (element !== undef) {
  27282. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  27283. // is not the empty string, let `member` {quote(property) + ":"}
  27284. // be the concatenation of `member` and the `space` character."
  27285. // The "`space` character" refers to the literal space
  27286. // character, not the `space` {width} argument provided to
  27287. // `JSON.stringify`.
  27288. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  27289. }
  27290. });
  27291. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  27292. }
  27293. // Remove the object from the traversed object stack.
  27294. stack.pop();
  27295. return result;
  27296. }
  27297. };
  27298. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  27299. JSON3.stringify = function (source, filter, width) {
  27300. var whitespace, callback, properties, className;
  27301. if (typeof filter == "function" || typeof filter == "object" && filter) {
  27302. if ((className = getClass.call(filter)) == functionClass) {
  27303. callback = filter;
  27304. } else if (className == arrayClass) {
  27305. // Convert the property names array into a makeshift set.
  27306. properties = {};
  27307. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  27308. }
  27309. }
  27310. if (width) {
  27311. if ((className = getClass.call(width)) == numberClass) {
  27312. // Convert the `width` to an integer and create a string containing
  27313. // `width` number of space characters.
  27314. if ((width -= width % 1) > 0) {
  27315. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  27316. }
  27317. } else if (className == stringClass) {
  27318. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  27319. }
  27320. }
  27321. // Opera <= 7.54u2 discards the values associated with empty string keys
  27322. // (`""`) only if they are used directly within an object member list
  27323. // (e.g., `!("" in { "": 1})`).
  27324. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  27325. };
  27326. }
  27327. // Public: Parses a JSON source string.
  27328. if (!has("json-parse")) {
  27329. var fromCharCode = String.fromCharCode;
  27330. // Internal: A map of escaped control characters and their unescaped
  27331. // equivalents.
  27332. var Unescapes = {
  27333. 92: "\\",
  27334. 34: '"',
  27335. 47: "/",
  27336. 98: "\b",
  27337. 116: "\t",
  27338. 110: "\n",
  27339. 102: "\f",
  27340. 114: "\r"
  27341. };
  27342. // Internal: Stores the parser state.
  27343. var Index, Source;
  27344. // Internal: Resets the parser state and throws a `SyntaxError`.
  27345. var abort = function() {
  27346. Index = Source = null;
  27347. throw SyntaxError();
  27348. };
  27349. // Internal: Returns the next token, or `"$"` if the parser has reached
  27350. // the end of the source string. A token may be a string, number, `null`
  27351. // literal, or Boolean literal.
  27352. var lex = function () {
  27353. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  27354. while (Index < length) {
  27355. charCode = source.charCodeAt(Index);
  27356. switch (charCode) {
  27357. case 9: case 10: case 13: case 32:
  27358. // Skip whitespace tokens, including tabs, carriage returns, line
  27359. // feeds, and space characters.
  27360. Index++;
  27361. break;
  27362. case 123: case 125: case 91: case 93: case 58: case 44:
  27363. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  27364. // the current position.
  27365. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  27366. Index++;
  27367. return value;
  27368. case 34:
  27369. // `"` delimits a JSON string; advance to the next character and
  27370. // begin parsing the string. String tokens are prefixed with the
  27371. // sentinel `@` character to distinguish them from punctuators and
  27372. // end-of-string tokens.
  27373. for (value = "@", Index++; Index < length;) {
  27374. charCode = source.charCodeAt(Index);
  27375. if (charCode < 32) {
  27376. // Unescaped ASCII control characters (those with a code unit
  27377. // less than the space character) are not permitted.
  27378. abort();
  27379. } else if (charCode == 92) {
  27380. // A reverse solidus (`\`) marks the beginning of an escaped
  27381. // control character (including `"`, `\`, and `/`) or Unicode
  27382. // escape sequence.
  27383. charCode = source.charCodeAt(++Index);
  27384. switch (charCode) {
  27385. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  27386. // Revive escaped control characters.
  27387. value += Unescapes[charCode];
  27388. Index++;
  27389. break;
  27390. case 117:
  27391. // `\u` marks the beginning of a Unicode escape sequence.
  27392. // Advance to the first character and validate the
  27393. // four-digit code point.
  27394. begin = ++Index;
  27395. for (position = Index + 4; Index < position; Index++) {
  27396. charCode = source.charCodeAt(Index);
  27397. // A valid sequence comprises four hexdigits (case-
  27398. // insensitive) that form a single hexadecimal value.
  27399. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  27400. // Invalid Unicode escape sequence.
  27401. abort();
  27402. }
  27403. }
  27404. // Revive the escaped character.
  27405. value += fromCharCode("0x" + source.slice(begin, Index));
  27406. break;
  27407. default:
  27408. // Invalid escape sequence.
  27409. abort();
  27410. }
  27411. } else {
  27412. if (charCode == 34) {
  27413. // An unescaped double-quote character marks the end of the
  27414. // string.
  27415. break;
  27416. }
  27417. charCode = source.charCodeAt(Index);
  27418. begin = Index;
  27419. // Optimize for the common case where a string is valid.
  27420. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  27421. charCode = source.charCodeAt(++Index);
  27422. }
  27423. // Append the string as-is.
  27424. value += source.slice(begin, Index);
  27425. }
  27426. }
  27427. if (source.charCodeAt(Index) == 34) {
  27428. // Advance to the next character and return the revived string.
  27429. Index++;
  27430. return value;
  27431. }
  27432. // Unterminated string.
  27433. abort();
  27434. default:
  27435. // Parse numbers and literals.
  27436. begin = Index;
  27437. // Advance past the negative sign, if one is specified.
  27438. if (charCode == 45) {
  27439. isSigned = true;
  27440. charCode = source.charCodeAt(++Index);
  27441. }
  27442. // Parse an integer or floating-point value.
  27443. if (charCode >= 48 && charCode <= 57) {
  27444. // Leading zeroes are interpreted as octal literals.
  27445. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  27446. // Illegal octal literal.
  27447. abort();
  27448. }
  27449. isSigned = false;
  27450. // Parse the integer component.
  27451. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  27452. // Floats cannot contain a leading decimal point; however, this
  27453. // case is already accounted for by the parser.
  27454. if (source.charCodeAt(Index) == 46) {
  27455. position = ++Index;
  27456. // Parse the decimal component.
  27457. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27458. if (position == Index) {
  27459. // Illegal trailing decimal.
  27460. abort();
  27461. }
  27462. Index = position;
  27463. }
  27464. // Parse exponents. The `e` denoting the exponent is
  27465. // case-insensitive.
  27466. charCode = source.charCodeAt(Index);
  27467. if (charCode == 101 || charCode == 69) {
  27468. charCode = source.charCodeAt(++Index);
  27469. // Skip past the sign following the exponent, if one is
  27470. // specified.
  27471. if (charCode == 43 || charCode == 45) {
  27472. Index++;
  27473. }
  27474. // Parse the exponential component.
  27475. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27476. if (position == Index) {
  27477. // Illegal empty exponent.
  27478. abort();
  27479. }
  27480. Index = position;
  27481. }
  27482. // Coerce the parsed value to a JavaScript number.
  27483. return +source.slice(begin, Index);
  27484. }
  27485. // A negative sign may only precede numbers.
  27486. if (isSigned) {
  27487. abort();
  27488. }
  27489. // `true`, `false`, and `null` literals.
  27490. if (source.slice(Index, Index + 4) == "true") {
  27491. Index += 4;
  27492. return true;
  27493. } else if (source.slice(Index, Index + 5) == "false") {
  27494. Index += 5;
  27495. return false;
  27496. } else if (source.slice(Index, Index + 4) == "null") {
  27497. Index += 4;
  27498. return null;
  27499. }
  27500. // Unrecognized token.
  27501. abort();
  27502. }
  27503. }
  27504. // Return the sentinel `$` character if the parser has reached the end
  27505. // of the source string.
  27506. return "$";
  27507. };
  27508. // Internal: Parses a JSON `value` token.
  27509. var get = function (value) {
  27510. var results, hasMembers;
  27511. if (value == "$") {
  27512. // Unexpected end of input.
  27513. abort();
  27514. }
  27515. if (typeof value == "string") {
  27516. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  27517. // Remove the sentinel `@` character.
  27518. return value.slice(1);
  27519. }
  27520. // Parse object and array literals.
  27521. if (value == "[") {
  27522. // Parses a JSON array, returning a new JavaScript array.
  27523. results = [];
  27524. for (;; hasMembers || (hasMembers = true)) {
  27525. value = lex();
  27526. // A closing square bracket marks the end of the array literal.
  27527. if (value == "]") {
  27528. break;
  27529. }
  27530. // If the array literal contains elements, the current token
  27531. // should be a comma separating the previous element from the
  27532. // next.
  27533. if (hasMembers) {
  27534. if (value == ",") {
  27535. value = lex();
  27536. if (value == "]") {
  27537. // Unexpected trailing `,` in array literal.
  27538. abort();
  27539. }
  27540. } else {
  27541. // A `,` must separate each array element.
  27542. abort();
  27543. }
  27544. }
  27545. // Elisions and leading commas are not permitted.
  27546. if (value == ",") {
  27547. abort();
  27548. }
  27549. results.push(get(value));
  27550. }
  27551. return results;
  27552. } else if (value == "{") {
  27553. // Parses a JSON object, returning a new JavaScript object.
  27554. results = {};
  27555. for (;; hasMembers || (hasMembers = true)) {
  27556. value = lex();
  27557. // A closing curly brace marks the end of the object literal.
  27558. if (value == "}") {
  27559. break;
  27560. }
  27561. // If the object literal contains members, the current token
  27562. // should be a comma separator.
  27563. if (hasMembers) {
  27564. if (value == ",") {
  27565. value = lex();
  27566. if (value == "}") {
  27567. // Unexpected trailing `,` in object literal.
  27568. abort();
  27569. }
  27570. } else {
  27571. // A `,` must separate each object member.
  27572. abort();
  27573. }
  27574. }
  27575. // Leading commas are not permitted, object property names must be
  27576. // double-quoted strings, and a `:` must separate each property
  27577. // name and value.
  27578. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  27579. abort();
  27580. }
  27581. results[value.slice(1)] = get(lex());
  27582. }
  27583. return results;
  27584. }
  27585. // Unexpected token encountered.
  27586. abort();
  27587. }
  27588. return value;
  27589. };
  27590. // Internal: Updates a traversed object member.
  27591. var update = function(source, property, callback) {
  27592. var element = walk(source, property, callback);
  27593. if (element === undef) {
  27594. delete source[property];
  27595. } else {
  27596. source[property] = element;
  27597. }
  27598. };
  27599. // Internal: Recursively traverses a parsed JSON object, invoking the
  27600. // `callback` function for each value. This is an implementation of the
  27601. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  27602. var walk = function (source, property, callback) {
  27603. var value = source[property], length;
  27604. if (typeof value == "object" && value) {
  27605. // `forEach` can't be used to traverse an array in Opera <= 8.54
  27606. // because its `Object#hasOwnProperty` implementation returns `false`
  27607. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  27608. if (getClass.call(value) == arrayClass) {
  27609. for (length = value.length; length--;) {
  27610. update(value, length, callback);
  27611. }
  27612. } else {
  27613. forEach(value, function (property) {
  27614. update(value, property, callback);
  27615. });
  27616. }
  27617. }
  27618. return callback.call(source, property, value);
  27619. };
  27620. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  27621. JSON3.parse = function (source, callback) {
  27622. var result, value;
  27623. Index = 0;
  27624. Source = "" + source;
  27625. result = get(lex());
  27626. // If a JSON string contains multiple tokens, it is invalid.
  27627. if (lex() != "$") {
  27628. abort();
  27629. }
  27630. // Reset the parser state.
  27631. Index = Source = null;
  27632. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  27633. };
  27634. }
  27635. }
  27636. // Export for asynchronous module loaders.
  27637. if (isLoader) {
  27638. define(function () {
  27639. return JSON3;
  27640. });
  27641. }
  27642. }(this));
  27643. },{}],135:[function(require,module,exports){
  27644. module.exports = toArray
  27645. function toArray(list, index) {
  27646. var array = []
  27647. index = index || 0
  27648. for (var i = index || 0; i < list.length; i++) {
  27649. array[i - index] = list[i]
  27650. }
  27651. return array
  27652. }
  27653. },{}],136:[function(require,module,exports){
  27654. var MediaStreamType = {
  27655. VIDEO_TYPE: "Video",
  27656. AUDIO_TYPE: "Audio"
  27657. };
  27658. module.exports = MediaStreamType;
  27659. },{}],137:[function(require,module,exports){
  27660. var RTCEvents = {
  27661. RTC_READY: "rtc.ready",
  27662. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27663. LASTN_CHANGED: "rtc.lastn_changed",
  27664. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27665. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27666. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27667. FAKE_VIDEO_TRACK_CREATED: "rtc.fake_video_track_created"
  27668. };
  27669. module.exports = RTCEvents;
  27670. },{}],138:[function(require,module,exports){
  27671. var Resolutions = {
  27672. "1080": {
  27673. width: 1920,
  27674. height: 1080,
  27675. order: 7
  27676. },
  27677. "fullhd": {
  27678. width: 1920,
  27679. height: 1080,
  27680. order: 7
  27681. },
  27682. "720": {
  27683. width: 1280,
  27684. height: 720,
  27685. order: 6
  27686. },
  27687. "hd": {
  27688. width: 1280,
  27689. height: 720,
  27690. order: 6
  27691. },
  27692. "960": {
  27693. width: 960,
  27694. height: 720,
  27695. order: 5
  27696. },
  27697. "640": {
  27698. width: 640,
  27699. height: 480,
  27700. order: 4
  27701. },
  27702. "vga": {
  27703. width: 640,
  27704. height: 480,
  27705. order: 4
  27706. },
  27707. "360": {
  27708. width: 640,
  27709. height: 360,
  27710. order: 3
  27711. },
  27712. "320": {
  27713. width: 320,
  27714. height: 240,
  27715. order: 2
  27716. },
  27717. "180": {
  27718. width: 320,
  27719. height: 180,
  27720. order: 1
  27721. }
  27722. };
  27723. module.exports = Resolutions;
  27724. },{}],139:[function(require,module,exports){
  27725. var AuthenticationEvents = {
  27726. /**
  27727. * Event callback arguments:
  27728. * function(authenticationEnabled, userIdentity)
  27729. * authenticationEnabled - indicates whether authentication has been enabled
  27730. * in this session
  27731. * userIdentity - if user has been logged in then it contains user name. If
  27732. * contains 'null' or 'undefined' then user is not logged in.
  27733. */
  27734. IDENTITY_UPDATED: "authentication.identity_updated"
  27735. };
  27736. module.exports = AuthenticationEvents;
  27737. },{}],140:[function(require,module,exports){
  27738. var DesktopSharingEventTypes = {
  27739. /**
  27740. * An event which indicates that the jidesha extension for Firefox is
  27741. * needed to proceed with screen sharing, and that it is not installed.
  27742. */
  27743. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27744. };
  27745. module.exports = DesktopSharingEventTypes;
  27746. },{}],141:[function(require,module,exports){
  27747. module.exports = {
  27748. /**
  27749. * An event carrying connection statistics.
  27750. */
  27751. CONNECTION_STATS: "statistics.connectionstats",
  27752. /**
  27753. * FIXME: needs documentation.
  27754. */
  27755. AUDIO_LEVEL: "statistics.audioLevel",
  27756. /**
  27757. * FIXME: needs documentation.
  27758. */
  27759. STOP: "statistics.stop"
  27760. };
  27761. },{}],142:[function(require,module,exports){
  27762. var Constants = {
  27763. LOCAL_JID: 'local'
  27764. };
  27765. module.exports = Constants;
  27766. },{}],143:[function(require,module,exports){
  27767. var XMPPEvents = {
  27768. // Designates an event indicating that the connection to the XMPP server
  27769. // failed.
  27770. CONNECTION_FAILED: "xmpp.connection.failed",
  27771. // Designates an event indicating that the media (ICE) connection was
  27772. // interrupted. This should go to the RTC module.
  27773. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27774. // Designates an event indicating that the media (ICE) connection was
  27775. // restored. This should go to the RTC module.
  27776. CONNECTION_RESTORED: "xmpp.connection.restored",
  27777. // Designates an event indicating that an offer (e.g. Jingle
  27778. // session-initiate) was received.
  27779. CALL_INCOMING: "xmpp.callincoming.jingle",
  27780. // Designates an event indicating that we were kicked from the XMPP MUC.
  27781. KICKED: "xmpp.kicked",
  27782. // Designates an event indicating that we have joined the XMPP MUC.
  27783. MUC_JOINED: "xmpp.muc_joined",
  27784. // Designates an event indicating that a participant joined the XMPP MUC.
  27785. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27786. // Designates an event indicating that a participant left the XMPP MUC.
  27787. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27788. // Designates an event indicating that the MUC role of a participant has
  27789. // changed.
  27790. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27791. // Designates an event indicating that the XMPP MUC was destroyed.
  27792. MUC_DESTROYED: "xmpp.muc_destroyed",
  27793. // Designates an event indicating that the display name of a participant
  27794. // has changed.
  27795. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27796. // Designates an event indicating that we received statistics from a
  27797. // participant in the MUC.
  27798. REMOTE_STATS: "xmpp.remote_stats",
  27799. // Designates an event indicating that our role in the XMPP MUC has changed.
  27800. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27801. // Designates an event indicating that the subject of the XMPP MUC has
  27802. // changed.
  27803. SUBJECT_CHANGED: "xmpp.subject_changed",
  27804. // Designates an event indicating that an XMPP message in the MUC was
  27805. // received.
  27806. MESSAGE_RECEIVED: "xmpp.message_received",
  27807. // Designates an event indicating that we sent an XMPP message to the MUC.
  27808. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27809. // Designates an event indicating that the video type (e.g. 'camera' or
  27810. // 'screen') for a participant has changed.
  27811. // Note: currently this event fires every time we receive presence from
  27812. // someone (regardless of whether or not the "video type" changed).
  27813. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  27814. // Designates an event indicating that a participant in the XMPP MUC has
  27815. // advertised that they have audio muted (or unmuted).
  27816. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  27817. // Designates an event indicating that a participant in the XMPP MUC has
  27818. // advertised that they have video muted (or unmuted).
  27819. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  27820. // Designates an event indicating that the focus has asked us to mute our
  27821. // audio.
  27822. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27823. // Designates an event indicating that we should join the conference with
  27824. // audio and/or video muted.
  27825. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27826. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27827. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27828. PASSWORD_REQUIRED: "xmpp.password_required",
  27829. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27830. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27831. ETHERPAD: "xmpp.etherpad",
  27832. BRIDGE_DOWN: "xmpp.bridge_down",
  27833. PRESENCE_STATUS: "xmpp.presence_status",
  27834. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27835. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27836. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27837. // TODO: only used in a hack, should probably be removed.
  27838. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27839. // TODO: only used in a hack, should probably be removed.
  27840. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27841. // TODO: only used in a hack, should probably be removed.
  27842. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27843. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27844. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27845. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27846. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27847. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27848. // xmpp is connected and obtained user media
  27849. READY_TO_JOIN: 'xmpp.ready_to_join',
  27850. FOCUS_LEFT: "xmpp.focus_left",
  27851. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  27852. /**
  27853. * Indicates that recording state changed.
  27854. */
  27855. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  27856. /**
  27857. * Indicates that phone number changed.
  27858. */
  27859. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  27860. /**
  27861. * Indicates error while create offer call.
  27862. */
  27863. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  27864. /**
  27865. * Indicates error while create answer call.
  27866. */
  27867. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  27868. /**
  27869. * Indicates error while set local description.
  27870. */
  27871. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  27872. /**
  27873. * Indicates error while set remote description.
  27874. */
  27875. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  27876. /**
  27877. * Indicates error while adding ice candidate.
  27878. */
  27879. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  27880. };
  27881. module.exports = XMPPEvents;
  27882. },{}]},{},[7])(7)
  27883. });