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

lib-jitsi-meet.js 999KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JitsiMeetJS = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. var Settings = require("./modules/settings/Settings");
  18. /**
  19. * Creates a JitsiConference object with the given name and properties.
  20. * Note: this constructor is not a part of the public API (objects should be
  21. * created using JitsiConnection.createConference).
  22. * @param options.config properties / settings related to the conference that will be created.
  23. * @param options.name the name of the conference
  24. * @param options.connection the JitsiConnection object for this JitsiConference.
  25. * @constructor
  26. */
  27. function JitsiConference(options) {
  28. if(!options.name || options.name.toLowerCase() !== options.name) {
  29. logger.error("Invalid conference name (no conference name passed or it"
  30. + "contains invalid characters like capital letters)!");
  31. return;
  32. }
  33. this.options = options;
  34. this.connection = this.options.connection;
  35. this.xmpp = this.connection.xmpp;
  36. this.eventEmitter = new EventEmitter();
  37. var confID = this.options.name + '@' + this.xmpp.options.hosts.muc;
  38. this.settings = new Settings(confID);
  39. this.room = this.xmpp.createRoom(this.options.name, this.options.config,
  40. this.settings);
  41. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  42. this.rtc = new RTC(this.room, options);
  43. this.statistics = new Statistics({
  44. callStatsID: this.options.config.callStatsID,
  45. callStatsSecret: this.options.config.callStatsSecret,
  46. disableThirdPartyRequests: this.options.config.disableThirdPartyRequests
  47. });
  48. setupListeners(this);
  49. JitsiMeetJS._gumFailedHandler.push(function(error) {
  50. this.statistics.sendGetUserMediaFailed(error);
  51. }.bind(this));
  52. this.participants = {};
  53. this.lastDominantSpeaker = null;
  54. this.dtmfManager = null;
  55. this.somebodySupportsDTMF = false;
  56. this.authEnabled = false;
  57. this.authIdentity;
  58. this.startAudioMuted = false;
  59. this.startVideoMuted = false;
  60. this.startMutedPolicy = {audio: false, video: false};
  61. }
  62. /**
  63. * Joins the conference.
  64. * @param password {string} the password
  65. */
  66. JitsiConference.prototype.join = function (password) {
  67. if(this.room)
  68. this.room.join(password);
  69. };
  70. /**
  71. * Check if joined to the conference.
  72. */
  73. JitsiConference.prototype.isJoined = function () {
  74. return this.room && this.room.joined;
  75. };
  76. /**
  77. * Leaves the conference.
  78. */
  79. JitsiConference.prototype.leave = function () {
  80. if(this.xmpp && this.room)
  81. this.xmpp.leaveRoom(this.room.roomjid);
  82. this.room = null;
  83. };
  84. /**
  85. * Returns name of this conference.
  86. */
  87. JitsiConference.prototype.getName = function () {
  88. return this.options.name;
  89. };
  90. /**
  91. * Check if authentication is enabled for this conference.
  92. */
  93. JitsiConference.prototype.isAuthEnabled = function () {
  94. return this.authEnabled;
  95. };
  96. /**
  97. * Check if user is logged in.
  98. */
  99. JitsiConference.prototype.isLoggedIn = function () {
  100. return !!this.authIdentity;
  101. };
  102. /**
  103. * Get authorized login.
  104. */
  105. JitsiConference.prototype.getAuthLogin = function () {
  106. return this.authIdentity;
  107. };
  108. /**
  109. * Check if external authentication is enabled for this conference.
  110. */
  111. JitsiConference.prototype.isExternalAuthEnabled = function () {
  112. return this.room && this.room.moderator.isExternalAuthEnabled();
  113. };
  114. /**
  115. * Get url for external authentication.
  116. * @param {boolean} [urlForPopup] if true then return url for login popup,
  117. * else url of login page.
  118. * @returns {Promise}
  119. */
  120. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  121. return new Promise(function (resolve, reject) {
  122. if (!this.isExternalAuthEnabled()) {
  123. reject();
  124. return;
  125. }
  126. if (urlForPopup) {
  127. this.room.moderator.getPopupLoginUrl(resolve, reject);
  128. } else {
  129. this.room.moderator.getLoginUrl(resolve, reject);
  130. }
  131. }.bind(this));
  132. };
  133. /**
  134. * Returns the local tracks.
  135. */
  136. JitsiConference.prototype.getLocalTracks = function () {
  137. if (this.rtc) {
  138. return this.rtc.localStreams;
  139. } else {
  140. return [];
  141. }
  142. };
  143. /**
  144. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  145. * in JitsiConferenceEvents.
  146. * @param eventId the event ID.
  147. * @param handler handler for the event.
  148. *
  149. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  150. */
  151. JitsiConference.prototype.on = function (eventId, handler) {
  152. if(this.eventEmitter)
  153. this.eventEmitter.on(eventId, handler);
  154. };
  155. /**
  156. * Removes event listener
  157. * @param eventId the event ID.
  158. * @param [handler] optional, the specific handler to unbind
  159. *
  160. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  161. */
  162. JitsiConference.prototype.off = function (eventId, handler) {
  163. if(this.eventEmitter)
  164. this.eventEmitter.removeListener(eventId, handler);
  165. };
  166. // Common aliases for event emitter
  167. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  168. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  169. /**
  170. * Receives notifications from another participants for commands / custom events
  171. * (send by sendPresenceCommand method).
  172. * @param command {String} the name of the command
  173. * @param handler {Function} handler for the command
  174. */
  175. JitsiConference.prototype.addCommandListener = function (command, handler) {
  176. if(this.room)
  177. this.room.addPresenceListener(command, handler);
  178. };
  179. /**
  180. * Removes command listener
  181. * @param command {String} the name of the command
  182. */
  183. JitsiConference.prototype.removeCommandListener = function (command) {
  184. if(this.room)
  185. this.room.removePresenceListener(command);
  186. };
  187. /**
  188. * Sends text message to the other participants in the conference
  189. * @param message the text message.
  190. */
  191. JitsiConference.prototype.sendTextMessage = function (message) {
  192. if(this.room)
  193. this.room.sendMessage(message);
  194. };
  195. /**
  196. * Send presence command.
  197. * @param name the name of the command.
  198. * @param values Object with keys and values that will be send.
  199. **/
  200. JitsiConference.prototype.sendCommand = function (name, values) {
  201. if(this.room) {
  202. this.room.addToPresence(name, values);
  203. this.room.sendPresence();
  204. }
  205. };
  206. /**
  207. * Send presence command one time.
  208. * @param name the name of the command.
  209. * @param values Object with keys and values that will be send.
  210. **/
  211. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  212. this.sendCommand(name, values);
  213. this.removeCommand(name);
  214. };
  215. /**
  216. * Send presence command.
  217. * @param name the name of the command.
  218. * @param values Object with keys and values that will be send.
  219. * @param persistent if false the command will be sent only one time
  220. **/
  221. JitsiConference.prototype.removeCommand = function (name) {
  222. if(this.room)
  223. this.room.removeFromPresence(name);
  224. };
  225. /**
  226. * Sets the display name for this conference.
  227. * @param name the display name to set
  228. */
  229. JitsiConference.prototype.setDisplayName = function(name) {
  230. if(this.room){
  231. // remove previously set nickname
  232. this.room.removeFromPresence("nick");
  233. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  234. this.room.sendPresence();
  235. }
  236. };
  237. /**
  238. * Adds JitsiLocalTrack object to the conference.
  239. * @param track the JitsiLocalTrack object.
  240. */
  241. JitsiConference.prototype.addTrack = function (track) {
  242. this.room.addStream(track.getOriginalStream(), function () {
  243. this.rtc.addLocalStream(track);
  244. if (track.startMuted) {
  245. track.mute();
  246. }
  247. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  248. track.stopHandler = this.removeTrack.bind(this, track);
  249. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  250. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  251. track.muteHandler);
  252. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
  253. track.stopHandler);
  254. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  255. track.audioLevelHandler);
  256. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  257. }.bind(this));
  258. };
  259. /**
  260. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  261. * @param audioLevel the audio level
  262. */
  263. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  264. this.eventEmitter.emit(
  265. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  266. this.myUserId(), audioLevel);
  267. };
  268. /**
  269. * Fires TRACK_MUTE_CHANGED change conference event.
  270. * @param track the JitsiTrack object related to the event.
  271. */
  272. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  273. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  274. };
  275. /**
  276. * Removes JitsiLocalTrack object to the conference.
  277. * @param track the JitsiLocalTrack object.
  278. */
  279. JitsiConference.prototype.removeTrack = function (track) {
  280. if(!this.room){
  281. if(this.rtc)
  282. this.rtc.removeLocalStream(track);
  283. return;
  284. }
  285. this.room.removeStream(track.getOriginalStream(), function(){
  286. this.rtc.removeLocalStream(track);
  287. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  288. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  289. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  290. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  291. }.bind(this));
  292. };
  293. /**
  294. * Get role of the local user.
  295. * @returns {string} user role: 'moderator' or 'none'
  296. */
  297. JitsiConference.prototype.getRole = function () {
  298. return this.room.role;
  299. };
  300. /**
  301. * Check if local user is moderator.
  302. * @returns {boolean} true if local user is moderator, false otherwise.
  303. */
  304. JitsiConference.prototype.isModerator = function () {
  305. return this.room.isModerator();
  306. };
  307. /**
  308. * Set password for the room.
  309. * @param {string} password new password for the room.
  310. * @returns {Promise}
  311. */
  312. JitsiConference.prototype.lock = function (password) {
  313. if (!this.isModerator()) {
  314. return Promise.reject();
  315. }
  316. var conference = this;
  317. return new Promise(function (resolve, reject) {
  318. conference.room.lockRoom(password || "", function () {
  319. resolve();
  320. }, function (err) {
  321. reject(err);
  322. }, function () {
  323. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  324. });
  325. });
  326. };
  327. /**
  328. * Remove password from the room.
  329. * @returns {Promise}
  330. */
  331. JitsiConference.prototype.unlock = function () {
  332. return this.lock();
  333. };
  334. /**
  335. * Elects the participant with the given id to be the selected participant or the speaker.
  336. * @param id the identifier of the participant
  337. */
  338. JitsiConference.prototype.selectParticipant = function(participantId) {
  339. if (this.rtc) {
  340. this.rtc.selectedEndpoint(participantId);
  341. }
  342. };
  343. /**
  344. *
  345. * @param id the identifier of the participant
  346. */
  347. JitsiConference.prototype.pinParticipant = function(participantId) {
  348. if (this.rtc) {
  349. this.rtc.pinEndpoint(participantId);
  350. }
  351. };
  352. /**
  353. * Returns the list of participants for this conference.
  354. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  355. */
  356. JitsiConference.prototype.getParticipants = function() {
  357. return Object.keys(this.participants).map(function (key) {
  358. return this.participants[key];
  359. }, this);
  360. };
  361. /**
  362. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  363. * undefined if there isn't one).
  364. * @param id the id of the participant.
  365. */
  366. JitsiConference.prototype.getParticipantById = function(id) {
  367. return this.participants[id];
  368. };
  369. /**
  370. * Kick participant from this conference.
  371. * @param {string} id id of the participant to kick
  372. */
  373. JitsiConference.prototype.kickParticipant = function (id) {
  374. var participant = this.getParticipantById(id);
  375. if (!participant) {
  376. return;
  377. }
  378. this.room.kick(participant.getJid());
  379. };
  380. /**
  381. * Kick participant from this conference.
  382. * @param {string} id id of the participant to kick
  383. */
  384. JitsiConference.prototype.muteParticipant = function (id) {
  385. var participant = this.getParticipantById(id);
  386. if (!participant) {
  387. return;
  388. }
  389. this.room.muteParticipant(participant.getJid(), true);
  390. };
  391. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  392. var id = Strophe.getResourceFromJid(jid);
  393. if (id === 'focus' || this.myUserId() === id) {
  394. return;
  395. }
  396. var participant = new JitsiParticipant(jid, this, nick);
  397. participant._role = role;
  398. this.participants[id] = participant;
  399. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  400. this.xmpp.connection.disco.info(
  401. jid, "node", function(iq) {
  402. participant._supportsDTMF = $(iq).find(
  403. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  404. this.updateDTMFSupport();
  405. }.bind(this)
  406. );
  407. };
  408. JitsiConference.prototype.onMemberLeft = function (jid) {
  409. var id = Strophe.getResourceFromJid(jid);
  410. if (id === 'focus' || this.myUserId() === id) {
  411. return;
  412. }
  413. var participant = this.participants[id];
  414. delete this.participants[id];
  415. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  416. };
  417. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  418. var id = Strophe.getResourceFromJid(jid);
  419. var participant = this.getParticipantById(id);
  420. if (!participant) {
  421. return;
  422. }
  423. participant._role = role;
  424. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  425. };
  426. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  427. var id = Strophe.getResourceFromJid(jid);
  428. var participant = this.getParticipantById(id);
  429. if (!participant) {
  430. return;
  431. }
  432. participant._displayName = displayName;
  433. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  434. };
  435. JitsiConference.prototype.onTrackAdded = function (track) {
  436. var id = track.getParticipantId();
  437. var participant = this.getParticipantById(id);
  438. if (!participant) {
  439. return;
  440. }
  441. // add track to JitsiParticipant
  442. participant._tracks.push(track);
  443. var emitter = this.eventEmitter;
  444. track.addEventListener(
  445. JitsiTrackEvents.TRACK_STOPPED,
  446. function () {
  447. // remove track from JitsiParticipant
  448. var pos = participant._tracks.indexOf(track);
  449. if (pos > -1) {
  450. participant._tracks.splice(pos, 1);
  451. }
  452. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  453. }
  454. );
  455. track.addEventListener(
  456. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  457. function () {
  458. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  459. }
  460. );
  461. track.addEventListener(
  462. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  463. function (audioLevel) {
  464. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  465. }
  466. );
  467. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  468. };
  469. JitsiConference.prototype.updateDTMFSupport = function () {
  470. var somebodySupportsDTMF = false;
  471. var participants = this.getParticipants();
  472. // check if at least 1 participant supports DTMF
  473. for (var i = 0; i < participants.length; i += 1) {
  474. if (participants[i].supportsDTMF()) {
  475. somebodySupportsDTMF = true;
  476. break;
  477. }
  478. }
  479. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  480. this.somebodySupportsDTMF = somebodySupportsDTMF;
  481. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  482. }
  483. };
  484. /**
  485. * Allows to check if there is at least one user in the conference
  486. * that supports DTMF.
  487. * @returns {boolean} true if somebody supports DTMF, false otherwise
  488. */
  489. JitsiConference.prototype.isDTMFSupported = function () {
  490. return this.somebodySupportsDTMF;
  491. };
  492. /**
  493. * Returns the local user's ID
  494. * @return {string} local user's ID
  495. */
  496. JitsiConference.prototype.myUserId = function () {
  497. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  498. };
  499. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  500. if (!this.dtmfManager) {
  501. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  502. if (!connection) {
  503. logger.warn("cannot sendTones: no conneciton");
  504. return;
  505. }
  506. var tracks = this.getLocalTracks().filter(function (track) {
  507. return track.isAudioTrack();
  508. });
  509. if (!tracks.length) {
  510. logger.warn("cannot sendTones: no local audio stream");
  511. return;
  512. }
  513. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  514. }
  515. this.dtmfManager.sendTones(tones, duration, pause);
  516. };
  517. /**
  518. * Returns true if the recording is supproted and false if not.
  519. */
  520. JitsiConference.prototype.isRecordingSupported = function () {
  521. if(this.room)
  522. return this.room.isRecordingSupported();
  523. return false;
  524. };
  525. /**
  526. * Returns null if the recording is not supported, "on" if the recording started
  527. * and "off" if the recording is not started.
  528. */
  529. JitsiConference.prototype.getRecordingState = function () {
  530. if(this.room)
  531. return this.room.getRecordingState();
  532. return "off";
  533. }
  534. /**
  535. * Returns the url of the recorded video.
  536. */
  537. JitsiConference.prototype.getRecordingURL = function () {
  538. if(this.room)
  539. return this.room.getRecordingURL();
  540. return null;
  541. }
  542. /**
  543. * Starts/stops the recording
  544. */
  545. JitsiConference.prototype.toggleRecording = function (options) {
  546. if(this.room)
  547. return this.room.toggleRecording(options, function (status, error) {
  548. this.eventEmitter.emit(
  549. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  550. }.bind(this));
  551. this.eventEmitter.emit(
  552. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  553. new Error("The conference is not created yet!"));
  554. }
  555. /**
  556. * Returns true if the SIP calls are supported and false otherwise
  557. */
  558. JitsiConference.prototype.isSIPCallingSupported = function () {
  559. if(this.room)
  560. return this.room.isSIPCallingSupported();
  561. return false;
  562. }
  563. /**
  564. * Dials a number.
  565. * @param number the number
  566. */
  567. JitsiConference.prototype.dial = function (number) {
  568. if(this.room)
  569. return this.room.dial(number);
  570. return new Promise(function(resolve, reject){
  571. reject(new Error("The conference is not created yet!"))});
  572. }
  573. /**
  574. * Hangup an existing call
  575. */
  576. JitsiConference.prototype.hangup = function () {
  577. if(this.room)
  578. return this.room.hangup();
  579. return new Promise(function(resolve, reject){
  580. reject(new Error("The conference is not created yet!"))});
  581. }
  582. /**
  583. * Returns the phone number for joining the conference.
  584. */
  585. JitsiConference.prototype.getPhoneNumber = function () {
  586. if(this.room)
  587. return this.room.getPhoneNumber();
  588. return null;
  589. }
  590. /**
  591. * Returns the pin for joining the conference with phone.
  592. */
  593. JitsiConference.prototype.getPhonePin = function () {
  594. if(this.room)
  595. return this.room.getPhonePin();
  596. return null;
  597. }
  598. /**
  599. * Returns the connection state for the current room. Its ice connection state
  600. * for its session.
  601. */
  602. JitsiConference.prototype.getConnectionState = function () {
  603. if(this.room)
  604. return this.room.getConnectionState();
  605. return null;
  606. }
  607. /**
  608. * Make all new participants mute their audio/video on join.
  609. * @param policy {Object} object with 2 boolean properties for video and audio:
  610. * @param {boolean} audio if audio should be muted.
  611. * @param {boolean} video if video should be muted.
  612. */
  613. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  614. if (!this.isModerator()) {
  615. return;
  616. }
  617. this.startMutedPolicy = policy;
  618. this.room.removeFromPresence("startmuted");
  619. this.room.addToPresence("startmuted", {
  620. attributes: {
  621. audio: policy.audio,
  622. video: policy.video,
  623. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  624. }
  625. });
  626. this.room.sendPresence();
  627. };
  628. /**
  629. * Returns current start muted policy
  630. * @returns {Object} with 2 proprties - audio and video.
  631. */
  632. JitsiConference.prototype.getStartMutedPolicy = function () {
  633. return this.startMutedPolicy;
  634. };
  635. /**
  636. * Check if audio is muted on join.
  637. */
  638. JitsiConference.prototype.isStartAudioMuted = function () {
  639. return this.startAudioMuted;
  640. };
  641. /**
  642. * Check if video is muted on join.
  643. */
  644. JitsiConference.prototype.isStartVideoMuted = function () {
  645. return this.startVideoMuted;
  646. };
  647. /**
  648. * Get object with internal logs.
  649. */
  650. JitsiConference.prototype.getLogs = function () {
  651. var data = this.xmpp.getJingleLog();
  652. var metadata = {};
  653. metadata.time = new Date();
  654. metadata.url = window.location.href;
  655. metadata.ua = navigator.userAgent;
  656. var log = this.xmpp.getXmppLog();
  657. if (log) {
  658. metadata.xmpp = log;
  659. }
  660. data.metadata = metadata;
  661. return data;
  662. };
  663. /**
  664. * Sends the given feedback through CallStats if enabled.
  665. *
  666. * @param overallFeedback an integer between 1 and 5 indicating the
  667. * user feedback
  668. * @param detailedFeedback detailed feedback from the user. Not yet used
  669. */
  670. JitsiConference.prototype.sendFeedback =
  671. function(overallFeedback, detailedFeedback){
  672. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  673. }
  674. /**
  675. * Returns true if the callstats integration is enabled, otherwise returns
  676. * false.
  677. *
  678. * @returns true if the callstats integration is enabled, otherwise returns
  679. * false.
  680. */
  681. JitsiConference.prototype.isCallstatsEnabled = function () {
  682. return this.statistics.isCallstatsEnabled();
  683. }
  684. /**
  685. * Setups the listeners needed for the conference.
  686. * @param conference the conference
  687. */
  688. function setupListeners(conference) {
  689. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  690. conference.rtc.onIncommingCall(event);
  691. conference.statistics.startRemoteStats(event.peerconnection);
  692. });
  693. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  694. function (data, sid, thessrc) {
  695. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  696. if (track) {
  697. conference.onTrackAdded(track);
  698. }
  699. }
  700. );
  701. conference.rtc.addListener(RTCEvents.FAKE_VIDEO_TRACK_CREATED,
  702. function (track) {
  703. conference.onTrackAdded(track);
  704. }
  705. );
  706. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  707. function (value) {
  708. conference.rtc.setAudioMute(value);
  709. }
  710. );
  711. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  712. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  713. });
  714. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  715. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  716. });
  717. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  718. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  719. });
  720. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  721. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  722. });
  723. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  724. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  725. });
  726. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  727. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  728. });
  729. // FIXME
  730. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  731. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  732. // });
  733. conference.room.addListener(XMPPEvents.KICKED, function () {
  734. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  735. });
  736. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  737. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  738. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  739. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  740. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  741. });
  742. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  743. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  744. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  745. });
  746. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  747. function () {
  748. conference.eventEmitter.emit(
  749. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  750. });
  751. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  752. conference.eventEmitter.emit(
  753. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  754. });
  755. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  756. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  757. });
  758. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  759. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  760. });
  761. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  762. conference.authEnabled = authEnabled;
  763. conference.authIdentity = authIdentity;
  764. });
  765. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  766. var id = Strophe.getResourceFromJid(jid);
  767. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  768. });
  769. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  770. if(conference.lastDominantSpeaker !== id && conference.room) {
  771. conference.lastDominantSpeaker = id;
  772. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  773. }
  774. });
  775. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  776. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  777. });
  778. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  779. function (lastNEndpoints, endpointsEnteringLastN) {
  780. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  781. lastNEndpoints, endpointsEnteringLastN);
  782. });
  783. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  784. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  785. });
  786. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  787. function (audioMuted, videoMuted) {
  788. conference.startAudioMuted = audioMuted;
  789. conference.startVideoMuted = videoMuted;
  790. // mute existing local tracks because this is initial mute from
  791. // Jicofo
  792. conference.getLocalTracks().forEach(function (track) {
  793. if (conference.startAudioMuted && track.isAudioTrack()) {
  794. track.mute();
  795. }
  796. if (conference.startVideoMuted && track.isVideoTrack()) {
  797. track.mute();
  798. }
  799. });
  800. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  801. });
  802. conference.room.addPresenceListener("startmuted", function (data, from) {
  803. var isModerator = false;
  804. if (conference.myUserId() === from && conference.isModerator()) {
  805. isModerator = true;
  806. } else {
  807. var participant = conference.getParticipantById(from);
  808. if (participant && participant.isModerator()) {
  809. isModerator = true;
  810. }
  811. }
  812. if (!isModerator) {
  813. return;
  814. }
  815. var startAudioMuted = data.attributes.audio === 'true';
  816. var startVideoMuted = data.attributes.video === 'true';
  817. var updated = false;
  818. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  819. conference.startMutedPolicy.audio = startAudioMuted;
  820. updated = true;
  821. }
  822. if (startVideoMuted !== conference.startMutedPolicy.video) {
  823. conference.startMutedPolicy.video = startVideoMuted;
  824. updated = true;
  825. }
  826. if (updated) {
  827. conference.eventEmitter.emit(
  828. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  829. conference.startMutedPolicy
  830. );
  831. }
  832. });
  833. if(conference.statistics) {
  834. //FIXME: Maybe remove event should not be associated with the conference.
  835. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  836. var userId = null;
  837. var jid = conference.room.getJidBySSRC(ssrc);
  838. if (!jid)
  839. return;
  840. conference.rtc.setAudioLevel(jid, level);
  841. });
  842. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  843. function () {
  844. conference.statistics.dispose();
  845. });
  846. // FIXME: Maybe we should move this.
  847. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  848. // conference.room.updateDeviceAvailability(devices);
  849. // });
  850. conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
  851. function (session) {
  852. conference.statistics.startCallStats(
  853. session, conference.settings);
  854. });
  855. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
  856. function () {
  857. conference.statistics.sendSetupFailedEvent();
  858. });
  859. conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  860. function (track) {
  861. if(!track.isLocal())
  862. return;
  863. var type = (track.getType() === "audio")? "audio" : "video";
  864. conference.statistics.sendMuteEvent(track.isMuted(), type);
  865. });
  866. conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
  867. conference.statistics.sendCreateOfferFailed(e, pc);
  868. });
  869. conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
  870. conference.statistics.sendCreateAnswerFailed(e, pc);
  871. });
  872. conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  873. function (e, pc) {
  874. conference.statistics.sendSetLocalDescFailed(e, pc);
  875. }
  876. );
  877. conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  878. function (e, pc) {
  879. conference.statistics.sendSetRemoteDescFailed(e, pc);
  880. }
  881. );
  882. conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  883. function (e, pc) {
  884. conference.statistics.sendAddIceCandidateFailed(e, pc);
  885. }
  886. );
  887. }
  888. }
  889. module.exports = JitsiConference;
  890. }).call(this,"/JitsiConference.js")
  891. },{"./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":131,"./service/authentication/AuthenticationEvents":133,"./service/xmpp/XMPPEvents":137,"events":51,"jitsi-meet-logger":79}],2:[function(require,module,exports){
  892. /**
  893. * Enumeration with the errors for the conference.
  894. * @type {{string: string}}
  895. */
  896. var JitsiConferenceErrors = {
  897. /**
  898. * Indicates that a password is required in order to join the conference.
  899. */
  900. PASSWORD_REQUIRED: "conference.passwordRequired",
  901. /**
  902. * Indicates that client must be authenticated to create the conference.
  903. */
  904. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  905. /**
  906. * Indicates that password cannot be set for this conference.
  907. */
  908. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  909. /**
  910. * Indicates that a connection error occurred when trying to join a
  911. * conference.
  912. */
  913. CONNECTION_ERROR: "conference.connectionError",
  914. /**
  915. * Indicates that the conference setup failed.
  916. */
  917. SETUP_FAILED: "conference.setup_failed",
  918. /**
  919. * Indicates that there is no available videobridge.
  920. */
  921. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable"
  922. /**
  923. * Many more errors TBD here.
  924. */
  925. };
  926. module.exports = JitsiConferenceErrors;
  927. },{}],3:[function(require,module,exports){
  928. /**
  929. * Enumeration with the events for the conference.
  930. * @type {{string: string}}
  931. */
  932. var JitsiConferenceEvents = {
  933. /**
  934. * A new media track was added to the conference.
  935. */
  936. TRACK_ADDED: "conference.trackAdded",
  937. /**
  938. * The media track was removed from the conference.
  939. */
  940. TRACK_REMOVED: "conference.trackRemoved",
  941. /**
  942. * The dominant speaker was changed.
  943. */
  944. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  945. /**
  946. * A new user joinned the conference.
  947. */
  948. USER_JOINED: "conference.userJoined",
  949. /**
  950. * A user has left the conference.
  951. */
  952. USER_LEFT: "conference.userLeft",
  953. /**
  954. * User role changed.
  955. */
  956. USER_ROLE_CHANGED: "conference.roleChanged",
  957. /**
  958. * New text message was received.
  959. */
  960. MESSAGE_RECEIVED: "conference.messageReceived",
  961. /**
  962. * A user has changed it display name
  963. */
  964. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  965. /**
  966. * A participant avatar has changed.
  967. */
  968. AVATAR_CHANGED: "conference.avatarChanged",
  969. /**
  970. * New connection statistics are received.
  971. */
  972. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  973. /**
  974. * The Last N set is changed.
  975. */
  976. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  977. /**
  978. * You are included / excluded in somebody's last N set
  979. */
  980. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  981. /**
  982. * A media track ( attached to the conference) mute status was changed.
  983. */
  984. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  985. /**
  986. * Audio levels of a media track ( attached to the conference) was changed.
  987. */
  988. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  989. /**
  990. * Indicates that the connection to the conference has been interrupted
  991. * for some reason.
  992. */
  993. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  994. /**
  995. * Indicates that the connection to the conference has been restored.
  996. */
  997. CONNECTION_RESTORED: "conference.connectionRestored",
  998. /**
  999. * Indicates that conference failed.
  1000. */
  1001. CONFERENCE_FAILED: "conference.failed",
  1002. /**
  1003. * Indicates that conference has been joined.
  1004. */
  1005. CONFERENCE_JOINED: "conference.joined",
  1006. /**
  1007. * Indicates that conference has been left.
  1008. */
  1009. CONFERENCE_LEFT: "conference.left",
  1010. /**
  1011. * You are kicked from the conference.
  1012. */
  1013. KICKED: "conferenece.kicked",
  1014. /**
  1015. * Indicates that start muted settings changed.
  1016. */
  1017. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  1018. /**
  1019. * Indicates that the local user has started muted.
  1020. */
  1021. STARTED_MUTED: "conference.started_muted",
  1022. /**
  1023. * Indicates that DTMF support changed.
  1024. */
  1025. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  1026. /**
  1027. * Indicates that recording state changed.
  1028. */
  1029. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  1030. /**
  1031. * Indicates that phone number changed.
  1032. */
  1033. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
  1034. };
  1035. module.exports = JitsiConferenceEvents;
  1036. },{}],4:[function(require,module,exports){
  1037. var JitsiConference = require("./JitsiConference");
  1038. var XMPP = require("./modules/xmpp/xmpp");
  1039. /**
  1040. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  1041. * JitsiConference interface.
  1042. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  1043. * @param token the JWT token used to authenticate with the server(optional)
  1044. * @param options Object with properties / settings related to connection with the server.
  1045. * @constructor
  1046. */
  1047. function JitsiConnection(appID, token, options) {
  1048. this.appID = appID;
  1049. this.token = token;
  1050. this.options = options;
  1051. this.xmpp = new XMPP(options);
  1052. this.conferences = {};
  1053. }
  1054. /**
  1055. * Connect the client with the server.
  1056. * @param options {object} connecting options (for example authentications parameters).
  1057. */
  1058. JitsiConnection.prototype.connect = function (options) {
  1059. if(!options)
  1060. options = {};
  1061. this.xmpp.connect(options.id, options.password);
  1062. }
  1063. /**
  1064. * Disconnect the client from the server.
  1065. */
  1066. JitsiConnection.prototype.disconnect = function () {
  1067. this.xmpp.disconnect();
  1068. }
  1069. /**
  1070. * This method allows renewal of the tokens if they are expiring.
  1071. * @param token the new token.
  1072. */
  1073. JitsiConnection.prototype.setToken = function (token) {
  1074. this.token = token;
  1075. }
  1076. /**
  1077. * Creates and joins new conference.
  1078. * @param name the name of the conference; if null - a generated name will be
  1079. * provided from the api
  1080. * @param options Object with properties / settings related to the conference
  1081. * that will be created.
  1082. * @returns {JitsiConference} returns the new conference object.
  1083. */
  1084. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1085. this.conferences[name] = new JitsiConference({name: name, config: options,
  1086. connection: this});
  1087. return this.conferences[name];
  1088. }
  1089. /**
  1090. * Subscribes the passed listener to the event.
  1091. * @param event {JitsiConnectionEvents} the connection event.
  1092. * @param listener {Function} the function that will receive the event
  1093. */
  1094. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1095. this.xmpp.addListener(event, listener);
  1096. }
  1097. /**
  1098. * Unsubscribes the passed handler.
  1099. * @param event {JitsiConnectionEvents} the connection event.
  1100. * @param listener {Function} the function that will receive the event
  1101. */
  1102. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1103. this.xmpp.removeListener(event, listener);
  1104. }
  1105. module.exports = JitsiConnection;
  1106. },{"./JitsiConference":1,"./modules/xmpp/xmpp":44}],5:[function(require,module,exports){
  1107. /**
  1108. * Enumeration with the errors for the connection.
  1109. * @type {{string: string}}
  1110. */
  1111. var JitsiConnectionErrors = {
  1112. /**
  1113. * Indicates that a password is required in order to join the conference.
  1114. */
  1115. PASSWORD_REQUIRED: "connection.passwordRequired",
  1116. /**
  1117. * Indicates that a connection error occurred when trying to join a
  1118. * conference.
  1119. */
  1120. CONNECTION_ERROR: "connection.connectionError",
  1121. /**
  1122. * Not specified errors.
  1123. */
  1124. OTHER_ERROR: "connection.otherError"
  1125. };
  1126. module.exports = JitsiConnectionErrors;
  1127. },{}],6:[function(require,module,exports){
  1128. /**
  1129. * Enumeration with the events for the connection.
  1130. * @type {{string: string}}
  1131. */
  1132. var JitsiConnnectionEvents = {
  1133. /**
  1134. * Indicates that the connection has been failed for some reason.
  1135. */
  1136. CONNECTION_FAILED: "connection.connectionFailed",
  1137. /**
  1138. * Indicates that the connection has been established.
  1139. */
  1140. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1141. /**
  1142. * Indicates that the connection has been disconnected.
  1143. */
  1144. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1145. /**
  1146. * Indicates that the perfomed action cannot be executed because the
  1147. * connection is not in the correct state(connected, disconnected, etc.)
  1148. */
  1149. WRONG_STATE: "connection.wrongState"
  1150. };
  1151. module.exports = JitsiConnnectionEvents;
  1152. },{}],7:[function(require,module,exports){
  1153. var JitsiConnection = require("./JitsiConnection");
  1154. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1155. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1156. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1157. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1158. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1159. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1160. var Logger = require("jitsi-meet-logger");
  1161. var RTC = require("./modules/RTC/RTC");
  1162. var Statistics = require("./modules/statistics/statistics");
  1163. var Resolutions = require("./service/RTC/Resolutions");
  1164. var ScriptUtil = require("./modules/util/ScriptUtil");
  1165. function getLowerResolution(resolution) {
  1166. if(!Resolutions[resolution])
  1167. return null;
  1168. var order = Resolutions[resolution].order;
  1169. var res = null;
  1170. var resName = null;
  1171. for(var i in Resolutions) {
  1172. var tmp = Resolutions[i];
  1173. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1174. resName = i;
  1175. res = tmp;
  1176. }
  1177. }
  1178. return resName;
  1179. }
  1180. /**
  1181. * Namespace for the interface of Jitsi Meet Library.
  1182. */
  1183. var LibJitsiMeet = {
  1184. JitsiConnection: JitsiConnection,
  1185. events: {
  1186. conference: JitsiConferenceEvents,
  1187. connection: JitsiConnectionEvents,
  1188. track: JitsiTrackEvents
  1189. },
  1190. errors: {
  1191. conference: JitsiConferenceErrors,
  1192. connection: JitsiConnectionErrors,
  1193. track: JitsiTrackErrors
  1194. },
  1195. logLevels: Logger.levels,
  1196. /**
  1197. * Array of functions that will receive the GUM error.
  1198. */
  1199. _gumFailedHandler: [],
  1200. init: function (options) {
  1201. Statistics.audioLevelsEnabled = !options.disableAudioLevels || true;
  1202. return RTC.init(options || {});
  1203. },
  1204. /**
  1205. * Returns whether the desktop sharing is enabled or not.
  1206. * @returns {boolean}
  1207. */
  1208. isDesktopSharingEnabled: function () {
  1209. return RTC.isDesktopSharingEnabled();
  1210. },
  1211. setLogLevel: function (level) {
  1212. Logger.setLogLevel(level);
  1213. },
  1214. /**
  1215. * Creates the media tracks and returns them trough the callback.
  1216. * @param options Object with properties / settings specifying the tracks which should be created.
  1217. * should be created or some additional configurations about resolution for example.
  1218. * @param {Array} options.devices the devices that will be requested
  1219. * @param {string} options.resolution resolution constraints
  1220. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1221. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1222. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1223. * @param {string} options.cameraDeviceId
  1224. * @param {string} options.micDeviceId
  1225. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1226. * A promise that returns an array of created JitsiTracks if resolved,
  1227. * or a JitsiConferenceError if rejected.
  1228. */
  1229. createLocalTracks: function (options) {
  1230. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1231. function(tracks) {
  1232. if(!RTC.options.disableAudioLevels)
  1233. for(var i = 0; i < tracks.length; i++) {
  1234. var track = tracks[i];
  1235. var mStream = track.getOriginalStream();
  1236. if(track.getType() === "audio"){
  1237. Statistics.startLocalStats(mStream,
  1238. track.setAudioLevel.bind(track));
  1239. track.addEventListener(
  1240. JitsiTrackEvents.TRACK_STOPPED,
  1241. function(){
  1242. Statistics.stopLocalStats(mStream);
  1243. });
  1244. }
  1245. }
  1246. return tracks;
  1247. }).catch(function (error) {
  1248. this._gumFailedHandler.forEach(function (handler) {
  1249. handler(error);
  1250. });
  1251. if(!this._gumFailedHandler.length)
  1252. Statistics.sendGetUserMediaFailed(error);
  1253. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1254. var oldResolution = options.resolution || '360';
  1255. var newResolution = getLowerResolution(oldResolution);
  1256. if(newResolution === null)
  1257. return Promise.reject(error);
  1258. options.resolution = newResolution;
  1259. return LibJitsiMeet.createLocalTracks(options);
  1260. }
  1261. return Promise.reject(error);
  1262. }.bind(this));
  1263. },
  1264. /**
  1265. * Checks if its possible to enumerate available cameras/micropones.
  1266. * @returns {boolean} true if available, false otherwise.
  1267. */
  1268. isDeviceListAvailable: function () {
  1269. return RTC.isDeviceListAvailable();
  1270. },
  1271. /**
  1272. * Returns true if changing the camera / microphone device is supported and
  1273. * false if not.
  1274. * @returns {boolean} true if available, false otherwise.
  1275. */
  1276. isDeviceChangeAvailable: function () {
  1277. return RTC.isDeviceChangeAvailable();
  1278. },
  1279. enumerateDevices: function (callback) {
  1280. RTC.enumerateDevices(callback);
  1281. },
  1282. /**
  1283. * Represents a hub/namespace for utility functionality which may be of
  1284. * interest to LibJitsiMeet clients.
  1285. */
  1286. util: {
  1287. ScriptUtil: ScriptUtil,
  1288. },
  1289. };
  1290. //Setups the promise object.
  1291. window.Promise = window.Promise || require("es6-promise").Promise;
  1292. module.exports = LibJitsiMeet;
  1293. },{"./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":132,"es6-promise":72,"jitsi-meet-logger":79}],8:[function(require,module,exports){
  1294. /* global Strophe */
  1295. /**
  1296. * Represents a participant in (a member of) a conference.
  1297. */
  1298. function JitsiParticipant(jid, conference, displayName){
  1299. this._jid = jid;
  1300. this._id = Strophe.getResourceFromJid(jid);
  1301. this._conference = conference;
  1302. this._displayName = displayName;
  1303. this._supportsDTMF = false;
  1304. this._tracks = [];
  1305. this._role = 'none';
  1306. }
  1307. /**
  1308. * @returns {JitsiConference} The conference that this participant belongs to.
  1309. */
  1310. JitsiParticipant.prototype.getConference = function() {
  1311. return this._conference;
  1312. };
  1313. /**
  1314. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1315. */
  1316. JitsiParticipant.prototype.getTracks = function() {
  1317. return this._tracks;
  1318. };
  1319. /**
  1320. * @returns {String} The ID of this participant.
  1321. */
  1322. JitsiParticipant.prototype.getId = function() {
  1323. return this._id;
  1324. };
  1325. /**
  1326. * @returns {String} The JID of this participant.
  1327. */
  1328. JitsiParticipant.prototype.getJid = function() {
  1329. return this._jid;
  1330. };
  1331. /**
  1332. * @returns {String} The human-readable display name of this participant.
  1333. */
  1334. JitsiParticipant.prototype.getDisplayName = function() {
  1335. return this._displayName;
  1336. };
  1337. /**
  1338. * @returns {Boolean} Whether this participant is a moderator or not.
  1339. */
  1340. JitsiParticipant.prototype.isModerator = function() {
  1341. return this._role === 'moderator';
  1342. };
  1343. // Gets a link to an etherpad instance advertised by the participant?
  1344. //JitsiParticipant.prototype.getEtherpad = function() {
  1345. //
  1346. //}
  1347. /*
  1348. * @returns {Boolean} Whether this participant has muted their audio.
  1349. */
  1350. JitsiParticipant.prototype.isAudioMuted = function() {
  1351. return this.getTracks().reduce(function (track, isAudioMuted) {
  1352. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1353. }, true);
  1354. };
  1355. /*
  1356. * @returns {Boolean} Whether this participant has muted their video.
  1357. */
  1358. JitsiParticipant.prototype.isVideoMuted = function() {
  1359. return this.getTracks().reduce(function (track, isVideoMuted) {
  1360. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1361. }, true);
  1362. };
  1363. /*
  1364. * @returns {???} The latest statistics reported by this participant
  1365. * (i.e. info used to populate the GSM bars)
  1366. * TODO: do we expose this or handle it internally?
  1367. */
  1368. JitsiParticipant.prototype.getLatestStats = function() {
  1369. };
  1370. /**
  1371. * @returns {String} The role of this participant.
  1372. */
  1373. JitsiParticipant.prototype.getRole = function() {
  1374. return this._role;
  1375. };
  1376. /*
  1377. * @returns {Boolean} Whether this participant is
  1378. * the conference focus (i.e. jicofo).
  1379. */
  1380. JitsiParticipant.prototype.isFocus = function() {
  1381. };
  1382. /*
  1383. * @returns {Boolean} Whether this participant is
  1384. * a conference recorder (i.e. jirecon).
  1385. */
  1386. JitsiParticipant.prototype.isRecorder = function() {
  1387. };
  1388. /*
  1389. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1390. */
  1391. JitsiParticipant.prototype.isSipGateway = function() {
  1392. };
  1393. /**
  1394. * @returns {Boolean} Whether this participant
  1395. * is currently sharing their screen.
  1396. */
  1397. JitsiParticipant.prototype.isScreenSharing = function() {
  1398. };
  1399. /**
  1400. * @returns {String} The user agent of this participant
  1401. * (i.e. browser userAgent string).
  1402. */
  1403. JitsiParticipant.prototype.getUserAgent = function() {
  1404. };
  1405. /**
  1406. * Kicks the participant from the conference (requires certain privileges).
  1407. */
  1408. JitsiParticipant.prototype.kick = function() {
  1409. };
  1410. /**
  1411. * Asks this participant to mute themselves.
  1412. */
  1413. JitsiParticipant.prototype.askToMute = function() {
  1414. };
  1415. JitsiParticipant.prototype.supportsDTMF = function () {
  1416. return this._supportsDTMF;
  1417. };
  1418. module.exports = JitsiParticipant;
  1419. },{}],9:[function(require,module,exports){
  1420. module.exports = {
  1421. /**
  1422. * Returns JitsiTrackErrors based on the error object passed by GUM
  1423. * @param error the error
  1424. * @param {Array} devices Array with the requested devices
  1425. */
  1426. parseError: function (error, devices) {
  1427. devices = devices || [];
  1428. if (typeof error == "object" && error.constraintName && error.name
  1429. && (error.name == "ConstraintNotSatisfiedError" ||
  1430. error.name == "OverconstrainedError") &&
  1431. (error.constraintName == "minWidth" ||
  1432. error.constraintName == "maxWidth" ||
  1433. error.constraintName == "minHeight" ||
  1434. error.constraintName == "maxHeight") &&
  1435. devices.indexOf("video") !== -1) {
  1436. return this.UNSUPPORTED_RESOLUTION;
  1437. } else if(typeof error === "object" && error.type === "jitsiError") {
  1438. return error.errorObject;
  1439. } else {
  1440. return this.GENERAL;
  1441. }
  1442. },
  1443. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1444. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1445. GENERAL: "gum.general"
  1446. };
  1447. },{}],10:[function(require,module,exports){
  1448. var JitsiTrackEvents = {
  1449. /**
  1450. * A media track mute status was changed.
  1451. */
  1452. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1453. /**
  1454. * Audio levels of a this track was changed.
  1455. */
  1456. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1457. /**
  1458. * The media track was removed to the conference.
  1459. */
  1460. TRACK_STOPPED: "track.stopped"
  1461. };
  1462. module.exports = JitsiTrackEvents;
  1463. },{}],11:[function(require,module,exports){
  1464. (function (__filename){
  1465. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1466. function JitsiDTMFManager (localAudio, peerConnection) {
  1467. var tracks = localAudio._getTracks();
  1468. if (!tracks.length) {
  1469. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1470. }
  1471. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1472. logger.debug("Initialized DTMFSender");
  1473. }
  1474. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1475. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1476. };
  1477. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1478. },{"jitsi-meet-logger":79}],12:[function(require,module,exports){
  1479. (function (__filename){
  1480. /* global config, APP, Strophe */
  1481. // cache datachannels to avoid garbage collection
  1482. // https://code.google.com/p/chromium/issues/detail?id=405545
  1483. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1484. var RTCEvents = require("../../service/RTC/RTCEvents");
  1485. /**
  1486. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1487. * @param peerConnection WebRTC peer connection instance.
  1488. */
  1489. function DataChannels(peerConnection, emitter) {
  1490. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1491. this.eventEmitter = emitter;
  1492. this._dataChannels = [];
  1493. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1494. // Although it's not a requirement to open separate channels from both bridge
  1495. // and peer as single channel can be used for sending and receiving data.
  1496. // So either channel opened by the bridge or the one opened here is enough
  1497. // for communication with the bridge.
  1498. /*var dataChannelOptions =
  1499. {
  1500. reliable: true
  1501. };
  1502. var dataChannel
  1503. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1504. // Can be used only when is in open state
  1505. dataChannel.onopen = function ()
  1506. {
  1507. dataChannel.send("My channel !!!");
  1508. };
  1509. dataChannel.onmessage = function (event)
  1510. {
  1511. var msgData = event.data;
  1512. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1513. };*/
  1514. };
  1515. /**
  1516. * Callback triggered by PeerConnection when new data channel is opened
  1517. * on the bridge.
  1518. * @param event the event info object.
  1519. */
  1520. DataChannels.prototype.onDataChannel = function (event) {
  1521. var dataChannel = event.channel;
  1522. var self = this;
  1523. var lastSelectedEndpoint = null;
  1524. dataChannel.onopen = function () {
  1525. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1526. // Code sample for sending string and/or binary data
  1527. // Sends String message to the bridge
  1528. //dataChannel.send("Hello bridge!");
  1529. // Sends 12 bytes binary message to the bridge
  1530. //dataChannel.send(new ArrayBuffer(12));
  1531. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1532. // when the data channel becomes available, tell the bridge about video
  1533. // selections so that it can do adaptive simulcast,
  1534. // we want the notification to trigger even if userJid is undefined,
  1535. // or null.
  1536. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1537. };
  1538. dataChannel.onerror = function (error) {
  1539. logger.error("Data Channel Error:", error, dataChannel);
  1540. };
  1541. dataChannel.onmessage = function (event) {
  1542. var data = event.data;
  1543. // JSON
  1544. var obj;
  1545. try {
  1546. obj = JSON.parse(data);
  1547. }
  1548. catch (e) {
  1549. logger.error(
  1550. "Failed to parse data channel message as JSON: ",
  1551. data,
  1552. dataChannel);
  1553. }
  1554. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1555. var colibriClass = obj.colibriClass;
  1556. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1557. // Endpoint ID from the Videobridge.
  1558. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1559. logger.info(
  1560. "Data channel new dominant speaker event: ",
  1561. dominantSpeakerEndpoint);
  1562. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1563. }
  1564. else if ("InLastNChangeEvent" === colibriClass) {
  1565. var oldValue = obj.oldValue;
  1566. var newValue = obj.newValue;
  1567. // Make sure that oldValue and newValue are of type boolean.
  1568. var type;
  1569. if ((type = typeof oldValue) !== 'boolean') {
  1570. if (type === 'string') {
  1571. oldValue = (oldValue == "true");
  1572. } else {
  1573. oldValue = new Boolean(oldValue).valueOf();
  1574. }
  1575. }
  1576. if ((type = typeof newValue) !== 'boolean') {
  1577. if (type === 'string') {
  1578. newValue = (newValue == "true");
  1579. } else {
  1580. newValue = new Boolean(newValue).valueOf();
  1581. }
  1582. }
  1583. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1584. }
  1585. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1586. // The new/latest list of last-n endpoint IDs.
  1587. var lastNEndpoints = obj.lastNEndpoints;
  1588. // The list of endpoint IDs which are entering the list of
  1589. // last-n at this time i.e. were not in the old list of last-n
  1590. // endpoint IDs.
  1591. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1592. logger.info(
  1593. "Data channel new last-n event: ",
  1594. lastNEndpoints, endpointsEnteringLastN, obj);
  1595. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1596. lastNEndpoints, endpointsEnteringLastN, obj);
  1597. }
  1598. else {
  1599. logger.debug("Data channel JSON-formatted message: ", obj);
  1600. // The received message appears to be appropriately formatted
  1601. // (i.e. is a JSON object which assigns a value to the mandatory
  1602. // property colibriClass) so don't just swallow it, expose it to
  1603. // public consumption.
  1604. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1605. }
  1606. }
  1607. };
  1608. dataChannel.onclose = function () {
  1609. logger.info("The Data Channel closed", dataChannel);
  1610. var idx = self._dataChannels.indexOf(dataChannel);
  1611. if (idx > -1)
  1612. self._dataChannels = self._dataChannels.splice(idx, 1);
  1613. };
  1614. this._dataChannels.push(dataChannel);
  1615. };
  1616. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1617. this.lastSelectedEndpoint = userResource;
  1618. this._onXXXEndpointChanged("selected", userResource);
  1619. }
  1620. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1621. this._onXXXEndpointChanged("pinnned", userResource);
  1622. }
  1623. /**
  1624. * Notifies Videobridge about a change in the value of a specific
  1625. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1626. *
  1627. * @param xxx the name of the endpoint-related property whose value changed
  1628. * @param userResource the new value of the endpoint-related property after the
  1629. * change
  1630. */
  1631. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1632. // Derive the correct words from xxx such as selected and Selected, pinned
  1633. // and Pinned.
  1634. var head = xxx.charAt(0);
  1635. var tail = xxx.substring(1);
  1636. var lower = head.toLowerCase() + tail;
  1637. var upper = head.toUpperCase() + tail;
  1638. // Notify Videobridge about the specified endpoint change.
  1639. console.log(lower + ' endpoint changed: ', userResource);
  1640. this._some(function (dataChannel) {
  1641. if (dataChannel.readyState == 'open') {
  1642. console.log(
  1643. 'sending ' + lower
  1644. + ' endpoint changed notification to the bridge: ',
  1645. userResource);
  1646. var jsonObject = {};
  1647. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1648. jsonObject[lower + "Endpoint"]
  1649. = (userResource ? userResource : null);
  1650. dataChannel.send(JSON.stringify(jsonObject));
  1651. return true;
  1652. }
  1653. });
  1654. }
  1655. DataChannels.prototype._some = function (callback, thisArg) {
  1656. var dataChannels = this._dataChannels;
  1657. if (dataChannels && dataChannels.length !== 0) {
  1658. if (thisArg)
  1659. return dataChannels.some(callback, thisArg);
  1660. else
  1661. return dataChannels.some(callback);
  1662. } else {
  1663. return false;
  1664. }
  1665. }
  1666. module.exports = DataChannels;
  1667. }).call(this,"/modules/RTC/DataChannels.js")
  1668. },{"../../service/RTC/RTCEvents":131,"jitsi-meet-logger":79}],13:[function(require,module,exports){
  1669. var JitsiTrack = require("./JitsiTrack");
  1670. var RTCBrowserType = require("./RTCBrowserType");
  1671. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1672. var RTCUtils = require("./RTCUtils");
  1673. /**
  1674. * Represents a single media track (either audio or video).
  1675. * @constructor
  1676. */
  1677. function JitsiLocalTrack(stream, videoType,
  1678. resolution, deviceId)
  1679. {
  1680. this.videoType = videoType;
  1681. this.dontFireRemoveEvent = false;
  1682. this.resolution = resolution;
  1683. this.deviceId = deviceId;
  1684. this.startMuted = false;
  1685. var self = this;
  1686. JitsiTrack.call(this, null, stream,
  1687. function () {
  1688. if(!this.dontFireRemoveEvent)
  1689. this.eventEmitter.emit(
  1690. JitsiTrackEvents.TRACK_STOPPED);
  1691. this.dontFireRemoveEvent = false;
  1692. }.bind(this));
  1693. }
  1694. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1695. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1696. /**
  1697. * Mutes / unmutes the track.
  1698. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1699. */
  1700. JitsiLocalTrack.prototype._setMute = function (mute) {
  1701. if (this.isMuted() === mute) {
  1702. return;
  1703. }
  1704. if(!this.rtc) {
  1705. this.startMuted = mute;
  1706. return;
  1707. }
  1708. var isAudio = this.type === JitsiTrack.AUDIO;
  1709. this.dontFireRemoveEvent = false;
  1710. if ((window.location.protocol != "https:") ||
  1711. (isAudio) || this.videoType === "desktop" ||
  1712. // FIXME FF does not support 'removeStream' method used to mute
  1713. RTCBrowserType.isFirefox()) {
  1714. var tracks = this._getTracks();
  1715. for (var idx = 0; idx < tracks.length; idx++) {
  1716. tracks[idx].enabled = !mute;
  1717. }
  1718. if(isAudio)
  1719. this.rtc.room.setAudioMute(mute);
  1720. else
  1721. this.rtc.room.setVideoMute(mute);
  1722. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1723. } else {
  1724. if (mute) {
  1725. this.dontFireRemoveEvent = true;
  1726. this.rtc.room.removeStream(this.stream, function () {});
  1727. RTCUtils.stopMediaStream(this.stream);
  1728. if(isAudio)
  1729. this.rtc.room.setAudioMute(mute);
  1730. else
  1731. this.rtc.room.setVideoMute(mute);
  1732. this.stream = null;
  1733. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1734. //FIXME: Maybe here we should set the SRC for the containers to something
  1735. } else {
  1736. var self = this;
  1737. var streamOptions = {
  1738. devices: (isAudio ? ["audio"] : ["video"]),
  1739. resolution: self.resolution
  1740. };
  1741. if (isAudio) {
  1742. streamOptions['micDeviceId'] = self.deviceId;
  1743. } else {self.videoType === 'camera'} {
  1744. streamOptions['cameraDeviceId'] = self.deviceId;
  1745. }
  1746. RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  1747. .then(function (streams) {
  1748. var stream = null;
  1749. for(var i = 0; i < streams.length; i++) {
  1750. stream = streams[i];
  1751. if(stream.type === self.type) {
  1752. self.stream = stream.stream;
  1753. self.videoType = stream.videoType;
  1754. break;
  1755. }
  1756. }
  1757. if(!stream)
  1758. return;
  1759. for(var i = 0; i < self.containers.length; i++)
  1760. {
  1761. RTCUtils.attachMediaStream(
  1762. self.containers[i], self.stream);
  1763. }
  1764. self.rtc.room.addStream(stream.stream,
  1765. function () {
  1766. if(isAudio)
  1767. self.rtc.room.setAudioMute(mute);
  1768. else
  1769. self.rtc.room.setVideoMute(mute);
  1770. self.eventEmitter.emit(
  1771. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1772. });
  1773. });
  1774. }
  1775. }
  1776. }
  1777. /**
  1778. * Stops sending the media track. And removes it from the HTML.
  1779. * NOTE: Works for local tracks only.
  1780. */
  1781. JitsiLocalTrack.prototype.stop = function () {
  1782. if(!this.stream)
  1783. return;
  1784. if(this.rtc)
  1785. this.rtc.room.removeStream(this.stream, function () {});
  1786. RTCUtils.stopMediaStream(this.stream);
  1787. this.detach();
  1788. }
  1789. /**
  1790. * Returns <tt>true</tt> - if the stream is muted
  1791. * and <tt>false</tt> otherwise.
  1792. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1793. * and <tt>false</tt> otherwise.
  1794. */
  1795. JitsiLocalTrack.prototype.isMuted = function () {
  1796. if (!this.stream)
  1797. return true;
  1798. var tracks = [];
  1799. var isAudio = this.type === JitsiTrack.AUDIO;
  1800. if (isAudio) {
  1801. tracks = this.stream.getAudioTracks();
  1802. } else {
  1803. if (!this.isActive())
  1804. return true;
  1805. tracks = this.stream.getVideoTracks();
  1806. }
  1807. for (var idx = 0; idx < tracks.length; idx++) {
  1808. if(tracks[idx].enabled)
  1809. return false;
  1810. }
  1811. return true;
  1812. };
  1813. /**
  1814. * Private method. Updates rtc property of the track.
  1815. * @param rtc the rtc instance.
  1816. */
  1817. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1818. this.rtc = rtc;
  1819. };
  1820. /**
  1821. * Return true;
  1822. */
  1823. JitsiLocalTrack.prototype.isLocal = function () {
  1824. return true;
  1825. }
  1826. module.exports = JitsiLocalTrack;
  1827. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1828. var JitsiTrack = require("./JitsiTrack");
  1829. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1830. /**
  1831. * Represents a single media track (either audio or video).
  1832. * @param RTC the rtc instance.
  1833. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1834. * @param sid sid for the Media Stream
  1835. * @param ssrc ssrc for the Media Stream
  1836. * @param eventEmitter the event emitter
  1837. * @constructor
  1838. */
  1839. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1840. JitsiTrack.call(this, RTC, data.stream,
  1841. function () {
  1842. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1843. }.bind(this), data.jitsiTrackType);
  1844. this.rtc = RTC;
  1845. this.sid = sid;
  1846. this.stream = data.stream;
  1847. this.peerjid = data.peerjid;
  1848. this.videoType = data.videoType;
  1849. this.ssrc = ssrc;
  1850. this.muted = false;
  1851. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1852. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1853. this.muted = true;
  1854. }
  1855. }
  1856. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1857. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1858. /**
  1859. * Sets current muted status and fires an events for the change.
  1860. * @param value the muted status.
  1861. */
  1862. JitsiRemoteTrack.prototype.setMute = function (value) {
  1863. if(this.muted === value)
  1864. return;
  1865. // we can have a fake video stream
  1866. if(this.stream)
  1867. this.stream.muted = value;
  1868. this.muted = value;
  1869. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1870. };
  1871. /**
  1872. * Returns the current muted status of the track.
  1873. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1874. */
  1875. JitsiRemoteTrack.prototype.isMuted = function () {
  1876. return this.muted;
  1877. };
  1878. /**
  1879. * Returns the participant id which owns the track.
  1880. * @returns {string} the id of the participants.
  1881. */
  1882. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1883. return Strophe.getResourceFromJid(this.peerjid);
  1884. };
  1885. /**
  1886. * Return false;
  1887. */
  1888. JitsiRemoteTrack.prototype.isLocal = function () {
  1889. return false;
  1890. };
  1891. delete JitsiRemoteTrack.prototype.stop;
  1892. module.exports = JitsiRemoteTrack;
  1893. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  1894. var RTCBrowserType = require("./RTCBrowserType");
  1895. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1896. var EventEmitter = require("events");
  1897. var RTC = require("./RTCUtils");
  1898. /**
  1899. * This implements 'onended' callback normally fired by WebRTC after the stream
  1900. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  1901. * @param jitsiTrack our track object holding the original WebRTC stream object
  1902. * to which 'onended' handling will be added.
  1903. */
  1904. function implementOnEndedHandling(jitsiTrack) {
  1905. var stream = jitsiTrack.getOriginalStream();
  1906. if(!stream)
  1907. return;
  1908. var originalStop = stream.stop;
  1909. stream.stop = function () {
  1910. originalStop.apply(stream);
  1911. if (jitsiTrack.isActive()) {
  1912. stream.onended();
  1913. }
  1914. };
  1915. }
  1916. /**
  1917. * Adds onended/oninactive handler to a MediaStream.
  1918. * @param mediaStream a MediaStream to attach onended/oninactive handler
  1919. * @param handler the handler
  1920. */
  1921. function addMediaStreamInactiveHandler(mediaStream, handler) {
  1922. if(RTCBrowserType.isTemasysPluginUsed()) {
  1923. // themasys
  1924. //FIXME: Seems that not working properly.
  1925. if(mediaStream.onended) {
  1926. mediaStream.onended = handler;
  1927. } else if(mediaStream.addEventListener) {
  1928. mediaStream.addEventListener('ended', function () {
  1929. handler(mediaStream);
  1930. });
  1931. } else if(mediaStream.attachEvent) {
  1932. mediaStream.attachEvent('ended', function () {
  1933. handler(mediaStream);
  1934. });
  1935. }
  1936. }
  1937. else {
  1938. if(typeof mediaStream.active !== "undefined")
  1939. mediaStream.oninactive = handler;
  1940. else
  1941. mediaStream.onended = handler;
  1942. }
  1943. }
  1944. /**
  1945. * Represents a single media track (either audio or video).
  1946. * @constructor
  1947. * @param rtc the rtc instance
  1948. * @param stream the stream
  1949. * @param streamInactiveHandler the function that will handle
  1950. * onended/oninactive events of the stream.
  1951. * @param jitsiTrackType optionally a type can be specified.
  1952. * This is the case where we are creating a dummy track with no stream
  1953. * Currently this happens when a remote side is starting with video muted
  1954. */
  1955. function JitsiTrack(rtc, stream, streamInactiveHandler, jitsiTrackType)
  1956. {
  1957. /**
  1958. * Array with the HTML elements that are displaying the streams.
  1959. * @type {Array}
  1960. */
  1961. this.containers = [];
  1962. this.rtc = rtc;
  1963. this.stream = stream;
  1964. this.eventEmitter = new EventEmitter();
  1965. this.audioLevel = -1;
  1966. this.type = jitsiTrackType || (this.stream.getVideoTracks().length > 0)?
  1967. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  1968. if(this.type == JitsiTrack.AUDIO) {
  1969. this._getTracks = function () {
  1970. return this.stream.getAudioTracks();
  1971. }.bind(this);
  1972. } else {
  1973. this._getTracks = function () {
  1974. return this.stream.getVideoTracks();
  1975. }.bind(this);
  1976. }
  1977. if (RTCBrowserType.isFirefox() && this.stream) {
  1978. implementOnEndedHandling(this);
  1979. }
  1980. if(stream)
  1981. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  1982. }
  1983. /**
  1984. * JitsiTrack video type.
  1985. * @type {string}
  1986. */
  1987. JitsiTrack.VIDEO = "video";
  1988. /**
  1989. * JitsiTrack audio type.
  1990. * @type {string}
  1991. */
  1992. JitsiTrack.AUDIO = "audio";
  1993. /**
  1994. * Returns the type (audio or video) of this track.
  1995. */
  1996. JitsiTrack.prototype.getType = function() {
  1997. return this.type;
  1998. };
  1999. /**
  2000. * Check if this is audiotrack.
  2001. */
  2002. JitsiTrack.prototype.isAudioTrack = function () {
  2003. return this.getType() === JitsiTrack.AUDIO;
  2004. };
  2005. /**
  2006. * Check if this is videotrack.
  2007. */
  2008. JitsiTrack.prototype.isVideoTrack = function () {
  2009. return this.getType() === JitsiTrack.VIDEO;
  2010. };
  2011. /**
  2012. * Returns the RTCMediaStream from the browser (?).
  2013. */
  2014. JitsiTrack.prototype.getOriginalStream = function() {
  2015. return this.stream;
  2016. }
  2017. /**
  2018. * Mutes the track.
  2019. */
  2020. JitsiTrack.prototype.mute = function () {
  2021. this._setMute(true);
  2022. }
  2023. /**
  2024. * Unmutes the stream.
  2025. */
  2026. JitsiTrack.prototype.unmute = function () {
  2027. this._setMute(false);
  2028. }
  2029. /**
  2030. * Attaches the MediaStream of this track to an HTML container (?).
  2031. * Adds the container to the list of containers that are displaying the track.
  2032. * @param container the HTML container
  2033. */
  2034. JitsiTrack.prototype.attach = function (container) {
  2035. if(this.stream)
  2036. require("./RTCUtils").attachMediaStream(container, this.stream);
  2037. this.containers.push(container);
  2038. }
  2039. /**
  2040. * Removes the track from the passed HTML container.
  2041. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  2042. */
  2043. JitsiTrack.prototype.detach = function (container) {
  2044. for(var i = 0; i < this.containers.length; i++)
  2045. {
  2046. if(this.containers[i].is(container))
  2047. {
  2048. this.containers.splice(i,1);
  2049. }
  2050. if(!container)
  2051. {
  2052. this.containers[i].find(">video").remove();
  2053. }
  2054. }
  2055. if(container)
  2056. $(container).find(">video").remove();
  2057. }
  2058. /**
  2059. * Stops sending the media track. And removes it from the HTML.
  2060. * NOTE: Works for local tracks only.
  2061. */
  2062. JitsiTrack.prototype.stop = function () {
  2063. }
  2064. /**
  2065. * Returns true if this is a video track and the source of the video is a
  2066. * screen capture as opposed to a camera.
  2067. */
  2068. JitsiTrack.prototype.isScreenSharing = function(){
  2069. }
  2070. /**
  2071. * Returns id of the track.
  2072. * @returns {string} id of the track or null if this is fake track.
  2073. */
  2074. JitsiTrack.prototype._getId = function () {
  2075. var tracks = this.stream.getTracks();
  2076. if(!tracks || tracks.length === 0)
  2077. return null;
  2078. return tracks[0].id;
  2079. };
  2080. /**
  2081. * Returns id of the track.
  2082. * @returns {string} id of the track or null if this is fake track.
  2083. */
  2084. JitsiTrack.prototype.getId = function () {
  2085. if(this.stream)
  2086. return RTC.getStreamID(this.stream);
  2087. else
  2088. return null;
  2089. };
  2090. /**
  2091. * Checks whether the MediaStream is avtive/not ended.
  2092. * When there is no check for active we don't have information and so
  2093. * will return that stream is active (in case of FF).
  2094. * @returns {boolean} whether MediaStream is active.
  2095. */
  2096. JitsiTrack.prototype.isActive = function () {
  2097. if((typeof this.stream.active !== "undefined"))
  2098. return this.stream.active;
  2099. else
  2100. return true;
  2101. };
  2102. /**
  2103. * Attaches a handler for events(For example - "audio level changed".).
  2104. * All possible event are defined in JitsiTrackEvents.
  2105. * @param eventId the event ID.
  2106. * @param handler handler for the event.
  2107. */
  2108. JitsiTrack.prototype.on = function (eventId, handler) {
  2109. if(this.eventEmitter)
  2110. this.eventEmitter.on(eventId, handler);
  2111. }
  2112. /**
  2113. * Removes event listener
  2114. * @param eventId the event ID.
  2115. * @param [handler] optional, the specific handler to unbind
  2116. */
  2117. JitsiTrack.prototype.off = function (eventId, handler) {
  2118. if(this.eventEmitter)
  2119. this.eventEmitter.removeListener(eventId, handler);
  2120. }
  2121. // Common aliases for event emitter
  2122. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2123. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2124. /**
  2125. * Sets the audio level for the stream
  2126. * @param audioLevel the new audio level
  2127. */
  2128. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2129. if(this.audioLevel !== audioLevel) {
  2130. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2131. audioLevel);
  2132. this.audioLevel = audioLevel;
  2133. }
  2134. }
  2135. module.exports = JitsiTrack;
  2136. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":51}],16:[function(require,module,exports){
  2137. /* global APP */
  2138. var EventEmitter = require("events");
  2139. var RTCBrowserType = require("./RTCBrowserType");
  2140. var RTCUtils = require("./RTCUtils.js");
  2141. var JitsiTrack = require("./JitsiTrack");
  2142. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2143. var DataChannels = require("./DataChannels");
  2144. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2145. var DesktopSharingEventTypes
  2146. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2147. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2148. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2149. function createLocalTracks(streams, options) {
  2150. var newStreams = []
  2151. var deviceId = null;
  2152. for (var i = 0; i < streams.length; i++) {
  2153. if (streams[i].type === 'audio') {
  2154. deviceId = options.micDeviceId;
  2155. } else if (streams[i].videoType === 'camera'){
  2156. deviceId = options.cameraDeviceId;
  2157. }
  2158. var localStream = new JitsiLocalTrack(streams[i].stream,
  2159. streams[i].videoType, streams[i].resolution, deviceId);
  2160. newStreams.push(localStream);
  2161. if (streams[i].isMuted === true)
  2162. localStream.setMute(true);
  2163. }
  2164. return newStreams;
  2165. }
  2166. function RTC(room, options) {
  2167. this.room = room;
  2168. this.localStreams = [];
  2169. //FIXME: we should start removing those streams.
  2170. //FIXME: We should support multiple streams per jid.
  2171. this.remoteStreams = {};
  2172. this.localAudio = null;
  2173. this.localVideo = null;
  2174. this.eventEmitter = new EventEmitter();
  2175. var self = this;
  2176. this.options = options || {};
  2177. room.addPresenceListener("videomuted", function (values, from) {
  2178. if(self.remoteStreams[from]) {
  2179. // If there is no video track, but we receive it is muted,
  2180. // we need to create a dummy track which we will mute, so we can
  2181. // notify interested about the muting
  2182. if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
  2183. var track = self.createRemoteStream(
  2184. {peerjid:room.roomjid + "/" + from,
  2185. videoType:"camera",
  2186. jitsiTrackType:JitsiTrack.VIDEO},
  2187. null, null);
  2188. self.eventEmitter
  2189. .emit(RTCEvents.FAKE_VIDEO_TRACK_CREATED, track);
  2190. }
  2191. self.remoteStreams[from][JitsiTrack.VIDEO]
  2192. .setMute(values.value == "true");
  2193. }
  2194. });
  2195. room.addPresenceListener("audiomuted", function (values, from) {
  2196. if(self.remoteStreams[from]) {
  2197. self.remoteStreams[from][JitsiTrack.AUDIO]
  2198. .setMute(values.value == "true");
  2199. }
  2200. });
  2201. }
  2202. /**
  2203. * Creates the local MediaStreams.
  2204. * @param {Object} [options] optional parameters
  2205. * @param {Array} options.devices the devices that will be requested
  2206. * @param {string} options.resolution resolution constraints
  2207. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2208. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2209. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2210. * @param {string} options.cameraDeviceId
  2211. * @param {string} options.micDeviceId
  2212. * @returns {*} Promise object that will receive the new JitsiTracks
  2213. */
  2214. RTC.obtainAudioAndVideoPermissions = function (options) {
  2215. return RTCUtils.obtainAudioAndVideoPermissions(options).then(function (streams) {
  2216. return createLocalTracks(streams, options);
  2217. });
  2218. }
  2219. RTC.prototype.onIncommingCall = function(event) {
  2220. if(this.options.config.openSctp)
  2221. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2222. for(var i = 0; i < this.localStreams.length; i++)
  2223. if(this.localStreams[i])
  2224. {
  2225. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2226. }
  2227. }
  2228. RTC.prototype.selectedEndpoint = function (id) {
  2229. if(this.dataChannels)
  2230. this.dataChannels.handleSelectedEndpointEvent(id);
  2231. }
  2232. RTC.prototype.pinEndpoint = function (id) {
  2233. if(this.dataChannels)
  2234. this.dataChannels.handlePinnedEndpointEvent(id);
  2235. }
  2236. RTC.prototype.addListener = function (type, listener) {
  2237. this.eventEmitter.on(type, listener);
  2238. };
  2239. RTC.prototype.removeListener = function (eventType, listener) {
  2240. this.eventEmitter.removeListener(eventType, listener);
  2241. };
  2242. RTC.addListener = function (eventType, listener) {
  2243. RTCUtils.addListener(eventType, listener);
  2244. }
  2245. RTC.removeListener = function (eventType, listener) {
  2246. RTCUtils.removeListener(eventType, listener)
  2247. }
  2248. RTC.isRTCReady = function () {
  2249. return RTCUtils.isRTCReady();
  2250. }
  2251. RTC.init = function (options) {
  2252. this.options = options || {};
  2253. return RTCUtils.init(this.options);
  2254. }
  2255. RTC.getDeviceAvailability = function () {
  2256. return RTCUtils.getDeviceAvailability();
  2257. }
  2258. RTC.prototype.addLocalStream = function (stream) {
  2259. this.localStreams.push(stream);
  2260. stream._setRTC(this);
  2261. if (stream.type == "audio") {
  2262. this.localAudio = stream;
  2263. } else {
  2264. this.localVideo = stream;
  2265. }
  2266. };
  2267. /**
  2268. * Set mute for all local audio streams attached to the conference.
  2269. * @param value the mute value
  2270. */
  2271. RTC.prototype.setAudioMute = function (value) {
  2272. for(var i = 0; i < this.localStreams.length; i++) {
  2273. var stream = this.localStreams[i];
  2274. if(stream.getType() !== "audio") {
  2275. continue;
  2276. }
  2277. stream._setMute(value);
  2278. }
  2279. }
  2280. RTC.prototype.removeLocalStream = function (track) {
  2281. var pos = this.localStreams.indexOf(track);
  2282. if (pos > -1) {
  2283. this.localStreams.splice(pos, 1);
  2284. }
  2285. };
  2286. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2287. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2288. if(!data.peerjid)
  2289. return;
  2290. var jid = Strophe.getResourceFromJid(data.peerjid);
  2291. if(!this.remoteStreams[jid]) {
  2292. this.remoteStreams[jid] = {};
  2293. }
  2294. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2295. return remoteStream;
  2296. };
  2297. RTC.getPCConstraints = function () {
  2298. return RTCUtils.pc_constraints;
  2299. };
  2300. RTC.attachMediaStream = function (elSelector, stream) {
  2301. RTCUtils.attachMediaStream(elSelector, stream);
  2302. };
  2303. RTC.getStreamID = function (stream) {
  2304. return RTCUtils.getStreamID(stream);
  2305. };
  2306. RTC.getVideoSrc = function (element) {
  2307. return RTCUtils.getVideoSrc(element);
  2308. };
  2309. /**
  2310. * Returns true if retrieving the the list of input devices is supported and
  2311. * false if not.
  2312. */
  2313. RTC.isDeviceListAvailable = function () {
  2314. return RTCUtils.isDeviceListAvailable();
  2315. };
  2316. /**
  2317. * Returns true if changing the camera / microphone device is supported and
  2318. * false if not.
  2319. */
  2320. RTC.isDeviceChangeAvailable = function () {
  2321. return RTCUtils.isDeviceChangeAvailable();
  2322. }
  2323. /**
  2324. * Allows to receive list of available cameras/microphones.
  2325. * @param {function} callback would receive array of devices as an argument
  2326. */
  2327. RTC.enumerateDevices = function (callback) {
  2328. RTCUtils.enumerateDevices(callback);
  2329. };
  2330. RTC.setVideoSrc = function (element, src) {
  2331. RTCUtils.setVideoSrc(element, src);
  2332. };
  2333. /**
  2334. * A method to handle stopping of the stream.
  2335. * One point to handle the differences in various implementations.
  2336. * @param mediaStream MediaStream object to stop.
  2337. */
  2338. RTC.stopMediaStream = function (mediaStream) {
  2339. RTCUtils.stopMediaStream(mediaStream);
  2340. };
  2341. /**
  2342. * Returns whether the desktop sharing is enabled or not.
  2343. * @returns {boolean}
  2344. */
  2345. RTC.isDesktopSharingEnabled = function () {
  2346. return RTCUtils.isDesktopSharingEnabled();
  2347. }
  2348. RTC.prototype.getVideoElementName = function () {
  2349. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2350. };
  2351. RTC.prototype.dispose = function() {
  2352. };
  2353. RTC.prototype.switchVideoStreams = function (newStream) {
  2354. this.localVideo.stream = newStream;
  2355. this.localStreams = [];
  2356. //in firefox we have only one stream object
  2357. if (this.localAudio.getOriginalStream() != newStream)
  2358. this.localStreams.push(this.localAudio);
  2359. this.localStreams.push(this.localVideo);
  2360. };
  2361. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2362. if(!jid)
  2363. return;
  2364. var resource = Strophe.getResourceFromJid(jid);
  2365. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2366. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2367. }
  2368. module.exports = RTC;
  2369. },{"../../service/RTC/MediaStreamTypes":130,"../../service/RTC/RTCEvents.js":131,"../../service/desktopsharing/DesktopSharingEventTypes":134,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":51}],17:[function(require,module,exports){
  2370. var currentBrowser;
  2371. var browserVersion;
  2372. var isAndroid;
  2373. var RTCBrowserType = {
  2374. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2375. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2376. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2377. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2378. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2379. getBrowserType: function () {
  2380. return currentBrowser;
  2381. },
  2382. isChrome: function () {
  2383. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2384. },
  2385. isOpera: function () {
  2386. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2387. },
  2388. isFirefox: function () {
  2389. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2390. },
  2391. isIExplorer: function () {
  2392. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2393. },
  2394. isSafari: function () {
  2395. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2396. },
  2397. isTemasysPluginUsed: function () {
  2398. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2399. },
  2400. getFirefoxVersion: function () {
  2401. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2402. },
  2403. getChromeVersion: function () {
  2404. return RTCBrowserType.isChrome() ? browserVersion : null;
  2405. },
  2406. usesPlanB: function() {
  2407. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2408. RTCBrowserType.isTemasysPluginUsed();
  2409. },
  2410. usesUnifiedPlan: function() {
  2411. return RTCBrowserType.isFirefox();
  2412. },
  2413. /**
  2414. * Whether the browser is running on an android device.
  2415. */
  2416. isAndroid: function() {
  2417. return isAndroid;
  2418. }
  2419. // Add version getters for other browsers when needed
  2420. };
  2421. // detectOpera() must be called before detectChrome() !!!
  2422. // otherwise Opera wil be detected as Chrome
  2423. function detectChrome() {
  2424. if (navigator.webkitGetUserMedia) {
  2425. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2426. var userAgent = navigator.userAgent.toLowerCase();
  2427. // We can assume that user agent is chrome, because it's
  2428. // enforced when 'ext' streaming method is set
  2429. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2430. console.log("This appears to be Chrome, ver: " + ver);
  2431. return ver;
  2432. }
  2433. return null;
  2434. }
  2435. function detectOpera() {
  2436. var userAgent = navigator.userAgent;
  2437. if (userAgent.match(/Opera|OPR/)) {
  2438. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2439. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2440. console.info("This appears to be Opera, ver: " + version);
  2441. return version;
  2442. }
  2443. return null;
  2444. }
  2445. function detectFirefox() {
  2446. if (navigator.mozGetUserMedia) {
  2447. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2448. var version = parseInt(
  2449. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2450. console.log('This appears to be Firefox, ver: ' + version);
  2451. return version;
  2452. }
  2453. return null;
  2454. }
  2455. function detectSafari() {
  2456. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2457. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2458. console.info("This appears to be Safari");
  2459. // FIXME detect Safari version when needed
  2460. return 1;
  2461. }
  2462. return null;
  2463. }
  2464. function detectIE() {
  2465. var version;
  2466. var ua = window.navigator.userAgent;
  2467. var msie = ua.indexOf('MSIE ');
  2468. if (msie > 0) {
  2469. // IE 10 or older => return version number
  2470. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2471. }
  2472. var trident = ua.indexOf('Trident/');
  2473. if (!version && trident > 0) {
  2474. // IE 11 => return version number
  2475. var rv = ua.indexOf('rv:');
  2476. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2477. }
  2478. var edge = ua.indexOf('Edge/');
  2479. if (!version && edge > 0) {
  2480. // IE 12 => return version number
  2481. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2482. }
  2483. if (version) {
  2484. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2485. console.info("This appears to be IExplorer, ver: " + version);
  2486. }
  2487. return version;
  2488. }
  2489. function detectBrowser() {
  2490. var version;
  2491. var detectors = [
  2492. detectOpera,
  2493. detectChrome,
  2494. detectFirefox,
  2495. detectIE,
  2496. detectSafari
  2497. ];
  2498. // Try all browser detectors
  2499. for (var i = 0; i < detectors.length; i++) {
  2500. version = detectors[i]();
  2501. if (version)
  2502. return version;
  2503. }
  2504. console.warn("Browser type defaults to Safari ver 1");
  2505. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2506. return 1;
  2507. }
  2508. browserVersion = detectBrowser();
  2509. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2510. module.exports = RTCBrowserType;
  2511. },{}],18:[function(require,module,exports){
  2512. (function (__filename){
  2513. /* global config, require, attachMediaStream, getUserMedia,
  2514. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2515. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2516. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2517. */
  2518. /* jshint -W101 */
  2519. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2520. var RTCBrowserType = require("./RTCBrowserType");
  2521. var Resolutions = require("../../service/RTC/Resolutions");
  2522. var RTCEvents = require("../../service/RTC/RTCEvents");
  2523. var AdapterJS = require("./adapter.screenshare");
  2524. var SDPUtil = require("../xmpp/SDPUtil");
  2525. var EventEmitter = require("events");
  2526. var screenObtainer = require("./ScreenObtainer");
  2527. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2528. var eventEmitter = new EventEmitter();
  2529. var devices = {
  2530. audio: true,
  2531. video: true
  2532. };
  2533. var rtcReady = false;
  2534. function setResolutionConstraints(constraints, resolution) {
  2535. var isAndroid = RTCBrowserType.isAndroid();
  2536. if (Resolutions[resolution]) {
  2537. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2538. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2539. }
  2540. else if (isAndroid) {
  2541. // FIXME can't remember if the purpose of this was to always request
  2542. // low resolution on Android ? if yes it should be moved up front
  2543. constraints.video.mandatory.minWidth = 320;
  2544. constraints.video.mandatory.minHeight = 240;
  2545. constraints.video.mandatory.maxFrameRate = 15;
  2546. }
  2547. if (constraints.video.mandatory.minWidth)
  2548. constraints.video.mandatory.maxWidth =
  2549. constraints.video.mandatory.minWidth;
  2550. if (constraints.video.mandatory.minHeight)
  2551. constraints.video.mandatory.maxHeight =
  2552. constraints.video.mandatory.minHeight;
  2553. }
  2554. /**
  2555. * @param {string[]} um required user media types
  2556. *
  2557. * @param {Object} [options={}] optional parameters
  2558. * @param {string} options.resolution
  2559. * @param {number} options.bandwidth
  2560. * @param {number} options.fps
  2561. * @param {string} options.desktopStream
  2562. * @param {string} options.cameraDeviceId
  2563. * @param {string} options.micDeviceId
  2564. * @param {bool} firefox_fake_device
  2565. */
  2566. function getConstraints(um, options) {
  2567. var constraints = {audio: false, video: false};
  2568. if (um.indexOf('video') >= 0) {
  2569. // same behaviour as true
  2570. constraints.video = { mandatory: {}, optional: [] };
  2571. if (options.cameraDeviceId) {
  2572. constraints.video.optional.push({
  2573. sourceId: options.cameraDeviceId
  2574. });
  2575. }
  2576. constraints.video.optional.push({ googLeakyBucket: true });
  2577. setResolutionConstraints(constraints, options.resolution);
  2578. }
  2579. if (um.indexOf('audio') >= 0) {
  2580. if (!RTCBrowserType.isFirefox()) {
  2581. // same behaviour as true
  2582. constraints.audio = { mandatory: {}, optional: []};
  2583. if (options.micDeviceId) {
  2584. constraints.audio.optional.push({
  2585. sourceId: options.micDeviceId
  2586. });
  2587. }
  2588. // if it is good enough for hangouts...
  2589. constraints.audio.optional.push(
  2590. {googEchoCancellation: true},
  2591. {googAutoGainControl: true},
  2592. {googNoiseSupression: true},
  2593. {googHighpassFilter: true},
  2594. {googNoisesuppression2: true},
  2595. {googEchoCancellation2: true},
  2596. {googAutoGainControl2: true}
  2597. );
  2598. } else {
  2599. if (options.micDeviceId) {
  2600. constraints.audio = {
  2601. mandatory: {},
  2602. optional: [{
  2603. sourceId: options.micDeviceId
  2604. }]};
  2605. } else {
  2606. constraints.audio = true;
  2607. }
  2608. }
  2609. }
  2610. if (um.indexOf('screen') >= 0) {
  2611. if (RTCBrowserType.isChrome()) {
  2612. constraints.video = {
  2613. mandatory: {
  2614. chromeMediaSource: "screen",
  2615. googLeakyBucket: true,
  2616. maxWidth: window.screen.width,
  2617. maxHeight: window.screen.height,
  2618. maxFrameRate: 3
  2619. },
  2620. optional: []
  2621. };
  2622. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2623. constraints.video = {
  2624. optional: [
  2625. {
  2626. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2627. }
  2628. ]
  2629. };
  2630. } else if (RTCBrowserType.isFirefox()) {
  2631. constraints.video = {
  2632. mozMediaSource: "window",
  2633. mediaSource: "window"
  2634. };
  2635. } else {
  2636. logger.error(
  2637. "'screen' WebRTC media source is supported only in Chrome" +
  2638. " and with Temasys plugin");
  2639. }
  2640. }
  2641. if (um.indexOf('desktop') >= 0) {
  2642. constraints.video = {
  2643. mandatory: {
  2644. chromeMediaSource: "desktop",
  2645. chromeMediaSourceId: options.desktopStream,
  2646. googLeakyBucket: true,
  2647. maxWidth: window.screen.width,
  2648. maxHeight: window.screen.height,
  2649. maxFrameRate: 3
  2650. },
  2651. optional: []
  2652. };
  2653. }
  2654. if (options.bandwidth) {
  2655. if (!constraints.video) {
  2656. //same behaviour as true
  2657. constraints.video = {mandatory: {}, optional: []};
  2658. }
  2659. constraints.video.optional.push({bandwidth: options.bandwidth});
  2660. }
  2661. if (options.fps) {
  2662. // for some cameras it might be necessary to request 30fps
  2663. // so they choose 30fps mjpg over 10fps yuy2
  2664. if (!constraints.video) {
  2665. // same behaviour as true;
  2666. constraints.video = {mandatory: {}, optional: []};
  2667. }
  2668. constraints.video.mandatory.minFrameRate = options.fps;
  2669. }
  2670. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2671. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2672. // this later can be a problem with some of the tests
  2673. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2674. {
  2675. // seems to be fixed now, removing this experimental fix, as having
  2676. // multiple audio tracks brake the tests
  2677. //constraints.audio = true;
  2678. constraints.fake = true;
  2679. }
  2680. return constraints;
  2681. }
  2682. function setAvailableDevices(um, available) {
  2683. if (um.indexOf("video") != -1) {
  2684. devices.video = available;
  2685. }
  2686. if (um.indexOf("audio") != -1) {
  2687. devices.audio = available;
  2688. }
  2689. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2690. }
  2691. // In case of IE we continue from 'onReady' callback
  2692. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2693. // once it is initialized.
  2694. function onReady (options, GUM) {
  2695. rtcReady = true;
  2696. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2697. screenObtainer.init(options, GUM);
  2698. }
  2699. /**
  2700. * Apply function with arguments if function exists.
  2701. * Do nothing if function not provided.
  2702. * @param {function} [fn] function to apply
  2703. * @param {Array} [args=[]] arguments for function
  2704. */
  2705. function maybeApply(fn, args) {
  2706. if (fn) {
  2707. fn.apply(null, args || []);
  2708. }
  2709. }
  2710. var getUserMediaStatus = {
  2711. initialized: false,
  2712. callbacks: []
  2713. };
  2714. /**
  2715. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2716. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2717. * @param {Function} getUserMedia native function
  2718. * @returns {Function} wrapped function
  2719. */
  2720. function wrapGetUserMedia(getUserMedia) {
  2721. return function (constraints, successCallback, errorCallback) {
  2722. getUserMedia(constraints, function (stream) {
  2723. maybeApply(successCallback, [stream]);
  2724. if (!getUserMediaStatus.initialized) {
  2725. getUserMediaStatus.initialized = true;
  2726. getUserMediaStatus.callbacks.forEach(function (callback) {
  2727. callback();
  2728. });
  2729. getUserMediaStatus.callbacks.length = 0;
  2730. }
  2731. }, function (error) {
  2732. maybeApply(errorCallback, [error]);
  2733. });
  2734. };
  2735. }
  2736. /**
  2737. * Create stub device which equals to auto selected device.
  2738. * @param {string} kind if that should be `audio` or `video` device
  2739. * @returns {Object} stub device description in `enumerateDevices` format
  2740. */
  2741. function createAutoDeviceInfo(kind) {
  2742. return {
  2743. facing: null,
  2744. label: 'Auto',
  2745. kind: kind,
  2746. deviceId: '',
  2747. groupId: null
  2748. };
  2749. }
  2750. /**
  2751. * Execute function after getUserMedia was executed at least once.
  2752. * @param {Function} callback function to execute after getUserMedia
  2753. */
  2754. function afterUserMediaInitialized(callback) {
  2755. if (getUserMediaStatus.initialized) {
  2756. callback();
  2757. } else {
  2758. getUserMediaStatus.callbacks.push(callback);
  2759. }
  2760. }
  2761. /**
  2762. * Wrapper function which makes enumerateDevices to wait
  2763. * until someone executes getUserMedia first time.
  2764. * @param {Function} enumerateDevices native function
  2765. * @returns {Funtion} wrapped function
  2766. */
  2767. function wrapEnumerateDevices(enumerateDevices) {
  2768. return function (callback) {
  2769. // enumerate devices only after initial getUserMedia
  2770. afterUserMediaInitialized(function () {
  2771. enumerateDevices().then(function (devices) {
  2772. //add auto devices
  2773. devices.unshift(
  2774. createAutoDeviceInfo('audioinput'),
  2775. createAutoDeviceInfo('videoinput')
  2776. );
  2777. callback(devices);
  2778. }, function (err) {
  2779. console.error('cannot enumerate devices: ', err);
  2780. // return only auto devices
  2781. callback([createAutoDeviceInfo('audioInput'),
  2782. createAutoDeviceInfo('videoinput')]);
  2783. });
  2784. });
  2785. };
  2786. }
  2787. /**
  2788. * Use old MediaStreamTrack to get devices list and
  2789. * convert it to enumerateDevices format.
  2790. * @param {Function} callback function to call when received devices list.
  2791. */
  2792. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2793. MediaStreamTrack.getSources(function (sources) {
  2794. var devices = sources.map(function (source) {
  2795. var kind = (source.kind || '').toLowerCase();
  2796. return {
  2797. facing: source.facing || null,
  2798. label: source.label,
  2799. kind: kind ? kind + 'input': null,
  2800. deviceId: source.id,
  2801. groupId: source.groupId || null
  2802. };
  2803. });
  2804. //add auto devices
  2805. devices.unshift(
  2806. createAutoDeviceInfo('audioinput'),
  2807. createAutoDeviceInfo('videoinput')
  2808. );
  2809. callback(devices);
  2810. });
  2811. }
  2812. function obtainDevices(options) {
  2813. if(!options.devices || options.devices.length === 0) {
  2814. return options.successCallback(options.streams || {});
  2815. }
  2816. var device = options.devices.splice(0, 1);
  2817. var devices = [];
  2818. devices.push(device);
  2819. options.deviceGUM[device](function (stream) {
  2820. options.streams = options.streams || {};
  2821. options.streams[device] = stream;
  2822. obtainDevices(options);
  2823. },
  2824. function (error) {
  2825. Object.keys(options.streams).forEach(function(device) {
  2826. RTCUtils.stopMediaStream(options.streams[device]);
  2827. });
  2828. logger.error(
  2829. "failed to obtain " + device + " stream - stop", error);
  2830. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2831. });
  2832. }
  2833. /**
  2834. * Handles the newly created Media Streams.
  2835. * @param streams the new Media Streams
  2836. * @param resolution the resolution of the video streams
  2837. * @returns {*[]} object that describes the new streams
  2838. */
  2839. function handleLocalStream(streams, resolution) {
  2840. var audioStream, videoStream, desktopStream, res = [];
  2841. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2842. // an object with two properties: audioStream, videoStream.
  2843. if (window.webkitMediaStream) {
  2844. var audioVideo = streams.audioVideo;
  2845. if (audioVideo) {
  2846. var audioTracks = audioVideo.getAudioTracks();
  2847. if(audioTracks.length) {
  2848. audioStream = new webkitMediaStream();
  2849. for (var i = 0; i < audioTracks.length; i++) {
  2850. audioStream.addTrack(audioTracks[i]);
  2851. }
  2852. }
  2853. var videoTracks = audioVideo.getVideoTracks();
  2854. if(videoTracks.length) {
  2855. videoStream = new webkitMediaStream();
  2856. for (var j = 0; j < videoTracks.length; j++) {
  2857. videoStream.addTrack(videoTracks[j]);
  2858. }
  2859. }
  2860. }
  2861. if (streams && streams.desktopStream)
  2862. desktopStream = streams.desktopStream;
  2863. }
  2864. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2865. if (streams && streams.audio)
  2866. audioStream = streams.audio;
  2867. if (streams && streams.video)
  2868. videoStream = streams.video;
  2869. if(streams && streams.desktop)
  2870. desktopStream = streams.desktop;
  2871. }
  2872. if (desktopStream)
  2873. res.push({stream: desktopStream,
  2874. type: "video", videoType: "desktop"});
  2875. if(audioStream)
  2876. res.push({stream: audioStream, type: "audio", videoType: null});
  2877. if(videoStream)
  2878. res.push({stream: videoStream, type: "video", videoType: "camera",
  2879. resolution: resolution});
  2880. return res;
  2881. }
  2882. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2883. var RTCUtils = {
  2884. init: function (options) {
  2885. return new Promise(function(resolve, reject) {
  2886. if (RTCBrowserType.isFirefox()) {
  2887. var FFversion = RTCBrowserType.getFirefoxVersion();
  2888. if (FFversion < 40) {
  2889. logger.error(
  2890. "Firefox version too old: " + FFversion +
  2891. ". Required >= 40.");
  2892. reject(new Error("Firefox version too old: " + FFversion +
  2893. ". Required >= 40."));
  2894. return;
  2895. }
  2896. this.peerconnection = mozRTCPeerConnection;
  2897. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  2898. this.enumerateDevices = wrapEnumerateDevices(
  2899. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2900. );
  2901. this.pc_constraints = {};
  2902. this.attachMediaStream = function (element, stream) {
  2903. // srcObject is being standardized and FF will eventually
  2904. // support that unprefixed. FF also supports the
  2905. // "element.src = URL.createObjectURL(...)" combo, but that
  2906. // will be deprecated in favour of srcObject.
  2907. //
  2908. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  2909. // https://github.com/webrtc/samples/issues/302
  2910. if (!element[0])
  2911. return;
  2912. element[0].mozSrcObject = stream;
  2913. element[0].play();
  2914. };
  2915. this.getStreamID = function (stream) {
  2916. var id = stream.id;
  2917. if (!id) {
  2918. var tracks = stream.getVideoTracks();
  2919. if (!tracks || tracks.length === 0) {
  2920. tracks = stream.getAudioTracks();
  2921. }
  2922. id = tracks[0].id;
  2923. }
  2924. return SDPUtil.filter_special_chars(id);
  2925. };
  2926. this.getVideoSrc = function (element) {
  2927. if (!element)
  2928. return null;
  2929. return element.mozSrcObject;
  2930. };
  2931. this.setVideoSrc = function (element, src) {
  2932. if (element)
  2933. element.mozSrcObject = src;
  2934. };
  2935. RTCSessionDescription = mozRTCSessionDescription;
  2936. RTCIceCandidate = mozRTCIceCandidate;
  2937. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  2938. this.peerconnection = webkitRTCPeerConnection;
  2939. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2940. if (navigator.mediaDevices) {
  2941. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  2942. this.enumerateDevices = wrapEnumerateDevices(
  2943. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  2944. );
  2945. } else {
  2946. this.getUserMedia = getUserMedia;
  2947. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  2948. }
  2949. this.attachMediaStream = function (element, stream) {
  2950. // saves the created url for the stream, so we can reuse it
  2951. // and not keep creating urls
  2952. if (!stream.jitsiObjectURL) {
  2953. stream.jitsiObjectURL
  2954. = webkitURL.createObjectURL(stream);
  2955. }
  2956. element.attr('src', stream.jitsiObjectURL);
  2957. };
  2958. this.getStreamID = function (stream) {
  2959. // streams from FF endpoints have the characters '{' and '}'
  2960. // that make jQuery choke.
  2961. return SDPUtil.filter_special_chars(stream.id);
  2962. };
  2963. this.getVideoSrc = function (element) {
  2964. if (!element)
  2965. return null;
  2966. return element.getAttribute("src");
  2967. };
  2968. this.setVideoSrc = function (element, src) {
  2969. if (element)
  2970. element.setAttribute("src", src);
  2971. };
  2972. // DTLS should now be enabled by default but..
  2973. this.pc_constraints = {'optional': [
  2974. {'DtlsSrtpKeyAgreement': 'true'}
  2975. ]};
  2976. if (options.useIPv6) {
  2977. // https://code.google.com/p/webrtc/issues/detail?id=2828
  2978. this.pc_constraints.optional.push({googIPv6: true});
  2979. }
  2980. if (RTCBrowserType.isAndroid()) {
  2981. this.pc_constraints = {}; // disable DTLS on Android
  2982. }
  2983. if (!webkitMediaStream.prototype.getVideoTracks) {
  2984. webkitMediaStream.prototype.getVideoTracks = function () {
  2985. return this.videoTracks;
  2986. };
  2987. }
  2988. if (!webkitMediaStream.prototype.getAudioTracks) {
  2989. webkitMediaStream.prototype.getAudioTracks = function () {
  2990. return this.audioTracks;
  2991. };
  2992. }
  2993. }
  2994. // Detect IE/Safari
  2995. else if (RTCBrowserType.isTemasysPluginUsed()) {
  2996. //AdapterJS.WebRTCPlugin.setLogLevel(
  2997. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  2998. var self = this;
  2999. AdapterJS.webRTCReady(function (isPlugin) {
  3000. self.peerconnection = RTCPeerConnection;
  3001. self.getUserMedia = window.getUserMedia;
  3002. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3003. self.attachMediaStream = function (elSel, stream) {
  3004. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  3005. return;
  3006. }
  3007. attachMediaStream(elSel[0], stream);
  3008. };
  3009. self.getStreamID = function (stream) {
  3010. var id = SDPUtil.filter_special_chars(stream.label);
  3011. return id;
  3012. };
  3013. self.getVideoSrc = function (element) {
  3014. if (!element) {
  3015. logger.warn("Attempt to get video SRC of null element");
  3016. return null;
  3017. }
  3018. var children = element.children;
  3019. for (var i = 0; i !== children.length; ++i) {
  3020. if (children[i].name === 'streamId') {
  3021. return children[i].value;
  3022. }
  3023. }
  3024. //logger.info(element.id + " SRC: " + src);
  3025. return null;
  3026. };
  3027. self.setVideoSrc = function (element, src) {
  3028. //logger.info("Set video src: ", element, src);
  3029. if (!src) {
  3030. logger.warn("Not attaching video stream, 'src' is null");
  3031. return;
  3032. }
  3033. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3034. var stream = AdapterJS.WebRTCPlugin.plugin
  3035. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  3036. attachMediaStream(element, stream);
  3037. };
  3038. onReady(options, self.getUserMediaWithConstraints);
  3039. resolve();
  3040. });
  3041. } else {
  3042. try {
  3043. logger.error('Browser does not appear to be WebRTC-capable');
  3044. } catch (e) {
  3045. }
  3046. reject('Browser does not appear to be WebRTC-capable');
  3047. return;
  3048. }
  3049. // Call onReady() if Temasys plugin is not used
  3050. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3051. onReady(options, this.getUserMediaWithConstraints);
  3052. resolve();
  3053. }
  3054. }.bind(this));
  3055. },
  3056. /**
  3057. * @param {string[]} um required user media types
  3058. * @param {function} success_callback
  3059. * @param {Function} failure_callback
  3060. * @param {Object} [options] optional parameters
  3061. * @param {string} options.resolution
  3062. * @param {number} options.bandwidth
  3063. * @param {number} options.fps
  3064. * @param {string} options.desktopStream
  3065. * @param {string} options.cameraDeviceId
  3066. * @param {string} options.micDeviceId
  3067. **/
  3068. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3069. options = options || {};
  3070. var resolution = options.resolution;
  3071. var constraints = getConstraints(um, options);
  3072. logger.info("Get media constraints", constraints);
  3073. try {
  3074. this.getUserMedia(constraints,
  3075. function (stream) {
  3076. logger.log('onUserMediaSuccess');
  3077. setAvailableDevices(um, true);
  3078. success_callback(stream);
  3079. },
  3080. function (error) {
  3081. setAvailableDevices(um, false);
  3082. logger.warn('Failed to get access to local media. Error ',
  3083. error, constraints);
  3084. if (failure_callback) {
  3085. failure_callback(error, resolution);
  3086. }
  3087. });
  3088. } catch (e) {
  3089. logger.error('GUM failed: ', e);
  3090. if (failure_callback) {
  3091. failure_callback(e);
  3092. }
  3093. }
  3094. },
  3095. /**
  3096. * Creates the local MediaStreams.
  3097. * @param {Object} [options] optional parameters
  3098. * @param {Array} options.devices the devices that will be requested
  3099. * @param {string} options.resolution resolution constraints
  3100. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3101. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3102. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3103. * @param {string} options.cameraDeviceId
  3104. * @param {string} options.micDeviceId
  3105. * @returns {*} Promise object that will receive the new JitsiTracks
  3106. */
  3107. obtainAudioAndVideoPermissions: function (options) {
  3108. var self = this;
  3109. options = options || {};
  3110. return new Promise(function (resolve, reject) {
  3111. var successCallback = function (stream) {
  3112. resolve(handleLocalStream(stream, options.resolution));
  3113. };
  3114. options.devices = options.devices || ['audio', 'video'];
  3115. if(!screenObtainer.isSupported()
  3116. && options.devices.indexOf("desktop") !== -1){
  3117. reject(new Error("Desktop sharing is not supported!"));
  3118. }
  3119. if (RTCBrowserType.isFirefox() ||
  3120. RTCBrowserType.isTemasysPluginUsed()) {
  3121. var GUM = function (device, s, e) {
  3122. this.getUserMediaWithConstraints(device, s, e, options);
  3123. };
  3124. var deviceGUM = {
  3125. "audio": GUM.bind(self, ["audio"]),
  3126. "video": GUM.bind(self, ["video"])
  3127. };
  3128. if(screenObtainer.isSupported()){
  3129. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3130. screenObtainer);
  3131. }
  3132. // With FF/IE we can't split the stream into audio and video because FF
  3133. // doesn't support media stream constructors. So, we need to get the
  3134. // audio stream separately from the video stream using two distinct GUM
  3135. // calls. Not very user friendly :-( but we don't have many other
  3136. // options neither.
  3137. //
  3138. // Note that we pack those 2 streams in a single object and pass it to
  3139. // the successCallback method.
  3140. obtainDevices({
  3141. devices: options.devices,
  3142. streams: [],
  3143. successCallback: successCallback,
  3144. errorCallback: reject,
  3145. deviceGUM: deviceGUM
  3146. });
  3147. } else {
  3148. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3149. if (hasDesktop) {
  3150. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3151. }
  3152. options.resolution = options.resolution || '360';
  3153. if(options.devices.length) {
  3154. this.getUserMediaWithConstraints(
  3155. options.devices,
  3156. function (stream) {
  3157. if((options.devices.indexOf("audio") !== -1 &&
  3158. !stream.getAudioTracks().length) ||
  3159. (options.devices.indexOf("video") !== -1 &&
  3160. !stream.getVideoTracks().length))
  3161. {
  3162. self.stopMediaStream(stream);
  3163. reject(JitsiTrackErrors.parseError(
  3164. new Error("Unable to get the audio and " +
  3165. "video tracks."),
  3166. options.devices));
  3167. return;
  3168. }
  3169. if(hasDesktop) {
  3170. screenObtainer.obtainStream(
  3171. function (desktopStream) {
  3172. successCallback({audioVideo: stream,
  3173. desktopStream: desktopStream});
  3174. }, function (error) {
  3175. self.stopMediaStream(stream);
  3176. reject(
  3177. JitsiTrackErrors.parseError(error,
  3178. options.devices));
  3179. });
  3180. } else {
  3181. successCallback({audioVideo: stream});
  3182. }
  3183. },
  3184. function (error) {
  3185. reject(JitsiTrackErrors.parseError(error,
  3186. options.devices));
  3187. },
  3188. options);
  3189. } else if (hasDesktop) {
  3190. screenObtainer.obtainStream(
  3191. function (stream) {
  3192. successCallback({desktopStream: stream});
  3193. }, function (error) {
  3194. reject(
  3195. JitsiTrackErrors.parseError(error,
  3196. ["desktop"]));
  3197. });
  3198. }
  3199. }
  3200. }.bind(this));
  3201. },
  3202. addListener: function (eventType, listener) {
  3203. eventEmitter.on(eventType, listener);
  3204. },
  3205. removeListener: function (eventType, listener) {
  3206. eventEmitter.removeListener(eventType, listener);
  3207. },
  3208. getDeviceAvailability: function () {
  3209. return devices;
  3210. },
  3211. isRTCReady: function () {
  3212. return rtcReady;
  3213. },
  3214. /**
  3215. * Checks if its possible to enumerate available cameras/micropones.
  3216. * @returns {boolean} true if available, false otherwise.
  3217. */
  3218. isDeviceListAvailable: function () {
  3219. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3220. if (isEnumerateDevicesAvailable) {
  3221. return true;
  3222. }
  3223. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3224. },
  3225. /**
  3226. * Returns true if changing the camera / microphone device is supported and
  3227. * false if not.
  3228. */
  3229. isDeviceChangeAvailable: function () {
  3230. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3231. RTCBrowserType.isTemasysPluginUsed())
  3232. return true;
  3233. return false;
  3234. },
  3235. /**
  3236. * A method to handle stopping of the stream.
  3237. * One point to handle the differences in various implementations.
  3238. * @param mediaStream MediaStream object to stop.
  3239. */
  3240. stopMediaStream: function (mediaStream) {
  3241. mediaStream.getTracks().forEach(function (track) {
  3242. // stop() not supported with IE
  3243. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3244. track.stop();
  3245. }
  3246. });
  3247. // leave stop for implementation still using it
  3248. if (mediaStream.stop) {
  3249. mediaStream.stop();
  3250. }
  3251. // if we have done createObjectURL, lets clean it
  3252. if (mediaStream.jitsiObjectURL) {
  3253. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3254. }
  3255. },
  3256. /**
  3257. * Returns whether the desktop sharing is enabled or not.
  3258. * @returns {boolean}
  3259. */
  3260. isDesktopSharingEnabled: function () {
  3261. return screenObtainer.isSupported();
  3262. }
  3263. };
  3264. module.exports = RTCUtils;
  3265. }).call(this,"/modules/RTC/RTCUtils.js")
  3266. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":131,"../../service/RTC/Resolutions":132,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":51,"jitsi-meet-logger":79}],19:[function(require,module,exports){
  3267. (function (__filename){
  3268. /* global chrome, $, alert */
  3269. /* jshint -W003 */
  3270. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3271. var RTCBrowserType = require("./RTCBrowserType");
  3272. var AdapterJS = require("./adapter.screenshare");
  3273. var DesktopSharingEventTypes
  3274. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3275. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3276. /**
  3277. * Indicates whether the Chrome desktop sharing extension is installed.
  3278. * @type {boolean}
  3279. */
  3280. var chromeExtInstalled = false;
  3281. /**
  3282. * Indicates whether an update of the Chrome desktop sharing extension is
  3283. * required.
  3284. * @type {boolean}
  3285. */
  3286. var chromeExtUpdateRequired = false;
  3287. /**
  3288. * Whether the jidesha extension for firefox is installed for the domain on
  3289. * which we are running. Null designates an unknown value.
  3290. * @type {null}
  3291. */
  3292. var firefoxExtInstalled = null;
  3293. /**
  3294. * If set to true, detection of an installed firefox extension will be started
  3295. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3296. * user tries to enable screen sharing).
  3297. */
  3298. var reDetectFirefoxExtension = false;
  3299. var GUM = null;
  3300. /**
  3301. * Handles obtaining a stream from a screen capture on different browsers.
  3302. */
  3303. var ScreenObtainer = {
  3304. obtainStream: null,
  3305. /**
  3306. * Initializes the function used to obtain a screen capture
  3307. * (this.obtainStream).
  3308. *
  3309. * If the browser is Chrome, it uses the value of
  3310. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3311. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3312. * use the "screen" media source (if the value is 'webrtc'),
  3313. * or disable screen capture (if the value is other).
  3314. * Note that for the "screen" media source to work the
  3315. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3316. */
  3317. init: function(options, gum) {
  3318. var obtainDesktopStream = null;
  3319. this.options = options = options || {};
  3320. GUM = gum;
  3321. if (RTCBrowserType.isFirefox())
  3322. initFirefoxExtensionDetection(options);
  3323. // TODO remove this, options.desktopSharing is deprecated.
  3324. var chromeMethod =
  3325. (options.desktopSharingChromeMethod || options.desktopSharing);
  3326. if (RTCBrowserType.isTemasysPluginUsed()) {
  3327. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3328. logger.info("Screensharing not supported by this plugin " +
  3329. "version");
  3330. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3331. logger.info(
  3332. "Screensharing not available with Temasys plugin on" +
  3333. " this site");
  3334. } else {
  3335. obtainDesktopStream = obtainWebRTCScreen;
  3336. logger.info("Using Temasys plugin for desktop sharing");
  3337. }
  3338. } else if (RTCBrowserType.isChrome()) {
  3339. if (chromeMethod == "ext") {
  3340. if (RTCBrowserType.getChromeVersion() >= 34) {
  3341. obtainDesktopStream =
  3342. this.obtainScreenFromExtension;
  3343. logger.info("Using Chrome extension for desktop sharing");
  3344. initChromeExtension(options);
  3345. } else {
  3346. logger.info("Chrome extension not supported until ver 34");
  3347. }
  3348. } else if (chromeMethod == "webrtc") {
  3349. obtainDesktopStream = obtainWebRTCScreen;
  3350. logger.info("Using Chrome WebRTC for desktop sharing");
  3351. }
  3352. } else if (RTCBrowserType.isFirefox()) {
  3353. if (options.desktopSharingFirefoxDisabled) {
  3354. obtainDesktopStream = null;
  3355. } else if (window.location.protocol === "http:"){
  3356. logger.log("Screen sharing is not supported over HTTP. " +
  3357. "Use of HTTPS is required.");
  3358. obtainDesktopStream = null;
  3359. } else {
  3360. obtainDesktopStream = this.obtainScreenOnFirefox;
  3361. }
  3362. }
  3363. if (!obtainDesktopStream) {
  3364. logger.info("Desktop sharing disabled");
  3365. }
  3366. this.obtainStream = obtainDesktopStream;
  3367. },
  3368. /**
  3369. * Checks whether obtaining a screen capture is supported in the current
  3370. * environment.
  3371. * @returns {boolean}
  3372. */
  3373. isSupported: function() {
  3374. return !!this.obtainStream;
  3375. },
  3376. /**
  3377. * Obtains a screen capture stream on Firefox.
  3378. * @param callback
  3379. * @param errorCallback
  3380. */
  3381. obtainScreenOnFirefox:
  3382. function (callback, errorCallback) {
  3383. var self = this;
  3384. var extensionRequired = false;
  3385. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3386. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3387. RTCBrowserType.getFirefoxVersion() <=
  3388. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3389. extensionRequired = true;
  3390. logger.log("Jidesha extension required on firefox version " +
  3391. RTCBrowserType.getFirefoxVersion());
  3392. }
  3393. if (!extensionRequired || firefoxExtInstalled === true) {
  3394. obtainWebRTCScreen(callback, errorCallback);
  3395. return;
  3396. }
  3397. if (reDetectFirefoxExtension) {
  3398. reDetectFirefoxExtension = false;
  3399. initFirefoxExtensionDetection(this.options);
  3400. }
  3401. // Give it some (more) time to initialize, and assume lack of
  3402. // extension if it hasn't.
  3403. if (firefoxExtInstalled === null) {
  3404. window.setTimeout(
  3405. function() {
  3406. if (firefoxExtInstalled === null)
  3407. firefoxExtInstalled = false;
  3408. self.obtainScreenOnFirefox(callback, errorCallback);
  3409. },
  3410. 300
  3411. );
  3412. logger.log("Waiting for detection of jidesha on firefox to " +
  3413. "finish.");
  3414. return;
  3415. }
  3416. // We need an extension and it isn't installed.
  3417. // Make sure we check for the extension when the user clicks again.
  3418. firefoxExtInstalled = null;
  3419. reDetectFirefoxExtension = true;
  3420. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3421. // stuck in 'switching' mode.
  3422. errorCallback({
  3423. type: "jitsiError",
  3424. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3425. });
  3426. },
  3427. /**
  3428. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3429. * 'desktop' stream for returned stream token.
  3430. */
  3431. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3432. var self = this;
  3433. if (chromeExtInstalled) {
  3434. doGetStreamFromExtension(this.options, streamCallback,
  3435. failCallback);
  3436. } else {
  3437. if (chromeExtUpdateRequired) {
  3438. alert(
  3439. 'Jitsi Desktop Streamer requires update. ' +
  3440. 'Changes will take effect after next Chrome restart.');
  3441. }
  3442. chrome.webstore.install(
  3443. getWebStoreInstallUrl(this.options),
  3444. function (arg) {
  3445. logger.log("Extension installed successfully", arg);
  3446. chromeExtInstalled = true;
  3447. // We need to give a moment for the endpoint to become
  3448. // available
  3449. window.setTimeout(function () {
  3450. doGetStreamFromExtension(self.options, streamCallback,
  3451. failCallback);
  3452. }, 500);
  3453. },
  3454. function (arg) {
  3455. logger.log("Failed to install the extension", arg);
  3456. failCallback(arg);
  3457. }
  3458. );
  3459. }
  3460. }
  3461. };
  3462. /**
  3463. * Obtains a desktop stream using getUserMedia.
  3464. * For this to work on Chrome, the
  3465. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3466. *
  3467. * On firefox, the document's domain must be white-listed in the
  3468. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3469. * 'about:config'.
  3470. */
  3471. function obtainWebRTCScreen(streamCallback, failCallback) {
  3472. GUM(
  3473. ['screen'],
  3474. streamCallback,
  3475. failCallback
  3476. );
  3477. }
  3478. /**
  3479. * Constructs inline install URL for Chrome desktop streaming extension.
  3480. * The 'chromeExtensionId' must be defined in options parameter.
  3481. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3482. * @returns {string}
  3483. */
  3484. function getWebStoreInstallUrl(options)
  3485. {
  3486. //TODO remove chromeExtensionId (deprecated)
  3487. return "https://chrome.google.com/webstore/detail/" +
  3488. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3489. }
  3490. /**
  3491. * Checks whether an update of the Chrome extension is required.
  3492. * @param minVersion minimal required version
  3493. * @param extVersion current extension version
  3494. * @returns {boolean}
  3495. */
  3496. function isUpdateRequired(minVersion, extVersion) {
  3497. try {
  3498. var s1 = minVersion.split('.');
  3499. var s2 = extVersion.split('.');
  3500. var len = Math.max(s1.length, s2.length);
  3501. for (var i = 0; i < len; i++) {
  3502. var n1 = 0,
  3503. n2 = 0;
  3504. if (i < s1.length)
  3505. n1 = parseInt(s1[i]);
  3506. if (i < s2.length)
  3507. n2 = parseInt(s2[i]);
  3508. if (isNaN(n1) || isNaN(n2)) {
  3509. return true;
  3510. } else if (n1 !== n2) {
  3511. return n1 > n2;
  3512. }
  3513. }
  3514. // will happen if both versions have identical numbers in
  3515. // their components (even if one of them is longer, has more components)
  3516. return false;
  3517. }
  3518. catch (e) {
  3519. logger.error("Failed to parse extension version", e);
  3520. return true;
  3521. }
  3522. }
  3523. function checkChromeExtInstalled(callback, options) {
  3524. if (!chrome || !chrome.runtime) {
  3525. // No API, so no extension for sure
  3526. callback(false, false);
  3527. return;
  3528. }
  3529. chrome.runtime.sendMessage(
  3530. //TODO: remove chromeExtensionId (deprecated)
  3531. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3532. { getVersion: true },
  3533. function (response) {
  3534. if (!response || !response.version) {
  3535. // Communication failure - assume that no endpoint exists
  3536. logger.warn(
  3537. "Extension not installed?: ", chrome.runtime.lastError);
  3538. callback(false, false);
  3539. return;
  3540. }
  3541. // Check installed extension version
  3542. var extVersion = response.version;
  3543. logger.log('Extension version is: ' + extVersion);
  3544. //TODO: remove minChromeExtVersion (deprecated)
  3545. var updateRequired
  3546. = isUpdateRequired(
  3547. (options.desktopSharingChromeMinExtVersion ||
  3548. options.minChromeExtVersion),
  3549. extVersion);
  3550. callback(!updateRequired, updateRequired);
  3551. }
  3552. );
  3553. }
  3554. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3555. // Sends 'getStream' msg to the extension.
  3556. // Extension id must be defined in the config.
  3557. chrome.runtime.sendMessage(
  3558. //TODO: remove chromeExtensionId (deprecated)
  3559. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3560. {
  3561. getStream: true,
  3562. //TODO: remove desktopSharingSources (deprecated).
  3563. sources: (options.desktopSharingChromeSources ||
  3564. options.desktopSharingSources)
  3565. },
  3566. function (response) {
  3567. if (!response) {
  3568. failCallback(chrome.runtime.lastError);
  3569. return;
  3570. }
  3571. logger.log("Response from extension: " + response);
  3572. if (response.streamId) {
  3573. GUM(
  3574. ['desktop'],
  3575. function (stream) {
  3576. streamCallback(stream);
  3577. },
  3578. failCallback,
  3579. {desktopStream: response.streamId});
  3580. } else {
  3581. failCallback("Extension failed to get the stream");
  3582. }
  3583. }
  3584. );
  3585. }
  3586. /**
  3587. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3588. * config.js to support inline installs. Host site must be selected as main
  3589. * website of published extension.
  3590. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3591. */
  3592. function initInlineInstalls(options)
  3593. {
  3594. $("link[rel=chrome-webstore-item]").attr("href",
  3595. getWebStoreInstallUrl(options));
  3596. }
  3597. function initChromeExtension(options) {
  3598. // Initialize Chrome extension inline installs
  3599. initInlineInstalls(options);
  3600. // Check if extension is installed
  3601. checkChromeExtInstalled(function (installed, updateRequired) {
  3602. chromeExtInstalled = installed;
  3603. chromeExtUpdateRequired = updateRequired;
  3604. logger.info(
  3605. "Chrome extension installed: " + chromeExtInstalled +
  3606. " updateRequired: " + chromeExtUpdateRequired);
  3607. }, options);
  3608. }
  3609. /**
  3610. * Starts the detection of an installed jidesha extension for firefox.
  3611. * @param options supports "desktopSharingFirefoxDisabled",
  3612. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3613. */
  3614. function initFirefoxExtensionDetection(options) {
  3615. if (options.desktopSharingFirefoxDisabled) {
  3616. return;
  3617. }
  3618. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3619. return;
  3620. if (!options.desktopSharingFirefoxExtId) {
  3621. firefoxExtInstalled = false;
  3622. return;
  3623. }
  3624. var img = document.createElement('img');
  3625. img.onload = function(){
  3626. logger.log("Detected firefox screen sharing extension.");
  3627. firefoxExtInstalled = true;
  3628. };
  3629. img.onerror = function(){
  3630. logger.log("Detected lack of firefox screen sharing extension.");
  3631. firefoxExtInstalled = false;
  3632. };
  3633. // The jidesha extension exposes an empty image file under the url:
  3634. // "chrome://EXT_ID/content/DOMAIN.png"
  3635. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3636. // DOMAIN is a domain whitelisted by the extension.
  3637. var src = "chrome://" +
  3638. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3639. "/content/" + document.location.hostname + ".png";
  3640. img.setAttribute('src', src);
  3641. }
  3642. module.exports = ScreenObtainer;
  3643. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3644. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":134,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":79}],20:[function(require,module,exports){
  3645. (function (__filename){
  3646. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3647. var console = require("jitsi-meet-logger").getLogger(__filename);
  3648. // Adapter's interface.
  3649. var AdapterJS = AdapterJS || {};
  3650. // Browserify compatibility
  3651. if(typeof exports !== 'undefined') {
  3652. module.exports = AdapterJS;
  3653. }
  3654. AdapterJS.options = AdapterJS.options || {};
  3655. // uncomment to get virtual webcams
  3656. // AdapterJS.options.getAllCams = true;
  3657. // uncomment to prevent the install prompt when the plugin in not yet installed
  3658. // AdapterJS.options.hidePluginInstallPrompt = true;
  3659. // AdapterJS version
  3660. AdapterJS.VERSION = '0.12.3';
  3661. // This function will be called when the WebRTC API is ready to be used
  3662. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3663. // the plugin
  3664. // You may Override this function to synchronise the start of your application
  3665. // with the WebRTC API being ready.
  3666. // If you decide not to override use this synchronisation, it may result in
  3667. // an extensive CPU usage on the plugin start (once per tab loaded)
  3668. // Params:
  3669. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3670. //
  3671. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3672. // The WebRTC API is ready.
  3673. // Override me and do whatever you want here
  3674. };
  3675. // Sets a callback function to be called when the WebRTC interface is ready.
  3676. // The first argument is the function to callback.\
  3677. // Throws an error if the first argument is not a function
  3678. AdapterJS.webRTCReady = function (callback) {
  3679. if (typeof callback !== 'function') {
  3680. throw new Error('Callback provided is not a function');
  3681. }
  3682. if (true === AdapterJS.onwebrtcreadyDone) {
  3683. // All WebRTC interfaces are ready, just call the callback
  3684. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3685. } else {
  3686. // will be triggered automatically when your browser/plugin is ready.
  3687. AdapterJS.onwebrtcready = callback;
  3688. }
  3689. };
  3690. // Plugin namespace
  3691. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3692. // The object to store plugin information
  3693. AdapterJS.WebRTCPlugin.pluginInfo = {
  3694. prefix : 'Tem',
  3695. plugName : 'TemWebRTCPlugin',
  3696. pluginId : 'plugin0',
  3697. type : 'application/x-temwebrtcplugin',
  3698. onload : '__TemWebRTCReady0',
  3699. portalLink : 'http://skylink.io/plugin/',
  3700. downloadLink : null, //set below
  3701. companyName: 'Temasys'
  3702. };
  3703. if(!!navigator.platform.match(/^Mac/i)) {
  3704. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3705. }
  3706. else if(!!navigator.platform.match(/^Win/i)) {
  3707. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3708. }
  3709. AdapterJS.WebRTCPlugin.TAGS = {
  3710. NONE : 'none',
  3711. AUDIO : 'audio',
  3712. VIDEO : 'video'
  3713. };
  3714. // Unique identifier of each opened page
  3715. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3716. // Use this whenever you want to call the plugin.
  3717. AdapterJS.WebRTCPlugin.plugin = null;
  3718. // Set log level for the plugin once it is ready.
  3719. // The different values are
  3720. // This is an asynchronous function that will run when the plugin is ready
  3721. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3722. // Defines webrtc's JS interface according to the plugin's implementation.
  3723. // Define plugin Browsers as WebRTC Interface.
  3724. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3725. // This function detects whether or not a plugin is installed.
  3726. // Checks if Not IE (firefox, for example), else if it's IE,
  3727. // we're running IE and do something. If not it is not supported.
  3728. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3729. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3730. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3731. // Inject the HTML DOM object element into the page.
  3732. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3733. // States of readiness that the plugin goes through when
  3734. // being injected and stated
  3735. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3736. NONE : 0, // no plugin use
  3737. INITIALIZING : 1, // Detected need for plugin
  3738. INJECTING : 2, // Injecting plugin
  3739. INJECTED: 3, // Plugin element injected but not usable yet
  3740. READY: 4 // Plugin ready to be used
  3741. };
  3742. // Current state of the plugin. You cannot use the plugin before this is
  3743. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3744. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3745. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3746. // Used to make sure AdapterJS.onwebrtcready is only called once
  3747. AdapterJS.onwebrtcreadyDone = false;
  3748. // Log levels for the plugin.
  3749. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3750. /*
  3751. Log outputs are prefixed in some cases.
  3752. INFO: Information reported by the plugin.
  3753. ERROR: Errors originating from within the plugin.
  3754. WEBRTC: Error originating from within the libWebRTC library
  3755. */
  3756. // From the least verbose to the most verbose
  3757. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3758. NONE : 'NONE',
  3759. ERROR : 'ERROR',
  3760. WARNING : 'WARNING',
  3761. INFO: 'INFO',
  3762. VERBOSE: 'VERBOSE',
  3763. SENSITIVE: 'SENSITIVE'
  3764. };
  3765. // Does a waiting check before proceeding to load the plugin.
  3766. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3767. // This methid will use an interval to wait for the plugin to be ready.
  3768. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3769. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3770. // This function will be called when plugin is ready. It sends necessary
  3771. // details to the plugin.
  3772. // The function will wait for the document to be ready and the set the
  3773. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3774. // indicating that it can start being requested.
  3775. // This function is not in the IE/Safari condition brackets so that
  3776. // TemPluginLoaded function might be called on Chrome/Firefox.
  3777. // This function is the only private function that is not encapsulated to
  3778. // allow the plugin method to be called.
  3779. __TemWebRTCReady0 = function () {
  3780. if (document.readyState === 'complete') {
  3781. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3782. AdapterJS.maybeThroughWebRTCReady();
  3783. } else {
  3784. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3785. if (document.readyState === 'complete') {
  3786. // TODO: update comments, we wait for the document to be ready
  3787. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3788. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3789. AdapterJS.maybeThroughWebRTCReady();
  3790. }
  3791. }, 100);
  3792. }
  3793. };
  3794. AdapterJS.maybeThroughWebRTCReady = function() {
  3795. if (!AdapterJS.onwebrtcreadyDone) {
  3796. AdapterJS.onwebrtcreadyDone = true;
  3797. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3798. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3799. }
  3800. }
  3801. };
  3802. // Text namespace
  3803. AdapterJS.TEXT = {
  3804. PLUGIN: {
  3805. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3806. 'to work on this browser.',
  3807. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3808. BUTTON: 'Install Now'
  3809. },
  3810. REFRESH: {
  3811. REQUIRE_REFRESH: 'Please refresh page',
  3812. BUTTON: 'Refresh Page'
  3813. }
  3814. };
  3815. // The result of ice connection states.
  3816. // - starting: Ice connection is starting.
  3817. // - checking: Ice connection is checking.
  3818. // - connected Ice connection is connected.
  3819. // - completed Ice connection is connected.
  3820. // - done Ice connection has been completed.
  3821. // - disconnected Ice connection has been disconnected.
  3822. // - failed Ice connection has failed.
  3823. // - closed Ice connection is closed.
  3824. AdapterJS._iceConnectionStates = {
  3825. starting : 'starting',
  3826. checking : 'checking',
  3827. connected : 'connected',
  3828. completed : 'connected',
  3829. done : 'completed',
  3830. disconnected : 'disconnected',
  3831. failed : 'failed',
  3832. closed : 'closed'
  3833. };
  3834. //The IceConnection states that has been fired for each peer.
  3835. AdapterJS._iceConnectionFiredStates = [];
  3836. // Check if WebRTC Interface is defined.
  3837. AdapterJS.isDefined = null;
  3838. // This function helps to retrieve the webrtc detected browser information.
  3839. // This sets:
  3840. // - webrtcDetectedBrowser: The browser agent name.
  3841. // - webrtcDetectedVersion: The browser version.
  3842. // - webrtcDetectedType: The types of webRTC support.
  3843. // - 'moz': Mozilla implementation of webRTC.
  3844. // - 'webkit': WebKit implementation of webRTC.
  3845. // - 'plugin': Using the plugin implementation.
  3846. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3847. var hasMatch, checkMatch = navigator.userAgent.match(
  3848. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3849. if (/trident/i.test(checkMatch[1])) {
  3850. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3851. webrtcDetectedBrowser = 'IE';
  3852. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3853. } else if (checkMatch[1] === 'Chrome') {
  3854. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3855. if (hasMatch !== null) {
  3856. webrtcDetectedBrowser = 'opera';
  3857. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3858. }
  3859. }
  3860. if (navigator.userAgent.indexOf('Safari')) {
  3861. if (typeof InstallTrigger !== 'undefined') {
  3862. webrtcDetectedBrowser = 'firefox';
  3863. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3864. webrtcDetectedBrowser = 'IE';
  3865. } else if (
  3866. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3867. webrtcDetectedBrowser = 'safari';
  3868. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3869. webrtcDetectedBrowser = 'opera';
  3870. } else if (!!window.chrome) {
  3871. webrtcDetectedBrowser = 'chrome';
  3872. }
  3873. }
  3874. if (!webrtcDetectedBrowser) {
  3875. webrtcDetectedVersion = checkMatch[1];
  3876. }
  3877. if (!webrtcDetectedVersion) {
  3878. try {
  3879. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3880. [navigator.appName, navigator.appVersion, '-?'];
  3881. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3882. checkMatch.splice(1, 1, hasMatch[1]);
  3883. }
  3884. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3885. } catch (error) { }
  3886. }
  3887. };
  3888. // To fix configuration as some browsers does not support
  3889. // the 'urls' attribute.
  3890. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  3891. if (pcConfig === null) {
  3892. return;
  3893. }
  3894. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  3895. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  3896. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  3897. delete pcConfig.iceServers[i].urls;
  3898. }
  3899. }
  3900. };
  3901. AdapterJS.addEvent = function(elem, evnt, func) {
  3902. if (elem.addEventListener) { // W3C DOM
  3903. elem.addEventListener(evnt, func, false);
  3904. } else if (elem.attachEvent) {// OLD IE DOM
  3905. elem.attachEvent('on'+evnt, func);
  3906. } else { // No much to do
  3907. elem[evnt] = func;
  3908. }
  3909. };
  3910. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  3911. // only inject once the page is ready
  3912. if (document.readyState !== 'complete') {
  3913. return;
  3914. }
  3915. var w = window;
  3916. var i = document.createElement('iframe');
  3917. i.style.position = 'fixed';
  3918. i.style.top = '-41px';
  3919. i.style.left = 0;
  3920. i.style.right = 0;
  3921. i.style.width = '100%';
  3922. i.style.height = '40px';
  3923. i.style.backgroundColor = '#ffffe1';
  3924. i.style.border = 'none';
  3925. i.style.borderBottom = '1px solid #888888';
  3926. i.style.zIndex = '9999999';
  3927. if(typeof i.style.webkitTransition === 'string') {
  3928. i.style.webkitTransition = 'all .5s ease-out';
  3929. } else if(typeof i.style.transition === 'string') {
  3930. i.style.transition = 'all .5s ease-out';
  3931. }
  3932. document.body.appendChild(i);
  3933. c = (i.contentWindow) ? i.contentWindow :
  3934. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  3935. c.document.open();
  3936. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  3937. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  3938. 'middle; cursor: default;">' + text + '</span>');
  3939. if(buttonText && buttonLink) {
  3940. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  3941. c.document.close();
  3942. // On click on okay
  3943. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  3944. if (!!displayRefreshBar) {
  3945. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  3946. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  3947. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  3948. }
  3949. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  3950. e.preventDefault();
  3951. try {
  3952. event.cancelBubble = true;
  3953. } catch(error) { }
  3954. var pluginInstallInterval = setInterval(function(){
  3955. if(! isIE) {
  3956. navigator.plugins.refresh(false);
  3957. }
  3958. AdapterJS.WebRTCPlugin.isPluginInstalled(
  3959. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  3960. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  3961. function() { // plugin now installed
  3962. clearInterval(pluginInstallInterval);
  3963. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  3964. },
  3965. function() {
  3966. // still no plugin detected, nothing to do
  3967. });
  3968. } , 500);
  3969. });
  3970. // On click on Cancel
  3971. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  3972. w.document.body.removeChild(i);
  3973. });
  3974. } else {
  3975. c.document.close();
  3976. }
  3977. setTimeout(function() {
  3978. if(typeof i.style.webkitTransform === 'string') {
  3979. i.style.webkitTransform = 'translateY(40px)';
  3980. } else if(typeof i.style.transform === 'string') {
  3981. i.style.transform = 'translateY(40px)';
  3982. } else {
  3983. i.style.top = '0px';
  3984. }
  3985. }, 300);
  3986. };
  3987. // -----------------------------------------------------------
  3988. // Detected webrtc implementation. Types are:
  3989. // - 'moz': Mozilla implementation of webRTC.
  3990. // - 'webkit': WebKit implementation of webRTC.
  3991. // - 'plugin': Using the plugin implementation.
  3992. webrtcDetectedType = null;
  3993. // Detected webrtc datachannel support. Types are:
  3994. // - 'SCTP': SCTP datachannel support.
  3995. // - 'RTP': RTP datachannel support.
  3996. webrtcDetectedDCSupport = null;
  3997. // Set the settings for creating DataChannels, MediaStream for
  3998. // Cross-browser compability.
  3999. // - This is only for SCTP based support browsers.
  4000. // the 'urls' attribute.
  4001. checkMediaDataChannelSettings =
  4002. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  4003. if (typeof callback !== 'function') {
  4004. return;
  4005. }
  4006. var beOfferer = true;
  4007. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  4008. // Nightly version does not require MozDontOfferDataChannel for interop
  4009. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  4010. var isPeerFirefox = peerBrowserAgent === 'firefox';
  4011. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  4012. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  4013. // Resends an updated version of constraints for MozDataChannel to work
  4014. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  4015. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  4016. try {
  4017. delete constraints.mandatory.MozDontOfferDataChannel;
  4018. } catch (error) {
  4019. console.error('Failed deleting MozDontOfferDataChannel');
  4020. console.error(error);
  4021. }
  4022. } else if ((isLocalFirefox && !isPeerFirefox)) {
  4023. constraints.mandatory.MozDontOfferDataChannel = true;
  4024. }
  4025. if (!isLocalFirefox) {
  4026. // temporary measure to remove Moz* constraints in non Firefox browsers
  4027. for (var prop in constraints.mandatory) {
  4028. if (constraints.mandatory.hasOwnProperty(prop)) {
  4029. if (prop.indexOf('Moz') !== -1) {
  4030. delete constraints.mandatory[prop];
  4031. }
  4032. }
  4033. }
  4034. }
  4035. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  4036. // interopability of the media stream
  4037. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4038. beOfferer = false;
  4039. }
  4040. callback(beOfferer, constraints);
  4041. };
  4042. // Handles the differences for all browsers ice connection state output.
  4043. // - Tested outcomes are:
  4044. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4045. // - Chrome (answerer) : 'checking' > 'connected'
  4046. // - Firefox (offerer) : 'checking' > 'connected'
  4047. // - Firefox (answerer): 'checking' > 'connected'
  4048. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4049. if (typeof callback !== 'function') {
  4050. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4051. return;
  4052. }
  4053. peerId = (peerId) ? peerId : 'peer';
  4054. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4055. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4056. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4057. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4058. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4059. }
  4060. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4061. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4062. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4063. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4064. setTimeout(function () {
  4065. AdapterJS._iceConnectionFiredStates[peerId]
  4066. .push(AdapterJS._iceConnectionStates.done);
  4067. callback(AdapterJS._iceConnectionStates.done);
  4068. }, 1000);
  4069. }
  4070. callback(iceConnectionState);
  4071. }
  4072. return;
  4073. };
  4074. // Firefox:
  4075. // - Creates iceServer from the url for Firefox.
  4076. // - Create iceServer with stun url.
  4077. // - Create iceServer with turn url.
  4078. // - Ignore the transport parameter from TURN url for FF version <=27.
  4079. // - Return null for createIceServer if transport=tcp.
  4080. // - FF 27 and above supports transport parameters in TURN url,
  4081. // - So passing in the full url to create iceServer.
  4082. // Chrome:
  4083. // - Creates iceServer from the url for Chrome M33 and earlier.
  4084. // - Create iceServer with stun url.
  4085. // - Chrome M28 & above uses below TURN format.
  4086. // Plugin:
  4087. // - Creates Ice Server for Plugin Browsers
  4088. // - If Stun - Create iceServer with stun url.
  4089. // - Else - Create iceServer with turn url
  4090. // - This is a WebRTC Function
  4091. createIceServer = null;
  4092. // Firefox:
  4093. // - Creates IceServers for Firefox
  4094. // - Use .url for FireFox.
  4095. // - Multiple Urls support
  4096. // Chrome:
  4097. // - Creates iceServers from the urls for Chrome M34 and above.
  4098. // - .urls is supported since Chrome M34.
  4099. // - Multiple Urls support
  4100. // Plugin:
  4101. // - Creates Ice Servers for Plugin Browsers
  4102. // - Multiple Urls support
  4103. // - This is a WebRTC Function
  4104. createIceServers = null;
  4105. //------------------------------------------------------------
  4106. //The RTCPeerConnection object.
  4107. RTCPeerConnection = null;
  4108. // Creates RTCSessionDescription object for Plugin Browsers
  4109. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4110. RTCSessionDescription : null;
  4111. // Creates RTCIceCandidate object for Plugin Browsers
  4112. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4113. RTCIceCandidate : null;
  4114. // Get UserMedia (only difference is the prefix).
  4115. // Code from Adam Barth.
  4116. getUserMedia = null;
  4117. // Attach a media stream to an element.
  4118. attachMediaStream = null;
  4119. // Re-attach a media stream to an element.
  4120. reattachMediaStream = null;
  4121. // Detected browser agent name. Types are:
  4122. // - 'firefox': Firefox browser.
  4123. // - 'chrome': Chrome browser.
  4124. // - 'opera': Opera browser.
  4125. // - 'safari': Safari browser.
  4126. // - 'IE' - Internet Explorer browser.
  4127. webrtcDetectedBrowser = null;
  4128. // Detected browser version.
  4129. webrtcDetectedVersion = null;
  4130. // Check for browser types and react accordingly
  4131. if (navigator.mozGetUserMedia) {
  4132. webrtcDetectedBrowser = 'firefox';
  4133. webrtcDetectedVersion = parseInt(navigator
  4134. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4135. webrtcDetectedType = 'moz';
  4136. webrtcDetectedDCSupport = 'SCTP';
  4137. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4138. AdapterJS.maybeFixConfiguration(pcConfig);
  4139. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4140. };
  4141. // The RTCSessionDescription object.
  4142. RTCSessionDescription = mozRTCSessionDescription;
  4143. window.RTCSessionDescription = RTCSessionDescription;
  4144. // The RTCIceCandidate object.
  4145. RTCIceCandidate = mozRTCIceCandidate;
  4146. window.RTCIceCandidate = RTCIceCandidate;
  4147. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4148. navigator.getUserMedia = window.getUserMedia;
  4149. // Shim for MediaStreamTrack.getSources.
  4150. MediaStreamTrack.getSources = function(successCb) {
  4151. setTimeout(function() {
  4152. var infos = [
  4153. { kind: 'audio', id: 'default', label:'', facing:'' },
  4154. { kind: 'video', id: 'default', label:'', facing:'' }
  4155. ];
  4156. successCb(infos);
  4157. }, 0);
  4158. };
  4159. createIceServer = function (url, username, password) {
  4160. var iceServer = null;
  4161. var url_parts = url.split(':');
  4162. if (url_parts[0].indexOf('stun') === 0) {
  4163. iceServer = { url : url };
  4164. } else if (url_parts[0].indexOf('turn') === 0) {
  4165. if (webrtcDetectedVersion < 27) {
  4166. var turn_url_parts = url.split('?');
  4167. if (turn_url_parts.length === 1 ||
  4168. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4169. iceServer = {
  4170. url : turn_url_parts[0],
  4171. credential : password,
  4172. username : username
  4173. };
  4174. }
  4175. } else {
  4176. iceServer = {
  4177. url : url,
  4178. credential : password,
  4179. username : username
  4180. };
  4181. }
  4182. }
  4183. return iceServer;
  4184. };
  4185. createIceServers = function (urls, username, password) {
  4186. var iceServers = [];
  4187. for (var i = 0; i < urls.length; i++) {
  4188. var iceServer = createIceServer(urls[i], username, password);
  4189. if (iceServer !== null) {
  4190. iceServers.push(iceServer);
  4191. }
  4192. }
  4193. return iceServers;
  4194. };
  4195. attachMediaStream = function (element, stream) {
  4196. element.mozSrcObject = stream;
  4197. if (stream !== null)
  4198. element.play();
  4199. return element;
  4200. };
  4201. reattachMediaStream = function (to, from) {
  4202. to.mozSrcObject = from.mozSrcObject;
  4203. to.play();
  4204. return to;
  4205. };
  4206. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4207. if (!callback) {
  4208. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4209. ': 1 argument required, but only 0 present.');
  4210. }
  4211. return callback([]);
  4212. };
  4213. // Fake get{Video,Audio}Tracks
  4214. if (!MediaStream.prototype.getVideoTracks) {
  4215. MediaStream.prototype.getVideoTracks = function () {
  4216. return [];
  4217. };
  4218. }
  4219. if (!MediaStream.prototype.getAudioTracks) {
  4220. MediaStream.prototype.getAudioTracks = function () {
  4221. return [];
  4222. };
  4223. }
  4224. AdapterJS.maybeThroughWebRTCReady();
  4225. } else if (navigator.webkitGetUserMedia) {
  4226. webrtcDetectedBrowser = 'chrome';
  4227. webrtcDetectedType = 'webkit';
  4228. webrtcDetectedVersion = parseInt(navigator
  4229. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4230. // check if browser is opera 20+
  4231. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4232. if (checkIfOpera !== null) {
  4233. webrtcDetectedBrowser = 'opera';
  4234. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4235. }
  4236. // check browser datachannel support
  4237. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4238. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4239. webrtcDetectedDCSupport = 'SCTP';
  4240. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4241. webrtcDetectedVersion > 24) {
  4242. webrtcDetectedDCSupport = 'RTP';
  4243. } else {
  4244. webrtcDetectedDCSupport = '';
  4245. }
  4246. createIceServer = function (url, username, password) {
  4247. var iceServer = null;
  4248. var url_parts = url.split(':');
  4249. if (url_parts[0].indexOf('stun') === 0) {
  4250. iceServer = { 'url' : url };
  4251. } else if (url_parts[0].indexOf('turn') === 0) {
  4252. iceServer = {
  4253. 'url' : url,
  4254. 'credential' : password,
  4255. 'username' : username
  4256. };
  4257. }
  4258. return iceServer;
  4259. };
  4260. createIceServers = function (urls, username, password) {
  4261. var iceServers = [];
  4262. if (webrtcDetectedVersion >= 34) {
  4263. iceServers = {
  4264. 'urls' : urls,
  4265. 'credential' : password,
  4266. 'username' : username
  4267. };
  4268. } else {
  4269. for (var i = 0; i < urls.length; i++) {
  4270. var iceServer = createIceServer(urls[i], username, password);
  4271. if (iceServer !== null) {
  4272. iceServers.push(iceServer);
  4273. }
  4274. }
  4275. }
  4276. return iceServers;
  4277. };
  4278. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4279. if (webrtcDetectedVersion < 34) {
  4280. AdapterJS.maybeFixConfiguration(pcConfig);
  4281. }
  4282. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4283. };
  4284. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4285. navigator.getUserMedia = window.getUserMedia;
  4286. attachMediaStream = function (element, stream) {
  4287. if (typeof element.srcObject !== 'undefined') {
  4288. element.srcObject = stream;
  4289. } else if (typeof element.mozSrcObject !== 'undefined') {
  4290. element.mozSrcObject = stream;
  4291. } else if (typeof element.src !== 'undefined') {
  4292. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4293. } else {
  4294. console.log('Error attaching stream to element.');
  4295. }
  4296. return element;
  4297. };
  4298. reattachMediaStream = function (to, from) {
  4299. to.src = from.src;
  4300. return to;
  4301. };
  4302. AdapterJS.maybeThroughWebRTCReady();
  4303. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4304. /Edge\/(\d+).(\d+)$/)) {
  4305. webrtcDetectedBrowser = 'edge';
  4306. webrtcDetectedVersion =
  4307. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4308. // the minimum version still supported by adapter.
  4309. webrtcMinimumVersion = 12;
  4310. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4311. attachMediaStream = function(element, stream) {
  4312. element.srcObject = stream;
  4313. return element;
  4314. };
  4315. reattachMediaStream = function(to, from) {
  4316. to.srcObject = from.srcObject;
  4317. return to;
  4318. };
  4319. AdapterJS.maybeThroughWebRTCReady();
  4320. } else { // TRY TO USE PLUGIN
  4321. // IE 9 is not offering an implementation of console.log until you open a console
  4322. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4323. /* jshint -W020 */
  4324. console = {} || console;
  4325. // Implemented based on console specs from MDN
  4326. // You may override these functions
  4327. console.log = function (arg) {};
  4328. console.info = function (arg) {};
  4329. console.error = function (arg) {};
  4330. console.dir = function (arg) {};
  4331. console.exception = function (arg) {};
  4332. console.trace = function (arg) {};
  4333. console.warn = function (arg) {};
  4334. console.count = function (arg) {};
  4335. console.debug = function (arg) {};
  4336. console.count = function (arg) {};
  4337. console.time = function (arg) {};
  4338. console.timeEnd = function (arg) {};
  4339. console.group = function (arg) {};
  4340. console.groupCollapsed = function (arg) {};
  4341. console.groupEnd = function (arg) {};
  4342. /* jshint +W020 */
  4343. }
  4344. webrtcDetectedType = 'plugin';
  4345. webrtcDetectedDCSupport = 'plugin';
  4346. AdapterJS.parseWebrtcDetectedBrowser();
  4347. isIE = webrtcDetectedBrowser === 'IE';
  4348. /* jshint -W035 */
  4349. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4350. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4351. /* empty because it needs to prevent the function from running. */
  4352. }
  4353. };
  4354. /* jshint +W035 */
  4355. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4356. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4357. // Call immediately if possible
  4358. // Once the plugin is set, the code will always take this path
  4359. callback();
  4360. } else {
  4361. // otherwise start a 100ms interval
  4362. var checkPluginReadyState = setInterval(function () {
  4363. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4364. clearInterval(checkPluginReadyState);
  4365. callback();
  4366. }
  4367. }, 100);
  4368. }
  4369. };
  4370. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4371. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4372. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4373. });
  4374. };
  4375. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4376. // only inject once the page is ready
  4377. if (document.readyState !== 'complete') {
  4378. return;
  4379. }
  4380. // Prevent multiple injections
  4381. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4382. return;
  4383. }
  4384. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4385. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4386. var frag = document.createDocumentFragment();
  4387. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4388. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4389. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4390. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4391. '<param name="pluginId" value="' +
  4392. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4393. '<param name="windowless" value="false" /> ' +
  4394. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4395. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4396. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4397. // uncomment to be able to use virtual cams
  4398. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4399. '</object>';
  4400. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4401. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4402. }
  4403. document.body.appendChild(frag);
  4404. // Need to re-fetch the plugin
  4405. AdapterJS.WebRTCPlugin.plugin =
  4406. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4407. } else {
  4408. // Load Plugin
  4409. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4410. AdapterJS.WebRTCPlugin.plugin.id =
  4411. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4412. // IE will only start the plugin if it's ACTUALLY visible
  4413. if (isIE) {
  4414. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4415. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4416. } else { // The size of the plugin on Safari should be 0x0px
  4417. // so that the autorisation prompt is at the top
  4418. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4419. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4420. }
  4421. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4422. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4423. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4424. '<param name="pluginId" value="' +
  4425. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4426. '<param name="windowless" value="false" /> ' +
  4427. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4428. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4429. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4430. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4431. }
  4432. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4433. };
  4434. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4435. function (comName, plugName, installedCb, notInstalledCb) {
  4436. if (!isIE) {
  4437. var pluginArray = navigator.plugins;
  4438. for (var i = 0; i < pluginArray.length; i++) {
  4439. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4440. installedCb();
  4441. return;
  4442. }
  4443. }
  4444. notInstalledCb();
  4445. } else {
  4446. try {
  4447. var axo = new ActiveXObject(comName + '.' + plugName);
  4448. } catch (e) {
  4449. notInstalledCb();
  4450. return;
  4451. }
  4452. installedCb();
  4453. }
  4454. };
  4455. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4456. if (AdapterJS.WebRTCPlugin.pluginState ===
  4457. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4458. console.error("AdapterJS - WebRTC interface has already been defined");
  4459. return;
  4460. }
  4461. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4462. AdapterJS.isDefined = function (variable) {
  4463. return variable !== null && variable !== undefined;
  4464. };
  4465. createIceServer = function (url, username, password) {
  4466. var iceServer = null;
  4467. var url_parts = url.split(':');
  4468. if (url_parts[0].indexOf('stun') === 0) {
  4469. iceServer = {
  4470. 'url' : url,
  4471. 'hasCredentials' : false
  4472. };
  4473. } else if (url_parts[0].indexOf('turn') === 0) {
  4474. iceServer = {
  4475. 'url' : url,
  4476. 'hasCredentials' : true,
  4477. 'credential' : password,
  4478. 'username' : username
  4479. };
  4480. }
  4481. return iceServer;
  4482. };
  4483. createIceServers = function (urls, username, password) {
  4484. var iceServers = [];
  4485. for (var i = 0; i < urls.length; ++i) {
  4486. iceServers.push(createIceServer(urls[i], username, password));
  4487. }
  4488. return iceServers;
  4489. };
  4490. RTCSessionDescription = function (info) {
  4491. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4492. return AdapterJS.WebRTCPlugin.plugin.
  4493. ConstructSessionDescription(info.type, info.sdp);
  4494. };
  4495. RTCPeerConnection = function (servers, constraints) {
  4496. var iceServers = null;
  4497. if (servers) {
  4498. iceServers = servers.iceServers;
  4499. for (var i = 0; i < iceServers.length; i++) {
  4500. if (iceServers[i].urls && !iceServers[i].url) {
  4501. iceServers[i].url = iceServers[i].urls;
  4502. }
  4503. iceServers[i].hasCredentials = AdapterJS.
  4504. isDefined(iceServers[i].username) &&
  4505. AdapterJS.isDefined(iceServers[i].credential);
  4506. }
  4507. }
  4508. var mandatory = (constraints && constraints.mandatory) ?
  4509. constraints.mandatory : null;
  4510. var optional = (constraints && constraints.optional) ?
  4511. constraints.optional : null;
  4512. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4513. return AdapterJS.WebRTCPlugin.plugin.
  4514. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4515. iceServers, mandatory, optional);
  4516. };
  4517. MediaStreamTrack = {};
  4518. MediaStreamTrack.getSources = function (callback) {
  4519. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4520. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4521. });
  4522. };
  4523. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4524. constraints.audio = constraints.audio || false;
  4525. constraints.video = constraints.video || false;
  4526. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4527. AdapterJS.WebRTCPlugin.plugin.
  4528. getUserMedia(constraints, successCallback, failureCallback);
  4529. });
  4530. };
  4531. window.navigator.getUserMedia = window.getUserMedia;
  4532. attachMediaStream = function (element, stream) {
  4533. if (!element || !element.parentNode) {
  4534. return;
  4535. }
  4536. var streamId;
  4537. if (stream === null) {
  4538. streamId = '';
  4539. } else {
  4540. if (typeof stream.enableSoundTracks !== 'undefined') {
  4541. stream.enableSoundTracks(true);
  4542. }
  4543. streamId = stream.id;
  4544. }
  4545. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4546. var nodeName = element.nodeName.toLowerCase();
  4547. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4548. var tag;
  4549. switch(nodeName) {
  4550. case 'audio':
  4551. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4552. break;
  4553. case 'video':
  4554. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4555. break;
  4556. default:
  4557. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4558. }
  4559. var frag = document.createDocumentFragment();
  4560. var temp = document.createElement('div');
  4561. var classHTML = '';
  4562. if (element.className) {
  4563. classHTML = 'class="' + element.className + '" ';
  4564. } else if (element.attributes && element.attributes['class']) {
  4565. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4566. }
  4567. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4568. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4569. '<param name="pluginId" value="' + elementId + '" /> ' +
  4570. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4571. '<param name="windowless" value="true" /> ' +
  4572. '<param name="streamId" value="' + streamId + '" /> ' +
  4573. '<param name="tag" value="' + tag + '" /> ' +
  4574. '</object>';
  4575. while (temp.firstChild) {
  4576. frag.appendChild(temp.firstChild);
  4577. }
  4578. var height = '';
  4579. var width = '';
  4580. if (element.clientWidth || element.clientHeight) {
  4581. width = element.clientWidth;
  4582. height = element.clientHeight;
  4583. }
  4584. else if (element.width || element.height) {
  4585. width = element.width;
  4586. height = element.height;
  4587. }
  4588. element.parentNode.insertBefore(frag, element);
  4589. frag = document.getElementById(elementId);
  4590. frag.width = width;
  4591. frag.height = height;
  4592. element.parentNode.removeChild(element);
  4593. } else { // already an <object> tag, just change the stream id
  4594. var children = element.children;
  4595. for (var i = 0; i !== children.length; ++i) {
  4596. if (children[i].name === 'streamId') {
  4597. children[i].value = streamId;
  4598. break;
  4599. }
  4600. }
  4601. element.setStreamId(streamId);
  4602. }
  4603. var newElement = document.getElementById(elementId);
  4604. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4605. return newElement;
  4606. };
  4607. reattachMediaStream = function (to, from) {
  4608. var stream = null;
  4609. var children = from.children;
  4610. for (var i = 0; i !== children.length; ++i) {
  4611. if (children[i].name === 'streamId') {
  4612. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4613. stream = AdapterJS.WebRTCPlugin.plugin
  4614. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4615. break;
  4616. }
  4617. }
  4618. if (stream !== null) {
  4619. return attachMediaStream(to, stream);
  4620. } else {
  4621. console.log('Could not find the stream associated with this element');
  4622. }
  4623. };
  4624. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4625. properties = Object.getOwnPropertyNames( prototype );
  4626. for(prop in properties) {
  4627. propName = properties[prop];
  4628. if (typeof(propName.slice) === 'function') {
  4629. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4630. if (isIE) {
  4631. destElem.attachEvent(propName,srcElem[propName]);
  4632. } else {
  4633. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4634. }
  4635. } else {
  4636. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4637. }
  4638. }
  4639. }
  4640. var subPrototype = Object.getPrototypeOf(prototype)
  4641. if(subPrototype != null) {
  4642. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4643. }
  4644. }
  4645. RTCIceCandidate = function (candidate) {
  4646. if (!candidate.sdpMid) {
  4647. candidate.sdpMid = '';
  4648. }
  4649. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4650. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4651. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4652. );
  4653. };
  4654. // inject plugin
  4655. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4656. AdapterJS.WebRTCPlugin.injectPlugin();
  4657. };
  4658. // This function will be called if the plugin is needed (browser different
  4659. // from Chrome or Firefox), but the plugin is not installed.
  4660. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4661. function() {
  4662. AdapterJS.addEvent(document,
  4663. 'readystatechange',
  4664. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4665. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4666. };
  4667. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4668. if (AdapterJS.options.hidePluginInstallPrompt) {
  4669. return;
  4670. }
  4671. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4672. if(downloadLink) { // if download link
  4673. var popupString;
  4674. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4675. popupString = 'This website requires you to install the ' +
  4676. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4677. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4678. ' WebRTC Plugin</a>' +
  4679. ' to work on this browser.';
  4680. } else { // no portal link, just print a generic explanation
  4681. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4682. }
  4683. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4684. } else { // no download link, just print a generic explanation
  4685. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4686. }
  4687. };
  4688. // Try to detect the plugin and act accordingly
  4689. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4690. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4691. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4692. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4693. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4694. }
  4695. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4696. },{"jitsi-meet-logger":79}],21:[function(require,module,exports){
  4697. (function (__filename){
  4698. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4699. var UsernameGenerator = require('../util/UsernameGenerator');
  4700. function supportsLocalStorage() {
  4701. try {
  4702. return 'localStorage' in window && window.localStorage !== null;
  4703. } catch (e) {
  4704. logger.log("localstorage is not supported");
  4705. return false;
  4706. }
  4707. }
  4708. function generateUniqueId() {
  4709. function _p8() {
  4710. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4711. }
  4712. return _p8() + _p8() + _p8() + _p8();
  4713. }
  4714. function Settings(conferenceID) {
  4715. this.displayName = '';
  4716. this.userId;
  4717. this.confSettings = null;
  4718. this.conferenceID = conferenceID;
  4719. this.callStatsUserName;
  4720. if (supportsLocalStorage()) {
  4721. if(!window.localStorage.getItem(conferenceID))
  4722. this.confSettings = {};
  4723. else
  4724. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4725. if(!this.confSettings.jitsiMeetId) {
  4726. this.confSettings.jitsiMeetId = generateUniqueId();
  4727. logger.log("generated id",
  4728. this.confSettings.jitsiMeetId);
  4729. this.save();
  4730. }
  4731. if (!this.confSettings.callStatsUserName) {
  4732. this.confSettings.callStatsUserName
  4733. = UsernameGenerator.generateUsername();
  4734. logger.log('generated callstats uid',
  4735. this.confSettings.callStatsUserName);
  4736. this.save();
  4737. }
  4738. this.userId = this.confSettings.jitsiMeetId || '';
  4739. this.displayName = this.confSettings.displayname || '';
  4740. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4741. } else {
  4742. logger.log("local storage is not supported");
  4743. this.userId = generateUniqueId();
  4744. this.callStatsUserName = UsernameGenerator.generateUsername();
  4745. }
  4746. }
  4747. Settings.prototype.save = function () {
  4748. if(!supportsLocalStorage())
  4749. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4750. }
  4751. Settings.prototype.setDisplayName = function (newDisplayName) {
  4752. this.displayName = newDisplayName;
  4753. if(this.confSettings != null)
  4754. this.confSettings.displayname = displayName;
  4755. this.save();
  4756. return this.displayName;
  4757. }
  4758. Settings.prototype.getSettings = function () {
  4759. return {
  4760. displayName: this.displayName,
  4761. uid: this.userId
  4762. };
  4763. }
  4764. /**
  4765. * Returns fake username for callstats
  4766. * @returns {string} fake username for callstats
  4767. */
  4768. Settings.prototype.getCallStatsUserName = function () {
  4769. return this.callStatsUserName;
  4770. }
  4771. module.exports = Settings;
  4772. }).call(this,"/modules/settings/Settings.js")
  4773. },{"../util/UsernameGenerator":28,"jitsi-meet-logger":79}],22:[function(require,module,exports){
  4774. (function (__filename){
  4775. /* global $, Strophe, callstats */
  4776. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4777. var jsSHA = require('jssha');
  4778. var io = require('socket.io-client');
  4779. /**
  4780. * @const
  4781. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4782. */
  4783. var wrtcFuncNames = {
  4784. createOffer: "createOffer",
  4785. createAnswer: "createAnswer",
  4786. setLocalDescription: "setLocalDescription",
  4787. setRemoteDescription: "setRemoteDescription",
  4788. addIceCandidate: "addIceCandidate",
  4789. getUserMedia: "getUserMedia"
  4790. };
  4791. var callStats = null;
  4792. function initCallback (err, msg) {
  4793. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4794. }
  4795. /**
  4796. * Returns a function which invokes f in a try/catch block, logs any exception
  4797. * to the console, and then swallows it.
  4798. *
  4799. * @param f the function to invoke in a try/catch block
  4800. * @return a function which invokes f in a try/catch block, logs any exception
  4801. * to the console, and then swallows it
  4802. */
  4803. function _try_catch (f) {
  4804. return function () {
  4805. try {
  4806. f.apply(this, arguments);
  4807. } catch (e) {
  4808. logger.error(e);
  4809. }
  4810. };
  4811. }
  4812. /**
  4813. * Creates new CallStats instance that handles all callstats API calls.
  4814. * @param peerConnection {JingleSessionPC} the session object
  4815. * @param Settings {Settings} the settings instance. Declared in
  4816. * /modules/settings/Settings.js
  4817. * @param options {object} credentials for callstats.
  4818. */
  4819. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4820. try{
  4821. //check weather that should work with more than 1 peerconnection
  4822. if(!callStats) {
  4823. callStats = new callstats($, io, jsSHA);
  4824. } else {
  4825. return;
  4826. }
  4827. this.session = jingleSession;
  4828. this.peerconnection = jingleSession.peerconnection.peerconnection;
  4829. this.userID = Settings.getCallStatsUserName();
  4830. //FIXME: change it to something else (maybe roomName)
  4831. var location = window.location;
  4832. this.confID = location.hostname + location.pathname;
  4833. //userID is generated or given by the origin server
  4834. callStats.initialize(options.callStatsID,
  4835. options.callStatsSecret,
  4836. this.userID,
  4837. initCallback);
  4838. callStats.addNewFabric(this.peerconnection,
  4839. Strophe.getResourceFromJid(jingleSession.peerjid),
  4840. callStats.fabricUsage.multiplex,
  4841. this.confID,
  4842. this.pcCallback.bind(this));
  4843. } catch (e) {
  4844. // The callstats.io API failed to initialize (e.g. because its
  4845. // download failed to succeed in general or on time). Further
  4846. // attempts to utilize it cannot possibly succeed.
  4847. callStats = null;
  4848. logger.error(e);
  4849. }
  4850. // notify callstats about failures if there were any
  4851. if (CallStats.pendingErrors.length) {
  4852. CallStats.pendingErrors.forEach(function (error) {
  4853. CallStats._reportError.call(this, error.type, error.error,
  4854. error.pc);
  4855. }, this);
  4856. CallStats.pendingErrors.length = 0;
  4857. }
  4858. });
  4859. // some errors may happen before CallStats init
  4860. // in this case we accumulate them in this array
  4861. // and send them to callstats on init
  4862. CallStats.pendingErrors = [];
  4863. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  4864. if (!callStats) {
  4865. return;
  4866. }
  4867. logger.log("Monitoring status: "+ err + " msg: " + msg);
  4868. callStats.sendFabricEvent(this.peerconnection,
  4869. callStats.fabricEvent.fabricSetup, this.confID);
  4870. });
  4871. /**
  4872. * Notifies CallStats for mute events
  4873. * @param mute {boolean} true for muted and false for not muted
  4874. * @param type {String} "audio"/"video"
  4875. */
  4876. CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
  4877. if (!callStats) {
  4878. return;
  4879. }
  4880. var event = null;
  4881. if (type === "video") {
  4882. event = (mute? callStats.fabricEvent.videoPause :
  4883. callStats.fabricEvent.videoResume);
  4884. }
  4885. else {
  4886. event = (mute? callStats.fabricEvent.audioMute :
  4887. callStats.fabricEvent.audioUnmute);
  4888. }
  4889. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  4890. });
  4891. /**
  4892. * Notifies CallStats for connection setup errors
  4893. */
  4894. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  4895. if(!callStats) {
  4896. return;
  4897. }
  4898. callStats.sendFabricEvent(this.peerconnection,
  4899. callStats.fabricEvent.fabricTerminated, this.confID);
  4900. });
  4901. /**
  4902. * Notifies CallStats for connection setup errors
  4903. */
  4904. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  4905. if(!callStats) {
  4906. return;
  4907. }
  4908. callStats.sendFabricEvent(this.peerconnection,
  4909. callStats.fabricEvent.fabricSetupFailed, this.confID);
  4910. });
  4911. /**
  4912. * Sends the given feedback through CallStats.
  4913. *
  4914. * @param overallFeedback an integer between 1 and 5 indicating the
  4915. * user feedback
  4916. * @param detailedFeedback detailed feedback from the user. Not yet used
  4917. */
  4918. CallStats.prototype.sendFeedback = _try_catch(
  4919. function(overallFeedback, detailedFeedback) {
  4920. if(!callStats) {
  4921. return;
  4922. }
  4923. var feedbackString = '{"userID":"' + this.userID + '"' +
  4924. ', "overall":' + overallFeedback +
  4925. ', "comment": "' + detailedFeedback + '"}';
  4926. var feedbackJSON = JSON.parse(feedbackString);
  4927. callStats.sendUserFeedback(this.confID, feedbackJSON);
  4928. });
  4929. /**
  4930. * Reports an error to callstats.
  4931. *
  4932. * @param type the type of the error, which will be one of the wrtcFuncNames
  4933. * @param e the error
  4934. * @param pc the peerconnection
  4935. * @private
  4936. */
  4937. CallStats._reportError = function (type, e, pc) {
  4938. if (callStats) {
  4939. callStats.reportError(pc, this.confID, type, e);
  4940. } else {
  4941. CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
  4942. }
  4943. // else just ignore it
  4944. };
  4945. /**
  4946. * Notifies CallStats that getUserMedia failed.
  4947. *
  4948. * @param {Error} e error to send
  4949. * @param {CallStats} cs callstats instance related to the error (optional)
  4950. */
  4951. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  4952. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  4953. });
  4954. /**
  4955. * Notifies CallStats that peer connection failed to create offer.
  4956. *
  4957. * @param {Error} e error to send
  4958. * @param {RTCPeerConnection} pc connection on which failure occured.
  4959. * @param {CallStats} cs callstats instance related to the error (optional)
  4960. */
  4961. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  4962. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  4963. });
  4964. /**
  4965. * Notifies CallStats that peer connection failed to create answer.
  4966. *
  4967. * @param {Error} e error to send
  4968. * @param {RTCPeerConnection} pc connection on which failure occured.
  4969. * @param {CallStats} cs callstats instance related to the error (optional)
  4970. */
  4971. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  4972. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  4973. });
  4974. /**
  4975. * Notifies CallStats that peer connection failed to set local description.
  4976. *
  4977. * @param {Error} e error to send
  4978. * @param {RTCPeerConnection} pc connection on which failure occured.
  4979. * @param {CallStats} cs callstats instance related to the error (optional)
  4980. */
  4981. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  4982. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  4983. });
  4984. /**
  4985. * Notifies CallStats that peer connection failed to set remote description.
  4986. *
  4987. * @param {Error} e error to send
  4988. * @param {RTCPeerConnection} pc connection on which failure occured.
  4989. * @param {CallStats} cs callstats instance related to the error (optional)
  4990. */
  4991. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  4992. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  4993. });
  4994. /**
  4995. * Notifies CallStats that peer connection failed to add ICE candidate.
  4996. *
  4997. * @param {Error} e error to send
  4998. * @param {RTCPeerConnection} pc connection on which failure occured.
  4999. * @param {CallStats} cs callstats instance related to the error (optional)
  5000. */
  5001. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  5002. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  5003. });
  5004. module.exports = CallStats;
  5005. }).call(this,"/modules/statistics/CallStats.js")
  5006. },{"jitsi-meet-logger":79,"jssha":81,"socket.io-client":118}],23:[function(require,module,exports){
  5007. /* global config */
  5008. /**
  5009. * Provides statistics for the local stream.
  5010. */
  5011. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5012. /**
  5013. * Size of the webaudio analyzer buffer.
  5014. * @type {number}
  5015. */
  5016. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  5017. /**
  5018. * Value of the webaudio analyzer smoothing time parameter.
  5019. * @type {number}
  5020. */
  5021. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  5022. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  5023. var context = null;
  5024. if(window.AudioContext) {
  5025. context = new AudioContext();
  5026. }
  5027. /**
  5028. * Converts time domain data array to audio level.
  5029. * @param samples the time domain data array.
  5030. * @returns {number} the audio level
  5031. */
  5032. function timeDomainDataToAudioLevel(samples) {
  5033. var maxVolume = 0;
  5034. var length = samples.length;
  5035. for (var i = 0; i < length; i++) {
  5036. if (maxVolume < samples[i])
  5037. maxVolume = samples[i];
  5038. }
  5039. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5040. }
  5041. /**
  5042. * Animates audio level change
  5043. * @param newLevel the new audio level
  5044. * @param lastLevel the last audio level
  5045. * @returns {Number} the audio level to be set
  5046. */
  5047. function animateLevel(newLevel, lastLevel) {
  5048. var value = 0;
  5049. var diff = lastLevel - newLevel;
  5050. if(diff > 0.2) {
  5051. value = lastLevel - 0.2;
  5052. }
  5053. else if(diff < -0.4) {
  5054. value = lastLevel + 0.4;
  5055. }
  5056. else {
  5057. value = newLevel;
  5058. }
  5059. return parseFloat(value.toFixed(3));
  5060. }
  5061. /**
  5062. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5063. *
  5064. * @param stream the local stream
  5065. * @param interval stats refresh interval given in ms.
  5066. * @param callback function that receives the audio levels.
  5067. * @constructor
  5068. */
  5069. function LocalStatsCollector(stream, interval, callback) {
  5070. this.stream = stream;
  5071. this.intervalId = null;
  5072. this.intervalMilis = interval;
  5073. this.audioLevel = 0;
  5074. this.callback = callback;
  5075. }
  5076. /**
  5077. * Starts the collecting the statistics.
  5078. */
  5079. LocalStatsCollector.prototype.start = function () {
  5080. if (!context ||
  5081. RTCBrowserType.isTemasysPluginUsed())
  5082. return;
  5083. var analyser = context.createAnalyser();
  5084. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5085. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5086. var source = context.createMediaStreamSource(this.stream);
  5087. source.connect(analyser);
  5088. var self = this;
  5089. this.intervalId = setInterval(
  5090. function () {
  5091. var array = new Uint8Array(analyser.frequencyBinCount);
  5092. analyser.getByteTimeDomainData(array);
  5093. var audioLevel = timeDomainDataToAudioLevel(array);
  5094. if (audioLevel != self.audioLevel) {
  5095. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5096. self.callback(self.audioLevel);
  5097. }
  5098. },
  5099. this.intervalMilis
  5100. );
  5101. };
  5102. /**
  5103. * Stops collecting the statistics.
  5104. */
  5105. LocalStatsCollector.prototype.stop = function () {
  5106. if (this.intervalId) {
  5107. clearInterval(this.intervalId);
  5108. this.intervalId = null;
  5109. }
  5110. };
  5111. module.exports = LocalStatsCollector;
  5112. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5113. (function (__filename){
  5114. /* global require, ssrc2jid */
  5115. /* jshint -W117 */
  5116. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5117. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5118. var StatisticsEvents = require("../../service/statistics/Events");
  5119. /* Whether we support the browser we are running into for logging statistics */
  5120. var browserSupported = RTCBrowserType.isChrome() ||
  5121. RTCBrowserType.isOpera();
  5122. var keyMap = {};
  5123. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5124. "ssrc": "ssrc",
  5125. "packetsReceived": "packetsReceived",
  5126. "packetsLost": "packetsLost",
  5127. "packetsSent": "packetsSent",
  5128. "bytesReceived": "bytesReceived",
  5129. "bytesSent": "bytesSent"
  5130. };
  5131. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5132. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5133. "sendBandwidth": "googAvailableSendBandwidth",
  5134. "remoteAddress": "googRemoteAddress",
  5135. "transportType": "googTransportType",
  5136. "localAddress": "googLocalAddress",
  5137. "activeConnection": "googActiveConnection",
  5138. "ssrc": "ssrc",
  5139. "packetsReceived": "packetsReceived",
  5140. "packetsSent": "packetsSent",
  5141. "packetsLost": "packetsLost",
  5142. "bytesReceived": "bytesReceived",
  5143. "bytesSent": "bytesSent",
  5144. "googFrameHeightReceived": "googFrameHeightReceived",
  5145. "googFrameWidthReceived": "googFrameWidthReceived",
  5146. "googFrameHeightSent": "googFrameHeightSent",
  5147. "googFrameWidthSent": "googFrameWidthSent",
  5148. "audioInputLevel": "audioInputLevel",
  5149. "audioOutputLevel": "audioOutputLevel"
  5150. };
  5151. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5152. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5153. /**
  5154. * Calculates packet lost percent using the number of lost packets and the
  5155. * number of all packet.
  5156. * @param lostPackets the number of lost packets
  5157. * @param totalPackets the number of all packets.
  5158. * @returns {number} packet loss percent
  5159. */
  5160. function calculatePacketLoss(lostPackets, totalPackets) {
  5161. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5162. return 0;
  5163. return Math.round((lostPackets/totalPackets)*100);
  5164. }
  5165. function getStatValue(item, name) {
  5166. var browserType = RTCBrowserType.getBrowserType();
  5167. if (!keyMap[browserType][name])
  5168. throw "The property isn't supported!";
  5169. var key = keyMap[browserType][name];
  5170. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5171. item.stat(key) : item[key];
  5172. }
  5173. function formatAudioLevel(audioLevel) {
  5174. return Math.min(Math.max(audioLevel, 0), 1);
  5175. }
  5176. /**
  5177. * Checks whether a certain record should be included in the logged statistics.
  5178. */
  5179. function acceptStat(reportId, reportType, statName) {
  5180. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5181. return false;
  5182. if (reportType == "ssrc") {
  5183. if (statName == "googTrackId" ||
  5184. statName == "transportId" ||
  5185. statName == "ssrc")
  5186. return false;
  5187. }
  5188. return true;
  5189. }
  5190. /**
  5191. * Checks whether a certain record should be included in the logged statistics.
  5192. */
  5193. function acceptReport(id, type) {
  5194. if (id.substring(0, 15) == "googCertificate" ||
  5195. id.substring(0, 9) == "googTrack" ||
  5196. id.substring(0, 20) == "googLibjingleSession")
  5197. return false;
  5198. if (type == "googComponent")
  5199. return false;
  5200. return true;
  5201. }
  5202. /**
  5203. * Peer statistics data holder.
  5204. * @constructor
  5205. */
  5206. function PeerStats()
  5207. {
  5208. this.ssrc2Loss = {};
  5209. this.ssrc2AudioLevel = {};
  5210. this.ssrc2bitrate = {};
  5211. this.ssrc2resolution = {};
  5212. }
  5213. /**
  5214. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5215. * represented by this instance.
  5216. * @param lossRate new packet loss rate value to be set.
  5217. */
  5218. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5219. {
  5220. this.ssrc2Loss = lossRate;
  5221. };
  5222. /**
  5223. * Sets resolution that belong to the ssrc
  5224. * represented by this instance.
  5225. * @param resolution new resolution value to be set.
  5226. */
  5227. PeerStats.prototype.setSsrcResolution = function (resolution)
  5228. {
  5229. if(resolution === null && this.ssrc2resolution[ssrc])
  5230. {
  5231. delete this.ssrc2resolution[ssrc];
  5232. }
  5233. else if(resolution !== null)
  5234. this.ssrc2resolution[ssrc] = resolution;
  5235. };
  5236. /**
  5237. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5238. * represented by this instance.
  5239. * @param ssrc audio or video RTP stream SSRC.
  5240. * @param bitrate new bitrate value to be set.
  5241. */
  5242. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5243. {
  5244. if(this.ssrc2bitrate[ssrc])
  5245. {
  5246. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5247. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5248. }
  5249. else {
  5250. this.ssrc2bitrate[ssrc] = bitrate;
  5251. }
  5252. };
  5253. /**
  5254. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5255. * the stream which belongs to the peer represented by this instance.
  5256. * @param ssrc RTP stream SSRC for which current audio level value will be
  5257. * updated.
  5258. * @param audioLevel the new audio level value to be set. Value is truncated to
  5259. * fit the range from 0 to 1.
  5260. */
  5261. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5262. {
  5263. // Range limit 0 - 1
  5264. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5265. };
  5266. function ConferenceStats() {
  5267. /**
  5268. * The bandwidth
  5269. * @type {{}}
  5270. */
  5271. this.bandwidth = {};
  5272. /**
  5273. * The bit rate
  5274. * @type {{}}
  5275. */
  5276. this.bitrate = {};
  5277. /**
  5278. * The packet loss rate
  5279. * @type {{}}
  5280. */
  5281. this.packetLoss = null;
  5282. /**
  5283. * Array with the transport information.
  5284. * @type {Array}
  5285. */
  5286. this.transport = [];
  5287. }
  5288. /**
  5289. * <tt>StatsCollector</tt> registers for stats updates of given
  5290. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5291. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5292. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5293. * instance as an event source.
  5294. *
  5295. * @param peerconnection webRTC peer connection object.
  5296. * @param interval stats refresh interval given in ms.
  5297. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5298. * called on stats update.
  5299. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5300. * @constructor
  5301. */
  5302. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5303. {
  5304. this.peerconnection = peerconnection;
  5305. this.baselineAudioLevelsReport = null;
  5306. this.currentAudioLevelsReport = null;
  5307. this.currentStatsReport = null;
  5308. this.baselineStatsReport = null;
  5309. this.audioLevelsIntervalId = null;
  5310. this.eventEmitter = eventEmitter;
  5311. this.config = config || {};
  5312. this.conferenceStats = new ConferenceStats();
  5313. /**
  5314. * Gather PeerConnection stats once every this many milliseconds.
  5315. */
  5316. this.GATHER_INTERVAL = 15000;
  5317. /**
  5318. * Log stats via the focus once every this many milliseconds.
  5319. */
  5320. this.LOG_INTERVAL = 60000;
  5321. /**
  5322. * Gather stats and store them in this.statsToBeLogged.
  5323. */
  5324. this.gatherStatsIntervalId = null;
  5325. /**
  5326. * Send the stats already saved in this.statsToBeLogged to be logged via
  5327. * the focus.
  5328. */
  5329. this.logStatsIntervalId = null;
  5330. /**
  5331. * Stores the statistics which will be send to the focus to be logged.
  5332. */
  5333. this.statsToBeLogged =
  5334. {
  5335. timestamps: [],
  5336. stats: {}
  5337. };
  5338. // Updates stats interval
  5339. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5340. this.statsIntervalId = null;
  5341. this.statsIntervalMilis = statsInterval;
  5342. // Map of ssrcs to PeerStats
  5343. this.ssrc2stats = {};
  5344. }
  5345. module.exports = StatsCollector;
  5346. /**
  5347. * Stops stats updates.
  5348. */
  5349. StatsCollector.prototype.stop = function () {
  5350. if (this.audioLevelsIntervalId) {
  5351. clearInterval(this.audioLevelsIntervalId);
  5352. this.audioLevelsIntervalId = null;
  5353. }
  5354. if (this.statsIntervalId)
  5355. {
  5356. clearInterval(this.statsIntervalId);
  5357. this.statsIntervalId = null;
  5358. }
  5359. if(this.logStatsIntervalId)
  5360. {
  5361. clearInterval(this.logStatsIntervalId);
  5362. this.logStatsIntervalId = null;
  5363. }
  5364. if(this.gatherStatsIntervalId)
  5365. {
  5366. clearInterval(this.gatherStatsIntervalId);
  5367. this.gatherStatsIntervalId = null;
  5368. }
  5369. };
  5370. /**
  5371. * Callback passed to <tt>getStats</tt> method.
  5372. * @param error an error that occurred on <tt>getStats</tt> call.
  5373. */
  5374. StatsCollector.prototype.errorCallback = function (error)
  5375. {
  5376. logger.error("Get stats error", error);
  5377. this.stop();
  5378. };
  5379. /**
  5380. * Starts stats updates.
  5381. */
  5382. StatsCollector.prototype.start = function ()
  5383. {
  5384. var self = this;
  5385. this.audioLevelsIntervalId = setInterval(
  5386. function () {
  5387. // Interval updates
  5388. self.peerconnection.getStats(
  5389. function (report) {
  5390. var results = null;
  5391. if (!report || !report.result ||
  5392. typeof report.result != 'function') {
  5393. results = report;
  5394. }
  5395. else {
  5396. results = report.result();
  5397. }
  5398. //logger.error("Got interval report", results);
  5399. self.currentAudioLevelsReport = results;
  5400. self.processAudioLevelReport();
  5401. self.baselineAudioLevelsReport =
  5402. self.currentAudioLevelsReport;
  5403. },
  5404. self.errorCallback
  5405. );
  5406. },
  5407. self.audioLevelsIntervalMilis
  5408. );
  5409. // if (!this.config.disableStats && browserSupported) {
  5410. // this.statsIntervalId = setInterval(
  5411. // function () {
  5412. // // Interval updates
  5413. // self.peerconnection.getStats(
  5414. // function (report) {
  5415. // var results = null;
  5416. // if (!report || !report.result ||
  5417. // typeof report.result != 'function') {
  5418. // //firefox
  5419. // results = report;
  5420. // }
  5421. // else {
  5422. // //chrome
  5423. // results = report.result();
  5424. // }
  5425. // //logger.error("Got interval report", results);
  5426. // self.currentStatsReport = results;
  5427. // try {
  5428. // self.processStatsReport();
  5429. // }
  5430. // catch (e) {
  5431. // logger.error("Unsupported key:" + e, e);
  5432. // }
  5433. //
  5434. // self.baselineStatsReport = self.currentStatsReport;
  5435. // },
  5436. // self.errorCallback
  5437. // );
  5438. // },
  5439. // self.statsIntervalMilis
  5440. // );
  5441. // }
  5442. //
  5443. // if (this.config.logStats && browserSupported) {
  5444. // this.gatherStatsIntervalId = setInterval(
  5445. // function () {
  5446. // self.peerconnection.getStats(
  5447. // function (report) {
  5448. // self.addStatsToBeLogged(report.result());
  5449. // },
  5450. // function () {
  5451. // }
  5452. // );
  5453. // },
  5454. // this.GATHER_INTERVAL
  5455. // );
  5456. //
  5457. // this.logStatsIntervalId = setInterval(
  5458. // function() { self.logStats(); },
  5459. // this.LOG_INTERVAL);
  5460. // }
  5461. };
  5462. /**
  5463. * Converts the stats to the format used for logging, and saves the data in
  5464. * this.statsToBeLogged.
  5465. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5466. */
  5467. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5468. var self = this;
  5469. var num_records = this.statsToBeLogged.timestamps.length;
  5470. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5471. reports.map(function (report) {
  5472. if (!acceptReport(report.id, report.type))
  5473. return;
  5474. var stat = self.statsToBeLogged.stats[report.id];
  5475. if (!stat) {
  5476. stat = self.statsToBeLogged.stats[report.id] = {};
  5477. }
  5478. stat.type = report.type;
  5479. report.names().map(function (name) {
  5480. if (!acceptStat(report.id, report.type, name))
  5481. return;
  5482. var values = stat[name];
  5483. if (!values) {
  5484. values = stat[name] = [];
  5485. }
  5486. while (values.length < num_records) {
  5487. values.push(null);
  5488. }
  5489. values.push(report.stat(name));
  5490. });
  5491. });
  5492. };
  5493. //FIXME:
  5494. //StatsCollector.prototype.logStats = function () {
  5495. //
  5496. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5497. // return;
  5498. // // Reset the stats
  5499. // this.statsToBeLogged.stats = {};
  5500. // this.statsToBeLogged.timestamps = [];
  5501. //};
  5502. /**
  5503. * Stats processing logic.
  5504. */
  5505. StatsCollector.prototype.processStatsReport = function () {
  5506. if (!this.baselineStatsReport) {
  5507. return;
  5508. }
  5509. for (var idx in this.currentStatsReport) {
  5510. var now = this.currentStatsReport[idx];
  5511. try {
  5512. if (getStatValue(now, 'receiveBandwidth') ||
  5513. getStatValue(now, 'sendBandwidth')) {
  5514. this.conferenceStats.bandwidth = {
  5515. "download": Math.round(
  5516. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5517. "upload": Math.round(
  5518. (getStatValue(now, 'sendBandwidth')) / 1000)
  5519. };
  5520. }
  5521. }
  5522. catch(e){/*not supported*/}
  5523. if(now.type == 'googCandidatePair')
  5524. {
  5525. var ip, type, localIP, active;
  5526. try {
  5527. ip = getStatValue(now, 'remoteAddress');
  5528. type = getStatValue(now, "transportType");
  5529. localIP = getStatValue(now, "localAddress");
  5530. active = getStatValue(now, "activeConnection");
  5531. }
  5532. catch(e){/*not supported*/}
  5533. if(!ip || !type || !localIP || active != "true")
  5534. continue;
  5535. var addressSaved = false;
  5536. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5537. {
  5538. if(this.conferenceStats.transport[i].ip == ip &&
  5539. this.conferenceStats.transport[i].type == type &&
  5540. this.conferenceStats.transport[i].localip == localIP)
  5541. {
  5542. addressSaved = true;
  5543. }
  5544. }
  5545. if(addressSaved)
  5546. continue;
  5547. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5548. continue;
  5549. }
  5550. if(now.type == "candidatepair")
  5551. {
  5552. if(now.state == "succeeded")
  5553. continue;
  5554. var local = this.currentStatsReport[now.localCandidateId];
  5555. var remote = this.currentStatsReport[now.remoteCandidateId];
  5556. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5557. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5558. }
  5559. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5560. now.type != "inboundrtp") {
  5561. continue;
  5562. }
  5563. var before = this.baselineStatsReport[idx];
  5564. if (!before) {
  5565. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5566. continue;
  5567. }
  5568. var ssrc = getStatValue(now, 'ssrc');
  5569. if(!ssrc)
  5570. continue;
  5571. var ssrcStats = this.ssrc2stats[ssrc];
  5572. if (!ssrcStats) {
  5573. ssrcStats = new PeerStats();
  5574. this.ssrc2stats[ssrc] = ssrcStats;
  5575. }
  5576. var isDownloadStream = true;
  5577. var key = 'packetsReceived';
  5578. var packetsNow = getStatValue(now, key);
  5579. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5580. isDownloadStream = false;
  5581. key = 'packetsSent';
  5582. packetsNow = getStatValue(now, key);
  5583. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5584. console.warn("No packetsReceived nor packetsSent stat found");
  5585. continue;
  5586. }
  5587. }
  5588. if (!packetsNow || packetsNow < 0)
  5589. packetsNow = 0;
  5590. var packetsBefore = getStatValue(before, key);
  5591. if (!packetsBefore || packetsBefore < 0)
  5592. packetsBefore = 0;
  5593. var packetRate = packetsNow - packetsBefore;
  5594. if (!packetRate || packetRate < 0)
  5595. packetRate = 0;
  5596. var currentLoss = getStatValue(now, 'packetsLost');
  5597. if (!currentLoss || currentLoss < 0)
  5598. currentLoss = 0;
  5599. var previousLoss = getStatValue(before, 'packetsLost');
  5600. if (!previousLoss || previousLoss < 0)
  5601. previousLoss = 0;
  5602. var lossRate = currentLoss - previousLoss;
  5603. if (!lossRate || lossRate < 0)
  5604. lossRate = 0;
  5605. var packetsTotal = (packetRate + lossRate);
  5606. ssrcStats.setSsrcLoss(ssrc,
  5607. {"packetsTotal": packetsTotal,
  5608. "packetsLost": lossRate,
  5609. "isDownloadStream": isDownloadStream});
  5610. var bytesReceived = 0, bytesSent = 0;
  5611. if(getStatValue(now, "bytesReceived")) {
  5612. bytesReceived = getStatValue(now, "bytesReceived") -
  5613. getStatValue(before, "bytesReceived");
  5614. }
  5615. if (getStatValue(now, "bytesSent")) {
  5616. bytesSent = getStatValue(now, "bytesSent") -
  5617. getStatValue(before, "bytesSent");
  5618. }
  5619. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5620. if (bytesReceived <= 0 || time <= 0) {
  5621. bytesReceived = 0;
  5622. } else {
  5623. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5624. }
  5625. if (bytesSent <= 0 || time <= 0) {
  5626. bytesSent = 0;
  5627. } else {
  5628. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5629. }
  5630. ssrcStats.setSsrcBitrate(ssrc, {
  5631. "download": bytesReceived,
  5632. "upload": bytesSent});
  5633. var resolution = {height: null, width: null};
  5634. try {
  5635. if (getStatValue(now, "googFrameHeightReceived") &&
  5636. getStatValue(now, "googFrameWidthReceived")) {
  5637. resolution.height =
  5638. getStatValue(now, "googFrameHeightReceived");
  5639. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5640. }
  5641. else if (getStatValue(now, "googFrameHeightSent") &&
  5642. getStatValue(now, "googFrameWidthSent")) {
  5643. resolution.height = getStatValue(now, "googFrameHeightSent");
  5644. resolution.width = getStatValue(now, "googFrameWidthSent");
  5645. }
  5646. }
  5647. catch(e){/*not supported*/}
  5648. if (resolution.height && resolution.width) {
  5649. ssrcStats.setSsrcResolution(ssrc, resolution);
  5650. } else {
  5651. ssrcStats.setSsrcResolution(ssrc, null);
  5652. }
  5653. }
  5654. var self = this;
  5655. // Jid stats
  5656. var totalPackets = {download: 0, upload: 0};
  5657. var lostPackets = {download: 0, upload: 0};
  5658. var bitrateDownload = 0;
  5659. var bitrateUpload = 0;
  5660. var resolutions = {};
  5661. Object.keys(this.ssrc2stats).forEach(
  5662. function (jid) {
  5663. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5664. function (ssrc) {
  5665. var type = "upload";
  5666. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5667. type = "download";
  5668. totalPackets[type] +=
  5669. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5670. lostPackets[type] +=
  5671. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5672. }
  5673. );
  5674. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5675. function (ssrc) {
  5676. bitrateDownload +=
  5677. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5678. bitrateUpload +=
  5679. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5680. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5681. }
  5682. );
  5683. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5684. }
  5685. );
  5686. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5687. this.conferenceStats.packetLoss = {
  5688. total:
  5689. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5690. totalPackets.download + totalPackets.upload),
  5691. download:
  5692. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5693. upload:
  5694. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5695. };
  5696. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5697. {
  5698. "bitrate": this.conferenceStats.bitrate,
  5699. "packetLoss": this.conferenceStats.packetLoss,
  5700. "bandwidth": this.conferenceStats.bandwidth,
  5701. "resolution": resolutions,
  5702. "transport": this.conferenceStats.transport
  5703. });
  5704. this.conferenceStats.transport = [];
  5705. };
  5706. /**
  5707. * Stats processing logic.
  5708. */
  5709. StatsCollector.prototype.processAudioLevelReport = function () {
  5710. if (!this.baselineAudioLevelsReport) {
  5711. return;
  5712. }
  5713. for (var idx in this.currentAudioLevelsReport) {
  5714. var now = this.currentAudioLevelsReport[idx];
  5715. //if we don't have "packetsReceived" this is local stream
  5716. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5717. continue;
  5718. }
  5719. var before = this.baselineAudioLevelsReport[idx];
  5720. if (!before) {
  5721. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5722. continue;
  5723. }
  5724. var ssrc = getStatValue(now, 'ssrc');
  5725. if (!ssrc) {
  5726. if((Date.now() - now.timestamp) < 3000)
  5727. logger.warn("No ssrc: ");
  5728. continue;
  5729. }
  5730. var ssrcStats = this.ssrc2stats[ssrc];
  5731. if (!ssrcStats) {
  5732. ssrcStats = new PeerStats();
  5733. this.ssrc2stats[ssrc] = ssrcStats;
  5734. }
  5735. // Audio level
  5736. var audioLevel = null;
  5737. try {
  5738. audioLevel = getStatValue(now, 'audioInputLevel');
  5739. if (!audioLevel)
  5740. audioLevel = getStatValue(now, 'audioOutputLevel');
  5741. }
  5742. catch(e) {/*not supported*/
  5743. logger.warn("Audio Levels are not available in the statistics.");
  5744. clearInterval(this.audioLevelsIntervalId);
  5745. return;
  5746. }
  5747. if (audioLevel) {
  5748. // TODO: can't find specs about what this value really is,
  5749. // but it seems to vary between 0 and around 32k.
  5750. audioLevel = audioLevel / 32767;
  5751. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5752. this.eventEmitter.emit(
  5753. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5754. }
  5755. }
  5756. };
  5757. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5758. },{"../../service/statistics/Events":135,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":79}],25:[function(require,module,exports){
  5759. /* global require, APP */
  5760. var LocalStats = require("./LocalStatsCollector.js");
  5761. var RTPStats = require("./RTPStatsCollector.js");
  5762. var EventEmitter = require("events");
  5763. var StatisticsEvents = require("../../service/statistics/Events");
  5764. var CallStats = require("./CallStats");
  5765. var ScriptUtil = require('../util/ScriptUtil');
  5766. // Since callstats.io is a third party, we cannot guarantee the quality of
  5767. // their service. More specifically, their server may take noticeably long
  5768. // time to respond. Consequently, it is in our best interest (in the sense
  5769. // that the intergration of callstats.io is pretty important to us but not
  5770. // enough to allow it to prevent people from joining a conference) to (1)
  5771. // start downloading their API as soon as possible and (2) do the
  5772. // downloading asynchronously.
  5773. function loadCallStatsAPI() {
  5774. ScriptUtil.loadScript(
  5775. 'https://api.callstats.io/static/callstats.min.js',
  5776. /* async */ true,
  5777. /* prepend */ true);
  5778. // FIXME At the time of this writing, we hope that the callstats.io API will
  5779. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5780. }
  5781. var eventEmitter = new EventEmitter();
  5782. function Statistics(options) {
  5783. this.rtpStats = null;
  5784. this.eventEmitter = new EventEmitter();
  5785. this.options = options || {};
  5786. this.callStatsIntegrationEnabled
  5787. = this.options.callStatsID && this.options.callStatsSecret
  5788. // Even though AppID and AppSecret may be specified, the integration of
  5789. // callstats.io may be disabled because of globally-disallowed requests
  5790. // to any third parties.
  5791. && (this.options.disableThirdPartyRequests !== true);
  5792. if(this.callStatsIntegrationEnabled)
  5793. loadCallStatsAPI();
  5794. this.callStats = null;
  5795. }
  5796. Statistics.audioLevelsEnabled = false;
  5797. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5798. if(!Statistics.audioLevelsEnabled)
  5799. return;
  5800. if (this.rtpStats) {
  5801. this.rtpStats.stop();
  5802. }
  5803. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5804. this.rtpStats.start();
  5805. }
  5806. Statistics.localStats = [];
  5807. Statistics.startLocalStats = function (stream, callback) {
  5808. if(!Statistics.audioLevelsEnabled)
  5809. return;
  5810. var localStats = new LocalStats(stream, 200, callback);
  5811. this.localStats.push(localStats);
  5812. localStats.start();
  5813. }
  5814. Statistics.prototype.addAudioLevelListener = function(listener)
  5815. {
  5816. if(!Statistics.audioLevelsEnabled)
  5817. return;
  5818. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5819. }
  5820. Statistics.prototype.removeAudioLevelListener = function(listener)
  5821. {
  5822. if(!Statistics.audioLevelsEnabled)
  5823. return;
  5824. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5825. }
  5826. Statistics.prototype.dispose = function () {
  5827. if(Statistics.audioLevelsEnabled) {
  5828. Statistics.stopAllLocalStats();
  5829. this.stopRemote();
  5830. if(this.eventEmitter)
  5831. this.eventEmitter.removeAllListeners();
  5832. if(eventEmitter)
  5833. eventEmitter.removeAllListeners();
  5834. }
  5835. if(this.callstats)
  5836. {
  5837. this.callstats.sendTerminateEvent();
  5838. this.callstats = null;
  5839. }
  5840. }
  5841. Statistics.stopAllLocalStats = function () {
  5842. if(!Statistics.audioLevelsEnabled)
  5843. return;
  5844. for(var i = 0; i < this.localStats.length; i++)
  5845. this.localStats[i].stop();
  5846. this.localStats = [];
  5847. }
  5848. Statistics.stopLocalStats = function (stream) {
  5849. if(!Statistics.audioLevelsEnabled)
  5850. return;
  5851. for(var i = 0; i < Statistics.localStats.length; i++)
  5852. if(Statistics.localStats[i].stream === stream){
  5853. var localStats = Statistics.localStats.splice(i, 1);
  5854. localStats.stop();
  5855. break;
  5856. }
  5857. }
  5858. Statistics.prototype.stopRemote = function () {
  5859. if (this.rtpStats && Statistics.audioLevelsEnabled) {
  5860. this.rtpStats.stop();
  5861. this.eventEmitter.emit(StatisticsEvents.STOP);
  5862. this.rtpStats = null;
  5863. }
  5864. };
  5865. /**
  5866. * Obtains audio level reported in the stats for specified peer.
  5867. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5868. * audio level.
  5869. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5870. * level.
  5871. * @returns {*} a float form 0 to 1 that represents current audio level or
  5872. * <tt>null</tt> if for any reason the value is not available
  5873. * at this time.
  5874. */
  5875. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5876. if(!Statistics.audioLevelsEnabled)
  5877. return;
  5878. var peerStats = this.rtpStats.jid2stats[peerJid];
  5879. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5880. };
  5881. //CALSTATS METHODS
  5882. /**
  5883. * Initializes the callstats.io API.
  5884. * @param peerConnection {JingleSessionPC} the session object
  5885. * @param Settings {Settings} the settings instance. Declared in
  5886. * /modules/settings/Settings.js
  5887. */
  5888. Statistics.prototype.startCallStats = function (session, settings) {
  5889. if(this.callStatsIntegrationEnabled && !this.callstats) {
  5890. this.callstats = new CallStats(session, settings, this.options);
  5891. }
  5892. }
  5893. /**
  5894. * Returns true if the callstats integration is enabled, otherwise returns
  5895. * false.
  5896. *
  5897. * @returns true if the callstats integration is enabled, otherwise returns
  5898. * false.
  5899. */
  5900. Statistics.prototype.isCallstatsEnabled = function () {
  5901. return this.callStatsIntegrationEnabled;
  5902. }
  5903. /**
  5904. * Notifies CallStats for connection setup errors
  5905. */
  5906. Statistics.prototype.sendSetupFailedEvent = function () {
  5907. if(this.callStatsIntegrationEnabled && this.callstats)
  5908. this.callstats.sendSetupFailedEvent();
  5909. }
  5910. /**
  5911. * Notifies CallStats for mute events
  5912. * @param mute {boolean} true for muted and false for not muted
  5913. * @param type {String} "audio"/"video"
  5914. */
  5915. Statistics.prototype.sendMuteEvent = function (muted, type) {
  5916. if(this.callStatsIntegrationEnabled && this.callstats)
  5917. this.callstats.sendMuteEvent(muted, type);
  5918. }
  5919. /**
  5920. * Notifies CallStats that getUserMedia failed.
  5921. *
  5922. * @param {Error} e error to send
  5923. */
  5924. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  5925. if(this.callStatsIntegrationEnabled)
  5926. CallStats.sendGetUserMediaFailed(e, this.callstats);
  5927. };
  5928. /**
  5929. * Notifies CallStats that getUserMedia failed.
  5930. *
  5931. * @param {Error} e error to send
  5932. */
  5933. Statistics.sendGetUserMediaFailed = function (e) {
  5934. CallStats.sendGetUserMediaFailed(e, null);
  5935. };
  5936. /**
  5937. * Notifies CallStats that peer connection failed to create offer.
  5938. *
  5939. * @param {Error} e error to send
  5940. * @param {RTCPeerConnection} pc connection on which failure occured.
  5941. */
  5942. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  5943. if(this.callStatsIntegrationEnabled)
  5944. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  5945. };
  5946. /**
  5947. * Notifies CallStats that peer connection failed to create answer.
  5948. *
  5949. * @param {Error} e error to send
  5950. * @param {RTCPeerConnection} pc connection on which failure occured.
  5951. */
  5952. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  5953. if(this.callStatsIntegrationEnabled)
  5954. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  5955. };
  5956. /**
  5957. * Notifies CallStats that peer connection failed to set local description.
  5958. *
  5959. * @param {Error} e error to send
  5960. * @param {RTCPeerConnection} pc connection on which failure occured.
  5961. */
  5962. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  5963. if(this.callStatsIntegrationEnabled)
  5964. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  5965. }
  5966. /**
  5967. * Notifies CallStats that peer connection failed to set remote description.
  5968. *
  5969. * @param {Error} e error to send
  5970. * @param {RTCPeerConnection} pc connection on which failure occured.
  5971. */
  5972. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  5973. if(this.callStatsIntegrationEnabled)
  5974. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  5975. }
  5976. /**
  5977. * Notifies CallStats that peer connection failed to add ICE candidate.
  5978. *
  5979. * @param {Error} e error to send
  5980. * @param {RTCPeerConnection} pc connection on which failure occured.
  5981. */
  5982. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  5983. if(this.callStatsIntegrationEnabled)
  5984. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  5985. }
  5986. /**
  5987. * Sends the given feedback through CallStats.
  5988. *
  5989. * @param overallFeedback an integer between 1 and 5 indicating the
  5990. * user feedback
  5991. * @param detailedFeedback detailed feedback from the user. Not yet used
  5992. */
  5993. Statistics.prototype.sendFeedback =
  5994. function(overallFeedback, detailedFeedback){
  5995. if(this.callStatsIntegrationEnabled && this.callstats)
  5996. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  5997. }
  5998. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  5999. module.exports = Statistics;
  6000. },{"../../service/statistics/Events":135,"../../service/statistics/constants":136,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":51}],26:[function(require,module,exports){
  6001. /**
  6002. /**
  6003. * @const
  6004. */
  6005. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6006. /**
  6007. * Hexadecimal digits.
  6008. * @const
  6009. */
  6010. var HEX_DIGITS = '0123456789abcdef';
  6011. /**
  6012. * Generates random int within the range [min, max]
  6013. * @param min the minimum value for the generated number
  6014. * @param max the maximum value for the generated number
  6015. * @returns random int number
  6016. */
  6017. function randomInt(min, max) {
  6018. return Math.floor(Math.random() * (max - min + 1)) + min;
  6019. }
  6020. /**
  6021. * Get random element from array or string.
  6022. * @param {Array|string} arr source
  6023. * @returns array element or string character
  6024. */
  6025. function randomElement(arr) {
  6026. return arr[randomInt(0, arr.length - 1)];
  6027. }
  6028. /**
  6029. * Generate random alphanumeric string.
  6030. * @param {number} length expected string length
  6031. * @returns {string} random string of specified length
  6032. */
  6033. function randomAlphanumStr(length) {
  6034. var result = '';
  6035. for (var i = 0; i < length; i += 1) {
  6036. result += randomElement(ALPHANUM);
  6037. }
  6038. return result;
  6039. }
  6040. /**
  6041. * Exported interface.
  6042. */
  6043. var RandomUtil = {
  6044. /**
  6045. * Returns a random hex digit.
  6046. * @returns {*}
  6047. */
  6048. randomHexDigit: function() {
  6049. return randomElement(HEX_DIGITS);
  6050. },
  6051. /**
  6052. * Returns a random string of hex digits with length 'len'.
  6053. * @param len the length.
  6054. */
  6055. randomHexString: function (len) {
  6056. var ret = '';
  6057. while (len--) {
  6058. ret += this.randomHexDigit();
  6059. }
  6060. return ret;
  6061. },
  6062. randomElement: randomElement,
  6063. randomAlphanumStr: randomAlphanumStr,
  6064. randomInt: randomInt
  6065. };
  6066. module.exports = RandomUtil;
  6067. },{}],27:[function(require,module,exports){
  6068. /**
  6069. * Implements utility functions which facilitate the dealing with scripts such
  6070. * as the download and execution of a JavaScript file.
  6071. */
  6072. var ScriptUtil = {
  6073. /**
  6074. * Loads a script from a specific source.
  6075. *
  6076. * @param src the source from the which the script is to be (down)loaded
  6077. * @param async true to asynchronously load the script or false to
  6078. * synchronously load the script
  6079. * @param prepend true to schedule the loading of the script as soon as
  6080. * possible or false to schedule the loading of the script at the end of the
  6081. * scripts known at the time
  6082. */
  6083. loadScript: function (src, async, prepend) {
  6084. var d = document;
  6085. var tagName = 'script';
  6086. var script = d.createElement(tagName);
  6087. var referenceNode = d.getElementsByTagName(tagName)[0];
  6088. script.async = async;
  6089. script.src = src;
  6090. if (prepend) {
  6091. referenceNode.parentNode.insertBefore(script, referenceNode);
  6092. } else {
  6093. referenceNode.parentNode.appendChild(script);
  6094. }
  6095. },
  6096. };
  6097. module.exports = ScriptUtil;
  6098. },{}],28:[function(require,module,exports){
  6099. var RandomUtil = require('./RandomUtil');
  6100. /**
  6101. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6102. * MIT License
  6103. * http://github.com/marak/faker.js/
  6104. *
  6105. * @const
  6106. */
  6107. var names = [
  6108. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6109. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6110. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6111. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6112. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6113. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6114. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6115. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6116. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6117. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6118. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6119. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6120. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6121. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6122. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6123. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6124. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6125. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6126. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6127. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6128. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6129. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6130. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6131. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6132. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6133. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6134. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6135. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6136. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6137. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6138. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6139. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6140. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6141. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6142. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6143. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6144. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6145. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6146. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6147. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6148. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6149. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6150. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6151. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6152. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6153. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6154. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6155. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6156. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6157. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6158. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6159. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6160. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6161. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6162. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6163. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6164. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6165. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6166. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6167. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6168. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6169. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6170. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6171. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6172. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6173. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6174. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6175. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6176. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6177. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6178. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6179. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6180. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6181. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6182. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6183. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6184. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6185. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6186. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6187. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6188. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6189. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6190. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6191. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6192. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6193. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6194. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6195. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6196. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6197. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6198. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6199. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6200. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6201. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6202. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6203. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6204. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6205. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6206. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6207. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6208. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6209. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6210. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6211. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6212. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6213. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6214. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6215. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6216. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6217. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6218. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6219. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6220. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6221. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6222. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6223. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6224. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6225. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6226. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6227. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6228. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6229. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6230. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6231. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6232. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6233. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6234. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6235. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6236. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6237. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6238. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6239. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6240. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6241. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6242. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6243. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6244. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6245. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6246. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6247. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6248. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6249. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6250. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6251. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6252. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6253. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6254. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6255. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6256. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6257. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6258. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6259. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6260. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6261. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6262. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6263. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6264. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6265. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6266. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6267. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6268. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6269. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6270. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6271. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6272. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6273. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6274. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6275. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6276. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6277. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6278. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6279. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6280. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6281. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6282. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6283. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6284. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6285. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6286. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6287. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6288. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6289. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6290. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6291. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6292. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6293. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6294. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6295. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6296. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6297. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6298. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6299. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6300. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6301. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6302. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6303. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6304. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6305. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6306. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6307. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6308. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6309. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6310. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6311. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6312. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6313. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6314. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6315. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6316. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6317. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6318. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6319. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6320. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6321. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6322. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6323. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6324. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6325. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6326. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6327. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6328. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6329. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6330. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6331. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6332. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6333. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6334. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6335. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6336. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6337. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6338. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6339. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6340. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6341. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6342. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6343. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6344. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6345. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6346. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6347. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6348. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6349. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6350. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6351. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6352. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6353. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6354. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6355. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6356. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6357. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6358. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6359. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6360. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6361. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6362. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6363. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6364. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6365. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6366. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6367. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6368. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6369. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6370. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6371. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6372. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6373. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6374. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6375. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6376. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6377. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6378. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6379. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6380. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6381. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6382. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6383. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6384. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6385. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6386. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6387. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6388. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6389. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6390. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6391. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6392. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6393. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6394. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6395. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6396. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6397. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6398. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6399. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6400. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6401. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6402. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6403. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6404. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6405. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6406. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6407. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6408. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6409. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6410. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6411. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6412. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6413. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6414. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6415. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6416. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6417. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6418. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6419. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6420. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6421. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6422. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6423. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6424. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6425. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6426. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6427. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6428. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6429. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6430. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6431. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6432. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6433. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6434. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6435. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6436. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6437. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6438. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6439. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6440. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6441. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6442. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6443. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6444. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6445. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6446. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6447. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6448. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6449. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6450. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6451. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6452. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6453. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6454. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6455. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6456. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6457. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6458. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6459. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6460. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6461. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6462. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6463. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6464. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6465. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6466. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6467. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6468. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6469. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6470. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6471. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6472. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6473. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6474. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6475. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6476. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6477. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6478. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6479. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6480. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6481. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6482. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6483. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6484. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6485. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6486. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6487. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6488. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6489. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6490. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6491. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6492. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6493. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6494. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6495. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6496. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6497. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6498. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6499. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6500. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6501. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6502. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6503. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6504. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6505. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6506. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6507. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6508. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6509. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6510. "Zora", "Zula"
  6511. ];
  6512. /**
  6513. * Generate random username.
  6514. * @returns {string} random username
  6515. */
  6516. function generateUsername () {
  6517. var name = RandomUtil.randomElement(names);
  6518. var suffix = RandomUtil.randomAlphanumStr(3);
  6519. return name + '-' + suffix;
  6520. }
  6521. module.exports = {
  6522. generateUsername: generateUsername
  6523. };
  6524. },{"./RandomUtil":26}],29:[function(require,module,exports){
  6525. (function (__filename){
  6526. /* global Strophe, $, $pres, $iq, $msg */
  6527. /* jshint -W101,-W069 */
  6528. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6529. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6530. var Moderator = require("./moderator");
  6531. var EventEmitter = require("events");
  6532. var Recorder = require("./recording");
  6533. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6534. var parser = {
  6535. packet2JSON: function (packet, nodes) {
  6536. var self = this;
  6537. $(packet).children().each(function (index) {
  6538. var tagName = $(this).prop("tagName");
  6539. var node = {
  6540. tagName: tagName
  6541. };
  6542. node.attributes = {};
  6543. $($(this)[0].attributes).each(function( index, attr ) {
  6544. node.attributes[ attr.name ] = attr.value;
  6545. });
  6546. var text = Strophe.getText($(this)[0]);
  6547. if (text) {
  6548. node.value = text;
  6549. }
  6550. node.children = [];
  6551. nodes.push(node);
  6552. self.packet2JSON($(this), node.children);
  6553. });
  6554. },
  6555. JSON2packet: function (nodes, packet) {
  6556. for(var i = 0; i < nodes.length; i++) {
  6557. var node = nodes[i];
  6558. if(!node || node === null){
  6559. continue;
  6560. }
  6561. packet.c(node.tagName, node.attributes);
  6562. if(node.value)
  6563. packet.t(node.value);
  6564. if(node.children)
  6565. this.JSON2packet(node.children, packet);
  6566. packet.up();
  6567. }
  6568. // packet.up();
  6569. }
  6570. };
  6571. /**
  6572. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6573. * @param pres the presence JSON
  6574. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6575. */
  6576. function filterNodeFromPresenceJSON(pres, nodeName){
  6577. var res = [];
  6578. for(var i = 0; i < pres.length; i++)
  6579. if(pres[i].tagName === nodeName)
  6580. res.push(pres[i]);
  6581. return res;
  6582. }
  6583. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6584. this.eventEmitter = new EventEmitter();
  6585. this.xmpp = XMPP;
  6586. this.connection = connection;
  6587. this.roomjid = Strophe.getBareJidFromJid(jid);
  6588. this.myroomjid = jid;
  6589. this.password = password;
  6590. logger.info("Joined MUC as " + this.myroomjid);
  6591. this.members = {};
  6592. this.presMap = {};
  6593. this.presHandlers = {};
  6594. this.joined = false;
  6595. this.role = 'none';
  6596. this.focusMucJid = null;
  6597. this.bridgeIsDown = false;
  6598. this.options = options || {};
  6599. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6600. settings);
  6601. this.initPresenceMap();
  6602. this.session = null;
  6603. var self = this;
  6604. this.lastPresences = {};
  6605. this.phoneNumber = null;
  6606. this.phonePin = null;
  6607. }
  6608. ChatRoom.prototype.initPresenceMap = function () {
  6609. this.presMap['to'] = this.myroomjid;
  6610. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6611. this.presMap["nodes"] = [];
  6612. this.presMap["nodes"].push( {
  6613. "tagName": "user-agent",
  6614. "value": navigator.userAgent,
  6615. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6616. });
  6617. };
  6618. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6619. this.presMap["nodes"].push( {
  6620. "tagName": "devices",
  6621. "children": [
  6622. {
  6623. "tagName": "audio",
  6624. "value": devices.audio,
  6625. },
  6626. {
  6627. "tagName": "video",
  6628. "value": devices.video,
  6629. }
  6630. ]
  6631. });
  6632. };
  6633. ChatRoom.prototype.join = function (password) {
  6634. if(password)
  6635. this.password = password;
  6636. var self = this;
  6637. this.moderator.allocateConferenceFocus(function()
  6638. {
  6639. self.sendPresence(true);
  6640. }.bind(this));
  6641. };
  6642. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6643. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6644. // Too early to send presence - not initialized
  6645. return;
  6646. }
  6647. var pres = $pres({to: this.presMap['to'] });
  6648. pres.c('x', {xmlns: this.presMap['xns']});
  6649. if (this.password) {
  6650. pres.c('password').t(this.password).up();
  6651. }
  6652. pres.up();
  6653. // Send XEP-0115 'c' stanza that contains our capabilities info
  6654. if (this.connection.caps) {
  6655. this.connection.caps.node = this.xmpp.options.clientNode;
  6656. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6657. }
  6658. parser.JSON2packet(this.presMap.nodes, pres);
  6659. this.connection.send(pres);
  6660. };
  6661. ChatRoom.prototype.doLeave = function () {
  6662. logger.log("do leave", this.myroomjid);
  6663. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6664. this.presMap.length = 0;
  6665. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  6666. // means that there may not be enough time to send the unavailable presence.
  6667. // Switching Strophe to synchronous sending is not much of an option because
  6668. // it may lead to a noticeable delay in navigating away from the current
  6669. // location. As a compromise, we will try to increase the chances of sending
  6670. // the unavailable presence within the short time span that we have upon
  6671. // unloading by invoking flush() on the connection. We flush() once before
  6672. // sending/queuing the unavailable presence in order to attemtp to have the
  6673. // unavailable presence at the top of the send queue. We flush() once more
  6674. // after sending/queuing the unavailable presence in order to attempt to
  6675. // have it sent as soon as possible.
  6676. this.connection.flush();
  6677. this.connection.send(pres);
  6678. this.connection.flush();
  6679. };
  6680. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6681. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6682. var getForm = $iq({type: 'get', to: this.roomjid})
  6683. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6684. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6685. var self = this;
  6686. this.connection.sendIQ(getForm, function (form) {
  6687. if (!$(form).find(
  6688. '>query>x[xmlns="jabber:x:data"]' +
  6689. '>field[var="muc#roomconfig_whois"]').length) {
  6690. logger.error('non-anonymous rooms not supported');
  6691. return;
  6692. }
  6693. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6694. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6695. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6696. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6697. .c('value')
  6698. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6699. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6700. .c('value').t('anyone').up().up();
  6701. self.connection.sendIQ(formSubmit);
  6702. }, function (error) {
  6703. logger.error("Error getting room configuration form");
  6704. });
  6705. };
  6706. ChatRoom.prototype.onPresence = function (pres) {
  6707. var from = pres.getAttribute('from');
  6708. // Parse roles.
  6709. var member = {};
  6710. member.show = $(pres).find('>show').text();
  6711. member.status = $(pres).find('>status').text();
  6712. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6713. member.affiliation = tmp.attr('affiliation');
  6714. member.role = tmp.attr('role');
  6715. // Focus recognition
  6716. member.jid = tmp.attr('jid');
  6717. member.isFocus = false;
  6718. if (member.jid
  6719. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6720. member.isFocus = true;
  6721. }
  6722. $(pres).find(">x").remove();
  6723. var nodes = [];
  6724. parser.packet2JSON(pres, nodes);
  6725. this.lastPresences[from] = nodes;
  6726. var jibri = null;
  6727. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6728. // events
  6729. for(var i = 0; i < nodes.length; i++)
  6730. {
  6731. var node = nodes[i];
  6732. switch(node.tagName)
  6733. {
  6734. case "nick":
  6735. member.nick = node.value;
  6736. break;
  6737. case "userId":
  6738. member.id = node.value;
  6739. break;
  6740. }
  6741. }
  6742. if (from == this.myroomjid) {
  6743. if (member.affiliation == 'owner'
  6744. && this.role !== member.role) {
  6745. this.role = member.role;
  6746. this.eventEmitter.emit(
  6747. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6748. }
  6749. if (!this.joined) {
  6750. this.joined = true;
  6751. console.log("(TIME) MUC joined:\t", window.performance.now());
  6752. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6753. }
  6754. } else if (this.members[from] === undefined) {
  6755. // new participant
  6756. this.members[from] = member;
  6757. logger.log('entered', from, member);
  6758. if (member.isFocus) {
  6759. this.focusMucJid = from;
  6760. if(!this.recording) {
  6761. this.recording = new Recorder(this.options.recordingType,
  6762. this.eventEmitter, this.connection, this.focusMucJid,
  6763. this.options.jirecon, this.roomjid);
  6764. if(this.lastJibri)
  6765. this.recording.handleJibriPresence(this.lastJibri);
  6766. }
  6767. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6768. }
  6769. else {
  6770. this.eventEmitter.emit(
  6771. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6772. }
  6773. } else {
  6774. // Presence update for existing participant
  6775. // Watch role change:
  6776. if (this.members[from].role != member.role) {
  6777. this.members[from].role = member.role;
  6778. this.eventEmitter.emit(
  6779. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6780. }
  6781. // store the new display name
  6782. if(member.displayName)
  6783. this.members[from].displayName = member.displayName;
  6784. }
  6785. // after we had fired member or room joined events, lets fire events
  6786. // for the rest info we got in presence
  6787. for(var i = 0; i < nodes.length; i++)
  6788. {
  6789. var node = nodes[i];
  6790. switch(node.tagName)
  6791. {
  6792. case "nick":
  6793. if(!member.isFocus) {
  6794. var displayName = !this.xmpp.options.displayJids
  6795. ? member.nick : Strophe.getResourceFromJid(from);
  6796. if (displayName && displayName.length > 0) {
  6797. this.eventEmitter.emit(
  6798. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6799. }
  6800. }
  6801. break;
  6802. case "bridgeIsDown":
  6803. if(!this.bridgeIsDown) {
  6804. this.bridgeIsDown = true;
  6805. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6806. }
  6807. break;
  6808. case "jibri-recording-status":
  6809. var jibri = node;
  6810. break;
  6811. case "call-control":
  6812. var att = node.attributes;
  6813. if(!att)
  6814. break;
  6815. this.phoneNumber = att.phone || null;
  6816. this.phonePin = att.pin || null;
  6817. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  6818. break;
  6819. default :
  6820. this.processNode(node, from);
  6821. }
  6822. }
  6823. if(!member.isFocus)
  6824. this.eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, member.id);
  6825. // Trigger status message update
  6826. if (member.status) {
  6827. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  6828. }
  6829. if(jibri)
  6830. {
  6831. this.lastJibri = jibri;
  6832. if(this.recording)
  6833. this.recording.handleJibriPresence(jibri);
  6834. }
  6835. };
  6836. ChatRoom.prototype.processNode = function (node, from) {
  6837. if(this.presHandlers[node.tagName])
  6838. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  6839. };
  6840. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6841. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6842. msg.c('body', body).up();
  6843. if (nickname) {
  6844. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6845. }
  6846. this.connection.send(msg);
  6847. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6848. };
  6849. ChatRoom.prototype.setSubject = function (subject) {
  6850. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6851. msg.c('subject', subject);
  6852. this.connection.send(msg);
  6853. logger.log("topic changed to " + subject);
  6854. };
  6855. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6856. delete this.lastPresences[jid];
  6857. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6858. this.moderator.onMucMemberLeft(jid);
  6859. };
  6860. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6861. // room destroyed ?
  6862. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6863. '>destroy').length) {
  6864. var reason;
  6865. var reasonSelect = $(pres).find(
  6866. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6867. '>destroy>reason');
  6868. if (reasonSelect.length) {
  6869. reason = reasonSelect.text();
  6870. }
  6871. this.xmpp.leaveRoom(this.roomjid);
  6872. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  6873. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  6874. return true;
  6875. }
  6876. // Status code 110 indicates that this notification is "self-presence".
  6877. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  6878. delete this.members[from];
  6879. this.onParticipantLeft(from);
  6880. }
  6881. // If the status code is 110 this means we're leaving and we would like
  6882. // to remove everyone else from our view, so we trigger the event.
  6883. else if (Object.keys(this.members).length > 1) {
  6884. for (var i in this.members) {
  6885. var member = this.members[i];
  6886. delete this.members[i];
  6887. this.onParticipantLeft(member);
  6888. }
  6889. }
  6890. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  6891. if (this.myroomjid === from) {
  6892. this.xmpp.leaveRoom(this.roomjid);
  6893. this.eventEmitter.emit(XMPPEvents.KICKED);
  6894. }
  6895. }
  6896. };
  6897. ChatRoom.prototype.onMessage = function (msg, from) {
  6898. var nick =
  6899. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  6900. .text() ||
  6901. Strophe.getResourceFromJid(from);
  6902. var txt = $(msg).find('>body').text();
  6903. var type = msg.getAttribute("type");
  6904. if (type == "error") {
  6905. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  6906. $(msg).find('>text').text(), txt);
  6907. return true;
  6908. }
  6909. var subject = $(msg).find('>subject');
  6910. if (subject.length) {
  6911. var subjectText = subject.text();
  6912. if (subjectText || subjectText === "") {
  6913. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  6914. logger.log("Subject is changed to " + subjectText);
  6915. }
  6916. }
  6917. // xep-0203 delay
  6918. var stamp = $(msg).find('>delay').attr('stamp');
  6919. if (!stamp) {
  6920. // or xep-0091 delay, UTC timestamp
  6921. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  6922. if (stamp) {
  6923. // the format is CCYYMMDDThh:mm:ss
  6924. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  6925. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  6926. }
  6927. }
  6928. if (txt) {
  6929. logger.log('chat', nick, txt);
  6930. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  6931. from, nick, txt, this.myroomjid, stamp);
  6932. }
  6933. };
  6934. ChatRoom.prototype.onPresenceError = function (pres, from) {
  6935. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6936. logger.log('on password required', from);
  6937. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  6938. } else if ($(pres).find(
  6939. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  6940. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  6941. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  6942. // enter the room by replying with 'not-authorized'. This would
  6943. // result in reconnection from authorized domain.
  6944. // We're either missing Jicofo/Prosody config for anonymous
  6945. // domains or something is wrong.
  6946. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  6947. } else {
  6948. logger.warn('onPresError ', pres);
  6949. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6950. }
  6951. } else {
  6952. logger.warn('onPresError ', pres);
  6953. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  6954. }
  6955. };
  6956. ChatRoom.prototype.kick = function (jid) {
  6957. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  6958. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  6959. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  6960. .c('reason').t('You have been kicked.').up().up().up();
  6961. this.connection.sendIQ(
  6962. kickIQ,
  6963. function (result) {
  6964. logger.log('Kick participant with jid: ', jid, result);
  6965. },
  6966. function (error) {
  6967. logger.log('Kick participant error: ', error);
  6968. });
  6969. };
  6970. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  6971. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  6972. var ob = this;
  6973. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  6974. function (res) {
  6975. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  6976. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6977. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6978. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6979. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  6980. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  6981. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  6982. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  6983. ob.connection.sendIQ(formsubmit,
  6984. onSuccess,
  6985. onError);
  6986. } else {
  6987. onNotSupported();
  6988. }
  6989. }, onError);
  6990. };
  6991. ChatRoom.prototype.addToPresence = function (key, values) {
  6992. values.tagName = key;
  6993. this.presMap["nodes"].push(values);
  6994. };
  6995. ChatRoom.prototype.removeFromPresence = function (key) {
  6996. for(var i = 0; i < this.presMap.nodes.length; i++)
  6997. {
  6998. if(key === this.presMap.nodes[i].tagName)
  6999. this.presMap.nodes.splice(i, 1);
  7000. }
  7001. };
  7002. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  7003. this.presHandlers[name] = handler;
  7004. };
  7005. ChatRoom.prototype.removePresenceListener = function (name) {
  7006. delete this.presHandlers[name];
  7007. };
  7008. ChatRoom.prototype.isModerator = function () {
  7009. return this.role === 'moderator';
  7010. };
  7011. ChatRoom.prototype.getMemberRole = function (peerJid) {
  7012. if (this.members[peerJid]) {
  7013. return this.members[peerJid].role;
  7014. }
  7015. return null;
  7016. };
  7017. ChatRoom.prototype.setJingleSession = function(session){
  7018. this.session = session;
  7019. this.session.room = this;
  7020. };
  7021. ChatRoom.prototype.removeStream = function (stream, callback) {
  7022. if(!this.session)
  7023. return;
  7024. this.session.removeStream(stream, callback);
  7025. };
  7026. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  7027. if(this.session) {
  7028. // FIXME: will block switchInProgress on true value in case of exception
  7029. this.session.switchStreams(stream, oldStream, callback, isAudio);
  7030. } else {
  7031. // We are done immediately
  7032. logger.warn("No conference handler or conference not started yet");
  7033. callback();
  7034. }
  7035. };
  7036. ChatRoom.prototype.addStream = function (stream, callback) {
  7037. if(this.session) {
  7038. // FIXME: will block switchInProgress on true value in case of exception
  7039. this.session.addStream(stream, callback);
  7040. } else {
  7041. // We are done immediately
  7042. logger.warn("No conference handler or conference not started yet");
  7043. callback();
  7044. }
  7045. };
  7046. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  7047. var self = this;
  7048. var localCallback = function (mute) {
  7049. self.sendVideoInfoPresence(mute);
  7050. if(callback)
  7051. callback(mute);
  7052. };
  7053. if(this.session)
  7054. {
  7055. this.session.setVideoMute(
  7056. mute, localCallback, options);
  7057. }
  7058. else {
  7059. localCallback(mute);
  7060. }
  7061. };
  7062. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  7063. //This will be for remote streams only
  7064. // if (this.forceMuted && !mute) {
  7065. // logger.info("Asking focus for unmute");
  7066. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  7067. // // FIXME: wait for result before resetting muted status
  7068. // this.forceMuted = false;
  7069. // }
  7070. return this.sendAudioInfoPresence(mute, callback);
  7071. };
  7072. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  7073. this.removeFromPresence("audiomuted");
  7074. this.addToPresence("audiomuted",
  7075. {attributes:
  7076. {"audions": "http://jitsi.org/jitmeet/audio"},
  7077. value: mute.toString()});
  7078. };
  7079. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7080. this.addAudioInfoToPresence(mute);
  7081. if(this.connection) {
  7082. this.sendPresence();
  7083. }
  7084. if(callback)
  7085. callback();
  7086. };
  7087. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7088. this.removeFromPresence("videomuted");
  7089. this.addToPresence("videomuted",
  7090. {attributes:
  7091. {"videons": "http://jitsi.org/jitmeet/video"},
  7092. value: mute.toString()});
  7093. };
  7094. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7095. this.addVideoInfoToPresence(mute);
  7096. if(!this.connection)
  7097. return;
  7098. this.sendPresence();
  7099. };
  7100. ChatRoom.prototype.addListener = function(type, listener) {
  7101. this.eventEmitter.on(type, listener);
  7102. };
  7103. ChatRoom.prototype.removeListener = function (type, listener) {
  7104. this.eventEmitter.removeListener(type, listener);
  7105. };
  7106. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7107. if(this.lastPresences[data.peerjid])
  7108. {
  7109. var pres = this.lastPresences[data.peerjid];
  7110. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7111. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7112. data.videomuted = ((videomuted.length > 0
  7113. && videomuted[0]
  7114. && videomuted[0]["value"] === "true")? true : false);
  7115. data.audiomuted = ((audiomuted.length > 0
  7116. && audiomuted[0]
  7117. && audiomuted[0]["value"] === "true")? true : false);
  7118. }
  7119. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7120. };
  7121. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7122. if (!this.session)
  7123. return null;
  7124. return this.session.getSsrcOwner(ssrc);
  7125. };
  7126. /**
  7127. * Returns true if the recording is supproted and false if not.
  7128. */
  7129. ChatRoom.prototype.isRecordingSupported = function () {
  7130. if(this.recording)
  7131. return this.recording.isSupported();
  7132. return false;
  7133. };
  7134. /**
  7135. * Returns null if the recording is not supported, "on" if the recording started
  7136. * and "off" if the recording is not started.
  7137. */
  7138. ChatRoom.prototype.getRecordingState = function () {
  7139. if(this.recording)
  7140. return this.recording.getState();
  7141. return "off";
  7142. }
  7143. /**
  7144. * Returns the url of the recorded video.
  7145. */
  7146. ChatRoom.prototype.getRecordingURL = function () {
  7147. if(this.recording)
  7148. return this.recording.getURL();
  7149. return null;
  7150. }
  7151. /**
  7152. * Starts/stops the recording
  7153. * @param token token for authentication
  7154. * @param statusChangeHandler {function} receives the new status as argument.
  7155. */
  7156. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7157. if(this.recording)
  7158. return this.recording.toggleRecording(options, statusChangeHandler);
  7159. return statusChangeHandler("error",
  7160. new Error("The conference is not created yet!"));
  7161. }
  7162. /**
  7163. * Returns true if the SIP calls are supported and false otherwise
  7164. */
  7165. ChatRoom.prototype.isSIPCallingSupported = function () {
  7166. if(this.moderator)
  7167. return this.moderator.isSipGatewayEnabled();
  7168. return false;
  7169. }
  7170. /**
  7171. * Dials a number.
  7172. * @param number the number
  7173. */
  7174. ChatRoom.prototype.dial = function (number) {
  7175. return this.connection.rayo.dial(number, "fromnumber",
  7176. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7177. this.focusMucJid);
  7178. }
  7179. /**
  7180. * Hangup an existing call
  7181. */
  7182. ChatRoom.prototype.hangup = function () {
  7183. return this.connection.rayo.hangup();
  7184. }
  7185. /**
  7186. * Returns the phone number for joining the conference.
  7187. */
  7188. ChatRoom.prototype.getPhoneNumber = function () {
  7189. return this.phoneNumber;
  7190. }
  7191. /**
  7192. * Returns the pin for joining the conference with phone.
  7193. */
  7194. ChatRoom.prototype.getPhonePin = function () {
  7195. return this.phonePin;
  7196. }
  7197. /**
  7198. * Returns the connection state for the current session.
  7199. */
  7200. ChatRoom.prototype.getConnectionState = function () {
  7201. if(!this.session)
  7202. return null;
  7203. return this.session.getIceConnectionState();
  7204. }
  7205. /**
  7206. * Mutes remote participant.
  7207. * @param jid of the participant
  7208. * @param mute
  7209. */
  7210. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7211. logger.info("set mute", mute);
  7212. var iqToFocus = $iq(
  7213. {to: this.focusMucJid, type: 'set'})
  7214. .c('mute', {
  7215. xmlns: 'http://jitsi.org/jitmeet/audio',
  7216. jid: jid
  7217. })
  7218. .t(mute.toString())
  7219. .up();
  7220. this.connection.sendIQ(
  7221. iqToFocus,
  7222. function (result) {
  7223. logger.log('set mute', result);
  7224. },
  7225. function (error) {
  7226. logger.log('set mute error', error);
  7227. });
  7228. }
  7229. ChatRoom.prototype.onMute = function (iq) {
  7230. var from = iq.getAttribute('from');
  7231. if (from !== this.focusMucJid) {
  7232. logger.warn("Ignored mute from non focus peer");
  7233. return false;
  7234. }
  7235. var mute = $(iq).find('mute');
  7236. if (mute.length) {
  7237. var doMuteAudio = mute.text() === "true";
  7238. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7239. }
  7240. return true;
  7241. }
  7242. module.exports = ChatRoom;
  7243. }).call(this,"/modules/xmpp/ChatRoom.js")
  7244. },{"../../service/xmpp/XMPPEvents":137,"./moderator":36,"./recording":37,"events":51,"jitsi-meet-logger":79}],30:[function(require,module,exports){
  7245. (function (__filename){
  7246. /*
  7247. * JingleSession provides an API to manage a single Jingle session. We will
  7248. * have different implementations depending on the underlying interface used
  7249. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7250. */
  7251. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7252. function JingleSession(me, sid, connection, service, eventEmitter) {
  7253. /**
  7254. * Our JID.
  7255. */
  7256. this.me = me;
  7257. /**
  7258. * The Jingle session identifier.
  7259. */
  7260. this.sid = sid;
  7261. /**
  7262. * The XMPP connection.
  7263. */
  7264. this.connection = connection;
  7265. /**
  7266. * The XMPP service.
  7267. */
  7268. this.service = service;
  7269. /**
  7270. * The event emitter.
  7271. */
  7272. this.eventEmitter = eventEmitter;
  7273. /**
  7274. * Whether to use dripping or not. Dripping is sending trickle candidates
  7275. * not one-by-one.
  7276. * Note: currently we do not support 'false'.
  7277. */
  7278. this.usedrip = true;
  7279. /**
  7280. * When dripping is used, stores ICE candidates which are to be sent.
  7281. */
  7282. this.drip_container = [];
  7283. // Media constraints. Is this WebRTC only?
  7284. this.media_constraints = null;
  7285. // ICE servers config (RTCConfiguration?).
  7286. this.ice_config = {};
  7287. // The chat room instance associated with the session.
  7288. this.room = null;
  7289. }
  7290. /**
  7291. * Prepares this object to initiate a session.
  7292. * @param peerjid the JID of the remote peer.
  7293. * @param isInitiator whether we will be the Jingle initiator.
  7294. * @param media_constraints
  7295. * @param ice_config
  7296. */
  7297. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7298. media_constraints, ice_config) {
  7299. this.media_constraints = media_constraints;
  7300. this.ice_config = ice_config;
  7301. if (this.state !== null) {
  7302. logger.error('attempt to initiate on session ' + this.sid +
  7303. 'in state ' + this.state);
  7304. return;
  7305. }
  7306. this.state = 'pending';
  7307. this.initiator = isInitiator ? this.me : peerjid;
  7308. this.responder = !isInitiator ? this.me : peerjid;
  7309. this.peerjid = peerjid;
  7310. this.doInitialize();
  7311. };
  7312. /**
  7313. * Finishes initialization.
  7314. */
  7315. JingleSession.prototype.doInitialize = function() {};
  7316. /**
  7317. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7318. * Note: currently only used on transport-info
  7319. */
  7320. JingleSession.prototype.addIceCandidates = function(contents) {};
  7321. /**
  7322. * Handles an 'add-source' event.
  7323. *
  7324. * @param contents an array of Jingle 'content' elements.
  7325. */
  7326. JingleSession.prototype.addSources = function(contents) {};
  7327. /**
  7328. * Handles a 'remove-source' event.
  7329. *
  7330. * @param contents an array of Jingle 'content' elements.
  7331. */
  7332. JingleSession.prototype.removeSources = function(contents) {};
  7333. /**
  7334. * Terminates this Jingle session (stops sending media and closes the streams?)
  7335. */
  7336. JingleSession.prototype.terminate = function() {};
  7337. /**
  7338. * Sends a Jingle session-terminate message to the peer and terminates the
  7339. * session.
  7340. * @param reason
  7341. * @param text
  7342. */
  7343. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7344. /**
  7345. * Handles an offer from the remote peer (prepares to accept a session).
  7346. * @param jingle the 'jingle' XML element.
  7347. */
  7348. JingleSession.prototype.setOffer = function(jingle) {};
  7349. /**
  7350. * Handles an answer from the remote peer (prepares to accept a session).
  7351. * @param jingle the 'jingle' XML element.
  7352. */
  7353. JingleSession.prototype.setAnswer = function(jingle) {};
  7354. module.exports = JingleSession;
  7355. }).call(this,"/modules/xmpp/JingleSession.js")
  7356. },{"jitsi-meet-logger":79}],31:[function(require,module,exports){
  7357. (function (__filename){
  7358. /* jshint -W117 */
  7359. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7360. var JingleSession = require("./JingleSession");
  7361. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7362. var SDPDiffer = require("./SDPDiffer");
  7363. var SDPUtil = require("./SDPUtil");
  7364. var SDP = require("./SDP");
  7365. var async = require("async");
  7366. var transform = require("sdp-transform");
  7367. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7368. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7369. var RTC = require("../RTC/RTC");
  7370. // Jingle stuff
  7371. function JingleSessionPC(me, sid, connection, service) {
  7372. JingleSession.call(this, me, sid, connection, service);
  7373. this.initiator = null;
  7374. this.responder = null;
  7375. this.peerjid = null;
  7376. this.state = null;
  7377. this.localSDP = null;
  7378. this.remoteSDP = null;
  7379. this.relayedStreams = [];
  7380. this.usetrickle = true;
  7381. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7382. this.hadstuncandidate = false;
  7383. this.hadturncandidate = false;
  7384. this.lasticecandidate = false;
  7385. this.statsinterval = null;
  7386. this.reason = null;
  7387. this.addssrc = [];
  7388. this.removessrc = [];
  7389. this.pendingop = null;
  7390. this.switchstreams = false;
  7391. this.addingStreams = false;
  7392. this.wait = true;
  7393. /**
  7394. * A map that stores SSRCs of local streams
  7395. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7396. */
  7397. this.localStreamsSSRC = {};
  7398. this.ssrcOwners = {};
  7399. this.ssrcVideoTypes = {};
  7400. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7401. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7402. /**
  7403. * The indicator which determines whether the (local) video has been muted
  7404. * in response to a user command in contrast to an automatic decision made
  7405. * by the application logic.
  7406. */
  7407. this.videoMuteByUser = false;
  7408. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7409. // We start with the queue paused. We resume it when the signaling state is
  7410. // stable and the ice connection state is connected.
  7411. this.modifySourcesQueue.pause();
  7412. }
  7413. //XXX this is badly broken...
  7414. JingleSessionPC.prototype = JingleSession.prototype;
  7415. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7416. JingleSessionPC.prototype.setOffer = function(offer) {
  7417. this.setRemoteDescription(offer, 'offer');
  7418. };
  7419. JingleSessionPC.prototype.setAnswer = function(answer) {
  7420. this.setRemoteDescription(answer, 'answer');
  7421. };
  7422. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7423. var signalingState = this.peerconnection.signalingState;
  7424. var iceConnectionState = this.peerconnection.iceConnectionState;
  7425. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7426. this.modifySourcesQueue.resume();
  7427. } else {
  7428. this.modifySourcesQueue.pause();
  7429. }
  7430. };
  7431. JingleSessionPC.prototype.doInitialize = function () {
  7432. var self = this;
  7433. this.hadstuncandidate = false;
  7434. this.hadturncandidate = false;
  7435. this.lasticecandidate = false;
  7436. // True if reconnect is in progress
  7437. this.isreconnect = false;
  7438. // Set to true if the connection was ever stable
  7439. this.wasstable = false;
  7440. this.peerconnection = new TraceablePeerConnection(
  7441. this.connection.jingle.ice_config,
  7442. RTC.getPCConstraints(),
  7443. this);
  7444. this.peerconnection.onicecandidate = function (event) {
  7445. var protocol;
  7446. if (event && event.candidate) {
  7447. protocol = (typeof event.candidate.protocol === 'string')
  7448. ? event.candidate.protocol.toLowerCase() : '';
  7449. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7450. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7451. return;
  7452. }
  7453. }
  7454. self.sendIceCandidate(event.candidate);
  7455. };
  7456. this.peerconnection.onaddstream = function (event) {
  7457. if (event.stream.id !== 'default') {
  7458. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7459. self.remoteStreamAdded(event);
  7460. } else {
  7461. // This is a recvonly stream. Clients that implement Unified Plan,
  7462. // such as Firefox use recvonly "streams/channels/tracks" for
  7463. // receiving remote stream/tracks, as opposed to Plan B where there
  7464. // are only 3 channels: audio, video and data.
  7465. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7466. }
  7467. };
  7468. this.peerconnection.onremovestream = function (event) {
  7469. // Remove the stream from remoteStreams
  7470. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7471. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7472. };
  7473. this.peerconnection.onsignalingstatechange = function (event) {
  7474. if (!(self && self.peerconnection)) return;
  7475. if (self.peerconnection.signalingState === 'stable') {
  7476. self.wasstable = true;
  7477. }
  7478. self.updateModifySourcesQueue();
  7479. };
  7480. /**
  7481. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7482. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7483. * RTCPeerConnection.iceConnectionState changes.
  7484. *
  7485. * @param event the event containing information about the change
  7486. */
  7487. this.peerconnection.oniceconnectionstatechange = function (event) {
  7488. if (!(self && self.peerconnection)) return;
  7489. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7490. ":\t", window.performance.now());
  7491. self.updateModifySourcesQueue();
  7492. switch (self.peerconnection.iceConnectionState) {
  7493. case 'connected':
  7494. // Informs interested parties that the connection has been restored.
  7495. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7496. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7497. self.isreconnect = false;
  7498. break;
  7499. case 'disconnected':
  7500. self.isreconnect = true;
  7501. // Informs interested parties that the connection has been interrupted.
  7502. if (self.wasstable)
  7503. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7504. break;
  7505. case 'failed':
  7506. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7507. break;
  7508. }
  7509. onIceConnectionStateChange(self.sid, self);
  7510. };
  7511. this.peerconnection.onnegotiationneeded = function (event) {
  7512. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7513. };
  7514. this.relayedStreams.forEach(function(stream) {
  7515. self.peerconnection.addStream(stream);
  7516. });
  7517. };
  7518. function onIceConnectionStateChange(sid, session) {
  7519. switch (session.peerconnection.iceConnectionState) {
  7520. case 'checking':
  7521. session.timeChecking = (new Date()).getTime();
  7522. session.firstconnect = true;
  7523. break;
  7524. case 'completed': // on caller side
  7525. case 'connected':
  7526. if (session.firstconnect) {
  7527. session.firstconnect = false;
  7528. var metadata = {};
  7529. metadata.setupTime
  7530. = (new Date()).getTime() - session.timeChecking;
  7531. session.peerconnection.getStats(function (res) {
  7532. if(res && res.result) {
  7533. res.result().forEach(function (report) {
  7534. if (report.type == 'googCandidatePair' &&
  7535. report.stat('googActiveConnection') == 'true') {
  7536. metadata.localCandidateType
  7537. = report.stat('googLocalCandidateType');
  7538. metadata.remoteCandidateType
  7539. = report.stat('googRemoteCandidateType');
  7540. // log pair as well so we can get nice pie
  7541. // charts
  7542. metadata.candidatePair
  7543. = report.stat('googLocalCandidateType') +
  7544. ';' +
  7545. report.stat('googRemoteCandidateType');
  7546. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7547. {
  7548. metadata.ipv6 = true;
  7549. }
  7550. }
  7551. });
  7552. }
  7553. });
  7554. }
  7555. break;
  7556. }
  7557. }
  7558. JingleSessionPC.prototype.accept = function () {
  7559. this.state = 'active';
  7560. var pranswer = this.peerconnection.localDescription;
  7561. if (!pranswer || pranswer.type != 'pranswer') {
  7562. return;
  7563. }
  7564. logger.log('going from pranswer to answer');
  7565. if (this.usetrickle) {
  7566. // remove candidates already sent from session-accept
  7567. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7568. for (var i = 0; i < lines.length; i++) {
  7569. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7570. }
  7571. }
  7572. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7573. // FIXME: change any inactive to sendrecv or whatever they were originally
  7574. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7575. }
  7576. var prsdp = new SDP(pranswer.sdp);
  7577. if (this.webrtcIceTcpDisable) {
  7578. prsdp.removeTcpCandidates = true;
  7579. }
  7580. if (this.webrtcIceUdpDisable) {
  7581. prsdp.removeUdpCandidates = true;
  7582. }
  7583. var accept = $iq({to: this.peerjid,
  7584. type: 'set'})
  7585. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7586. action: 'session-accept',
  7587. initiator: this.initiator,
  7588. responder: this.responder,
  7589. sid: this.sid });
  7590. // FIXME why do we generate session-accept in 3 different places ?
  7591. prsdp.toJingle(
  7592. accept,
  7593. this.initiator == this.me ? 'initiator' : 'responder');
  7594. var sdp = this.peerconnection.localDescription.sdp;
  7595. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7596. // FIXME: change any inactive to sendrecv or whatever they were originally
  7597. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7598. }
  7599. var self = this;
  7600. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7601. function () {
  7602. //logger.log('setLocalDescription success');
  7603. self.setLocalDescription();
  7604. self.connection.sendIQ(accept,
  7605. function () {
  7606. var ack = {};
  7607. ack.source = 'answer';
  7608. $(document).trigger('ack.jingle', [self.sid, ack]);
  7609. },
  7610. function (stanza) {
  7611. var error = ($(stanza).find('error').length) ? {
  7612. code: $(stanza).find('error').attr('code'),
  7613. reason: $(stanza).find('error :first')[0].tagName
  7614. }:{};
  7615. error.source = 'answer';
  7616. JingleSessionPC.onJingleError(self.sid, error);
  7617. },
  7618. 10000);
  7619. },
  7620. function (e) {
  7621. logger.error('setLocalDescription failed', e);
  7622. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7623. }
  7624. );
  7625. };
  7626. JingleSessionPC.prototype.terminate = function (reason) {
  7627. this.state = 'ended';
  7628. this.reason = reason;
  7629. this.peerconnection.close();
  7630. if (this.statsinterval !== null) {
  7631. window.clearInterval(this.statsinterval);
  7632. this.statsinterval = null;
  7633. }
  7634. };
  7635. JingleSessionPC.prototype.active = function () {
  7636. return this.state == 'active';
  7637. };
  7638. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7639. var self = this;
  7640. if (candidate && !this.lasticecandidate) {
  7641. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7642. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7643. if (!(ice && jcand)) {
  7644. logger.error('failed to get ice && jcand');
  7645. return;
  7646. }
  7647. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7648. if (jcand.type === 'srflx') {
  7649. this.hadstuncandidate = true;
  7650. } else if (jcand.type === 'relay') {
  7651. this.hadturncandidate = true;
  7652. }
  7653. if (this.usetrickle) {
  7654. if (this.usedrip) {
  7655. if (this.drip_container.length === 0) {
  7656. // start 20ms callout
  7657. window.setTimeout(function () {
  7658. if (self.drip_container.length === 0) return;
  7659. self.sendIceCandidates(self.drip_container);
  7660. self.drip_container = [];
  7661. }, 20);
  7662. }
  7663. this.drip_container.push(candidate);
  7664. return;
  7665. } else {
  7666. self.sendIceCandidate([candidate]);
  7667. }
  7668. }
  7669. } else {
  7670. //logger.log('sendIceCandidate: last candidate.');
  7671. if (!this.usetrickle) {
  7672. //logger.log('should send full offer now...');
  7673. //FIXME why do we generate session-accept in 3 different places ?
  7674. var init = $iq({to: this.peerjid,
  7675. type: 'set'})
  7676. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7677. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7678. initiator: this.initiator,
  7679. sid: this.sid});
  7680. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7681. if (self.webrtcIceTcpDisable) {
  7682. this.localSDP.removeTcpCandidates = true;
  7683. }
  7684. if (self.webrtcIceUdpDisable) {
  7685. this.localSDP.removeUdpCandidates = true;
  7686. }
  7687. var sendJingle = function (ssrc) {
  7688. if(!ssrc)
  7689. ssrc = {};
  7690. self.localSDP.toJingle(
  7691. init,
  7692. self.initiator == self.me ? 'initiator' : 'responder',
  7693. ssrc);
  7694. self.connection.sendIQ(init,
  7695. function () {
  7696. //logger.log('session initiate ack');
  7697. var ack = {};
  7698. ack.source = 'offer';
  7699. $(document).trigger('ack.jingle', [self.sid, ack]);
  7700. },
  7701. function (stanza) {
  7702. self.state = 'error';
  7703. self.peerconnection.close();
  7704. var error = ($(stanza).find('error').length) ? {
  7705. code: $(stanza).find('error').attr('code'),
  7706. reason: $(stanza).find('error :first')[0].tagName,
  7707. }:{};
  7708. error.source = 'offer';
  7709. JingleSessionPC.onJingleError(self.sid, error);
  7710. },
  7711. 10000);
  7712. };
  7713. sendJingle();
  7714. }
  7715. this.lasticecandidate = true;
  7716. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7717. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7718. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7719. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7720. }
  7721. }
  7722. };
  7723. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7724. logger.log('sendIceCandidates', candidates);
  7725. var cand = $iq({to: this.peerjid, type: 'set'})
  7726. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7727. action: 'transport-info',
  7728. initiator: this.initiator,
  7729. sid: this.sid});
  7730. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7731. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7732. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7733. if (cands.length > 0) {
  7734. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7735. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7736. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7737. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7738. }).c('transport', ice);
  7739. for (var i = 0; i < cands.length; i++) {
  7740. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7741. }
  7742. // add fingerprint
  7743. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7744. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7745. tmp.required = true;
  7746. cand.c(
  7747. 'fingerprint',
  7748. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7749. .t(tmp.fingerprint);
  7750. delete tmp.fingerprint;
  7751. cand.attrs(tmp);
  7752. cand.up();
  7753. }
  7754. cand.up(); // transport
  7755. cand.up(); // content
  7756. }
  7757. }
  7758. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7759. //logger.log('was this the last candidate', this.lasticecandidate);
  7760. this.connection.sendIQ(cand,
  7761. function () {
  7762. var ack = {};
  7763. ack.source = 'transportinfo';
  7764. $(document).trigger('ack.jingle', [this.sid, ack]);
  7765. },
  7766. function (stanza) {
  7767. var error = ($(stanza).find('error').length) ? {
  7768. code: $(stanza).find('error').attr('code'),
  7769. reason: $(stanza).find('error :first')[0].tagName,
  7770. }:{};
  7771. error.source = 'transportinfo';
  7772. JingleSessionPC.onJingleError(this.sid, error);
  7773. },
  7774. 10000);
  7775. };
  7776. JingleSessionPC.prototype.sendOffer = function () {
  7777. //logger.log('sendOffer...');
  7778. var self = this;
  7779. this.peerconnection.createOffer(function (sdp) {
  7780. self.createdOffer(sdp);
  7781. },
  7782. function (e) {
  7783. logger.error('createOffer failed', e);
  7784. },
  7785. this.media_constraints
  7786. );
  7787. };
  7788. // FIXME createdOffer is never used in jitsi-meet
  7789. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7790. //logger.log('createdOffer', sdp);
  7791. var self = this;
  7792. this.localSDP = new SDP(sdp.sdp);
  7793. //this.localSDP.mangle();
  7794. var sendJingle = function () {
  7795. var init = $iq({to: this.peerjid,
  7796. type: 'set'})
  7797. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7798. action: 'session-initiate',
  7799. initiator: this.initiator,
  7800. sid: this.sid});
  7801. self.localSDP.toJingle(
  7802. init,
  7803. this.initiator == this.me ? 'initiator' : 'responder');
  7804. self.connection.sendIQ(init,
  7805. function () {
  7806. var ack = {};
  7807. ack.source = 'offer';
  7808. $(document).trigger('ack.jingle', [self.sid, ack]);
  7809. },
  7810. function (stanza) {
  7811. self.state = 'error';
  7812. self.peerconnection.close();
  7813. var error = ($(stanza).find('error').length) ? {
  7814. code: $(stanza).find('error').attr('code'),
  7815. reason: $(stanza).find('error :first')[0].tagName,
  7816. }:{};
  7817. error.source = 'offer';
  7818. JingleSessionPC.onJingleError(self.sid, error);
  7819. },
  7820. 10000);
  7821. }
  7822. sdp.sdp = this.localSDP.raw;
  7823. this.peerconnection.setLocalDescription(sdp,
  7824. function () {
  7825. if(self.usetrickle)
  7826. {
  7827. sendJingle();
  7828. }
  7829. self.setLocalDescription();
  7830. //logger.log('setLocalDescription success');
  7831. },
  7832. function (e) {
  7833. logger.error('setLocalDescription failed', e);
  7834. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7835. }
  7836. );
  7837. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7838. for (var i = 0; i < cands.length; i++) {
  7839. var cand = SDPUtil.parse_icecandidate(cands[i]);
  7840. if (cand.type == 'srflx') {
  7841. this.hadstuncandidate = true;
  7842. } else if (cand.type == 'relay') {
  7843. this.hadturncandidate = true;
  7844. }
  7845. }
  7846. };
  7847. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  7848. var self = this;
  7849. $(contents).each(function (idx, content) {
  7850. var name = $(content).attr('name');
  7851. var mediaType = this.getAttribute('name');
  7852. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7853. ssrcs.each(function () {
  7854. var ssrc = this.getAttribute('ssrc');
  7855. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  7856. function () {
  7857. var owner = this.getAttribute('owner');
  7858. self.ssrcOwners[ssrc] = owner;
  7859. }
  7860. );
  7861. });
  7862. });
  7863. };
  7864. /**
  7865. * Returns the SSRC of local audio stream.
  7866. * @param mediaType 'audio' or 'video' media type
  7867. * @returns {*} the SSRC number of local audio or video stream.
  7868. */
  7869. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  7870. return this.localStreamsSSRC[mediaType];
  7871. };
  7872. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  7873. return this.ssrcOwners[ssrc];
  7874. };
  7875. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  7876. //logger.log('setting remote description... ', desctype);
  7877. this.remoteSDP = new SDP('');
  7878. if (this.webrtcIceTcpDisable) {
  7879. this.remoteSDP.removeTcpCandidates = true;
  7880. }
  7881. if (this.webrtcIceUdpDisable) {
  7882. this.remoteSDP.removeUdpCandidates = true;
  7883. }
  7884. this.remoteSDP.fromJingle(elem);
  7885. this.readSsrcInfo($(elem).find(">content"));
  7886. if (this.peerconnection.remoteDescription) {
  7887. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  7888. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  7889. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  7890. for (var i = 0; i < pranswer.media.length; i++) {
  7891. // make sure we have ice ufrag and pwd
  7892. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  7893. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  7894. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  7895. } else {
  7896. logger.warn('no ice ufrag?');
  7897. }
  7898. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  7899. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  7900. } else {
  7901. logger.warn('no ice pwd?');
  7902. }
  7903. }
  7904. // copy over candidates
  7905. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  7906. for (var j = 0; j < lines.length; j++) {
  7907. this.remoteSDP.media[i] += lines[j] + '\r\n';
  7908. }
  7909. }
  7910. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7911. }
  7912. }
  7913. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  7914. this.peerconnection.setRemoteDescription(remotedesc,
  7915. function () {
  7916. //logger.log('setRemoteDescription success');
  7917. },
  7918. function (e) {
  7919. logger.error('setRemoteDescription error', e);
  7920. JingleSessionPC.onJingleFatalError(self, e);
  7921. }
  7922. );
  7923. };
  7924. /**
  7925. * Adds remote ICE candidates to this Jingle session.
  7926. * @param elem An array of Jingle "content" elements?
  7927. */
  7928. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  7929. var self = this;
  7930. if (this.peerconnection.signalingState == 'closed') {
  7931. return;
  7932. }
  7933. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  7934. logger.log('trickle ice candidate arriving before session accept...');
  7935. // create a PRANSWER for setRemoteDescription
  7936. if (!this.remoteSDP) {
  7937. var cobbled = 'v=0\r\n' +
  7938. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  7939. 's=-\r\n' +
  7940. 't=0 0\r\n';
  7941. // first, take some things from the local description
  7942. for (var i = 0; i < this.localSDP.media.length; i++) {
  7943. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  7944. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  7945. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  7946. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  7947. }
  7948. cobbled += 'a=inactive\r\n';
  7949. }
  7950. this.remoteSDP = new SDP(cobbled);
  7951. }
  7952. // then add things like ice and dtls from remote candidate
  7953. elem.each(function () {
  7954. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  7955. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  7956. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  7957. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  7958. var tmp = $(this).find('transport');
  7959. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  7960. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  7961. tmp = $(this).find('transport>fingerprint');
  7962. if (tmp.length) {
  7963. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  7964. } else {
  7965. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  7966. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  7967. }
  7968. break;
  7969. }
  7970. }
  7971. }
  7972. });
  7973. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  7974. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  7975. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  7976. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  7977. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  7978. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  7979. }).length == this.remoteSDP.media.length;
  7980. if (iscomplete) {
  7981. logger.log('setting pranswer');
  7982. try {
  7983. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  7984. function() {
  7985. },
  7986. function(e) {
  7987. logger.log('setRemoteDescription pranswer failed', e.toString());
  7988. });
  7989. } catch (e) {
  7990. logger.error('setting pranswer failed', e);
  7991. }
  7992. } else {
  7993. //logger.log('not yet setting pranswer');
  7994. }
  7995. }
  7996. // operate on each content element
  7997. elem.each(function () {
  7998. // would love to deactivate this, but firefox still requires it
  7999. var idx = -1;
  8000. var i;
  8001. for (i = 0; i < self.remoteSDP.media.length; i++) {
  8002. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8003. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8004. idx = i;
  8005. break;
  8006. }
  8007. }
  8008. if (idx == -1) { // fall back to localdescription
  8009. for (i = 0; i < self.localSDP.media.length; i++) {
  8010. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8011. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8012. idx = i;
  8013. break;
  8014. }
  8015. }
  8016. }
  8017. var name = $(this).attr('name');
  8018. // TODO: check ice-pwd and ice-ufrag?
  8019. $(this).find('transport>candidate').each(function () {
  8020. var line, candidate;
  8021. var protocol = this.getAttribute('protocol');
  8022. protocol =
  8023. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  8024. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  8025. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  8026. return;
  8027. }
  8028. line = SDPUtil.candidateFromJingle(this);
  8029. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  8030. sdpMid: name,
  8031. candidate: line});
  8032. try {
  8033. self.peerconnection.addIceCandidate(candidate);
  8034. } catch (e) {
  8035. logger.error('addIceCandidate failed', e.toString(), line);
  8036. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  8037. err, self.peerconnection);
  8038. }
  8039. });
  8040. });
  8041. };
  8042. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  8043. //logger.log('createAnswer', provisional);
  8044. var self = this;
  8045. this.peerconnection.createAnswer(
  8046. function (sdp) {
  8047. self.createdAnswer(sdp, provisional);
  8048. },
  8049. function (e) {
  8050. logger.error('createAnswer failed', e);
  8051. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8052. },
  8053. this.media_constraints
  8054. );
  8055. };
  8056. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  8057. //logger.log('createAnswer callback');
  8058. var self = this;
  8059. this.localSDP = new SDP(sdp.sdp);
  8060. //this.localSDP.mangle();
  8061. this.usepranswer = provisional === true;
  8062. if (this.usetrickle) {
  8063. if (this.usepranswer) {
  8064. sdp.type = 'pranswer';
  8065. for (var i = 0; i < this.localSDP.media.length; i++) {
  8066. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  8067. }
  8068. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  8069. }
  8070. }
  8071. var self = this;
  8072. var sendJingle = function (ssrcs) {
  8073. // FIXME why do we generate session-accept in 3 different places ?
  8074. var accept = $iq({to: self.peerjid,
  8075. type: 'set'})
  8076. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8077. action: 'session-accept',
  8078. initiator: self.initiator,
  8079. responder: self.responder,
  8080. sid: self.sid });
  8081. if (self.webrtcIceTcpDisable) {
  8082. self.localSDP.removeTcpCandidates = true;
  8083. }
  8084. if (self.webrtcIceUdpDisable) {
  8085. self.localSDP.removeUdpCandidates = true;
  8086. }
  8087. self.localSDP.toJingle(
  8088. accept,
  8089. self.initiator == self.me ? 'initiator' : 'responder',
  8090. ssrcs);
  8091. self.connection.sendIQ(accept,
  8092. function () {
  8093. var ack = {};
  8094. ack.source = 'answer';
  8095. $(document).trigger('ack.jingle', [self.sid, ack]);
  8096. },
  8097. function (stanza) {
  8098. var error = ($(stanza).find('error').length) ? {
  8099. code: $(stanza).find('error').attr('code'),
  8100. reason: $(stanza).find('error :first')[0].tagName,
  8101. }:{};
  8102. error.source = 'answer';
  8103. JingleSessionPC.onJingleError(self.sid, error);
  8104. },
  8105. 10000);
  8106. }
  8107. sdp.sdp = this.localSDP.raw;
  8108. this.peerconnection.setLocalDescription(sdp,
  8109. function () {
  8110. //logger.log('setLocalDescription success');
  8111. if (self.usetrickle && !self.usepranswer) {
  8112. sendJingle();
  8113. }
  8114. self.setLocalDescription();
  8115. },
  8116. function (e) {
  8117. logger.error('setLocalDescription failed', e);
  8118. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8119. }
  8120. );
  8121. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8122. for (var j = 0; j < cands.length; j++) {
  8123. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8124. if (cand.type == 'srflx') {
  8125. this.hadstuncandidate = true;
  8126. } else if (cand.type == 'relay') {
  8127. this.hadturncandidate = true;
  8128. }
  8129. }
  8130. };
  8131. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8132. var self = this,
  8133. term = $iq({to: this.peerjid,
  8134. type: 'set'})
  8135. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8136. action: 'session-terminate',
  8137. initiator: this.initiator,
  8138. sid: this.sid})
  8139. .c('reason')
  8140. .c(reason || 'success');
  8141. if (text) {
  8142. term.up().c('text').t(text);
  8143. }
  8144. this.connection.sendIQ(term,
  8145. function () {
  8146. self.peerconnection.close();
  8147. self.peerconnection = null;
  8148. self.terminate();
  8149. var ack = {};
  8150. ack.source = 'terminate';
  8151. $(document).trigger('ack.jingle', [self.sid, ack]);
  8152. },
  8153. function (stanza) {
  8154. var error = ($(stanza).find('error').length) ? {
  8155. code: $(stanza).find('error').attr('code'),
  8156. reason: $(stanza).find('error :first')[0].tagName,
  8157. }:{};
  8158. $(document).trigger('ack.jingle', [self.sid, error]);
  8159. },
  8160. 10000);
  8161. if (this.statsinterval !== null) {
  8162. window.clearInterval(this.statsinterval);
  8163. this.statsinterval = null;
  8164. }
  8165. };
  8166. /**
  8167. * Handles a Jingle source-add message for this Jingle session.
  8168. * @param elem An array of Jingle "content" elements.
  8169. */
  8170. JingleSessionPC.prototype.addSource = function (elem) {
  8171. var self = this;
  8172. // FIXME: dirty waiting
  8173. if (!this.peerconnection.localDescription)
  8174. {
  8175. logger.warn("addSource - localDescription not ready yet")
  8176. setTimeout(function()
  8177. {
  8178. self.addSource(elem);
  8179. },
  8180. 200
  8181. );
  8182. return;
  8183. }
  8184. logger.log('addssrc', new Date().getTime());
  8185. logger.log('ice', this.peerconnection.iceConnectionState);
  8186. this.readSsrcInfo(elem);
  8187. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8188. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8189. $(elem).each(function (idx, content) {
  8190. var name = $(content).attr('name');
  8191. var lines = '';
  8192. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8193. var semantics = this.getAttribute('semantics');
  8194. var ssrcs = $(this).find('>source').map(function () {
  8195. return this.getAttribute('ssrc');
  8196. }).get();
  8197. if (ssrcs.length) {
  8198. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8199. }
  8200. });
  8201. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8202. tmp.each(function () {
  8203. var ssrc = $(this).attr('ssrc');
  8204. if(mySdp.containsSSRC(ssrc)){
  8205. /**
  8206. * This happens when multiple participants change their streams at the same time and
  8207. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8208. * addssrc are scheduled for update IQ. See
  8209. */
  8210. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8211. return;
  8212. }
  8213. if (sdp.containsSSRC(ssrc)) {
  8214. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8215. return;
  8216. }
  8217. $(this).find('>parameter').each(function () {
  8218. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8219. if ($(this).attr('value') && $(this).attr('value').length)
  8220. lines += ':' + $(this).attr('value');
  8221. lines += '\r\n';
  8222. });
  8223. });
  8224. sdp.media.forEach(function(media, idx) {
  8225. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8226. return;
  8227. sdp.media[idx] += lines;
  8228. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8229. self.addssrc[idx] += lines;
  8230. });
  8231. sdp.raw = sdp.session + sdp.media.join('');
  8232. });
  8233. this.modifySourcesQueue.push(function() {
  8234. // When a source is added and if this is FF, a new channel is allocated
  8235. // for receiving the added source. We need to diffuse the SSRC of this
  8236. // new recvonly channel to the rest of the peers.
  8237. logger.log('modify sources done');
  8238. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8239. logger.log("SDPs", mySdp, newSdp);
  8240. self.notifyMySSRCUpdate(mySdp, newSdp);
  8241. });
  8242. };
  8243. /**
  8244. * Handles a Jingle source-remove message for this Jingle session.
  8245. * @param elem An array of Jingle "content" elements.
  8246. */
  8247. JingleSessionPC.prototype.removeSource = function (elem) {
  8248. var self = this;
  8249. // FIXME: dirty waiting
  8250. if (!this.peerconnection.localDescription) {
  8251. logger.warn("removeSource - localDescription not ready yet");
  8252. setTimeout(function() {
  8253. self.removeSource(elem);
  8254. },
  8255. 200
  8256. );
  8257. return;
  8258. }
  8259. logger.log('removessrc', new Date().getTime());
  8260. logger.log('ice', this.peerconnection.iceConnectionState);
  8261. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8262. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8263. $(elem).each(function (idx, content) {
  8264. var name = $(content).attr('name');
  8265. var lines = '';
  8266. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8267. var semantics = this.getAttribute('semantics');
  8268. var ssrcs = $(this).find('>source').map(function () {
  8269. return this.getAttribute('ssrc');
  8270. }).get();
  8271. if (ssrcs.length) {
  8272. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8273. }
  8274. });
  8275. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8276. tmp.each(function () {
  8277. var ssrc = $(this).attr('ssrc');
  8278. // This should never happen, but can be useful for bug detection
  8279. if(mySdp.containsSSRC(ssrc)){
  8280. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8281. return;
  8282. }
  8283. $(this).find('>parameter').each(function () {
  8284. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8285. if ($(this).attr('value') && $(this).attr('value').length)
  8286. lines += ':' + $(this).attr('value');
  8287. lines += '\r\n';
  8288. });
  8289. });
  8290. sdp.media.forEach(function(media, idx) {
  8291. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8292. return;
  8293. sdp.media[idx] += lines;
  8294. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8295. self.removessrc[idx] += lines;
  8296. });
  8297. sdp.raw = sdp.session + sdp.media.join('');
  8298. });
  8299. this.modifySourcesQueue.push(function() {
  8300. // When a source is removed and if this is FF, the recvonly channel that
  8301. // receives the remote stream is deactivated . We need to diffuse the
  8302. // recvonly SSRC removal to the rest of the peers.
  8303. logger.log('modify sources done');
  8304. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8305. logger.log("SDPs", mySdp, newSdp);
  8306. self.notifyMySSRCUpdate(mySdp, newSdp);
  8307. });
  8308. };
  8309. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8310. var self = this;
  8311. if (this.peerconnection.signalingState == 'closed') return;
  8312. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8313. || this.switchstreams || this.addingStreams)){
  8314. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8315. this.setLocalDescription();
  8316. if(successCallback){
  8317. successCallback();
  8318. }
  8319. queueCallback();
  8320. return;
  8321. }
  8322. // Reset switch streams flags
  8323. this.switchstreams = false;
  8324. this.addingStreams = false;
  8325. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8326. // add sources
  8327. this.addssrc.forEach(function(lines, idx) {
  8328. sdp.media[idx] += lines;
  8329. });
  8330. this.addssrc = [];
  8331. // remove sources
  8332. this.removessrc.forEach(function(lines, idx) {
  8333. lines = lines.split('\r\n');
  8334. lines.pop(); // remove empty last element;
  8335. lines.forEach(function(line) {
  8336. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8337. });
  8338. });
  8339. this.removessrc = [];
  8340. sdp.raw = sdp.session + sdp.media.join('');
  8341. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8342. function() {
  8343. if(self.signalingState == 'closed') {
  8344. logger.error("createAnswer attempt on closed state");
  8345. queueCallback("createAnswer attempt on closed state");
  8346. return;
  8347. }
  8348. self.peerconnection.createAnswer(
  8349. function(modifiedAnswer) {
  8350. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8351. if (self.pendingop !== null) {
  8352. var sdp = new SDP(modifiedAnswer.sdp);
  8353. if (sdp.media.length > 1) {
  8354. switch(self.pendingop) {
  8355. case 'mute':
  8356. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8357. break;
  8358. case 'unmute':
  8359. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8360. break;
  8361. }
  8362. sdp.raw = sdp.session + sdp.media.join('');
  8363. modifiedAnswer.sdp = sdp.raw;
  8364. }
  8365. self.pendingop = null;
  8366. }
  8367. // FIXME: pushing down an answer while ice connection state
  8368. // is still checking is bad...
  8369. //logger.log(self.peerconnection.iceConnectionState);
  8370. // trying to work around another chrome bug
  8371. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8372. self.peerconnection.setLocalDescription(modifiedAnswer,
  8373. function() {
  8374. //logger.log('modified setLocalDescription ok');
  8375. self.setLocalDescription();
  8376. if(successCallback){
  8377. successCallback();
  8378. }
  8379. queueCallback();
  8380. },
  8381. function(error) {
  8382. logger.error('modified setLocalDescription failed', error);
  8383. queueCallback(error);
  8384. }
  8385. );
  8386. },
  8387. function(error) {
  8388. logger.error('modified answer failed', error);
  8389. queueCallback(error);
  8390. }
  8391. );
  8392. },
  8393. function(error) {
  8394. logger.error('modify failed', error);
  8395. queueCallback(error);
  8396. }
  8397. );
  8398. };
  8399. /**
  8400. * Switches video streams.
  8401. * @param newStream new stream that will be used as video of this session.
  8402. * @param oldStream old video stream of this session.
  8403. * @param successCallback callback executed after successful stream switch.
  8404. * @param isAudio whether the streams are audio (if true) or video (if false).
  8405. */
  8406. JingleSessionPC.prototype.switchStreams =
  8407. function (newStream, oldStream, successCallback, isAudio) {
  8408. var self = this;
  8409. var sender, newTrack;
  8410. var senderKind = isAudio ? 'audio' : 'video';
  8411. // Remember SDP to figure out added/removed SSRCs
  8412. var oldSdp = null;
  8413. if (self.peerconnection) {
  8414. if (self.peerconnection.localDescription) {
  8415. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8416. }
  8417. if (RTCBrowserType.getBrowserType() ===
  8418. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8419. // On Firefox we don't replace MediaStreams as this messes up the
  8420. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8421. // of complications. Instead, we use the RTPSender and replace just
  8422. // the track.
  8423. // Find the right sender (for audio or video)
  8424. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8425. if (s.track && s.track.kind === senderKind) {
  8426. sender = s;
  8427. return true;
  8428. }
  8429. });
  8430. if (sender) {
  8431. // We assume that our streams have a single track, either audio
  8432. // or video.
  8433. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8434. newStream.getVideoTracks()[0];
  8435. sender.replaceTrack(newTrack)
  8436. .then(function() {
  8437. console.log("Replaced a track, isAudio=" + isAudio);
  8438. })
  8439. .catch(function(err) {
  8440. console.log("Failed to replace a track: " + err);
  8441. });
  8442. } else {
  8443. console.log("Cannot switch tracks: no RTPSender.");
  8444. }
  8445. } else {
  8446. self.peerconnection.removeStream(oldStream, true);
  8447. if (newStream) {
  8448. self.peerconnection.addStream(newStream);
  8449. }
  8450. }
  8451. }
  8452. // Conference is not active
  8453. if (!oldSdp) {
  8454. successCallback();
  8455. return;
  8456. }
  8457. self.switchstreams = true;
  8458. self.modifySourcesQueue.push(function() {
  8459. logger.log('modify sources done');
  8460. successCallback();
  8461. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8462. logger.log("SDPs", oldSdp, newSdp);
  8463. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8464. });
  8465. };
  8466. /**
  8467. * Adds streams.
  8468. * @param stream new stream that will be added.
  8469. * @param success_callback callback executed after successful stream addition.
  8470. */
  8471. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8472. var self = this;
  8473. // Remember SDP to figure out added/removed SSRCs
  8474. var oldSdp = null;
  8475. if(this.peerconnection) {
  8476. if(this.peerconnection.localDescription) {
  8477. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8478. }
  8479. if(stream)
  8480. this.peerconnection.addStream(stream);
  8481. }
  8482. // Conference is not active
  8483. if(!oldSdp || !this.peerconnection) {
  8484. callback();
  8485. return;
  8486. }
  8487. this.addingStreams = true;
  8488. this.modifySourcesQueue.push(function() {
  8489. logger.log('modify sources done');
  8490. callback();
  8491. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8492. logger.log("SDPs", oldSdp, newSdp);
  8493. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8494. });
  8495. }
  8496. /**
  8497. * Remove streams.
  8498. * @param stream stream that will be removed.
  8499. * @param success_callback callback executed after successful stream addition.
  8500. */
  8501. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8502. var self = this;
  8503. // Remember SDP to figure out added/removed SSRCs
  8504. var oldSdp = null;
  8505. if(this.peerconnection) {
  8506. if(this.peerconnection.localDescription) {
  8507. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8508. }
  8509. if (RTCBrowserType.getBrowserType() ===
  8510. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8511. var sender = null;
  8512. // On Firefox we don't replace MediaStreams as this messes up the
  8513. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8514. // of complications. Instead, we use the RTPSender and replace just
  8515. // the track.
  8516. var track = null;
  8517. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8518. track = stream.getAudioTracks()[0];
  8519. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8520. {
  8521. track = stream.getVideoTracks()[0];
  8522. }
  8523. if(!track) {
  8524. console.log("Cannot switch tracks: no tracks.");
  8525. return;
  8526. }
  8527. // Find the right sender (for audio or video)
  8528. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8529. if (s.track === track) {
  8530. sender = s;
  8531. return true;
  8532. }
  8533. });
  8534. if (sender) {
  8535. self.peerconnection.peerconnection.removeTrack(sender);
  8536. // .then(function() {
  8537. // console.log("Replaced a track, isAudio=" + isAudio);
  8538. // })
  8539. // .catch(function(err) {
  8540. // console.log("Failed to replace a track: " + err);
  8541. // });
  8542. } else {
  8543. console.log("Cannot switch tracks: no RTPSender.");
  8544. }
  8545. } else if(stream)
  8546. this.peerconnection.removeStream(stream);
  8547. }
  8548. // Conference is not active
  8549. if(!oldSdp || !this.peerconnection) {
  8550. callback();
  8551. return;
  8552. }
  8553. this.addingStreams = true;
  8554. this.modifySourcesQueue.push(function() {
  8555. logger.log('modify sources done');
  8556. callback();
  8557. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8558. logger.log("SDPs", oldSdp, newSdp);
  8559. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8560. });
  8561. }
  8562. /**
  8563. * Figures out added/removed ssrcs and send update IQs.
  8564. * @param old_sdp SDP object for old description.
  8565. * @param new_sdp SDP object for new description.
  8566. */
  8567. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8568. if (!(this.peerconnection.signalingState == 'stable' &&
  8569. this.peerconnection.iceConnectionState == 'connected')){
  8570. logger.log("Too early to send updates");
  8571. return;
  8572. }
  8573. // send source-remove IQ.
  8574. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8575. var remove = $iq({to: this.peerjid, type: 'set'})
  8576. .c('jingle', {
  8577. xmlns: 'urn:xmpp:jingle:1',
  8578. action: 'source-remove',
  8579. initiator: this.initiator,
  8580. sid: this.sid
  8581. }
  8582. );
  8583. var removed = sdpDiffer.toJingle(remove);
  8584. if (removed && remove) {
  8585. logger.info("Sending source-remove", remove);
  8586. this.connection.sendIQ(remove,
  8587. function (res) {
  8588. logger.info('got remove result', res);
  8589. },
  8590. function (err) {
  8591. logger.error('got remove error', err);
  8592. }
  8593. );
  8594. } else {
  8595. logger.log('removal not necessary');
  8596. }
  8597. // send source-add IQ.
  8598. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8599. var add = $iq({to: this.peerjid, type: 'set'})
  8600. .c('jingle', {
  8601. xmlns: 'urn:xmpp:jingle:1',
  8602. action: 'source-add',
  8603. initiator: this.initiator,
  8604. sid: this.sid
  8605. }
  8606. );
  8607. var added = sdpDiffer.toJingle(add);
  8608. if (added && add) {
  8609. logger.info("Sending source-add", add);
  8610. this.connection.sendIQ(add,
  8611. function (res) {
  8612. logger.info('got add result', res);
  8613. },
  8614. function (err) {
  8615. logger.error('got add error', err);
  8616. }
  8617. );
  8618. } else {
  8619. logger.log('addition not necessary');
  8620. }
  8621. };
  8622. /**
  8623. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  8624. *
  8625. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  8626. * tracks; otherwise, <tt>false</tt>
  8627. * @param callback a function to be invoked with <tt>mute</tt> after all video
  8628. * tracks have been enabled/disabled. The function may, optionally, return
  8629. * another function which is to be invoked after the whole mute/unmute operation
  8630. * has completed successfully.
  8631. * @param options an object which specifies optional arguments such as the
  8632. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  8633. * specifies whether the method was initiated in response to a user command (in
  8634. * contrast to an automatic decision made by the application logic)
  8635. */
  8636. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  8637. var byUser;
  8638. if (options) {
  8639. byUser = options.byUser;
  8640. if (typeof byUser === 'undefined') {
  8641. byUser = true;
  8642. }
  8643. } else {
  8644. byUser = true;
  8645. }
  8646. // The user's command to mute the (local) video takes precedence over any
  8647. // automatic decision made by the application logic.
  8648. if (byUser) {
  8649. this.videoMuteByUser = mute;
  8650. } else if (this.videoMuteByUser) {
  8651. return;
  8652. }
  8653. this.hardMuteVideo(mute);
  8654. var self = this;
  8655. var oldSdp = null;
  8656. if(self.peerconnection) {
  8657. if(self.peerconnection.localDescription) {
  8658. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8659. }
  8660. }
  8661. this.modifySourcesQueue.push(function() {
  8662. logger.log('modify sources done');
  8663. callback(mute);
  8664. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8665. logger.log("SDPs", oldSdp, newSdp);
  8666. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8667. });
  8668. };
  8669. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  8670. this.pendingop = muted ? 'mute' : 'unmute';
  8671. };
  8672. JingleSessionPC.prototype.sendMute = function (muted, content) {
  8673. var info = $iq({to: this.peerjid,
  8674. type: 'set'})
  8675. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8676. action: 'session-info',
  8677. initiator: this.initiator,
  8678. sid: this.sid });
  8679. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8680. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  8681. if (content) {
  8682. info.attrs({'name': content});
  8683. }
  8684. this.connection.send(info);
  8685. };
  8686. JingleSessionPC.prototype.sendRinging = function () {
  8687. var info = $iq({to: this.peerjid,
  8688. type: 'set'})
  8689. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8690. action: 'session-info',
  8691. initiator: this.initiator,
  8692. sid: this.sid });
  8693. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8694. this.connection.send(info);
  8695. };
  8696. JingleSessionPC.prototype.getStats = function (interval) {
  8697. var self = this;
  8698. var recv = {audio: 0, video: 0};
  8699. var lost = {audio: 0, video: 0};
  8700. var lastrecv = {audio: 0, video: 0};
  8701. var lastlost = {audio: 0, video: 0};
  8702. var loss = {audio: 0, video: 0};
  8703. var delta = {audio: 0, video: 0};
  8704. this.statsinterval = window.setInterval(function () {
  8705. if (self && self.peerconnection && self.peerconnection.getStats) {
  8706. self.peerconnection.getStats(function (stats) {
  8707. var results = stats.result();
  8708. // TODO: there are so much statistics you can get from this..
  8709. for (var i = 0; i < results.length; ++i) {
  8710. if (results[i].type == 'ssrc') {
  8711. var packetsrecv = results[i].stat('packetsReceived');
  8712. var packetslost = results[i].stat('packetsLost');
  8713. if (packetsrecv && packetslost) {
  8714. packetsrecv = parseInt(packetsrecv, 10);
  8715. packetslost = parseInt(packetslost, 10);
  8716. if (results[i].stat('googFrameRateReceived')) {
  8717. lastlost.video = lost.video;
  8718. lastrecv.video = recv.video;
  8719. recv.video = packetsrecv;
  8720. lost.video = packetslost;
  8721. } else {
  8722. lastlost.audio = lost.audio;
  8723. lastrecv.audio = recv.audio;
  8724. recv.audio = packetsrecv;
  8725. lost.audio = packetslost;
  8726. }
  8727. }
  8728. }
  8729. }
  8730. delta.audio = recv.audio - lastrecv.audio;
  8731. delta.video = recv.video - lastrecv.video;
  8732. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8733. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8734. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8735. });
  8736. }
  8737. }, interval || 3000);
  8738. return this.statsinterval;
  8739. };
  8740. JingleSessionPC.onJingleError = function (session, error)
  8741. {
  8742. logger.error("Jingle error", error);
  8743. }
  8744. JingleSessionPC.onJingleFatalError = function (session, error)
  8745. {
  8746. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8747. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8748. }
  8749. JingleSessionPC.prototype.setLocalDescription = function () {
  8750. var self = this;
  8751. var newssrcs = [];
  8752. if(!this.peerconnection.localDescription)
  8753. return;
  8754. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8755. var i;
  8756. session.media.forEach(function (media) {
  8757. if (media.ssrcs && media.ssrcs.length > 0) {
  8758. // TODO(gp) maybe exclude FID streams?
  8759. media.ssrcs.forEach(function (ssrc) {
  8760. if (ssrc.attribute !== 'cname') {
  8761. return;
  8762. }
  8763. newssrcs.push({
  8764. 'ssrc': ssrc.id,
  8765. 'type': media.type
  8766. });
  8767. // FIXME allows for only one SSRC per media type
  8768. self.localStreamsSSRC[media.type] = ssrc.id;
  8769. });
  8770. }
  8771. });
  8772. logger.log('new ssrcs', newssrcs);
  8773. // Bind us as local SSRCs owner
  8774. if (newssrcs.length > 0) {
  8775. for (i = 0; i < newssrcs.length; i++) {
  8776. var ssrc = newssrcs[i].ssrc;
  8777. var myJid = self.me;
  8778. self.ssrcOwners[ssrc] = myJid;
  8779. }
  8780. }
  8781. }
  8782. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8783. JingleSessionPC.prototype.sendKeyframe = function () {
  8784. var pc = this.peerconnection;
  8785. logger.log('sendkeyframe', pc.iceConnectionState);
  8786. if (pc.iceConnectionState !== 'connected') return; // safe...
  8787. var self = this;
  8788. pc.setRemoteDescription(
  8789. pc.remoteDescription,
  8790. function () {
  8791. pc.createAnswer(
  8792. function (modifiedAnswer) {
  8793. pc.setLocalDescription(
  8794. modifiedAnswer,
  8795. function () {
  8796. // noop
  8797. },
  8798. function (error) {
  8799. logger.log('triggerKeyframe setLocalDescription failed', error);
  8800. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8801. }
  8802. );
  8803. },
  8804. function (error) {
  8805. logger.log('triggerKeyframe createAnswer failed', error);
  8806. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8807. }
  8808. );
  8809. },
  8810. function (error) {
  8811. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8812. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8813. }
  8814. );
  8815. }
  8816. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8817. var self = this;
  8818. var thessrc;
  8819. var streamId = RTC.getStreamID(data.stream);
  8820. // look up an associated JID for a stream id
  8821. if (!streamId) {
  8822. logger.error("No stream ID for", data.stream);
  8823. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8824. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8825. var ssrclines = this.peerconnection.remoteDescription?
  8826. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8827. ssrclines = ssrclines.filter(function (line) {
  8828. // NOTE(gp) previously we filtered on the mslabel, but that property
  8829. // is not always present.
  8830. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8831. if (RTCBrowserType.isTemasysPluginUsed()) {
  8832. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8833. } else {
  8834. return ((line.indexOf('msid:' + streamId) !== -1));
  8835. }
  8836. });
  8837. if (ssrclines.length) {
  8838. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8839. if (!self.ssrcOwners[thessrc]) {
  8840. logger.error("No SSRC owner known for: " + thessrc);
  8841. return;
  8842. }
  8843. data.peerjid = self.ssrcOwners[thessrc];
  8844. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8845. } else {
  8846. logger.error("No SSRC lines for ", streamId);
  8847. }
  8848. }
  8849. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8850. var isVideo = data.stream.getVideoTracks().length > 0;
  8851. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8852. if (isVideo &&
  8853. data.peerjid && this.peerjid === data.peerjid &&
  8854. data.stream.getVideoTracks().length === 0 &&
  8855. RTC.localVideo.getTracks().length > 0) {
  8856. window.setTimeout(function () {
  8857. self.sendKeyframe();
  8858. }, 3000);
  8859. }
  8860. }
  8861. /**
  8862. * Returns the ice connection state for the peer connection.
  8863. * @returns the ice connection state for the peer connection.
  8864. */
  8865. JingleSessionPC.prototype.getIceConnectionState = function () {
  8866. return this.peerconnection.iceConnectionState;
  8867. }
  8868. module.exports = JingleSessionPC;
  8869. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  8870. },{"../../service/xmpp/XMPPEvents":137,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":47,"jitsi-meet-logger":79,"sdp-transform":115}],32:[function(require,module,exports){
  8871. (function (__filename){
  8872. /* jshint -W117 */
  8873. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8874. var SDPUtil = require("./SDPUtil");
  8875. // SDP STUFF
  8876. function SDP(sdp) {
  8877. /**
  8878. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8879. * @type {boolean}
  8880. */
  8881. this.removeTcpCandidates = false;
  8882. /**
  8883. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8884. * @type {boolean}
  8885. */
  8886. this.removeUdpCandidates = false;
  8887. this.media = sdp.split('\r\nm=');
  8888. for (var i = 1; i < this.media.length; i++) {
  8889. this.media[i] = 'm=' + this.media[i];
  8890. if (i != this.media.length - 1) {
  8891. this.media[i] += '\r\n';
  8892. }
  8893. }
  8894. this.session = this.media.shift() + '\r\n';
  8895. this.raw = this.session + this.media.join('');
  8896. }
  8897. /**
  8898. * Returns map of MediaChannel mapped per channel idx.
  8899. */
  8900. SDP.prototype.getMediaSsrcMap = function() {
  8901. var self = this;
  8902. var media_ssrcs = {};
  8903. var tmp;
  8904. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  8905. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  8906. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  8907. var media = {
  8908. mediaindex: mediaindex,
  8909. mid: mid,
  8910. ssrcs: {},
  8911. ssrcGroups: []
  8912. };
  8913. media_ssrcs[mediaindex] = media;
  8914. tmp.forEach(function (line) {
  8915. var linessrc = line.substring(7).split(' ')[0];
  8916. // allocate new ChannelSsrc
  8917. if(!media.ssrcs[linessrc]) {
  8918. media.ssrcs[linessrc] = {
  8919. ssrc: linessrc,
  8920. lines: []
  8921. };
  8922. }
  8923. media.ssrcs[linessrc].lines.push(line);
  8924. });
  8925. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  8926. tmp.forEach(function(line){
  8927. var idx = line.indexOf(' ');
  8928. var semantics = line.substr(0, idx).substr(13);
  8929. var ssrcs = line.substr(14 + semantics.length).split(' ');
  8930. if (ssrcs.length) {
  8931. media.ssrcGroups.push({
  8932. semantics: semantics,
  8933. ssrcs: ssrcs
  8934. });
  8935. }
  8936. });
  8937. }
  8938. return media_ssrcs;
  8939. };
  8940. /**
  8941. * Returns <tt>true</tt> if this SDP contains given SSRC.
  8942. * @param ssrc the ssrc to check.
  8943. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  8944. */
  8945. SDP.prototype.containsSSRC = function (ssrc) {
  8946. // FIXME this code is really strange - improve it if you can
  8947. var medias = this.getMediaSsrcMap();
  8948. var result = false;
  8949. Object.keys(medias).forEach(function (mediaindex) {
  8950. if (result)
  8951. return;
  8952. if (medias[mediaindex].ssrcs[ssrc]) {
  8953. result = true;
  8954. }
  8955. });
  8956. return result;
  8957. };
  8958. // remove iSAC and CN from SDP
  8959. SDP.prototype.mangle = function () {
  8960. var i, j, mline, lines, rtpmap, newdesc;
  8961. for (i = 0; i < this.media.length; i++) {
  8962. lines = this.media[i].split('\r\n');
  8963. lines.pop(); // remove empty last element
  8964. mline = SDPUtil.parse_mline(lines.shift());
  8965. if (mline.media != 'audio')
  8966. continue;
  8967. newdesc = '';
  8968. mline.fmt.length = 0;
  8969. for (j = 0; j < lines.length; j++) {
  8970. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  8971. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  8972. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  8973. continue;
  8974. mline.fmt.push(rtpmap.id);
  8975. newdesc += lines[j] + '\r\n';
  8976. } else {
  8977. newdesc += lines[j] + '\r\n';
  8978. }
  8979. }
  8980. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  8981. this.media[i] += newdesc;
  8982. }
  8983. this.raw = this.session + this.media.join('');
  8984. };
  8985. // remove lines matching prefix from session section
  8986. SDP.prototype.removeSessionLines = function(prefix) {
  8987. var self = this;
  8988. var lines = SDPUtil.find_lines(this.session, prefix);
  8989. lines.forEach(function(line) {
  8990. self.session = self.session.replace(line + '\r\n', '');
  8991. });
  8992. this.raw = this.session + this.media.join('');
  8993. return lines;
  8994. }
  8995. // remove lines matching prefix from a media section specified by mediaindex
  8996. // TODO: non-numeric mediaindex could match mid
  8997. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  8998. var self = this;
  8999. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  9000. lines.forEach(function(line) {
  9001. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  9002. });
  9003. this.raw = this.session + this.media.join('');
  9004. return lines;
  9005. }
  9006. // add content's to a jingle element
  9007. SDP.prototype.toJingle = function (elem, thecreator) {
  9008. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  9009. var self = this;
  9010. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  9011. // new bundle plan
  9012. if (SDPUtil.find_line(this.session, 'a=group:')) {
  9013. lines = SDPUtil.find_lines(this.session, 'a=group:');
  9014. for (i = 0; i < lines.length; i++) {
  9015. tmp = lines[i].split(' ');
  9016. var semantics = tmp.shift().substr(8);
  9017. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  9018. for (j = 0; j < tmp.length; j++) {
  9019. elem.c('content', {name: tmp[j]}).up();
  9020. }
  9021. elem.up();
  9022. }
  9023. }
  9024. for (i = 0; i < this.media.length; i++) {
  9025. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  9026. if (!(mline.media === 'audio' ||
  9027. mline.media === 'video' ||
  9028. mline.media === 'application'))
  9029. {
  9030. continue;
  9031. }
  9032. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  9033. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  9034. } else {
  9035. ssrc = false;
  9036. }
  9037. elem.c('content', {creator: thecreator, name: mline.media});
  9038. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  9039. // prefer identifier from a=mid if present
  9040. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  9041. elem.attrs({ name: mid });
  9042. }
  9043. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  9044. elem.c('description',
  9045. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  9046. media: mline.media });
  9047. if (ssrc) {
  9048. elem.attrs({ssrc: ssrc});
  9049. }
  9050. for (j = 0; j < mline.fmt.length; j++) {
  9051. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  9052. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  9053. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  9054. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  9055. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  9056. for (k = 0; k < tmp.length; k++) {
  9057. elem.c('parameter', tmp[k]).up();
  9058. }
  9059. }
  9060. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  9061. elem.up();
  9062. }
  9063. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  9064. elem.c('encryption', {required: 1});
  9065. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  9066. crypto.forEach(function(line) {
  9067. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  9068. });
  9069. elem.up(); // end of encryption
  9070. }
  9071. if (ssrc) {
  9072. // new style mapping
  9073. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9074. // FIXME: group by ssrc and support multiple different ssrcs
  9075. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  9076. if(ssrclines.length > 0) {
  9077. ssrclines.forEach(function (line) {
  9078. var idx = line.indexOf(' ');
  9079. var linessrc = line.substr(0, idx).substr(7);
  9080. if (linessrc != ssrc) {
  9081. elem.up();
  9082. ssrc = linessrc;
  9083. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9084. }
  9085. var kv = line.substr(idx + 1);
  9086. elem.c('parameter');
  9087. if (kv.indexOf(':') == -1) {
  9088. elem.attrs({ name: kv });
  9089. } else {
  9090. var k = kv.split(':', 2)[0];
  9091. elem.attrs({ name: k });
  9092. var v = kv.split(':', 2)[1];
  9093. v = SDPUtil.filter_special_chars(v);
  9094. elem.attrs({ value: v });
  9095. }
  9096. elem.up();
  9097. });
  9098. } else {
  9099. elem.up();
  9100. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9101. elem.c('parameter');
  9102. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9103. elem.up();
  9104. var msid = null;
  9105. if(mline.media == "audio")
  9106. {
  9107. msid = APP.RTC.localAudio._getId();
  9108. }
  9109. else
  9110. {
  9111. msid = APP.RTC.localVideo._getId();
  9112. }
  9113. if(msid != null)
  9114. {
  9115. msid = SDPUtil.filter_special_chars(msid);
  9116. elem.c('parameter');
  9117. elem.attrs({name: "msid", value:msid});
  9118. elem.up();
  9119. elem.c('parameter');
  9120. elem.attrs({name: "mslabel", value:msid});
  9121. elem.up();
  9122. elem.c('parameter');
  9123. elem.attrs({name: "label", value:msid});
  9124. elem.up();
  9125. }
  9126. }
  9127. elem.up();
  9128. // XEP-0339 handle ssrc-group attributes
  9129. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9130. ssrc_group_lines.forEach(function(line) {
  9131. var idx = line.indexOf(' ');
  9132. var semantics = line.substr(0, idx).substr(13);
  9133. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9134. if (ssrcs.length) {
  9135. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9136. ssrcs.forEach(function(ssrc) {
  9137. elem.c('source', { ssrc: ssrc })
  9138. .up();
  9139. });
  9140. elem.up();
  9141. }
  9142. });
  9143. }
  9144. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9145. elem.c('rtcp-mux').up();
  9146. }
  9147. // XEP-0293 -- map a=rtcp-fb:*
  9148. this.rtcpFbToJingle(i, elem, '*');
  9149. // XEP-0294
  9150. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9151. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9152. for (j = 0; j < lines.length; j++) {
  9153. tmp = SDPUtil.parse_extmap(lines[j]);
  9154. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9155. uri: tmp.uri,
  9156. id: tmp.value });
  9157. if (tmp.hasOwnProperty('direction')) {
  9158. switch (tmp.direction) {
  9159. case 'sendonly':
  9160. elem.attrs({senders: 'responder'});
  9161. break;
  9162. case 'recvonly':
  9163. elem.attrs({senders: 'initiator'});
  9164. break;
  9165. case 'sendrecv':
  9166. elem.attrs({senders: 'both'});
  9167. break;
  9168. case 'inactive':
  9169. elem.attrs({senders: 'none'});
  9170. break;
  9171. }
  9172. }
  9173. // TODO: handle params
  9174. elem.up();
  9175. }
  9176. }
  9177. elem.up(); // end of description
  9178. }
  9179. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9180. this.transportToJingle(i, elem);
  9181. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9182. elem.attrs({senders: 'both'});
  9183. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9184. elem.attrs({senders: 'initiator'});
  9185. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9186. elem.attrs({senders: 'responder'});
  9187. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9188. elem.attrs({senders: 'none'});
  9189. }
  9190. if (mline.port == '0') {
  9191. // estos hack to reject an m-line
  9192. elem.attrs({senders: 'rejected'});
  9193. }
  9194. elem.up(); // end of content
  9195. }
  9196. elem.up();
  9197. return elem;
  9198. };
  9199. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9200. var tmp, sctpmap, sctpAttrs, fingerprints;
  9201. var self = this;
  9202. elem.c('transport');
  9203. // XEP-0343 DTLS/SCTP
  9204. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9205. {
  9206. sctpmap = SDPUtil.find_line(
  9207. this.media[mediaindex], 'a=sctpmap:', self.session);
  9208. if (sctpmap)
  9209. {
  9210. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9211. elem.c('sctpmap',
  9212. {
  9213. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9214. number: sctpAttrs[0], /* SCTP port */
  9215. protocol: sctpAttrs[1] /* protocol */
  9216. });
  9217. // Optional stream count attribute
  9218. if (sctpAttrs.length > 2)
  9219. elem.attrs({ streams: sctpAttrs[2]});
  9220. elem.up();
  9221. }
  9222. }
  9223. // XEP-0320
  9224. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9225. fingerprints.forEach(function(line) {
  9226. tmp = SDPUtil.parse_fingerprint(line);
  9227. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9228. elem.c('fingerprint').t(tmp.fingerprint);
  9229. delete tmp.fingerprint;
  9230. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9231. if (line) {
  9232. tmp.setup = line.substr(8);
  9233. }
  9234. elem.attrs(tmp);
  9235. elem.up(); // end of fingerprint
  9236. });
  9237. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9238. if (tmp) {
  9239. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9240. elem.attrs(tmp);
  9241. // XEP-0176
  9242. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9243. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9244. lines.forEach(function (line) {
  9245. var candidate = SDPUtil.candidateToJingle(line);
  9246. var protocol = (candidate &&
  9247. typeof candidate.protocol === 'string')
  9248. ? candidate.protocol.toLowerCase() : '';
  9249. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9250. (self.removeUdpCandidates && protocol === 'udp')) {
  9251. return;
  9252. }
  9253. elem.c('candidate', candidate).up();
  9254. });
  9255. }
  9256. }
  9257. elem.up(); // end of transport
  9258. }
  9259. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9260. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9261. lines.forEach(function (line) {
  9262. var tmp = SDPUtil.parse_rtcpfb(line);
  9263. if (tmp.type == 'trr-int') {
  9264. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9265. elem.up();
  9266. } else {
  9267. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9268. if (tmp.params.length > 0) {
  9269. elem.attrs({'subtype': tmp.params[0]});
  9270. }
  9271. elem.up();
  9272. }
  9273. });
  9274. };
  9275. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9276. var media = '';
  9277. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9278. if (tmp.length) {
  9279. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9280. if (tmp.attr('value')) {
  9281. media += tmp.attr('value');
  9282. } else {
  9283. media += '0';
  9284. }
  9285. media += '\r\n';
  9286. }
  9287. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9288. tmp.each(function () {
  9289. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9290. if ($(this).attr('subtype')) {
  9291. media += ' ' + $(this).attr('subtype');
  9292. }
  9293. media += '\r\n';
  9294. });
  9295. return media;
  9296. };
  9297. // construct an SDP from a jingle stanza
  9298. SDP.prototype.fromJingle = function (jingle) {
  9299. var self = this;
  9300. this.raw = 'v=0\r\n' +
  9301. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9302. 's=-\r\n' +
  9303. 't=0 0\r\n';
  9304. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9305. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9306. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9307. var contents = $(group).find('>content').map(function (idx, content) {
  9308. return content.getAttribute('name');
  9309. }).get();
  9310. if (contents.length > 0) {
  9311. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9312. }
  9313. });
  9314. }
  9315. this.session = this.raw;
  9316. jingle.find('>content').each(function () {
  9317. var m = self.jingle2media($(this));
  9318. self.media.push(m);
  9319. });
  9320. // reconstruct msid-semantic -- apparently not necessary
  9321. /*
  9322. var msid = SDPUtil.parse_ssrc(this.raw);
  9323. if (msid.hasOwnProperty('mslabel')) {
  9324. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9325. }
  9326. */
  9327. this.raw = this.session + this.media.join('');
  9328. };
  9329. // translate a jingle content element into an an SDP media part
  9330. SDP.prototype.jingle2media = function (content) {
  9331. var media = '',
  9332. desc = content.find('description'),
  9333. ssrc = desc.attr('ssrc'),
  9334. self = this,
  9335. tmp;
  9336. var sctp = content.find(
  9337. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9338. tmp = { media: desc.attr('media') };
  9339. tmp.port = '1';
  9340. if (content.attr('senders') == 'rejected') {
  9341. // estos hack to reject an m-line.
  9342. tmp.port = '0';
  9343. }
  9344. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9345. if (sctp.length)
  9346. tmp.proto = 'DTLS/SCTP';
  9347. else
  9348. tmp.proto = 'RTP/SAVPF';
  9349. } else {
  9350. tmp.proto = 'RTP/AVPF';
  9351. }
  9352. if (!sctp.length) {
  9353. tmp.fmt = desc.find('payload-type').map(
  9354. function () { return this.getAttribute('id'); }).get();
  9355. media += SDPUtil.build_mline(tmp) + '\r\n';
  9356. } else {
  9357. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9358. media += 'a=sctpmap:' + sctp.attr('number') +
  9359. ' ' + sctp.attr('protocol');
  9360. var streamCount = sctp.attr('streams');
  9361. if (streamCount)
  9362. media += ' ' + streamCount + '\r\n';
  9363. else
  9364. media += '\r\n';
  9365. }
  9366. media += 'c=IN IP4 0.0.0.0\r\n';
  9367. if (!sctp.length)
  9368. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9369. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9370. if (tmp.length) {
  9371. if (tmp.attr('ufrag')) {
  9372. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9373. }
  9374. if (tmp.attr('pwd')) {
  9375. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9376. }
  9377. tmp.find('>fingerprint').each(function () {
  9378. // FIXME: check namespace at some point
  9379. media += 'a=fingerprint:' + this.getAttribute('hash');
  9380. media += ' ' + $(this).text();
  9381. media += '\r\n';
  9382. if (this.getAttribute('setup')) {
  9383. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9384. }
  9385. });
  9386. }
  9387. switch (content.attr('senders')) {
  9388. case 'initiator':
  9389. media += 'a=sendonly\r\n';
  9390. break;
  9391. case 'responder':
  9392. media += 'a=recvonly\r\n';
  9393. break;
  9394. case 'none':
  9395. media += 'a=inactive\r\n';
  9396. break;
  9397. case 'both':
  9398. media += 'a=sendrecv\r\n';
  9399. break;
  9400. }
  9401. media += 'a=mid:' + content.attr('name') + '\r\n';
  9402. // <description><rtcp-mux/></description>
  9403. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9404. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9405. if (desc.find('rtcp-mux').length) {
  9406. media += 'a=rtcp-mux\r\n';
  9407. }
  9408. if (desc.find('encryption').length) {
  9409. desc.find('encryption>crypto').each(function () {
  9410. media += 'a=crypto:' + this.getAttribute('tag');
  9411. media += ' ' + this.getAttribute('crypto-suite');
  9412. media += ' ' + this.getAttribute('key-params');
  9413. if (this.getAttribute('session-params')) {
  9414. media += ' ' + this.getAttribute('session-params');
  9415. }
  9416. media += '\r\n';
  9417. });
  9418. }
  9419. desc.find('payload-type').each(function () {
  9420. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9421. if ($(this).find('>parameter').length) {
  9422. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9423. media += $(this).find('parameter').map(function () {
  9424. return (this.getAttribute('name')
  9425. ? (this.getAttribute('name') + '=') : '') +
  9426. this.getAttribute('value');
  9427. }).get().join('; ');
  9428. media += '\r\n';
  9429. }
  9430. // xep-0293
  9431. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9432. });
  9433. // xep-0293
  9434. media += self.rtcpFbFromJingle(desc, '*');
  9435. // xep-0294
  9436. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9437. tmp.each(function () {
  9438. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9439. });
  9440. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9441. var protocol = this.getAttribute('protocol');
  9442. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9443. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9444. (self.removeUdpCandidates && protocol === 'udp')) {
  9445. return;
  9446. }
  9447. media += SDPUtil.candidateFromJingle(this);
  9448. });
  9449. // XEP-0339 handle ssrc-group attributes
  9450. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9451. var semantics = this.getAttribute('semantics');
  9452. var ssrcs = $(this).find('>source').map(function() {
  9453. return this.getAttribute('ssrc');
  9454. }).get();
  9455. if (ssrcs.length) {
  9456. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9457. }
  9458. });
  9459. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9460. tmp.each(function () {
  9461. var ssrc = this.getAttribute('ssrc');
  9462. $(this).find('>parameter').each(function () {
  9463. var name = this.getAttribute('name');
  9464. var value = this.getAttribute('value');
  9465. value = SDPUtil.filter_special_chars(value);
  9466. media += 'a=ssrc:' + ssrc + ' ' + name;
  9467. if (value && value.length)
  9468. media += ':' + value;
  9469. media += '\r\n';
  9470. });
  9471. });
  9472. return media;
  9473. };
  9474. module.exports = SDP;
  9475. }).call(this,"/modules/xmpp/SDP.js")
  9476. },{"./SDPUtil":34,"jitsi-meet-logger":79}],33:[function(require,module,exports){
  9477. var SDPUtil = require("./SDPUtil");
  9478. function SDPDiffer(mySDP, otherSDP)
  9479. {
  9480. this.mySDP = mySDP;
  9481. this.otherSDP = otherSDP;
  9482. }
  9483. /**
  9484. * Returns map of MediaChannel that contains media contained in
  9485. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9486. */
  9487. SDPDiffer.prototype.getNewMedia = function() {
  9488. // this could be useful in Array.prototype.
  9489. function arrayEquals(array) {
  9490. // if the other array is a falsy value, return
  9491. if (!array)
  9492. return false;
  9493. // compare lengths - can save a lot of time
  9494. if (this.length != array.length)
  9495. return false;
  9496. for (var i = 0, l=this.length; i < l; i++) {
  9497. // Check if we have nested arrays
  9498. if (this[i] instanceof Array && array[i] instanceof Array) {
  9499. // recurse into the nested arrays
  9500. if (!this[i].equals(array[i]))
  9501. return false;
  9502. }
  9503. else if (this[i] != array[i]) {
  9504. // Warning - two different object instances will never be
  9505. // equal: {x:20} != {x:20}
  9506. return false;
  9507. }
  9508. }
  9509. return true;
  9510. }
  9511. var myMedias = this.mySDP.getMediaSsrcMap();
  9512. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9513. var newMedia = {};
  9514. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9515. var myMedia = myMedias[othersMediaIdx];
  9516. var othersMedia = othersMedias[othersMediaIdx];
  9517. if(!myMedia && othersMedia) {
  9518. // Add whole channel
  9519. newMedia[othersMediaIdx] = othersMedia;
  9520. return;
  9521. }
  9522. // Look for new ssrcs across the channel
  9523. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9524. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9525. // Allocate channel if we've found ssrc that doesn't exist in
  9526. // our channel
  9527. if(!newMedia[othersMediaIdx]){
  9528. newMedia[othersMediaIdx] = {
  9529. mediaindex: othersMedia.mediaindex,
  9530. mid: othersMedia.mid,
  9531. ssrcs: {},
  9532. ssrcGroups: []
  9533. };
  9534. }
  9535. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9536. }
  9537. });
  9538. // Look for new ssrc groups across the channels
  9539. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9540. // try to match the other ssrc-group with an ssrc-group of ours
  9541. var matched = false;
  9542. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9543. var mySsrcGroup = myMedia.ssrcGroups[i];
  9544. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9545. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9546. [mySsrcGroup.ssrcs])) {
  9547. matched = true;
  9548. break;
  9549. }
  9550. }
  9551. if (!matched) {
  9552. // Allocate channel if we've found an ssrc-group that doesn't
  9553. // exist in our channel
  9554. if(!newMedia[othersMediaIdx]){
  9555. newMedia[othersMediaIdx] = {
  9556. mediaindex: othersMedia.mediaindex,
  9557. mid: othersMedia.mid,
  9558. ssrcs: {},
  9559. ssrcGroups: []
  9560. };
  9561. }
  9562. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9563. }
  9564. });
  9565. });
  9566. return newMedia;
  9567. };
  9568. /**
  9569. * TODO: document!
  9570. */
  9571. SDPDiffer.prototype.toJingle = function(modify) {
  9572. var sdpMediaSsrcs = this.getNewMedia();
  9573. var modified = false;
  9574. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9575. modified = true;
  9576. var media = sdpMediaSsrcs[mediaindex];
  9577. modify.c('content', {name: media.mid});
  9578. modify.c('description',
  9579. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9580. // FIXME: not completely sure this operates on blocks and / or handles
  9581. // different ssrcs correctly
  9582. // generate sources from lines
  9583. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9584. var mediaSsrc = media.ssrcs[ssrcNum];
  9585. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9586. modify.attrs({ssrc: mediaSsrc.ssrc});
  9587. // iterate over ssrc lines
  9588. mediaSsrc.lines.forEach(function (line) {
  9589. var idx = line.indexOf(' ');
  9590. var kv = line.substr(idx + 1);
  9591. modify.c('parameter');
  9592. if (kv.indexOf(':') == -1) {
  9593. modify.attrs({ name: kv });
  9594. } else {
  9595. var nv = kv.split(':', 2);
  9596. var name = nv[0];
  9597. var value = SDPUtil.filter_special_chars(nv[1]);
  9598. modify.attrs({ name: name });
  9599. modify.attrs({ value: value });
  9600. }
  9601. modify.up(); // end of parameter
  9602. });
  9603. modify.up(); // end of source
  9604. });
  9605. // generate source groups from lines
  9606. media.ssrcGroups.forEach(function(ssrcGroup) {
  9607. if (ssrcGroup.ssrcs.length) {
  9608. modify.c('ssrc-group', {
  9609. semantics: ssrcGroup.semantics,
  9610. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9611. });
  9612. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9613. modify.c('source', { ssrc: ssrc })
  9614. .up(); // end of source
  9615. });
  9616. modify.up(); // end of ssrc-group
  9617. }
  9618. });
  9619. modify.up(); // end of description
  9620. modify.up(); // end of content
  9621. });
  9622. return modified;
  9623. };
  9624. module.exports = SDPDiffer;
  9625. },{"./SDPUtil":34}],34:[function(require,module,exports){
  9626. (function (__filename){
  9627. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9628. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9629. SDPUtil = {
  9630. filter_special_chars: function (text) {
  9631. return text.replace(/[\\\/\{,\}\+]/g, "");
  9632. },
  9633. iceparams: function (mediadesc, sessiondesc) {
  9634. var data = null;
  9635. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9636. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9637. data = {
  9638. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9639. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9640. };
  9641. }
  9642. return data;
  9643. },
  9644. parse_iceufrag: function (line) {
  9645. return line.substring(12);
  9646. },
  9647. build_iceufrag: function (frag) {
  9648. return 'a=ice-ufrag:' + frag;
  9649. },
  9650. parse_icepwd: function (line) {
  9651. return line.substring(10);
  9652. },
  9653. build_icepwd: function (pwd) {
  9654. return 'a=ice-pwd:' + pwd;
  9655. },
  9656. parse_mid: function (line) {
  9657. return line.substring(6);
  9658. },
  9659. parse_mline: function (line) {
  9660. var parts = line.substring(2).split(' '),
  9661. data = {};
  9662. data.media = parts.shift();
  9663. data.port = parts.shift();
  9664. data.proto = parts.shift();
  9665. if (parts[parts.length - 1] === '') { // trailing whitespace
  9666. parts.pop();
  9667. }
  9668. data.fmt = parts;
  9669. return data;
  9670. },
  9671. build_mline: function (mline) {
  9672. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9673. },
  9674. parse_rtpmap: function (line) {
  9675. var parts = line.substring(9).split(' '),
  9676. data = {};
  9677. data.id = parts.shift();
  9678. parts = parts[0].split('/');
  9679. data.name = parts.shift();
  9680. data.clockrate = parts.shift();
  9681. data.channels = parts.length ? parts.shift() : '1';
  9682. return data;
  9683. },
  9684. /**
  9685. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9686. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9687. * @returns [SCTP port number, protocol, streams]
  9688. */
  9689. parse_sctpmap: function (line)
  9690. {
  9691. var parts = line.substring(10).split(' ');
  9692. var sctpPort = parts[0];
  9693. var protocol = parts[1];
  9694. // Stream count is optional
  9695. var streamCount = parts.length > 2 ? parts[2] : null;
  9696. return [sctpPort, protocol, streamCount];// SCTP port
  9697. },
  9698. build_rtpmap: function (el) {
  9699. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9700. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9701. line += '/' + el.getAttribute('channels');
  9702. }
  9703. return line;
  9704. },
  9705. parse_crypto: function (line) {
  9706. var parts = line.substring(9).split(' '),
  9707. data = {};
  9708. data.tag = parts.shift();
  9709. data['crypto-suite'] = parts.shift();
  9710. data['key-params'] = parts.shift();
  9711. if (parts.length) {
  9712. data['session-params'] = parts.join(' ');
  9713. }
  9714. return data;
  9715. },
  9716. parse_fingerprint: function (line) { // RFC 4572
  9717. var parts = line.substring(14).split(' '),
  9718. data = {};
  9719. data.hash = parts.shift();
  9720. data.fingerprint = parts.shift();
  9721. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9722. return data;
  9723. },
  9724. parse_fmtp: function (line) {
  9725. var parts = line.split(' '),
  9726. i, key, value,
  9727. data = [];
  9728. parts.shift();
  9729. parts = parts.join(' ').split(';');
  9730. for (i = 0; i < parts.length; i++) {
  9731. key = parts[i].split('=')[0];
  9732. while (key.length && key[0] == ' ') {
  9733. key = key.substring(1);
  9734. }
  9735. value = parts[i].split('=')[1];
  9736. if (key && value) {
  9737. data.push({name: key, value: value});
  9738. } else if (key) {
  9739. // rfc 4733 (DTMF) style stuff
  9740. data.push({name: '', value: key});
  9741. }
  9742. }
  9743. return data;
  9744. },
  9745. parse_icecandidate: function (line) {
  9746. var candidate = {},
  9747. elems = line.split(' ');
  9748. candidate.foundation = elems[0].substring(12);
  9749. candidate.component = elems[1];
  9750. candidate.protocol = elems[2].toLowerCase();
  9751. candidate.priority = elems[3];
  9752. candidate.ip = elems[4];
  9753. candidate.port = elems[5];
  9754. // elems[6] => "typ"
  9755. candidate.type = elems[7];
  9756. candidate.generation = 0; // default value, may be overwritten below
  9757. for (var i = 8; i < elems.length; i += 2) {
  9758. switch (elems[i]) {
  9759. case 'raddr':
  9760. candidate['rel-addr'] = elems[i + 1];
  9761. break;
  9762. case 'rport':
  9763. candidate['rel-port'] = elems[i + 1];
  9764. break;
  9765. case 'generation':
  9766. candidate.generation = elems[i + 1];
  9767. break;
  9768. case 'tcptype':
  9769. candidate.tcptype = elems[i + 1];
  9770. break;
  9771. default: // TODO
  9772. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9773. }
  9774. }
  9775. candidate.network = '1';
  9776. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9777. return candidate;
  9778. },
  9779. build_icecandidate: function (cand) {
  9780. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9781. line += ' ';
  9782. switch (cand.type) {
  9783. case 'srflx':
  9784. case 'prflx':
  9785. case 'relay':
  9786. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9787. line += 'raddr';
  9788. line += ' ';
  9789. line += cand['rel-addr'];
  9790. line += ' ';
  9791. line += 'rport';
  9792. line += ' ';
  9793. line += cand['rel-port'];
  9794. line += ' ';
  9795. }
  9796. break;
  9797. }
  9798. if (cand.hasOwnAttribute('tcptype')) {
  9799. line += 'tcptype';
  9800. line += ' ';
  9801. line += cand.tcptype;
  9802. line += ' ';
  9803. }
  9804. line += 'generation';
  9805. line += ' ';
  9806. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9807. return line;
  9808. },
  9809. parse_ssrc: function (desc) {
  9810. // proprietary mapping of a=ssrc lines
  9811. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9812. // and parse according to that
  9813. var lines = desc.split('\r\n'),
  9814. data = {};
  9815. for (var i = 0; i < lines.length; i++) {
  9816. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9817. var idx = lines[i].indexOf(' ');
  9818. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9819. }
  9820. }
  9821. return data;
  9822. },
  9823. parse_rtcpfb: function (line) {
  9824. var parts = line.substr(10).split(' ');
  9825. var data = {};
  9826. data.pt = parts.shift();
  9827. data.type = parts.shift();
  9828. data.params = parts;
  9829. return data;
  9830. },
  9831. parse_extmap: function (line) {
  9832. var parts = line.substr(9).split(' ');
  9833. var data = {};
  9834. data.value = parts.shift();
  9835. if (data.value.indexOf('/') != -1) {
  9836. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9837. data.value = data.value.substr(0, data.value.indexOf('/'));
  9838. } else {
  9839. data.direction = 'both';
  9840. }
  9841. data.uri = parts.shift();
  9842. data.params = parts;
  9843. return data;
  9844. },
  9845. find_line: function (haystack, needle, sessionpart) {
  9846. var lines = haystack.split('\r\n');
  9847. for (var i = 0; i < lines.length; i++) {
  9848. if (lines[i].substring(0, needle.length) == needle) {
  9849. return lines[i];
  9850. }
  9851. }
  9852. if (!sessionpart) {
  9853. return false;
  9854. }
  9855. // search session part
  9856. lines = sessionpart.split('\r\n');
  9857. for (var j = 0; j < lines.length; j++) {
  9858. if (lines[j].substring(0, needle.length) == needle) {
  9859. return lines[j];
  9860. }
  9861. }
  9862. return false;
  9863. },
  9864. find_lines: function (haystack, needle, sessionpart) {
  9865. var lines = haystack.split('\r\n'),
  9866. needles = [];
  9867. for (var i = 0; i < lines.length; i++) {
  9868. if (lines[i].substring(0, needle.length) == needle)
  9869. needles.push(lines[i]);
  9870. }
  9871. if (needles.length || !sessionpart) {
  9872. return needles;
  9873. }
  9874. // search session part
  9875. lines = sessionpart.split('\r\n');
  9876. for (var j = 0; j < lines.length; j++) {
  9877. if (lines[j].substring(0, needle.length) == needle) {
  9878. needles.push(lines[j]);
  9879. }
  9880. }
  9881. return needles;
  9882. },
  9883. candidateToJingle: function (line) {
  9884. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9885. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9886. if (line.indexOf('candidate:') === 0) {
  9887. line = 'a=' + line;
  9888. } else if (line.substring(0, 12) != 'a=candidate:') {
  9889. logger.log('parseCandidate called with a line that is not a candidate line');
  9890. logger.log(line);
  9891. return null;
  9892. }
  9893. if (line.substring(line.length - 2) == '\r\n') // chomp it
  9894. line = line.substring(0, line.length - 2);
  9895. var candidate = {},
  9896. elems = line.split(' '),
  9897. i;
  9898. if (elems[6] != 'typ') {
  9899. logger.log('did not find typ in the right place');
  9900. logger.log(line);
  9901. return null;
  9902. }
  9903. candidate.foundation = elems[0].substring(12);
  9904. candidate.component = elems[1];
  9905. candidate.protocol = elems[2].toLowerCase();
  9906. candidate.priority = elems[3];
  9907. candidate.ip = elems[4];
  9908. candidate.port = elems[5];
  9909. // elems[6] => "typ"
  9910. candidate.type = elems[7];
  9911. candidate.generation = '0'; // default, may be overwritten below
  9912. for (i = 8; i < elems.length; i += 2) {
  9913. switch (elems[i]) {
  9914. case 'raddr':
  9915. candidate['rel-addr'] = elems[i + 1];
  9916. break;
  9917. case 'rport':
  9918. candidate['rel-port'] = elems[i + 1];
  9919. break;
  9920. case 'generation':
  9921. candidate.generation = elems[i + 1];
  9922. break;
  9923. case 'tcptype':
  9924. candidate.tcptype = elems[i + 1];
  9925. break;
  9926. default: // TODO
  9927. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9928. }
  9929. }
  9930. candidate.network = '1';
  9931. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9932. return candidate;
  9933. },
  9934. candidateFromJingle: function (cand) {
  9935. var line = 'a=candidate:';
  9936. line += cand.getAttribute('foundation');
  9937. line += ' ';
  9938. line += cand.getAttribute('component');
  9939. line += ' ';
  9940. var protocol = cand.getAttribute('protocol');
  9941. // use tcp candidates for FF
  9942. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  9943. protocol = 'tcp';
  9944. }
  9945. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  9946. line += ' ';
  9947. line += cand.getAttribute('priority');
  9948. line += ' ';
  9949. line += cand.getAttribute('ip');
  9950. line += ' ';
  9951. line += cand.getAttribute('port');
  9952. line += ' ';
  9953. line += 'typ';
  9954. line += ' ' + cand.getAttribute('type');
  9955. line += ' ';
  9956. switch (cand.getAttribute('type')) {
  9957. case 'srflx':
  9958. case 'prflx':
  9959. case 'relay':
  9960. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  9961. line += 'raddr';
  9962. line += ' ';
  9963. line += cand.getAttribute('rel-addr');
  9964. line += ' ';
  9965. line += 'rport';
  9966. line += ' ';
  9967. line += cand.getAttribute('rel-port');
  9968. line += ' ';
  9969. }
  9970. break;
  9971. }
  9972. if (protocol.toLowerCase() == 'tcp') {
  9973. line += 'tcptype';
  9974. line += ' ';
  9975. line += cand.getAttribute('tcptype');
  9976. line += ' ';
  9977. }
  9978. line += 'generation';
  9979. line += ' ';
  9980. line += cand.getAttribute('generation') || '0';
  9981. return line + '\r\n';
  9982. }
  9983. };
  9984. module.exports = SDPUtil;
  9985. }).call(this,"/modules/xmpp/SDPUtil.js")
  9986. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":79}],35:[function(require,module,exports){
  9987. (function (__filename){
  9988. /* global $ */
  9989. var RTC = require('../RTC/RTC');
  9990. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9991. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  9992. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9993. function TraceablePeerConnection(ice_config, constraints, session) {
  9994. var self = this;
  9995. this.session = session;
  9996. var RTCPeerConnectionType = null;
  9997. if (RTCBrowserType.isFirefox()) {
  9998. RTCPeerConnectionType = mozRTCPeerConnection;
  9999. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  10000. RTCPeerConnectionType = RTCPeerConnection;
  10001. } else {
  10002. RTCPeerConnectionType = webkitRTCPeerConnection;
  10003. }
  10004. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  10005. this.updateLog = [];
  10006. this.stats = {};
  10007. this.statsinterval = null;
  10008. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  10009. var Interop = require('sdp-interop').Interop;
  10010. this.interop = new Interop();
  10011. var Simulcast = require('sdp-simulcast');
  10012. this.simulcast = new Simulcast({numOfLayers: 3,
  10013. explodeRemoteSimulcast: false});
  10014. this.eventEmitter = this.session.room.eventEmitter;
  10015. // override as desired
  10016. this.trace = function (what, info) {
  10017. /*logger.warn('WTRACE', what, info);
  10018. if (info && RTCBrowserType.isIExplorer()) {
  10019. if (info.length > 1024) {
  10020. logger.warn('WTRACE', what, info.substr(1024));
  10021. }
  10022. if (info.length > 2048) {
  10023. logger.warn('WTRACE', what, info.substr(2048));
  10024. }
  10025. }*/
  10026. self.updateLog.push({
  10027. time: new Date(),
  10028. type: what,
  10029. value: info || ""
  10030. });
  10031. };
  10032. this.onicecandidate = null;
  10033. this.peerconnection.onicecandidate = function (event) {
  10034. // FIXME: this causes stack overflow with Temasys Plugin
  10035. if (!RTCBrowserType.isTemasysPluginUsed())
  10036. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  10037. if (self.onicecandidate !== null) {
  10038. self.onicecandidate(event);
  10039. }
  10040. };
  10041. this.onaddstream = null;
  10042. this.peerconnection.onaddstream = function (event) {
  10043. self.trace('onaddstream', event.stream.id);
  10044. if (self.onaddstream !== null) {
  10045. self.onaddstream(event);
  10046. }
  10047. };
  10048. this.onremovestream = null;
  10049. this.peerconnection.onremovestream = function (event) {
  10050. self.trace('onremovestream', event.stream.id);
  10051. if (self.onremovestream !== null) {
  10052. self.onremovestream(event);
  10053. }
  10054. };
  10055. this.onsignalingstatechange = null;
  10056. this.peerconnection.onsignalingstatechange = function (event) {
  10057. self.trace('onsignalingstatechange', self.signalingState);
  10058. if (self.onsignalingstatechange !== null) {
  10059. self.onsignalingstatechange(event);
  10060. }
  10061. };
  10062. this.oniceconnectionstatechange = null;
  10063. this.peerconnection.oniceconnectionstatechange = function (event) {
  10064. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  10065. if (self.oniceconnectionstatechange !== null) {
  10066. self.oniceconnectionstatechange(event);
  10067. }
  10068. };
  10069. this.onnegotiationneeded = null;
  10070. this.peerconnection.onnegotiationneeded = function (event) {
  10071. self.trace('onnegotiationneeded');
  10072. if (self.onnegotiationneeded !== null) {
  10073. self.onnegotiationneeded(event);
  10074. }
  10075. };
  10076. self.ondatachannel = null;
  10077. this.peerconnection.ondatachannel = function (event) {
  10078. self.trace('ondatachannel', event);
  10079. if (self.ondatachannel !== null) {
  10080. self.ondatachannel(event);
  10081. }
  10082. };
  10083. // XXX: do all non-firefox browsers which we support also support this?
  10084. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10085. this.statsinterval = window.setInterval(function() {
  10086. self.peerconnection.getStats(function(stats) {
  10087. var results = stats.result();
  10088. var now = new Date();
  10089. for (var i = 0; i < results.length; ++i) {
  10090. results[i].names().forEach(function (name) {
  10091. var id = results[i].id + '-' + name;
  10092. if (!self.stats[id]) {
  10093. self.stats[id] = {
  10094. startTime: now,
  10095. endTime: now,
  10096. values: [],
  10097. times: []
  10098. };
  10099. }
  10100. self.stats[id].values.push(results[i].stat(name));
  10101. self.stats[id].times.push(now.getTime());
  10102. if (self.stats[id].values.length > self.maxstats) {
  10103. self.stats[id].values.shift();
  10104. self.stats[id].times.shift();
  10105. }
  10106. self.stats[id].endTime = now;
  10107. });
  10108. }
  10109. });
  10110. }, 1000);
  10111. }
  10112. }
  10113. /**
  10114. * Returns a string representation of a SessionDescription object.
  10115. */
  10116. var dumpSDP = function(description) {
  10117. if (typeof description === 'undefined' || description == null) {
  10118. return '';
  10119. }
  10120. return 'type: ' + description.type + '\r\n' + description.sdp;
  10121. };
  10122. var insertRecvOnlySSRC = function (desc) {
  10123. if (typeof desc !== 'object' || desc === null ||
  10124. typeof desc.sdp !== 'string') {
  10125. console.warn('An empty description was passed as an argument.');
  10126. return desc;
  10127. }
  10128. var transform = require('sdp-transform');
  10129. var RandomUtil = require('../util/RandomUtil');
  10130. var session = transform.parse(desc.sdp);
  10131. if (!Array.isArray(session.media))
  10132. {
  10133. return;
  10134. }
  10135. var modded = false;
  10136. session.media.forEach(function (bLine) {
  10137. if (bLine.direction != 'recvonly')
  10138. {
  10139. return;
  10140. }
  10141. modded = true;
  10142. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10143. {
  10144. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  10145. bLine.ssrcs = [{
  10146. id: ssrc,
  10147. attribute: 'cname',
  10148. value: ['recvonly-', ssrc].join('')
  10149. }];
  10150. }
  10151. });
  10152. return (!modded) ? desc : new RTCSessionDescription({
  10153. type: desc.type,
  10154. sdp: transform.write(session),
  10155. });
  10156. };
  10157. /**
  10158. * Takes a SessionDescription object and returns a "normalized" version.
  10159. * Currently it only takes care of ordering the a=ssrc lines.
  10160. */
  10161. var normalizePlanB = function(desc) {
  10162. if (typeof desc !== 'object' || desc === null ||
  10163. typeof desc.sdp !== 'string') {
  10164. logger.warn('An empty description was passed as an argument.');
  10165. return desc;
  10166. }
  10167. var transform = require('sdp-transform');
  10168. var session = transform.parse(desc.sdp);
  10169. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10170. Array.isArray(session.media)) {
  10171. session.media.forEach(function (mLine) {
  10172. // Chrome appears to be picky about the order in which a=ssrc lines
  10173. // are listed in an m-line when rtx is enabled (and thus there are
  10174. // a=ssrc-group lines with FID semantics). Specifically if we have
  10175. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10176. // the "a=ssrc:S1" lines, SRD fails.
  10177. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10178. // first.
  10179. var firstSsrcs = [];
  10180. var newSsrcLines = [];
  10181. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10182. mLine.ssrcGroups.forEach(function (group) {
  10183. if (typeof group.semantics !== 'undefined' &&
  10184. group.semantics === 'FID') {
  10185. if (typeof group.ssrcs !== 'undefined') {
  10186. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10187. }
  10188. }
  10189. });
  10190. }
  10191. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10192. var i;
  10193. for (i = 0; i<mLine.ssrcs.length; i++){
  10194. if (typeof mLine.ssrcs[i] === 'object'
  10195. && typeof mLine.ssrcs[i].id !== 'undefined'
  10196. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10197. newSsrcLines.push(mLine.ssrcs[i]);
  10198. delete mLine.ssrcs[i];
  10199. }
  10200. }
  10201. for (i = 0; i<mLine.ssrcs.length; i++){
  10202. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10203. newSsrcLines.push(mLine.ssrcs[i]);
  10204. }
  10205. }
  10206. mLine.ssrcs = newSsrcLines;
  10207. }
  10208. });
  10209. }
  10210. var resStr = transform.write(session);
  10211. return new RTCSessionDescription({
  10212. type: desc.type,
  10213. sdp: resStr
  10214. });
  10215. };
  10216. var getters = {
  10217. signalingState: function () {
  10218. return this.peerconnection.signalingState;
  10219. },
  10220. iceConnectionState: function () {
  10221. return this.peerconnection.iceConnectionState;
  10222. },
  10223. localDescription: function() {
  10224. var desc = this.peerconnection.localDescription;
  10225. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10226. // if we're running on FF, transform to Plan B first.
  10227. if (RTCBrowserType.usesUnifiedPlan()) {
  10228. desc = this.interop.toPlanB(desc);
  10229. this.trace('getLocalDescription::postTransform (Plan B)',
  10230. dumpSDP(desc));
  10231. }
  10232. return desc;
  10233. },
  10234. remoteDescription: function() {
  10235. var desc = this.peerconnection.remoteDescription;
  10236. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10237. // if we're running on FF, transform to Plan B first.
  10238. if (RTCBrowserType.usesUnifiedPlan()) {
  10239. desc = this.interop.toPlanB(desc);
  10240. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10241. }
  10242. return desc;
  10243. }
  10244. };
  10245. Object.keys(getters).forEach(function (prop) {
  10246. Object.defineProperty(
  10247. TraceablePeerConnection.prototype,
  10248. prop, {
  10249. get: getters[prop]
  10250. }
  10251. );
  10252. });
  10253. TraceablePeerConnection.prototype.addStream = function (stream) {
  10254. this.trace('addStream', stream.id);
  10255. try
  10256. {
  10257. this.peerconnection.addStream(stream);
  10258. }
  10259. catch (e)
  10260. {
  10261. logger.error(e);
  10262. }
  10263. };
  10264. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10265. this.trace('removeStream', stream.id);
  10266. if(stopStreams) {
  10267. RTC.stopMediaStream(stream);
  10268. }
  10269. try {
  10270. // FF doesn't support this yet.
  10271. if (this.peerconnection.removeStream)
  10272. this.peerconnection.removeStream(stream);
  10273. } catch (e) {
  10274. logger.error(e);
  10275. }
  10276. };
  10277. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10278. this.trace('createDataChannel', label, opts);
  10279. return this.peerconnection.createDataChannel(label, opts);
  10280. };
  10281. TraceablePeerConnection.prototype.setLocalDescription
  10282. = function (description, successCallback, failureCallback) {
  10283. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10284. // if we're running on FF, transform to Plan A first.
  10285. if (RTCBrowserType.usesUnifiedPlan()) {
  10286. description = this.interop.toUnifiedPlan(description);
  10287. this.trace('setLocalDescription::postTransform (Plan A)',
  10288. dumpSDP(description));
  10289. }
  10290. var self = this;
  10291. this.peerconnection.setLocalDescription(description,
  10292. function () {
  10293. self.trace('setLocalDescriptionOnSuccess');
  10294. successCallback();
  10295. },
  10296. function (err) {
  10297. self.trace('setLocalDescriptionOnFailure', err);
  10298. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10299. err, self.peerconnection);
  10300. failureCallback(err);
  10301. }
  10302. );
  10303. };
  10304. TraceablePeerConnection.prototype.setRemoteDescription
  10305. = function (description, successCallback, failureCallback) {
  10306. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10307. // TODO the focus should squeze or explode the remote simulcast
  10308. description = this.simulcast.mungeRemoteDescription(description);
  10309. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10310. // if we're running on FF, transform to Plan A first.
  10311. if (RTCBrowserType.usesUnifiedPlan()) {
  10312. description = this.interop.toUnifiedPlan(description);
  10313. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10314. }
  10315. if (RTCBrowserType.usesPlanB()) {
  10316. description = normalizePlanB(description);
  10317. }
  10318. var self = this;
  10319. this.peerconnection.setRemoteDescription(description,
  10320. function () {
  10321. self.trace('setRemoteDescriptionOnSuccess');
  10322. successCallback();
  10323. },
  10324. function (err) {
  10325. self.trace('setRemoteDescriptionOnFailure', err);
  10326. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10327. err, self.peerconnection);
  10328. failureCallback(err);
  10329. }
  10330. );
  10331. /*
  10332. if (this.statsinterval === null && this.maxstats > 0) {
  10333. // start gathering stats
  10334. }
  10335. */
  10336. };
  10337. TraceablePeerConnection.prototype.close = function () {
  10338. this.trace('stop');
  10339. if (this.statsinterval !== null) {
  10340. window.clearInterval(this.statsinterval);
  10341. this.statsinterval = null;
  10342. }
  10343. this.peerconnection.close();
  10344. };
  10345. TraceablePeerConnection.prototype.createOffer
  10346. = function (successCallback, failureCallback, constraints) {
  10347. var self = this;
  10348. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10349. this.peerconnection.createOffer(
  10350. function (offer) {
  10351. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10352. // NOTE this is not tested because in meet the focus generates the
  10353. // offer.
  10354. // if we're running on FF, transform to Plan B first.
  10355. if (RTCBrowserType.usesUnifiedPlan()) {
  10356. offer = self.interop.toPlanB(offer);
  10357. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10358. }
  10359. if (RTCBrowserType.isChrome())
  10360. {
  10361. offer = insertRecvOnlySSRC(offer);
  10362. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  10363. }
  10364. if (!self.session.room.options.disableSimulcast
  10365. && self.simulcast.isSupported()) {
  10366. offer = self.simulcast.mungeLocalDescription(offer);
  10367. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10368. dumpSDP(offer));
  10369. }
  10370. successCallback(offer);
  10371. },
  10372. function(err) {
  10373. self.trace('createOfferOnFailure', err);
  10374. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10375. self.peerconnection);
  10376. failureCallback(err);
  10377. },
  10378. constraints
  10379. );
  10380. };
  10381. TraceablePeerConnection.prototype.createAnswer
  10382. = function (successCallback, failureCallback, constraints) {
  10383. var self = this;
  10384. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10385. this.peerconnection.createAnswer(
  10386. function (answer) {
  10387. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10388. // if we're running on FF, transform to Plan A first.
  10389. if (RTCBrowserType.usesUnifiedPlan()) {
  10390. answer = self.interop.toPlanB(answer);
  10391. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10392. dumpSDP(answer));
  10393. }
  10394. if (RTCBrowserType.isChrome())
  10395. {
  10396. answer = insertRecvOnlySSRC(answer);
  10397. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  10398. }
  10399. if (!self.session.room.options.disableSimulcast
  10400. && self.simulcast.isSupported()) {
  10401. answer = self.simulcast.mungeLocalDescription(answer);
  10402. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10403. dumpSDP(answer));
  10404. }
  10405. successCallback(answer);
  10406. },
  10407. function(err) {
  10408. self.trace('createAnswerOnFailure', err);
  10409. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10410. self.peerconnection);
  10411. failureCallback(err);
  10412. },
  10413. constraints
  10414. );
  10415. };
  10416. TraceablePeerConnection.prototype.addIceCandidate
  10417. = function (candidate, successCallback, failureCallback) {
  10418. //var self = this;
  10419. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10420. this.peerconnection.addIceCandidate(candidate);
  10421. /* maybe later
  10422. this.peerconnection.addIceCandidate(candidate,
  10423. function () {
  10424. self.trace('addIceCandidateOnSuccess');
  10425. successCallback();
  10426. },
  10427. function (err) {
  10428. self.trace('addIceCandidateOnFailure', err);
  10429. failureCallback(err);
  10430. }
  10431. );
  10432. */
  10433. };
  10434. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10435. // TODO: Is this the correct way to handle Opera, Temasys?
  10436. if (RTCBrowserType.isFirefox()) {
  10437. // ignore for now...
  10438. if(!errback)
  10439. errback = function () {};
  10440. this.peerconnection.getStats(null, callback, errback);
  10441. } else {
  10442. this.peerconnection.getStats(callback);
  10443. }
  10444. };
  10445. module.exports = TraceablePeerConnection;
  10446. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10447. },{"../../service/xmpp/XMPPEvents":137,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":79,"sdp-interop":105,"sdp-simulcast":112,"sdp-transform":115}],36:[function(require,module,exports){
  10448. (function (__filename){
  10449. /* global $, $iq, Promise, Strophe */
  10450. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10451. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10452. var AuthenticationEvents
  10453. = require("../../service/authentication/AuthenticationEvents");
  10454. function createExpBackoffTimer(step) {
  10455. var count = 1;
  10456. return function (reset) {
  10457. // Reset call
  10458. if (reset) {
  10459. count = 1;
  10460. return;
  10461. }
  10462. // Calculate next timeout
  10463. var timeout = Math.pow(2, count - 1);
  10464. count += 1;
  10465. return timeout * step;
  10466. };
  10467. }
  10468. function Moderator(roomName, xmpp, emitter, settings) {
  10469. this.roomName = roomName;
  10470. this.xmppService = xmpp;
  10471. this.getNextTimeout = createExpBackoffTimer(1000);
  10472. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10473. // External authentication stuff
  10474. this.externalAuthEnabled = false;
  10475. this.settings = settings;
  10476. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10477. // it will be enabled automatically if focus detects the component through
  10478. // service discovery.
  10479. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10480. this.xmppService.options.hosts.call_control !== undefined;
  10481. this.eventEmitter = emitter;
  10482. this.connection = this.xmppService.connection;
  10483. this.focusUserJid;
  10484. //FIXME:
  10485. // Message listener that talks to POPUP window
  10486. function listener(event) {
  10487. if (event.data && event.data.sessionId) {
  10488. if (event.origin !== window.location.origin) {
  10489. logger.warn("Ignoring sessionId from different origin: " +
  10490. event.origin);
  10491. return;
  10492. }
  10493. localStorage.setItem('sessionId', event.data.sessionId);
  10494. // After popup is closed we will authenticate
  10495. }
  10496. }
  10497. // Register
  10498. if (window.addEventListener) {
  10499. window.addEventListener("message", listener, false);
  10500. } else {
  10501. window.attachEvent("onmessage", listener);
  10502. }
  10503. }
  10504. Moderator.prototype.isExternalAuthEnabled = function () {
  10505. return this.externalAuthEnabled;
  10506. };
  10507. Moderator.prototype.isSipGatewayEnabled = function () {
  10508. return this.sipGatewayEnabled;
  10509. };
  10510. Moderator.prototype.onMucMemberLeft = function (jid) {
  10511. logger.info("Someone left is it focus ? " + jid);
  10512. var resource = Strophe.getResourceFromJid(jid);
  10513. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10514. logger.info(
  10515. "Focus has left the room - leaving conference");
  10516. //hangUp();
  10517. // We'd rather reload to have everything re-initialized
  10518. //FIXME: show some message before reload
  10519. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10520. }
  10521. };
  10522. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10523. if (!this.focusUserJid) {
  10524. this.focusUserJid = focusJid;
  10525. logger.info("Focus jid set to: " + this.focusUserJid);
  10526. }
  10527. };
  10528. Moderator.prototype.getFocusUserJid = function () {
  10529. return this.focusUserJid;
  10530. };
  10531. Moderator.prototype.getFocusComponent = function () {
  10532. // Get focus component address
  10533. var focusComponent = this.xmppService.options.hosts.focus;
  10534. // If not specified use default: 'focus.domain'
  10535. if (!focusComponent) {
  10536. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10537. }
  10538. return focusComponent;
  10539. };
  10540. Moderator.prototype.createConferenceIq = function () {
  10541. // Generate create conference IQ
  10542. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10543. // Session Id used for authentication
  10544. var sessionId = localStorage.getItem('sessionId');
  10545. var machineUID = this.settings.getSettings().uid;
  10546. logger.info(
  10547. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10548. elem.c('conference', {
  10549. xmlns: 'http://jitsi.org/protocol/focus',
  10550. room: this.roomName,
  10551. 'machine-uid': machineUID
  10552. });
  10553. if (sessionId) {
  10554. elem.attrs({ 'session-id': sessionId});
  10555. }
  10556. if (this.xmppService.options.hosts.bridge !== undefined) {
  10557. elem.c(
  10558. 'property', {
  10559. name: 'bridge',
  10560. value: this.xmppService.options.hosts.bridge
  10561. }).up();
  10562. }
  10563. if (this.xmppService.options.enforcedBridge !== undefined) {
  10564. elem.c(
  10565. 'property', {
  10566. name: 'enforcedBridge',
  10567. value: this.xmppService.options.enforcedBridge
  10568. }).up();
  10569. }
  10570. // Tell the focus we have Jigasi configured
  10571. if (this.xmppService.options.hosts.call_control !== undefined) {
  10572. elem.c(
  10573. 'property', {
  10574. name: 'call_control',
  10575. value: this.xmppService.options.hosts.call_control
  10576. }).up();
  10577. }
  10578. if (this.xmppService.options.channelLastN !== undefined) {
  10579. elem.c(
  10580. 'property', {
  10581. name: 'channelLastN',
  10582. value: this.xmppService.options.channelLastN
  10583. }).up();
  10584. }
  10585. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10586. elem.c(
  10587. 'property', {
  10588. name: 'adaptiveLastN',
  10589. value: this.xmppService.options.adaptiveLastN
  10590. }).up();
  10591. }
  10592. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10593. elem.c(
  10594. 'property', {
  10595. name: 'adaptiveSimulcast',
  10596. value: this.xmppService.options.adaptiveSimulcast
  10597. }).up();
  10598. }
  10599. if (this.xmppService.options.openSctp !== undefined) {
  10600. elem.c(
  10601. 'property', {
  10602. name: 'openSctp',
  10603. value: this.xmppService.options.openSctp
  10604. }).up();
  10605. }
  10606. if (this.xmppService.options.startAudioMuted !== undefined)
  10607. {
  10608. elem.c(
  10609. 'property', {
  10610. name: 'startAudioMuted',
  10611. value: this.xmppService.options.startAudioMuted
  10612. }).up();
  10613. }
  10614. if (this.xmppService.options.startVideoMuted !== undefined)
  10615. {
  10616. elem.c(
  10617. 'property', {
  10618. name: 'startVideoMuted',
  10619. value: this.xmppService.options.startVideoMuted
  10620. }).up();
  10621. }
  10622. elem.c(
  10623. 'property', {
  10624. name: 'simulcastMode',
  10625. value: 'rewriting'
  10626. }).up();
  10627. elem.up();
  10628. return elem;
  10629. };
  10630. Moderator.prototype.parseSessionId = function (resultIq) {
  10631. var sessionId = $(resultIq).find('conference').attr('session-id');
  10632. if (sessionId) {
  10633. logger.info('Received sessionId: ' + sessionId);
  10634. localStorage.setItem('sessionId', sessionId);
  10635. }
  10636. };
  10637. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10638. this.setFocusUserJid(
  10639. $(resultIq).find('conference').attr('focusjid'));
  10640. var authenticationEnabled
  10641. = $(resultIq).find(
  10642. '>conference>property' +
  10643. '[name=\'authentication\'][value=\'true\']').length > 0;
  10644. logger.info("Authentication enabled: " + authenticationEnabled);
  10645. this.externalAuthEnabled = $(resultIq).find(
  10646. '>conference>property' +
  10647. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10648. console.info(
  10649. 'External authentication enabled: ' + this.externalAuthEnabled);
  10650. if (!this.externalAuthEnabled) {
  10651. // We expect to receive sessionId in 'internal' authentication mode
  10652. this.parseSessionId(resultIq);
  10653. }
  10654. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10655. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10656. authenticationEnabled, authIdentity);
  10657. // Check if focus has auto-detected Jigasi component(this will be also
  10658. // included if we have passed our host from the config)
  10659. if ($(resultIq).find(
  10660. '>conference>property' +
  10661. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10662. this.sipGatewayEnabled = true;
  10663. }
  10664. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10665. };
  10666. // FIXME = we need to show the fact that we're waiting for the focus
  10667. // to the user(or that focus is not available)
  10668. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10669. // Try to use focus user JID from the config
  10670. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10671. // Send create conference IQ
  10672. var iq = this.createConferenceIq();
  10673. var self = this;
  10674. this.connection.sendIQ(
  10675. iq,
  10676. function (result) {
  10677. // Setup config options
  10678. self.parseConfigOptions(result);
  10679. if ('true' === $(result).find('conference').attr('ready')) {
  10680. // Reset both timers
  10681. self.getNextTimeout(true);
  10682. self.getNextErrorTimeout(true);
  10683. // Exec callback
  10684. callback();
  10685. } else {
  10686. var waitMs = self.getNextTimeout();
  10687. logger.info("Waiting for the focus... " + waitMs);
  10688. // Reset error timeout
  10689. self.getNextErrorTimeout(true);
  10690. window.setTimeout(
  10691. function () {
  10692. self.allocateConferenceFocus(callback);
  10693. }, waitMs);
  10694. }
  10695. },
  10696. function (error) {
  10697. // Invalid session ? remove and try again
  10698. // without session ID to get a new one
  10699. var invalidSession
  10700. = $(error).find('>error>session-invalid').length;
  10701. if (invalidSession) {
  10702. logger.info("Session expired! - removing");
  10703. localStorage.removeItem("sessionId");
  10704. }
  10705. if ($(error).find('>error>graceful-shutdown').length) {
  10706. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10707. return;
  10708. }
  10709. // Check for error returned by the reservation system
  10710. var reservationErr = $(error).find('>error>reservation-error');
  10711. if (reservationErr.length) {
  10712. // Trigger error event
  10713. var errorCode = reservationErr.attr('error-code');
  10714. var errorMsg;
  10715. if ($(error).find('>error>text')) {
  10716. errorMsg = $(error).find('>error>text').text();
  10717. }
  10718. self.eventEmitter.emit(
  10719. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10720. return;
  10721. }
  10722. // Not authorized to create new room
  10723. if ($(error).find('>error>not-authorized').length) {
  10724. logger.warn("Unauthorized to start the conference", error);
  10725. var toDomain
  10726. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10727. if (toDomain !==
  10728. this.xmppService.options.hosts.anonymousdomain) {
  10729. //FIXME: "is external" should come either from
  10730. // the focus or config.js
  10731. self.externalAuthEnabled = true;
  10732. }
  10733. self.eventEmitter.emit(
  10734. XMPPEvents.AUTHENTICATION_REQUIRED,
  10735. function () {
  10736. self.allocateConferenceFocus(
  10737. callback);
  10738. });
  10739. return;
  10740. }
  10741. var waitMs = self.getNextErrorTimeout();
  10742. logger.error("Focus error, retry after " + waitMs, error);
  10743. // Show message
  10744. var focusComponent = self.getFocusComponent();
  10745. var retrySec = waitMs / 1000;
  10746. //FIXME: message is duplicated ?
  10747. // Do not show in case of session invalid
  10748. // which means just a retry
  10749. if (!invalidSession) {
  10750. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10751. focusComponent, retrySec);
  10752. }
  10753. // Reset response timeout
  10754. self.getNextTimeout(true);
  10755. window.setTimeout(
  10756. function () {
  10757. self.allocateConferenceFocus(callback);
  10758. }, waitMs);
  10759. }
  10760. );
  10761. };
  10762. Moderator.prototype.authenticate = function () {
  10763. var self = this;
  10764. return new Promise(function (resolve, reject) {
  10765. self.connection.sendIQ(
  10766. self.createConferenceIq(),
  10767. function (result) {
  10768. self.parseSessionId(result);
  10769. resolve();
  10770. }, function (error) {
  10771. var code = $(error).find('>error').attr('code');
  10772. reject(error, code);
  10773. }
  10774. );
  10775. });
  10776. };
  10777. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10778. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10779. iq.c('login-url', {
  10780. xmlns: 'http://jitsi.org/protocol/focus',
  10781. room: this.roomName,
  10782. 'machine-uid': this.settings.getSettings().uid
  10783. });
  10784. this.connection.sendIQ(
  10785. iq,
  10786. function (result) {
  10787. var url = $(result).find('login-url').attr('url');
  10788. url = url = decodeURIComponent(url);
  10789. if (url) {
  10790. logger.info("Got auth url: " + url);
  10791. urlCallback(url);
  10792. } else {
  10793. logger.error(
  10794. "Failed to get auth url from the focus", result);
  10795. failureCallback(result);
  10796. }
  10797. },
  10798. function (error) {
  10799. logger.error("Get auth url error", error);
  10800. failureCallback(error);
  10801. }
  10802. );
  10803. };
  10804. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10805. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10806. iq.c('login-url', {
  10807. xmlns: 'http://jitsi.org/protocol/focus',
  10808. room: this.roomName,
  10809. 'machine-uid': this.settings.getSettings().uid,
  10810. popup: true
  10811. });
  10812. this.connection.sendIQ(
  10813. iq,
  10814. function (result) {
  10815. var url = $(result).find('login-url').attr('url');
  10816. url = url = decodeURIComponent(url);
  10817. if (url) {
  10818. logger.info("Got POPUP auth url: " + url);
  10819. urlCallback(url);
  10820. } else {
  10821. logger.error(
  10822. "Failed to get POPUP auth url from the focus", result);
  10823. failureCallback(result);
  10824. }
  10825. },
  10826. function (error) {
  10827. logger.error('Get POPUP auth url error', error);
  10828. failureCallback(error);
  10829. }
  10830. );
  10831. };
  10832. Moderator.prototype.logout = function (callback) {
  10833. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10834. var sessionId = localStorage.getItem('sessionId');
  10835. if (!sessionId) {
  10836. callback();
  10837. return;
  10838. }
  10839. iq.c('logout', {
  10840. xmlns: 'http://jitsi.org/protocol/focus',
  10841. 'session-id': sessionId
  10842. });
  10843. this.connection.sendIQ(
  10844. iq,
  10845. function (result) {
  10846. var logoutUrl = $(result).find('logout').attr('logout-url');
  10847. if (logoutUrl) {
  10848. logoutUrl = decodeURIComponent(logoutUrl);
  10849. }
  10850. logger.info("Log out OK, url: " + logoutUrl, result);
  10851. localStorage.removeItem('sessionId');
  10852. callback(logoutUrl);
  10853. },
  10854. function (error) {
  10855. logger.error("Logout error", error);
  10856. }
  10857. );
  10858. };
  10859. module.exports = Moderator;
  10860. }).call(this,"/modules/xmpp/moderator.js")
  10861. },{"../../service/authentication/AuthenticationEvents":133,"../../service/xmpp/XMPPEvents":137,"jitsi-meet-logger":79}],37:[function(require,module,exports){
  10862. (function (__filename){
  10863. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10864. Toolbar, Util, Promise */
  10865. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10866. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10867. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10868. roomjid) {
  10869. this.eventEmitter = eventEmitter;
  10870. this.connection = connection;
  10871. this.state = "off";
  10872. this.focusMucJid = focusMucJid;
  10873. this.jirecon = jirecon;
  10874. this.url = null;
  10875. this.type = type;
  10876. this._isSupported = ((type === Recording.types.JIBRI)
  10877. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10878. /**
  10879. * The ID of the jirecon recording session. Jirecon generates it when we
  10880. * initially start recording, and it needs to be used in subsequent requests
  10881. * to jirecon.
  10882. */
  10883. this.jireconRid = null;
  10884. this.roomjid = roomjid;
  10885. }
  10886. Recording.types = {
  10887. COLIBRI: "colibri",
  10888. JIRECON: "jirecon",
  10889. JIBRI: "jibri"
  10890. };
  10891. Recording.prototype.handleJibriPresence = function (jibri) {
  10892. var attributes = jibri.attributes;
  10893. if(!attributes)
  10894. return;
  10895. this._isSupported =
  10896. (attributes.status && attributes.status !== "undefined");
  10897. if(this._isSupported) {
  10898. this.url = attributes.url || null;
  10899. this.state = attributes.status || "off";
  10900. }
  10901. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  10902. };
  10903. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  10904. options) {
  10905. if (state == this.state){
  10906. errCallback(new Error("Invalid state!"));
  10907. }
  10908. options = options || {};
  10909. // FIXME jibri does not accept IQ without 'url' attribute set ?
  10910. var iq = $iq({to: this.focusMucJid, type: 'set'})
  10911. .c('jibri', {
  10912. "xmlns": 'http://jitsi.org/protocol/jibri',
  10913. "action": (state === 'on') ? 'start' : 'stop',
  10914. "streamid": options.streamId,
  10915. "follow-entity": options.followEntity
  10916. }).up();
  10917. logger.log('Set jibri recording: '+state, iq.nodeTree);
  10918. console.log(iq.nodeTree);
  10919. this.connection.sendIQ(
  10920. iq,
  10921. function (result) {
  10922. callback($(result).find('jibri').attr('state'),
  10923. $(result).find('jibri').attr('url'));
  10924. },
  10925. function (error) {
  10926. logger.log('Failed to start recording, error: ', error);
  10927. errCallback(error);
  10928. });
  10929. };
  10930. Recording.prototype.setRecordingJirecon =
  10931. function (state, callback, errCallback, options) {
  10932. if (state == this.state){
  10933. errCallback(new Error("Invalid state!"));
  10934. }
  10935. var iq = $iq({to: this.jirecon, type: 'set'})
  10936. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  10937. action: (state === 'on') ? 'start' : 'stop',
  10938. mucjid: this.roomjid});
  10939. if (state === 'off'){
  10940. iq.attrs({rid: this.jireconRid});
  10941. }
  10942. console.log('Start recording');
  10943. var self = this;
  10944. this.connection.sendIQ(
  10945. iq,
  10946. function (result) {
  10947. // TODO wait for an IQ with the real status, since this is
  10948. // provisional?
  10949. self.jireconRid = $(result).find('recording').attr('rid');
  10950. console.log('Recording ' +
  10951. ((state === 'on') ? 'started' : 'stopped') +
  10952. '(jirecon)' + result);
  10953. self.state = state;
  10954. if (state === 'off'){
  10955. self.jireconRid = null;
  10956. }
  10957. callback(state);
  10958. },
  10959. function (error) {
  10960. console.log('Failed to start recording, error: ', error);
  10961. errCallback(error);
  10962. });
  10963. };
  10964. // Sends a COLIBRI message which enables or disables (according to 'state')
  10965. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  10966. // with the new recording state, according to the IQ.
  10967. Recording.prototype.setRecordingColibri =
  10968. function (state, callback, errCallback, options) {
  10969. var elem = $iq({to: this.focusMucJid, type: 'set'});
  10970. elem.c('conference', {
  10971. xmlns: 'http://jitsi.org/protocol/colibri'
  10972. });
  10973. elem.c('recording', {state: state, token: options.token});
  10974. var self = this;
  10975. this.connection.sendIQ(elem,
  10976. function (result) {
  10977. console.log('Set recording "', state, '". Result:', result);
  10978. var recordingElem = $(result).find('>conference>recording');
  10979. var newState = recordingElem.attr('state');
  10980. self.state = newState;
  10981. callback(newState);
  10982. if (newState === 'pending') {
  10983. self.connection.addHandler(function(iq){
  10984. var state = $(iq).find('recording').attr('state');
  10985. if (state) {
  10986. self.state = newState;
  10987. callback(state);
  10988. }
  10989. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  10990. }
  10991. },
  10992. function (error) {
  10993. console.warn(error);
  10994. errCallback(error);
  10995. }
  10996. );
  10997. };
  10998. Recording.prototype.setRecording =
  10999. function (state, callback, errCallback, options) {
  11000. switch(this.type){
  11001. case Recording.types.JIRECON:
  11002. this.setRecordingJirecon(state, callback, errCallback, options);
  11003. break;
  11004. case Recording.types.COLIBRI:
  11005. this.setRecordingColibri(state, callback, errCallback, options);
  11006. break;
  11007. case Recording.types.JIBRI:
  11008. this.setRecordingJibri(state, callback, errCallback, options);
  11009. break;
  11010. default:
  11011. console.error("Unknown recording type!");
  11012. return;
  11013. }
  11014. };
  11015. /**
  11016. *Starts/stops the recording
  11017. * @param token token for authentication
  11018. * @param statusChangeHandler {function} receives the new status as argument.
  11019. */
  11020. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  11021. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  11022. (!options.streamId && this.type === Recording.types.JIBRI)){
  11023. statusChangeHandler("error", new Error("No token passed!"));
  11024. logger.error("No token passed!");
  11025. return;
  11026. }
  11027. var oldState = this.state;
  11028. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  11029. var self = this;
  11030. this.setRecording(newState,
  11031. function (state, url) {
  11032. logger.log("New recording state: ", state);
  11033. if (state && state !== oldState) {
  11034. self.state = state;
  11035. self.url = url;
  11036. statusChangeHandler(state);
  11037. } else {
  11038. statusChangeHandler("error", new Error("Status not changed!"));
  11039. }
  11040. }, function (error) {
  11041. statusChangeHandler("error", error);
  11042. }, options);
  11043. };
  11044. /**
  11045. * Returns true if the recording is supproted and false if not.
  11046. */
  11047. Recording.prototype.isSupported = function () {
  11048. return this._isSupported;
  11049. };
  11050. /**
  11051. * Returns null if the recording is not supported, "on" if the recording started
  11052. * and "off" if the recording is not started.
  11053. */
  11054. Recording.prototype.getState = function () {
  11055. return this.state;
  11056. };
  11057. /**
  11058. * Returns the url of the recorded video.
  11059. */
  11060. Recording.prototype.getURL = function () {
  11061. return this.url;
  11062. };
  11063. module.exports = Recording;
  11064. }).call(this,"/modules/xmpp/recording.js")
  11065. },{"../../service/xmpp/XMPPEvents":137,"jitsi-meet-logger":79}],38:[function(require,module,exports){
  11066. (function (__filename){
  11067. /* jshint -W117 */
  11068. /* a simple MUC connection plugin
  11069. * can only handle a single MUC room
  11070. */
  11071. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11072. var ChatRoom = require("./ChatRoom");
  11073. module.exports = function(XMPP) {
  11074. Strophe.addConnectionPlugin('emuc', {
  11075. connection: null,
  11076. rooms: {},//map with the rooms
  11077. init: function (conn) {
  11078. this.connection = conn;
  11079. // add handlers (just once)
  11080. this.connection.addHandler(this.onPresence.bind(this), null,
  11081. 'presence', null, null, null, null);
  11082. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11083. null, 'presence', 'unavailable', null);
  11084. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11085. 'presence', 'error', null);
  11086. this.connection.addHandler(this.onMessage.bind(this), null,
  11087. 'message', null, null);
  11088. this.connection.addHandler(this.onMute.bind(this),
  11089. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11090. },
  11091. createRoom: function (jid, password, options, settings) {
  11092. var roomJid = Strophe.getBareJidFromJid(jid);
  11093. if (this.rooms[roomJid]) {
  11094. logger.error("You are already in the room!");
  11095. return;
  11096. }
  11097. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11098. password, XMPP, options, settings);
  11099. return this.rooms[roomJid];
  11100. },
  11101. doLeave: function (jid) {
  11102. this.rooms[jid].doLeave();
  11103. delete this.rooms[jid];
  11104. },
  11105. onPresence: function (pres) {
  11106. var from = pres.getAttribute('from');
  11107. // What is this for? A workaround for something?
  11108. if (pres.getAttribute('type')) {
  11109. return true;
  11110. }
  11111. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11112. if(!room)
  11113. return;
  11114. // Parse status.
  11115. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11116. room.createNonAnonymousRoom();
  11117. }
  11118. room.onPresence(pres);
  11119. return true;
  11120. },
  11121. onPresenceUnavailable: function (pres) {
  11122. var from = pres.getAttribute('from');
  11123. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11124. if(!room)
  11125. return;
  11126. room.onPresenceUnavailable(pres, from);
  11127. return true;
  11128. },
  11129. onPresenceError: function (pres) {
  11130. var from = pres.getAttribute('from');
  11131. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11132. if(!room)
  11133. return;
  11134. room.onPresenceError(pres, from);
  11135. return true;
  11136. },
  11137. onMessage: function (msg) {
  11138. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11139. var from = msg.getAttribute('from');
  11140. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11141. if(!room)
  11142. return;
  11143. room.onMessage(msg, from);
  11144. return true;
  11145. },
  11146. setJingleSession: function (from, session) {
  11147. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11148. if(!room)
  11149. return;
  11150. room.setJingleSession(session);
  11151. },
  11152. onMute: function(iq) {
  11153. var from = iq.getAttribute('from');
  11154. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11155. if(!room)
  11156. return;
  11157. room.onMute(iq);
  11158. return true;
  11159. }
  11160. });
  11161. };
  11162. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11163. },{"./ChatRoom":29,"jitsi-meet-logger":79}],39:[function(require,module,exports){
  11164. (function (__filename){
  11165. /* jshint -W117 */
  11166. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11167. var JingleSession = require("./JingleSessionPC");
  11168. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11169. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11170. module.exports = function(XMPP, eventEmitter) {
  11171. Strophe.addConnectionPlugin('jingle', {
  11172. connection: null,
  11173. sessions: {},
  11174. jid2session: {},
  11175. ice_config: {iceServers: []},
  11176. media_constraints: {
  11177. mandatory: {
  11178. 'OfferToReceiveAudio': true,
  11179. 'OfferToReceiveVideo': true
  11180. }
  11181. // MozDontOfferDataChannel: true when this is firefox
  11182. },
  11183. init: function (conn) {
  11184. this.connection = conn;
  11185. if (this.connection.disco) {
  11186. // http://xmpp.org/extensions/xep-0167.html#support
  11187. // http://xmpp.org/extensions/xep-0176.html#support
  11188. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11189. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11190. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11191. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11192. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11193. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11194. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11195. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11196. || RTCBrowserType.isTemasysPluginUsed()) {
  11197. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11198. }
  11199. // this is dealt with by SDP O/A so we don't need to announce this
  11200. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11201. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11202. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11203. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11204. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11205. }
  11206. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11207. },
  11208. onJingle: function (iq) {
  11209. var sid = $(iq).find('jingle').attr('sid');
  11210. var action = $(iq).find('jingle').attr('action');
  11211. var fromJid = iq.getAttribute('from');
  11212. // send ack first
  11213. var ack = $iq({type: 'result',
  11214. to: fromJid,
  11215. id: iq.getAttribute('id')
  11216. });
  11217. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11218. var sess = this.sessions[sid];
  11219. if ('session-initiate' != action) {
  11220. if (sess === null) {
  11221. ack.type = 'error';
  11222. ack.c('error', {type: 'cancel'})
  11223. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11224. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11225. this.connection.send(ack);
  11226. return true;
  11227. }
  11228. // local jid is not checked
  11229. if (fromJid != sess.peerjid) {
  11230. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11231. ack.type = 'error';
  11232. ack.c('error', {type: 'cancel'})
  11233. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11234. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11235. this.connection.send(ack);
  11236. return true;
  11237. }
  11238. } else if (sess !== undefined) {
  11239. // existing session with same session id
  11240. // this might be out-of-order if the sess.peerjid is the same as from
  11241. ack.type = 'error';
  11242. ack.c('error', {type: 'cancel'})
  11243. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11244. logger.warn('duplicate session id', sid);
  11245. this.connection.send(ack);
  11246. return true;
  11247. }
  11248. // FIXME: check for a defined action
  11249. this.connection.send(ack);
  11250. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11251. switch (action) {
  11252. case 'session-initiate':
  11253. console.log("(TIME) received session-initiate:\t",
  11254. window.performance.now());
  11255. var startMuted = $(iq).find('jingle>startmuted');
  11256. if (startMuted && startMuted.length > 0) {
  11257. var audioMuted = startMuted.attr("audio");
  11258. var videoMuted = startMuted.attr("video");
  11259. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11260. audioMuted === "true", videoMuted === "true");
  11261. }
  11262. sess = new JingleSession(
  11263. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11264. this.connection, XMPP);
  11265. // configure session
  11266. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11267. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11268. sess.media_constraints = this.media_constraints;
  11269. sess.ice_config = this.ice_config;
  11270. sess.initialize(fromJid, false);
  11271. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11272. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11273. sess.setOffer($(iq).find('>jingle'));
  11274. this.sessions[sess.sid] = sess;
  11275. this.jid2session[sess.peerjid] = sess;
  11276. // the callback should either
  11277. // .sendAnswer and .accept
  11278. // or .sendTerminate -- not necessarily synchronous
  11279. sess.sendAnswer();
  11280. sess.accept();
  11281. break;
  11282. case 'session-accept':
  11283. sess.setAnswer($(iq).find('>jingle'));
  11284. sess.accept();
  11285. break;
  11286. case 'session-terminate':
  11287. // If this is not the focus sending the terminate, we have
  11288. // nothing more to do here.
  11289. if (Object.keys(this.sessions).length < 1
  11290. || !(this.sessions[Object.keys(this.sessions)[0]]
  11291. instanceof JingleSession))
  11292. {
  11293. break;
  11294. }
  11295. logger.log('terminating...', sess.sid);
  11296. sess.terminate();
  11297. this.terminate(sess.sid);
  11298. if ($(iq).find('>jingle>reason').length) {
  11299. $(document).trigger('callterminated.jingle', [
  11300. sess.sid,
  11301. sess.peerjid,
  11302. $(iq).find('>jingle>reason>:first')[0].tagName,
  11303. $(iq).find('>jingle>reason>text').text()
  11304. ]);
  11305. } else {
  11306. $(document).trigger('callterminated.jingle',
  11307. [sess.sid, sess.peerjid]);
  11308. }
  11309. break;
  11310. case 'transport-info':
  11311. sess.addIceCandidate($(iq).find('>jingle>content'));
  11312. break;
  11313. case 'session-info':
  11314. var affected;
  11315. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11316. $(document).trigger('ringing.jingle', [sess.sid]);
  11317. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11318. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11319. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11320. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11321. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11322. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11323. }
  11324. break;
  11325. case 'addsource': // FIXME: proprietary, un-jingleish
  11326. case 'source-add': // FIXME: proprietary
  11327. sess.addSource($(iq).find('>jingle>content'));
  11328. break;
  11329. case 'removesource': // FIXME: proprietary, un-jingleish
  11330. case 'source-remove': // FIXME: proprietary
  11331. sess.removeSource($(iq).find('>jingle>content'));
  11332. break;
  11333. default:
  11334. logger.warn('jingle action not implemented', action);
  11335. break;
  11336. }
  11337. return true;
  11338. },
  11339. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11340. if (sid === null || sid === undefined) {
  11341. for (sid in this.sessions) {
  11342. if (this.sessions[sid].state != 'ended') {
  11343. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11344. this.sessions[sid].terminate();
  11345. }
  11346. delete this.jid2session[this.sessions[sid].peerjid];
  11347. delete this.sessions[sid];
  11348. }
  11349. } else if (this.sessions.hasOwnProperty(sid)) {
  11350. if (this.sessions[sid].state != 'ended') {
  11351. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11352. this.sessions[sid].terminate();
  11353. }
  11354. delete this.jid2session[this.sessions[sid].peerjid];
  11355. delete this.sessions[sid];
  11356. }
  11357. },
  11358. getStunAndTurnCredentials: function () {
  11359. // get stun and turn configuration from server via xep-0215
  11360. // uses time-limited credentials as described in
  11361. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11362. //
  11363. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11364. // for a prosody module which implements this
  11365. //
  11366. // currently, this doesn't work with updateIce and therefore credentials with a long
  11367. // validity have to be fetched before creating the peerconnection
  11368. // TODO: implement refresh via updateIce as described in
  11369. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11370. var self = this;
  11371. this.connection.sendIQ(
  11372. $iq({type: 'get', to: this.connection.domain})
  11373. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11374. function (res) {
  11375. var iceservers = [];
  11376. $(res).find('>services>service').each(function (idx, el) {
  11377. el = $(el);
  11378. var dict = {};
  11379. var type = el.attr('type');
  11380. switch (type) {
  11381. case 'stun':
  11382. dict.url = 'stun:' + el.attr('host');
  11383. if (el.attr('port')) {
  11384. dict.url += ':' + el.attr('port');
  11385. }
  11386. iceservers.push(dict);
  11387. break;
  11388. case 'turn':
  11389. case 'turns':
  11390. dict.url = type + ':';
  11391. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11392. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11393. dict.url += el.attr('username') + '@';
  11394. } else {
  11395. dict.username = el.attr('username'); // only works in M28
  11396. }
  11397. }
  11398. dict.url += el.attr('host');
  11399. if (el.attr('port') && el.attr('port') != '3478') {
  11400. dict.url += ':' + el.attr('port');
  11401. }
  11402. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11403. dict.url += '?transport=' + el.attr('transport');
  11404. }
  11405. if (el.attr('password')) {
  11406. dict.credential = el.attr('password');
  11407. }
  11408. iceservers.push(dict);
  11409. break;
  11410. }
  11411. });
  11412. self.ice_config.iceServers = iceservers;
  11413. },
  11414. function (err) {
  11415. logger.warn('getting turn credentials failed', err);
  11416. logger.warn('is mod_turncredentials or similar installed?');
  11417. }
  11418. );
  11419. // implement push?
  11420. },
  11421. /**
  11422. * Returns the data saved in 'updateLog' in a format to be logged.
  11423. */
  11424. getLog: function () {
  11425. var data = {};
  11426. var self = this;
  11427. Object.keys(this.sessions).forEach(function (sid) {
  11428. var session = self.sessions[sid];
  11429. if (session.peerconnection && session.peerconnection.updateLog) {
  11430. // FIXME: should probably be a .dump call
  11431. data["jingle_" + session.sid] = {
  11432. updateLog: session.peerconnection.updateLog,
  11433. stats: session.peerconnection.stats,
  11434. url: window.location.href
  11435. };
  11436. }
  11437. });
  11438. return data;
  11439. }
  11440. });
  11441. };
  11442. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11443. },{"../../service/xmpp/XMPPEvents":137,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":79}],40:[function(require,module,exports){
  11444. /* global Strophe */
  11445. module.exports = function () {
  11446. Strophe.addConnectionPlugin('logger', {
  11447. // logs raw stanzas and makes them available for download as JSON
  11448. connection: null,
  11449. log: [],
  11450. init: function (conn) {
  11451. this.connection = conn;
  11452. this.connection.rawInput = this.log_incoming.bind(this);
  11453. this.connection.rawOutput = this.log_outgoing.bind(this);
  11454. },
  11455. log_incoming: function (stanza) {
  11456. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11457. },
  11458. log_outgoing: function (stanza) {
  11459. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11460. }
  11461. });
  11462. };
  11463. },{}],41:[function(require,module,exports){
  11464. (function (__filename){
  11465. /* global $, $iq, Strophe */
  11466. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11467. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11468. /**
  11469. * Ping every 10 sec
  11470. */
  11471. var PING_INTERVAL = 10000;
  11472. /**
  11473. * Ping timeout error after 15 sec of waiting.
  11474. */
  11475. var PING_TIMEOUT = 15000;
  11476. /**
  11477. * Will close the connection after 3 consecutive ping errors.
  11478. */
  11479. var PING_THRESHOLD = 3;
  11480. /**
  11481. * XEP-0199 ping plugin.
  11482. *
  11483. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11484. */
  11485. module.exports = function (XMPP, eventEmitter) {
  11486. Strophe.addConnectionPlugin('ping', {
  11487. connection: null,
  11488. failedPings: 0,
  11489. /**
  11490. * Initializes the plugin. Method called by Strophe.
  11491. * @param connection Strophe connection instance.
  11492. */
  11493. init: function (connection) {
  11494. this.connection = connection;
  11495. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11496. },
  11497. /**
  11498. * Sends "ping" to given <tt>jid</tt>
  11499. * @param jid the JID to which ping request will be sent.
  11500. * @param success callback called on success.
  11501. * @param error callback called on error.
  11502. * @param timeout ms how long are we going to wait for the response. On
  11503. * timeout <tt>error<//t> callback is called with undefined error
  11504. * argument.
  11505. */
  11506. ping: function (jid, success, error, timeout) {
  11507. var iq = $iq({type: 'get', to: jid});
  11508. iq.c('ping', {xmlns: Strophe.NS.PING});
  11509. this.connection.sendIQ(iq, success, error, timeout);
  11510. },
  11511. /**
  11512. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11513. * @param jid the JID to be checked for ping support.
  11514. * @param callback function with boolean argument which will be
  11515. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11516. */
  11517. hasPingSupport: function (jid, callback) {
  11518. this.connection.disco.info(
  11519. jid, null,
  11520. function (result) {
  11521. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11522. callback(ping.length > 0);
  11523. },
  11524. function (error) {
  11525. logger.error("Ping feature discovery error", error);
  11526. callback(false);
  11527. }
  11528. );
  11529. },
  11530. /**
  11531. * Starts to send ping in given interval to specified remote JID.
  11532. * This plugin supports only one such task and <tt>stopInterval</tt>
  11533. * must be called before starting a new one.
  11534. * @param remoteJid remote JID to which ping requests will be sent to.
  11535. * @param interval task interval in ms.
  11536. */
  11537. startInterval: function (remoteJid, interval) {
  11538. if (this.intervalId) {
  11539. logger.error("Ping task scheduled already");
  11540. return;
  11541. }
  11542. if (!interval)
  11543. interval = PING_INTERVAL;
  11544. var self = this;
  11545. this.intervalId = window.setInterval(function () {
  11546. self.ping(remoteJid,
  11547. function (result) {
  11548. // Ping OK
  11549. self.failedPings = 0;
  11550. },
  11551. function (error) {
  11552. self.failedPings += 1;
  11553. logger.error(
  11554. "Ping " + (error ? "error" : "timeout"), error);
  11555. if (self.failedPings >= PING_THRESHOLD) {
  11556. self.connection.disconnect();
  11557. }
  11558. }, PING_TIMEOUT);
  11559. }, interval);
  11560. logger.info("XMPP pings will be sent every " + interval + " ms");
  11561. },
  11562. /**
  11563. * Stops current "ping" interval task.
  11564. */
  11565. stopInterval: function () {
  11566. if (this.intervalId) {
  11567. window.clearInterval(this.intervalId);
  11568. this.intervalId = null;
  11569. this.failedPings = 0;
  11570. logger.info("Ping interval cleared");
  11571. }
  11572. }
  11573. });
  11574. };
  11575. }).call(this,"/modules/xmpp/strophe.ping.js")
  11576. },{"../../service/xmpp/XMPPEvents":137,"jitsi-meet-logger":79}],42:[function(require,module,exports){
  11577. (function (__filename){
  11578. /* jshint -W117 */
  11579. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11580. module.exports = function() {
  11581. Strophe.addConnectionPlugin('rayo',
  11582. {
  11583. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11584. connection: null,
  11585. init: function (conn) {
  11586. this.connection = conn;
  11587. if (this.connection.disco) {
  11588. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11589. }
  11590. this.connection.addHandler(
  11591. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11592. null, null);
  11593. },
  11594. onRayo: function (iq) {
  11595. logger.info("Rayo IQ", iq);
  11596. },
  11597. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11598. var self = this;
  11599. return new Promise(function (resolve, reject) {
  11600. if(!focusMucJid) {
  11601. reject(new Error("Internal error!"));
  11602. return;
  11603. }
  11604. var req = $iq(
  11605. {
  11606. type: 'set',
  11607. to: focusMucJid
  11608. }
  11609. );
  11610. req.c('dial',
  11611. {
  11612. xmlns: self.RAYO_XMLNS,
  11613. to: to,
  11614. from: from
  11615. });
  11616. req.c('header',
  11617. {
  11618. name: 'JvbRoomName',
  11619. value: roomName
  11620. }).up();
  11621. if (roomPass !== null && roomPass.length) {
  11622. req.c('header',
  11623. {
  11624. name: 'JvbRoomPassword',
  11625. value: roomPass
  11626. }).up();
  11627. }
  11628. self.connection.sendIQ(
  11629. req,
  11630. function (result) {
  11631. logger.info('Dial result ', result);
  11632. var resource = $(result).find('ref').attr('uri');
  11633. self.call_resource =
  11634. resource.substr('xmpp:'.length);
  11635. logger.info(
  11636. "Received call resource: " +
  11637. self.call_resource);
  11638. resolve();
  11639. },
  11640. function (error) {
  11641. logger.info('Dial error ', error);
  11642. reject(error);
  11643. }
  11644. );
  11645. });
  11646. },
  11647. hangup: function () {
  11648. var self = this;
  11649. return new Promise(function (resolve, reject) {
  11650. if (!self.call_resource) {
  11651. reject(new Error("No call in progress"));
  11652. logger.warn("No call in progress");
  11653. return;
  11654. }
  11655. var req = $iq(
  11656. {
  11657. type: 'set',
  11658. to: self.call_resource
  11659. }
  11660. );
  11661. req.c('hangup',
  11662. {
  11663. xmlns: self.RAYO_XMLNS
  11664. });
  11665. self.connection.sendIQ(
  11666. req,
  11667. function (result) {
  11668. logger.info('Hangup result ', result);
  11669. self.call_resource = null;
  11670. resolve();
  11671. },
  11672. function (error) {
  11673. logger.info('Hangup error ', error);
  11674. self.call_resource = null;
  11675. reject(new Error('Hangup error '));
  11676. }
  11677. );
  11678. });
  11679. }
  11680. }
  11681. );
  11682. };
  11683. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11684. },{"jitsi-meet-logger":79}],43:[function(require,module,exports){
  11685. (function (__filename){
  11686. /* global Strophe */
  11687. /**
  11688. * Strophe logger implementation. Logs from level WARN and above.
  11689. */
  11690. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11691. module.exports = function () {
  11692. Strophe.log = function (level, msg) {
  11693. switch (level) {
  11694. case Strophe.LogLevel.WARN:
  11695. logger.warn("Strophe: " + msg);
  11696. break;
  11697. case Strophe.LogLevel.ERROR:
  11698. case Strophe.LogLevel.FATAL:
  11699. logger.error("Strophe: " + msg);
  11700. break;
  11701. }
  11702. };
  11703. Strophe.getStatusString = function (status) {
  11704. switch (status) {
  11705. case Strophe.Status.ERROR:
  11706. return "ERROR";
  11707. case Strophe.Status.CONNECTING:
  11708. return "CONNECTING";
  11709. case Strophe.Status.CONNFAIL:
  11710. return "CONNFAIL";
  11711. case Strophe.Status.AUTHENTICATING:
  11712. return "AUTHENTICATING";
  11713. case Strophe.Status.AUTHFAIL:
  11714. return "AUTHFAIL";
  11715. case Strophe.Status.CONNECTED:
  11716. return "CONNECTED";
  11717. case Strophe.Status.DISCONNECTED:
  11718. return "DISCONNECTED";
  11719. case Strophe.Status.DISCONNECTING:
  11720. return "DISCONNECTING";
  11721. case Strophe.Status.ATTACHED:
  11722. return "ATTACHED";
  11723. default:
  11724. return "unknown";
  11725. }
  11726. };
  11727. };
  11728. }).call(this,"/modules/xmpp/strophe.util.js")
  11729. },{"jitsi-meet-logger":79}],44:[function(require,module,exports){
  11730. (function (__filename){
  11731. /* global $, APP, config, Strophe*/
  11732. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11733. var EventEmitter = require("events");
  11734. var Pako = require("pako");
  11735. var RTCEvents = require("../../service/RTC/RTCEvents");
  11736. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11737. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11738. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11739. var RTC = require("../RTC/RTC");
  11740. var authenticatedUser = false;
  11741. function createConnection(bosh) {
  11742. bosh = bosh || '/http-bind';
  11743. // Append token as URL param
  11744. if (this.token) {
  11745. bosh += bosh.indexOf('?') == -1 ?
  11746. '?token=' + this.token : '&token=' + this.token;
  11747. }
  11748. return new Strophe.Connection(bosh);
  11749. };
  11750. //!!!!!!!!!! FIXME: ...
  11751. function initStrophePlugins(XMPP)
  11752. {
  11753. require("./strophe.emuc")(XMPP);
  11754. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11755. // require("./strophe.moderate")(XMPP, eventEmitter);
  11756. require("./strophe.util")();
  11757. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11758. require("./strophe.rayo")();
  11759. require("./strophe.logger")();
  11760. }
  11761. //!!!!!!!!!! FIXME: ...
  11762. ///**
  11763. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11764. // * video type in MUC presence.
  11765. // * @param localStream new or modified <tt>LocalStream</tt>.
  11766. // */
  11767. //function broadcastLocalVideoType(localStream) {
  11768. // if (localStream.videoType)
  11769. // XMPP.addToPresence('videoType', localStream.videoType);
  11770. //}
  11771. //
  11772. //function registerListeners() {
  11773. // RTC.addStreamListener(
  11774. // broadcastLocalVideoType,
  11775. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11776. // );
  11777. // RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  11778. // XMPP.addToPresence("devices", devices);
  11779. // });
  11780. //}
  11781. function XMPP(options) {
  11782. this.eventEmitter = new EventEmitter();
  11783. this.connection = null;
  11784. this.disconnectInProgress = false;
  11785. this.forceMuted = false;
  11786. this.options = options;
  11787. initStrophePlugins(this);
  11788. // registerListeners();
  11789. this.connection = createConnection(options.bosh);
  11790. }
  11791. XMPP.prototype.getConnection = function(){ return connection; };
  11792. XMPP.prototype._connect = function (jid, password) {
  11793. var self = this;
  11794. // connection.connect() starts the connection process.
  11795. //
  11796. // As the connection process proceeds, the user supplied callback will
  11797. // be triggered multiple times with status updates. The callback should
  11798. // take two arguments - the status code and the error condition.
  11799. //
  11800. // The status code will be one of the values in the Strophe.Status
  11801. // constants. The error condition will be one of the conditions defined
  11802. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11803. //
  11804. // The Parameters wait, hold and route are optional and only relevant
  11805. // for BOSH connections. Please see XEP 124 for a more detailed
  11806. // explanation of the optional parameters.
  11807. //
  11808. // Connection status constants for use by the connection handler
  11809. // callback.
  11810. //
  11811. // Status.ERROR - An error has occurred (websockets specific)
  11812. // Status.CONNECTING - The connection is currently being made
  11813. // Status.CONNFAIL - The connection attempt failed
  11814. // Status.AUTHENTICATING - The connection is authenticating
  11815. // Status.AUTHFAIL - The authentication attempt failed
  11816. // Status.CONNECTED - The connection has succeeded
  11817. // Status.DISCONNECTED - The connection has been terminated
  11818. // Status.DISCONNECTING - The connection is currently being terminated
  11819. // Status.ATTACHED - The connection has been attached
  11820. var anonymousConnectionFailed = false;
  11821. var connectionFailed = false;
  11822. var lastErrorMsg;
  11823. this.connection.connect(jid, password, function (status, msg) {
  11824. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11825. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11826. if (status === Strophe.Status.CONNECTED) {
  11827. if (self.options.useStunTurn) {
  11828. self.connection.jingle.getStunAndTurnCredentials();
  11829. }
  11830. logger.info("My Jabber ID: " + self.connection.jid);
  11831. // Schedule ping ?
  11832. var pingJid = self.connection.domain;
  11833. self.connection.ping.hasPingSupport(
  11834. pingJid,
  11835. function (hasPing) {
  11836. if (hasPing)
  11837. self.connection.ping.startInterval(pingJid);
  11838. else
  11839. logger.warn("Ping NOT supported by " + pingJid);
  11840. }
  11841. );
  11842. if (password)
  11843. authenticatedUser = true;
  11844. if (self.connection && self.connection.connected &&
  11845. Strophe.getResourceFromJid(self.connection.jid)) {
  11846. // .connected is true while connecting?
  11847. // self.connection.send($pres());
  11848. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11849. Strophe.getResourceFromJid(self.connection.jid));
  11850. }
  11851. } else if (status === Strophe.Status.CONNFAIL) {
  11852. if (msg === 'x-strophe-bad-non-anon-jid') {
  11853. anonymousConnectionFailed = true;
  11854. }
  11855. else
  11856. {
  11857. connectionFailed = true;
  11858. }
  11859. lastErrorMsg = msg;
  11860. } else if (status === Strophe.Status.DISCONNECTED) {
  11861. // Stop ping interval
  11862. self.connection.ping.stopInterval();
  11863. self.disconnectInProgress = false;
  11864. if (anonymousConnectionFailed) {
  11865. // prompt user for username and password
  11866. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11867. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11868. } else if(connectionFailed) {
  11869. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11870. JitsiConnectionErrors.OTHER_ERROR,
  11871. msg ? msg : lastErrorMsg);
  11872. } else {
  11873. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11874. msg ? msg : lastErrorMsg);
  11875. }
  11876. } else if (status === Strophe.Status.AUTHFAIL) {
  11877. // wrong password or username, prompt user
  11878. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11879. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11880. }
  11881. });
  11882. }
  11883. XMPP.prototype.connect = function (jid, password) {
  11884. if(!jid) {
  11885. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11886. // Force authenticated domain if room is appended with '?login=true'
  11887. if (this.options.hosts.anonymousdomain &&
  11888. window.location.search.indexOf("login=true") !== -1) {
  11889. configDomain = this.options.hosts.domain;
  11890. }
  11891. jid = configDomain || window.location.hostname;
  11892. }
  11893. return this._connect(jid, password);
  11894. };
  11895. XMPP.prototype.createRoom = function (roomName, options, settings) {
  11896. var roomjid = roomName + '@' + this.options.hosts.muc;
  11897. if (options.useNicks) {
  11898. if (options.nick) {
  11899. roomjid += '/' + options.nick;
  11900. } else {
  11901. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  11902. }
  11903. } else {
  11904. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  11905. if(!authenticatedUser)
  11906. tmpJid = tmpJid.substr(0, 8);
  11907. roomjid += '/' + tmpJid;
  11908. }
  11909. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  11910. }
  11911. XMPP.prototype.addListener = function(type, listener) {
  11912. this.eventEmitter.on(type, listener);
  11913. };
  11914. XMPP.prototype.removeListener = function (type, listener) {
  11915. this.eventEmitter.removeListener(type, listener);
  11916. };
  11917. //FIXME: this should work with the room
  11918. XMPP.prototype.leaveRoom = function (jid) {
  11919. var handler = this.connection.jingle.jid2session[jid];
  11920. if (handler && handler.peerconnection) {
  11921. // FIXME: probably removing streams is not required and close() should
  11922. // be enough
  11923. if (RTC.localAudio) {
  11924. handler.peerconnection.removeStream(
  11925. RTC.localAudio.getOriginalStream(), true);
  11926. }
  11927. if (RTC.localVideo) {
  11928. handler.peerconnection.removeStream(
  11929. RTC.localVideo.getOriginalStream(), true);
  11930. }
  11931. handler.peerconnection.close();
  11932. }
  11933. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  11934. this.connection.emuc.doLeave(jid);
  11935. };
  11936. /**
  11937. * Sends 'data' as a log message to the focus. Returns true iff a message
  11938. * was sent.
  11939. * @param data
  11940. * @returns {boolean} true iff a message was sent.
  11941. */
  11942. XMPP.prototype.sendLogs = function (data) {
  11943. if(!this.connection.emuc.focusMucJid)
  11944. return false;
  11945. var deflate = true;
  11946. var content = JSON.stringify(data);
  11947. if (deflate) {
  11948. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  11949. }
  11950. content = Base64.encode(content);
  11951. // XEP-0337-ish
  11952. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  11953. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  11954. id: 'PeerConnectionStats'});
  11955. message.c('message').t(content).up();
  11956. if (deflate) {
  11957. message.c('tag', {name: "deflated", value: "true"}).up();
  11958. }
  11959. message.up();
  11960. this.connection.send(message);
  11961. return true;
  11962. };
  11963. // Gets the logs from strophe.jingle.
  11964. XMPP.prototype.getJingleLog = function () {
  11965. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  11966. };
  11967. // Gets the logs from strophe.
  11968. XMPP.prototype.getXmppLog = function () {
  11969. return this.connection.logger ? this.connection.logger.log : null;
  11970. };
  11971. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  11972. this.connection.rayo.dial(to, from, roomName,roomPass);
  11973. };
  11974. XMPP.prototype.setMute = function (jid, mute) {
  11975. this.connection.moderate.setMute(jid, mute);
  11976. };
  11977. XMPP.prototype.eject = function (jid) {
  11978. this.connection.moderate.eject(jid);
  11979. };
  11980. XMPP.prototype.getSessions = function () {
  11981. return this.connection.jingle.sessions;
  11982. };
  11983. XMPP.prototype.disconnect = function () {
  11984. if (this.disconnectInProgress
  11985. || !this.connection
  11986. || !this.connection.connected) {
  11987. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  11988. return;
  11989. }
  11990. this.disconnectInProgress = true;
  11991. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  11992. // means that there may not be enough time to send an unavailable presence
  11993. // or disconnect at all. Switching Strophe to synchronous sending is not
  11994. // much of an option because it may lead to a noticeable delay in navigating
  11995. // away from the current location. As a compromise, we will try to increase
  11996. // the chances of sending an unavailable presence and/or disconecting within
  11997. // the short time span that we have upon unloading by invoking flush() on
  11998. // the connection. We flush() once before disconnect() in order to attemtp
  11999. // to have its unavailable presence at the top of the send queue. We flush()
  12000. // once more after disconnect() in order to attempt to have its unavailable
  12001. // presence sent as soon as possible.
  12002. this.connection.flush();
  12003. this.connection.disconnect();
  12004. this.connection.flush();
  12005. };
  12006. module.exports = XMPP;
  12007. }).call(this,"/modules/xmpp/xmpp.js")
  12008. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":131,"../../service/xmpp/XMPPEvents":137,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":51,"jitsi-meet-logger":79,"pako":84}],45:[function(require,module,exports){
  12009. module.exports = after
  12010. function after(count, callback, err_cb) {
  12011. var bail = false
  12012. err_cb = err_cb || noop
  12013. proxy.count = count
  12014. return (count === 0) ? callback() : proxy
  12015. function proxy(err, result) {
  12016. if (proxy.count <= 0) {
  12017. throw new Error('after called too many times')
  12018. }
  12019. --proxy.count
  12020. // after first error, rest are passed to err_cb
  12021. if (err) {
  12022. bail = true
  12023. callback(err)
  12024. // future error callbacks will go to error handler
  12025. callback = err_cb
  12026. } else if (proxy.count === 0 && !bail) {
  12027. callback(null, result)
  12028. }
  12029. }
  12030. }
  12031. function noop() {}
  12032. },{}],46:[function(require,module,exports){
  12033. /**
  12034. * An abstraction for slicing an arraybuffer even when
  12035. * ArrayBuffer.prototype.slice is not supported
  12036. *
  12037. * @api public
  12038. */
  12039. module.exports = function(arraybuffer, start, end) {
  12040. var bytes = arraybuffer.byteLength;
  12041. start = start || 0;
  12042. end = end || bytes;
  12043. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  12044. if (start < 0) { start += bytes; }
  12045. if (end < 0) { end += bytes; }
  12046. if (end > bytes) { end = bytes; }
  12047. if (start >= bytes || start >= end || bytes === 0) {
  12048. return new ArrayBuffer(0);
  12049. }
  12050. var abv = new Uint8Array(arraybuffer);
  12051. var result = new Uint8Array(end - start);
  12052. for (var i = start, ii = 0; i < end; i++, ii++) {
  12053. result[ii] = abv[i];
  12054. }
  12055. return result.buffer;
  12056. };
  12057. },{}],47:[function(require,module,exports){
  12058. (function (process){
  12059. /*!
  12060. * async
  12061. * https://github.com/caolan/async
  12062. *
  12063. * Copyright 2010-2014 Caolan McMahon
  12064. * Released under the MIT license
  12065. */
  12066. /*jshint onevar: false, indent:4 */
  12067. /*global setImmediate: false, setTimeout: false, console: false */
  12068. (function () {
  12069. var async = {};
  12070. // global on the server, window in the browser
  12071. var root, previous_async;
  12072. root = this;
  12073. if (root != null) {
  12074. previous_async = root.async;
  12075. }
  12076. async.noConflict = function () {
  12077. root.async = previous_async;
  12078. return async;
  12079. };
  12080. function only_once(fn) {
  12081. var called = false;
  12082. return function() {
  12083. if (called) throw new Error("Callback was already called.");
  12084. called = true;
  12085. fn.apply(root, arguments);
  12086. }
  12087. }
  12088. //// cross-browser compatiblity functions ////
  12089. var _toString = Object.prototype.toString;
  12090. var _isArray = Array.isArray || function (obj) {
  12091. return _toString.call(obj) === '[object Array]';
  12092. };
  12093. var _each = function (arr, iterator) {
  12094. if (arr.forEach) {
  12095. return arr.forEach(iterator);
  12096. }
  12097. for (var i = 0; i < arr.length; i += 1) {
  12098. iterator(arr[i], i, arr);
  12099. }
  12100. };
  12101. var _map = function (arr, iterator) {
  12102. if (arr.map) {
  12103. return arr.map(iterator);
  12104. }
  12105. var results = [];
  12106. _each(arr, function (x, i, a) {
  12107. results.push(iterator(x, i, a));
  12108. });
  12109. return results;
  12110. };
  12111. var _reduce = function (arr, iterator, memo) {
  12112. if (arr.reduce) {
  12113. return arr.reduce(iterator, memo);
  12114. }
  12115. _each(arr, function (x, i, a) {
  12116. memo = iterator(memo, x, i, a);
  12117. });
  12118. return memo;
  12119. };
  12120. var _keys = function (obj) {
  12121. if (Object.keys) {
  12122. return Object.keys(obj);
  12123. }
  12124. var keys = [];
  12125. for (var k in obj) {
  12126. if (obj.hasOwnProperty(k)) {
  12127. keys.push(k);
  12128. }
  12129. }
  12130. return keys;
  12131. };
  12132. //// exported async module functions ////
  12133. //// nextTick implementation with browser-compatible fallback ////
  12134. if (typeof process === 'undefined' || !(process.nextTick)) {
  12135. if (typeof setImmediate === 'function') {
  12136. async.nextTick = function (fn) {
  12137. // not a direct alias for IE10 compatibility
  12138. setImmediate(fn);
  12139. };
  12140. async.setImmediate = async.nextTick;
  12141. }
  12142. else {
  12143. async.nextTick = function (fn) {
  12144. setTimeout(fn, 0);
  12145. };
  12146. async.setImmediate = async.nextTick;
  12147. }
  12148. }
  12149. else {
  12150. async.nextTick = process.nextTick;
  12151. if (typeof setImmediate !== 'undefined') {
  12152. async.setImmediate = function (fn) {
  12153. // not a direct alias for IE10 compatibility
  12154. setImmediate(fn);
  12155. };
  12156. }
  12157. else {
  12158. async.setImmediate = async.nextTick;
  12159. }
  12160. }
  12161. async.each = function (arr, iterator, callback) {
  12162. callback = callback || function () {};
  12163. if (!arr.length) {
  12164. return callback();
  12165. }
  12166. var completed = 0;
  12167. _each(arr, function (x) {
  12168. iterator(x, only_once(done) );
  12169. });
  12170. function done(err) {
  12171. if (err) {
  12172. callback(err);
  12173. callback = function () {};
  12174. }
  12175. else {
  12176. completed += 1;
  12177. if (completed >= arr.length) {
  12178. callback();
  12179. }
  12180. }
  12181. }
  12182. };
  12183. async.forEach = async.each;
  12184. async.eachSeries = function (arr, iterator, callback) {
  12185. callback = callback || function () {};
  12186. if (!arr.length) {
  12187. return callback();
  12188. }
  12189. var completed = 0;
  12190. var iterate = function () {
  12191. iterator(arr[completed], function (err) {
  12192. if (err) {
  12193. callback(err);
  12194. callback = function () {};
  12195. }
  12196. else {
  12197. completed += 1;
  12198. if (completed >= arr.length) {
  12199. callback();
  12200. }
  12201. else {
  12202. iterate();
  12203. }
  12204. }
  12205. });
  12206. };
  12207. iterate();
  12208. };
  12209. async.forEachSeries = async.eachSeries;
  12210. async.eachLimit = function (arr, limit, iterator, callback) {
  12211. var fn = _eachLimit(limit);
  12212. fn.apply(null, [arr, iterator, callback]);
  12213. };
  12214. async.forEachLimit = async.eachLimit;
  12215. var _eachLimit = function (limit) {
  12216. return function (arr, iterator, callback) {
  12217. callback = callback || function () {};
  12218. if (!arr.length || limit <= 0) {
  12219. return callback();
  12220. }
  12221. var completed = 0;
  12222. var started = 0;
  12223. var running = 0;
  12224. (function replenish () {
  12225. if (completed >= arr.length) {
  12226. return callback();
  12227. }
  12228. while (running < limit && started < arr.length) {
  12229. started += 1;
  12230. running += 1;
  12231. iterator(arr[started - 1], function (err) {
  12232. if (err) {
  12233. callback(err);
  12234. callback = function () {};
  12235. }
  12236. else {
  12237. completed += 1;
  12238. running -= 1;
  12239. if (completed >= arr.length) {
  12240. callback();
  12241. }
  12242. else {
  12243. replenish();
  12244. }
  12245. }
  12246. });
  12247. }
  12248. })();
  12249. };
  12250. };
  12251. var doParallel = function (fn) {
  12252. return function () {
  12253. var args = Array.prototype.slice.call(arguments);
  12254. return fn.apply(null, [async.each].concat(args));
  12255. };
  12256. };
  12257. var doParallelLimit = function(limit, fn) {
  12258. return function () {
  12259. var args = Array.prototype.slice.call(arguments);
  12260. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12261. };
  12262. };
  12263. var doSeries = function (fn) {
  12264. return function () {
  12265. var args = Array.prototype.slice.call(arguments);
  12266. return fn.apply(null, [async.eachSeries].concat(args));
  12267. };
  12268. };
  12269. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12270. arr = _map(arr, function (x, i) {
  12271. return {index: i, value: x};
  12272. });
  12273. if (!callback) {
  12274. eachfn(arr, function (x, callback) {
  12275. iterator(x.value, function (err) {
  12276. callback(err);
  12277. });
  12278. });
  12279. } else {
  12280. var results = [];
  12281. eachfn(arr, function (x, callback) {
  12282. iterator(x.value, function (err, v) {
  12283. results[x.index] = v;
  12284. callback(err);
  12285. });
  12286. }, function (err) {
  12287. callback(err, results);
  12288. });
  12289. }
  12290. };
  12291. async.map = doParallel(_asyncMap);
  12292. async.mapSeries = doSeries(_asyncMap);
  12293. async.mapLimit = function (arr, limit, iterator, callback) {
  12294. return _mapLimit(limit)(arr, iterator, callback);
  12295. };
  12296. var _mapLimit = function(limit) {
  12297. return doParallelLimit(limit, _asyncMap);
  12298. };
  12299. // reduce only has a series version, as doing reduce in parallel won't
  12300. // work in many situations.
  12301. async.reduce = function (arr, memo, iterator, callback) {
  12302. async.eachSeries(arr, function (x, callback) {
  12303. iterator(memo, x, function (err, v) {
  12304. memo = v;
  12305. callback(err);
  12306. });
  12307. }, function (err) {
  12308. callback(err, memo);
  12309. });
  12310. };
  12311. // inject alias
  12312. async.inject = async.reduce;
  12313. // foldl alias
  12314. async.foldl = async.reduce;
  12315. async.reduceRight = function (arr, memo, iterator, callback) {
  12316. var reversed = _map(arr, function (x) {
  12317. return x;
  12318. }).reverse();
  12319. async.reduce(reversed, memo, iterator, callback);
  12320. };
  12321. // foldr alias
  12322. async.foldr = async.reduceRight;
  12323. var _filter = function (eachfn, arr, iterator, callback) {
  12324. var results = [];
  12325. arr = _map(arr, function (x, i) {
  12326. return {index: i, value: x};
  12327. });
  12328. eachfn(arr, function (x, callback) {
  12329. iterator(x.value, function (v) {
  12330. if (v) {
  12331. results.push(x);
  12332. }
  12333. callback();
  12334. });
  12335. }, function (err) {
  12336. callback(_map(results.sort(function (a, b) {
  12337. return a.index - b.index;
  12338. }), function (x) {
  12339. return x.value;
  12340. }));
  12341. });
  12342. };
  12343. async.filter = doParallel(_filter);
  12344. async.filterSeries = doSeries(_filter);
  12345. // select alias
  12346. async.select = async.filter;
  12347. async.selectSeries = async.filterSeries;
  12348. var _reject = function (eachfn, arr, iterator, callback) {
  12349. var results = [];
  12350. arr = _map(arr, function (x, i) {
  12351. return {index: i, value: x};
  12352. });
  12353. eachfn(arr, function (x, callback) {
  12354. iterator(x.value, function (v) {
  12355. if (!v) {
  12356. results.push(x);
  12357. }
  12358. callback();
  12359. });
  12360. }, function (err) {
  12361. callback(_map(results.sort(function (a, b) {
  12362. return a.index - b.index;
  12363. }), function (x) {
  12364. return x.value;
  12365. }));
  12366. });
  12367. };
  12368. async.reject = doParallel(_reject);
  12369. async.rejectSeries = doSeries(_reject);
  12370. var _detect = function (eachfn, arr, iterator, main_callback) {
  12371. eachfn(arr, function (x, callback) {
  12372. iterator(x, function (result) {
  12373. if (result) {
  12374. main_callback(x);
  12375. main_callback = function () {};
  12376. }
  12377. else {
  12378. callback();
  12379. }
  12380. });
  12381. }, function (err) {
  12382. main_callback();
  12383. });
  12384. };
  12385. async.detect = doParallel(_detect);
  12386. async.detectSeries = doSeries(_detect);
  12387. async.some = function (arr, iterator, main_callback) {
  12388. async.each(arr, function (x, callback) {
  12389. iterator(x, function (v) {
  12390. if (v) {
  12391. main_callback(true);
  12392. main_callback = function () {};
  12393. }
  12394. callback();
  12395. });
  12396. }, function (err) {
  12397. main_callback(false);
  12398. });
  12399. };
  12400. // any alias
  12401. async.any = async.some;
  12402. async.every = function (arr, iterator, main_callback) {
  12403. async.each(arr, function (x, callback) {
  12404. iterator(x, function (v) {
  12405. if (!v) {
  12406. main_callback(false);
  12407. main_callback = function () {};
  12408. }
  12409. callback();
  12410. });
  12411. }, function (err) {
  12412. main_callback(true);
  12413. });
  12414. };
  12415. // all alias
  12416. async.all = async.every;
  12417. async.sortBy = function (arr, iterator, callback) {
  12418. async.map(arr, function (x, callback) {
  12419. iterator(x, function (err, criteria) {
  12420. if (err) {
  12421. callback(err);
  12422. }
  12423. else {
  12424. callback(null, {value: x, criteria: criteria});
  12425. }
  12426. });
  12427. }, function (err, results) {
  12428. if (err) {
  12429. return callback(err);
  12430. }
  12431. else {
  12432. var fn = function (left, right) {
  12433. var a = left.criteria, b = right.criteria;
  12434. return a < b ? -1 : a > b ? 1 : 0;
  12435. };
  12436. callback(null, _map(results.sort(fn), function (x) {
  12437. return x.value;
  12438. }));
  12439. }
  12440. });
  12441. };
  12442. async.auto = function (tasks, callback) {
  12443. callback = callback || function () {};
  12444. var keys = _keys(tasks);
  12445. var remainingTasks = keys.length
  12446. if (!remainingTasks) {
  12447. return callback();
  12448. }
  12449. var results = {};
  12450. var listeners = [];
  12451. var addListener = function (fn) {
  12452. listeners.unshift(fn);
  12453. };
  12454. var removeListener = function (fn) {
  12455. for (var i = 0; i < listeners.length; i += 1) {
  12456. if (listeners[i] === fn) {
  12457. listeners.splice(i, 1);
  12458. return;
  12459. }
  12460. }
  12461. };
  12462. var taskComplete = function () {
  12463. remainingTasks--
  12464. _each(listeners.slice(0), function (fn) {
  12465. fn();
  12466. });
  12467. };
  12468. addListener(function () {
  12469. if (!remainingTasks) {
  12470. var theCallback = callback;
  12471. // prevent final callback from calling itself if it errors
  12472. callback = function () {};
  12473. theCallback(null, results);
  12474. }
  12475. });
  12476. _each(keys, function (k) {
  12477. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12478. var taskCallback = function (err) {
  12479. var args = Array.prototype.slice.call(arguments, 1);
  12480. if (args.length <= 1) {
  12481. args = args[0];
  12482. }
  12483. if (err) {
  12484. var safeResults = {};
  12485. _each(_keys(results), function(rkey) {
  12486. safeResults[rkey] = results[rkey];
  12487. });
  12488. safeResults[k] = args;
  12489. callback(err, safeResults);
  12490. // stop subsequent errors hitting callback multiple times
  12491. callback = function () {};
  12492. }
  12493. else {
  12494. results[k] = args;
  12495. async.setImmediate(taskComplete);
  12496. }
  12497. };
  12498. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12499. var ready = function () {
  12500. return _reduce(requires, function (a, x) {
  12501. return (a && results.hasOwnProperty(x));
  12502. }, true) && !results.hasOwnProperty(k);
  12503. };
  12504. if (ready()) {
  12505. task[task.length - 1](taskCallback, results);
  12506. }
  12507. else {
  12508. var listener = function () {
  12509. if (ready()) {
  12510. removeListener(listener);
  12511. task[task.length - 1](taskCallback, results);
  12512. }
  12513. };
  12514. addListener(listener);
  12515. }
  12516. });
  12517. };
  12518. async.retry = function(times, task, callback) {
  12519. var DEFAULT_TIMES = 5;
  12520. var attempts = [];
  12521. // Use defaults if times not passed
  12522. if (typeof times === 'function') {
  12523. callback = task;
  12524. task = times;
  12525. times = DEFAULT_TIMES;
  12526. }
  12527. // Make sure times is a number
  12528. times = parseInt(times, 10) || DEFAULT_TIMES;
  12529. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12530. var retryAttempt = function(task, finalAttempt) {
  12531. return function(seriesCallback) {
  12532. task(function(err, result){
  12533. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12534. }, wrappedResults);
  12535. };
  12536. };
  12537. while (times) {
  12538. attempts.push(retryAttempt(task, !(times-=1)));
  12539. }
  12540. async.series(attempts, function(done, data){
  12541. data = data[data.length - 1];
  12542. (wrappedCallback || callback)(data.err, data.result);
  12543. });
  12544. }
  12545. // If a callback is passed, run this as a controll flow
  12546. return callback ? wrappedTask() : wrappedTask
  12547. };
  12548. async.waterfall = function (tasks, callback) {
  12549. callback = callback || function () {};
  12550. if (!_isArray(tasks)) {
  12551. var err = new Error('First argument to waterfall must be an array of functions');
  12552. return callback(err);
  12553. }
  12554. if (!tasks.length) {
  12555. return callback();
  12556. }
  12557. var wrapIterator = function (iterator) {
  12558. return function (err) {
  12559. if (err) {
  12560. callback.apply(null, arguments);
  12561. callback = function () {};
  12562. }
  12563. else {
  12564. var args = Array.prototype.slice.call(arguments, 1);
  12565. var next = iterator.next();
  12566. if (next) {
  12567. args.push(wrapIterator(next));
  12568. }
  12569. else {
  12570. args.push(callback);
  12571. }
  12572. async.setImmediate(function () {
  12573. iterator.apply(null, args);
  12574. });
  12575. }
  12576. };
  12577. };
  12578. wrapIterator(async.iterator(tasks))();
  12579. };
  12580. var _parallel = function(eachfn, tasks, callback) {
  12581. callback = callback || function () {};
  12582. if (_isArray(tasks)) {
  12583. eachfn.map(tasks, function (fn, callback) {
  12584. if (fn) {
  12585. fn(function (err) {
  12586. var args = Array.prototype.slice.call(arguments, 1);
  12587. if (args.length <= 1) {
  12588. args = args[0];
  12589. }
  12590. callback.call(null, err, args);
  12591. });
  12592. }
  12593. }, callback);
  12594. }
  12595. else {
  12596. var results = {};
  12597. eachfn.each(_keys(tasks), function (k, callback) {
  12598. tasks[k](function (err) {
  12599. var args = Array.prototype.slice.call(arguments, 1);
  12600. if (args.length <= 1) {
  12601. args = args[0];
  12602. }
  12603. results[k] = args;
  12604. callback(err);
  12605. });
  12606. }, function (err) {
  12607. callback(err, results);
  12608. });
  12609. }
  12610. };
  12611. async.parallel = function (tasks, callback) {
  12612. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12613. };
  12614. async.parallelLimit = function(tasks, limit, callback) {
  12615. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12616. };
  12617. async.series = function (tasks, callback) {
  12618. callback = callback || function () {};
  12619. if (_isArray(tasks)) {
  12620. async.mapSeries(tasks, function (fn, callback) {
  12621. if (fn) {
  12622. fn(function (err) {
  12623. var args = Array.prototype.slice.call(arguments, 1);
  12624. if (args.length <= 1) {
  12625. args = args[0];
  12626. }
  12627. callback.call(null, err, args);
  12628. });
  12629. }
  12630. }, callback);
  12631. }
  12632. else {
  12633. var results = {};
  12634. async.eachSeries(_keys(tasks), function (k, callback) {
  12635. tasks[k](function (err) {
  12636. var args = Array.prototype.slice.call(arguments, 1);
  12637. if (args.length <= 1) {
  12638. args = args[0];
  12639. }
  12640. results[k] = args;
  12641. callback(err);
  12642. });
  12643. }, function (err) {
  12644. callback(err, results);
  12645. });
  12646. }
  12647. };
  12648. async.iterator = function (tasks) {
  12649. var makeCallback = function (index) {
  12650. var fn = function () {
  12651. if (tasks.length) {
  12652. tasks[index].apply(null, arguments);
  12653. }
  12654. return fn.next();
  12655. };
  12656. fn.next = function () {
  12657. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12658. };
  12659. return fn;
  12660. };
  12661. return makeCallback(0);
  12662. };
  12663. async.apply = function (fn) {
  12664. var args = Array.prototype.slice.call(arguments, 1);
  12665. return function () {
  12666. return fn.apply(
  12667. null, args.concat(Array.prototype.slice.call(arguments))
  12668. );
  12669. };
  12670. };
  12671. var _concat = function (eachfn, arr, fn, callback) {
  12672. var r = [];
  12673. eachfn(arr, function (x, cb) {
  12674. fn(x, function (err, y) {
  12675. r = r.concat(y || []);
  12676. cb(err);
  12677. });
  12678. }, function (err) {
  12679. callback(err, r);
  12680. });
  12681. };
  12682. async.concat = doParallel(_concat);
  12683. async.concatSeries = doSeries(_concat);
  12684. async.whilst = function (test, iterator, callback) {
  12685. if (test()) {
  12686. iterator(function (err) {
  12687. if (err) {
  12688. return callback(err);
  12689. }
  12690. async.whilst(test, iterator, callback);
  12691. });
  12692. }
  12693. else {
  12694. callback();
  12695. }
  12696. };
  12697. async.doWhilst = function (iterator, test, callback) {
  12698. iterator(function (err) {
  12699. if (err) {
  12700. return callback(err);
  12701. }
  12702. var args = Array.prototype.slice.call(arguments, 1);
  12703. if (test.apply(null, args)) {
  12704. async.doWhilst(iterator, test, callback);
  12705. }
  12706. else {
  12707. callback();
  12708. }
  12709. });
  12710. };
  12711. async.until = function (test, iterator, callback) {
  12712. if (!test()) {
  12713. iterator(function (err) {
  12714. if (err) {
  12715. return callback(err);
  12716. }
  12717. async.until(test, iterator, callback);
  12718. });
  12719. }
  12720. else {
  12721. callback();
  12722. }
  12723. };
  12724. async.doUntil = function (iterator, test, callback) {
  12725. iterator(function (err) {
  12726. if (err) {
  12727. return callback(err);
  12728. }
  12729. var args = Array.prototype.slice.call(arguments, 1);
  12730. if (!test.apply(null, args)) {
  12731. async.doUntil(iterator, test, callback);
  12732. }
  12733. else {
  12734. callback();
  12735. }
  12736. });
  12737. };
  12738. async.queue = function (worker, concurrency) {
  12739. if (concurrency === undefined) {
  12740. concurrency = 1;
  12741. }
  12742. function _insert(q, data, pos, callback) {
  12743. if (!q.started){
  12744. q.started = true;
  12745. }
  12746. if (!_isArray(data)) {
  12747. data = [data];
  12748. }
  12749. if(data.length == 0) {
  12750. // call drain immediately if there are no tasks
  12751. return async.setImmediate(function() {
  12752. if (q.drain) {
  12753. q.drain();
  12754. }
  12755. });
  12756. }
  12757. _each(data, function(task) {
  12758. var item = {
  12759. data: task,
  12760. callback: typeof callback === 'function' ? callback : null
  12761. };
  12762. if (pos) {
  12763. q.tasks.unshift(item);
  12764. } else {
  12765. q.tasks.push(item);
  12766. }
  12767. if (q.saturated && q.tasks.length === q.concurrency) {
  12768. q.saturated();
  12769. }
  12770. async.setImmediate(q.process);
  12771. });
  12772. }
  12773. var workers = 0;
  12774. var q = {
  12775. tasks: [],
  12776. concurrency: concurrency,
  12777. saturated: null,
  12778. empty: null,
  12779. drain: null,
  12780. started: false,
  12781. paused: false,
  12782. push: function (data, callback) {
  12783. _insert(q, data, false, callback);
  12784. },
  12785. kill: function () {
  12786. q.drain = null;
  12787. q.tasks = [];
  12788. },
  12789. unshift: function (data, callback) {
  12790. _insert(q, data, true, callback);
  12791. },
  12792. process: function () {
  12793. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12794. var task = q.tasks.shift();
  12795. if (q.empty && q.tasks.length === 0) {
  12796. q.empty();
  12797. }
  12798. workers += 1;
  12799. var next = function () {
  12800. workers -= 1;
  12801. if (task.callback) {
  12802. task.callback.apply(task, arguments);
  12803. }
  12804. if (q.drain && q.tasks.length + workers === 0) {
  12805. q.drain();
  12806. }
  12807. q.process();
  12808. };
  12809. var cb = only_once(next);
  12810. worker(task.data, cb);
  12811. }
  12812. },
  12813. length: function () {
  12814. return q.tasks.length;
  12815. },
  12816. running: function () {
  12817. return workers;
  12818. },
  12819. idle: function() {
  12820. return q.tasks.length + workers === 0;
  12821. },
  12822. pause: function () {
  12823. if (q.paused === true) { return; }
  12824. q.paused = true;
  12825. q.process();
  12826. },
  12827. resume: function () {
  12828. if (q.paused === false) { return; }
  12829. q.paused = false;
  12830. q.process();
  12831. }
  12832. };
  12833. return q;
  12834. };
  12835. async.priorityQueue = function (worker, concurrency) {
  12836. function _compareTasks(a, b){
  12837. return a.priority - b.priority;
  12838. };
  12839. function _binarySearch(sequence, item, compare) {
  12840. var beg = -1,
  12841. end = sequence.length - 1;
  12842. while (beg < end) {
  12843. var mid = beg + ((end - beg + 1) >>> 1);
  12844. if (compare(item, sequence[mid]) >= 0) {
  12845. beg = mid;
  12846. } else {
  12847. end = mid - 1;
  12848. }
  12849. }
  12850. return beg;
  12851. }
  12852. function _insert(q, data, priority, callback) {
  12853. if (!q.started){
  12854. q.started = true;
  12855. }
  12856. if (!_isArray(data)) {
  12857. data = [data];
  12858. }
  12859. if(data.length == 0) {
  12860. // call drain immediately if there are no tasks
  12861. return async.setImmediate(function() {
  12862. if (q.drain) {
  12863. q.drain();
  12864. }
  12865. });
  12866. }
  12867. _each(data, function(task) {
  12868. var item = {
  12869. data: task,
  12870. priority: priority,
  12871. callback: typeof callback === 'function' ? callback : null
  12872. };
  12873. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12874. if (q.saturated && q.tasks.length === q.concurrency) {
  12875. q.saturated();
  12876. }
  12877. async.setImmediate(q.process);
  12878. });
  12879. }
  12880. // Start with a normal queue
  12881. var q = async.queue(worker, concurrency);
  12882. // Override push to accept second parameter representing priority
  12883. q.push = function (data, priority, callback) {
  12884. _insert(q, data, priority, callback);
  12885. };
  12886. // Remove unshift function
  12887. delete q.unshift;
  12888. return q;
  12889. };
  12890. async.cargo = function (worker, payload) {
  12891. var working = false,
  12892. tasks = [];
  12893. var cargo = {
  12894. tasks: tasks,
  12895. payload: payload,
  12896. saturated: null,
  12897. empty: null,
  12898. drain: null,
  12899. drained: true,
  12900. push: function (data, callback) {
  12901. if (!_isArray(data)) {
  12902. data = [data];
  12903. }
  12904. _each(data, function(task) {
  12905. tasks.push({
  12906. data: task,
  12907. callback: typeof callback === 'function' ? callback : null
  12908. });
  12909. cargo.drained = false;
  12910. if (cargo.saturated && tasks.length === payload) {
  12911. cargo.saturated();
  12912. }
  12913. });
  12914. async.setImmediate(cargo.process);
  12915. },
  12916. process: function process() {
  12917. if (working) return;
  12918. if (tasks.length === 0) {
  12919. if(cargo.drain && !cargo.drained) cargo.drain();
  12920. cargo.drained = true;
  12921. return;
  12922. }
  12923. var ts = typeof payload === 'number'
  12924. ? tasks.splice(0, payload)
  12925. : tasks.splice(0, tasks.length);
  12926. var ds = _map(ts, function (task) {
  12927. return task.data;
  12928. });
  12929. if(cargo.empty) cargo.empty();
  12930. working = true;
  12931. worker(ds, function () {
  12932. working = false;
  12933. var args = arguments;
  12934. _each(ts, function (data) {
  12935. if (data.callback) {
  12936. data.callback.apply(null, args);
  12937. }
  12938. });
  12939. process();
  12940. });
  12941. },
  12942. length: function () {
  12943. return tasks.length;
  12944. },
  12945. running: function () {
  12946. return working;
  12947. }
  12948. };
  12949. return cargo;
  12950. };
  12951. var _console_fn = function (name) {
  12952. return function (fn) {
  12953. var args = Array.prototype.slice.call(arguments, 1);
  12954. fn.apply(null, args.concat([function (err) {
  12955. var args = Array.prototype.slice.call(arguments, 1);
  12956. if (typeof console !== 'undefined') {
  12957. if (err) {
  12958. if (console.error) {
  12959. console.error(err);
  12960. }
  12961. }
  12962. else if (console[name]) {
  12963. _each(args, function (x) {
  12964. console[name](x);
  12965. });
  12966. }
  12967. }
  12968. }]));
  12969. };
  12970. };
  12971. async.log = _console_fn('log');
  12972. async.dir = _console_fn('dir');
  12973. /*async.info = _console_fn('info');
  12974. async.warn = _console_fn('warn');
  12975. async.error = _console_fn('error');*/
  12976. async.memoize = function (fn, hasher) {
  12977. var memo = {};
  12978. var queues = {};
  12979. hasher = hasher || function (x) {
  12980. return x;
  12981. };
  12982. var memoized = function () {
  12983. var args = Array.prototype.slice.call(arguments);
  12984. var callback = args.pop();
  12985. var key = hasher.apply(null, args);
  12986. if (key in memo) {
  12987. async.nextTick(function () {
  12988. callback.apply(null, memo[key]);
  12989. });
  12990. }
  12991. else if (key in queues) {
  12992. queues[key].push(callback);
  12993. }
  12994. else {
  12995. queues[key] = [callback];
  12996. fn.apply(null, args.concat([function () {
  12997. memo[key] = arguments;
  12998. var q = queues[key];
  12999. delete queues[key];
  13000. for (var i = 0, l = q.length; i < l; i++) {
  13001. q[i].apply(null, arguments);
  13002. }
  13003. }]));
  13004. }
  13005. };
  13006. memoized.memo = memo;
  13007. memoized.unmemoized = fn;
  13008. return memoized;
  13009. };
  13010. async.unmemoize = function (fn) {
  13011. return function () {
  13012. return (fn.unmemoized || fn).apply(null, arguments);
  13013. };
  13014. };
  13015. async.times = function (count, iterator, callback) {
  13016. var counter = [];
  13017. for (var i = 0; i < count; i++) {
  13018. counter.push(i);
  13019. }
  13020. return async.map(counter, iterator, callback);
  13021. };
  13022. async.timesSeries = function (count, iterator, callback) {
  13023. var counter = [];
  13024. for (var i = 0; i < count; i++) {
  13025. counter.push(i);
  13026. }
  13027. return async.mapSeries(counter, iterator, callback);
  13028. };
  13029. async.seq = function (/* functions... */) {
  13030. var fns = arguments;
  13031. return function () {
  13032. var that = this;
  13033. var args = Array.prototype.slice.call(arguments);
  13034. var callback = args.pop();
  13035. async.reduce(fns, args, function (newargs, fn, cb) {
  13036. fn.apply(that, newargs.concat([function () {
  13037. var err = arguments[0];
  13038. var nextargs = Array.prototype.slice.call(arguments, 1);
  13039. cb(err, nextargs);
  13040. }]))
  13041. },
  13042. function (err, results) {
  13043. callback.apply(that, [err].concat(results));
  13044. });
  13045. };
  13046. };
  13047. async.compose = function (/* functions... */) {
  13048. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  13049. };
  13050. var _applyEach = function (eachfn, fns /*args...*/) {
  13051. var go = function () {
  13052. var that = this;
  13053. var args = Array.prototype.slice.call(arguments);
  13054. var callback = args.pop();
  13055. return eachfn(fns, function (fn, cb) {
  13056. fn.apply(that, args.concat([cb]));
  13057. },
  13058. callback);
  13059. };
  13060. if (arguments.length > 2) {
  13061. var args = Array.prototype.slice.call(arguments, 2);
  13062. return go.apply(this, args);
  13063. }
  13064. else {
  13065. return go;
  13066. }
  13067. };
  13068. async.applyEach = doParallel(_applyEach);
  13069. async.applyEachSeries = doSeries(_applyEach);
  13070. async.forever = function (fn, callback) {
  13071. function next(err) {
  13072. if (err) {
  13073. if (callback) {
  13074. return callback(err);
  13075. }
  13076. throw err;
  13077. }
  13078. fn(next);
  13079. }
  13080. next();
  13081. };
  13082. // Node.js
  13083. if (typeof module !== 'undefined' && module.exports) {
  13084. module.exports = async;
  13085. }
  13086. // AMD / RequireJS
  13087. else if (typeof define !== 'undefined' && define.amd) {
  13088. define([], function () {
  13089. return async;
  13090. });
  13091. }
  13092. // included directly via <script> tag
  13093. else {
  13094. root.async = async;
  13095. }
  13096. }());
  13097. }).call(this,require('_process'))
  13098. },{"_process":103}],48:[function(require,module,exports){
  13099. /**
  13100. * Expose `Backoff`.
  13101. */
  13102. module.exports = Backoff;
  13103. /**
  13104. * Initialize backoff timer with `opts`.
  13105. *
  13106. * - `min` initial timeout in milliseconds [100]
  13107. * - `max` max timeout [10000]
  13108. * - `jitter` [0]
  13109. * - `factor` [2]
  13110. *
  13111. * @param {Object} opts
  13112. * @api public
  13113. */
  13114. function Backoff(opts) {
  13115. opts = opts || {};
  13116. this.ms = opts.min || 100;
  13117. this.max = opts.max || 10000;
  13118. this.factor = opts.factor || 2;
  13119. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  13120. this.attempts = 0;
  13121. }
  13122. /**
  13123. * Return the backoff duration.
  13124. *
  13125. * @return {Number}
  13126. * @api public
  13127. */
  13128. Backoff.prototype.duration = function(){
  13129. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  13130. if (this.jitter) {
  13131. var rand = Math.random();
  13132. var deviation = Math.floor(rand * this.jitter * ms);
  13133. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  13134. }
  13135. return Math.min(ms, this.max) | 0;
  13136. };
  13137. /**
  13138. * Reset the number of attempts.
  13139. *
  13140. * @api public
  13141. */
  13142. Backoff.prototype.reset = function(){
  13143. this.attempts = 0;
  13144. };
  13145. /**
  13146. * Set the minimum duration
  13147. *
  13148. * @api public
  13149. */
  13150. Backoff.prototype.setMin = function(min){
  13151. this.ms = min;
  13152. };
  13153. /**
  13154. * Set the maximum duration
  13155. *
  13156. * @api public
  13157. */
  13158. Backoff.prototype.setMax = function(max){
  13159. this.max = max;
  13160. };
  13161. /**
  13162. * Set the jitter
  13163. *
  13164. * @api public
  13165. */
  13166. Backoff.prototype.setJitter = function(jitter){
  13167. this.jitter = jitter;
  13168. };
  13169. },{}],49:[function(require,module,exports){
  13170. /*
  13171. * base64-arraybuffer
  13172. * https://github.com/niklasvh/base64-arraybuffer
  13173. *
  13174. * Copyright (c) 2012 Niklas von Hertzen
  13175. * Licensed under the MIT license.
  13176. */
  13177. (function(chars){
  13178. "use strict";
  13179. exports.encode = function(arraybuffer) {
  13180. var bytes = new Uint8Array(arraybuffer),
  13181. i, len = bytes.length, base64 = "";
  13182. for (i = 0; i < len; i+=3) {
  13183. base64 += chars[bytes[i] >> 2];
  13184. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  13185. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  13186. base64 += chars[bytes[i + 2] & 63];
  13187. }
  13188. if ((len % 3) === 2) {
  13189. base64 = base64.substring(0, base64.length - 1) + "=";
  13190. } else if (len % 3 === 1) {
  13191. base64 = base64.substring(0, base64.length - 2) + "==";
  13192. }
  13193. return base64;
  13194. };
  13195. exports.decode = function(base64) {
  13196. var bufferLength = base64.length * 0.75,
  13197. len = base64.length, i, p = 0,
  13198. encoded1, encoded2, encoded3, encoded4;
  13199. if (base64[base64.length - 1] === "=") {
  13200. bufferLength--;
  13201. if (base64[base64.length - 2] === "=") {
  13202. bufferLength--;
  13203. }
  13204. }
  13205. var arraybuffer = new ArrayBuffer(bufferLength),
  13206. bytes = new Uint8Array(arraybuffer);
  13207. for (i = 0; i < len; i+=4) {
  13208. encoded1 = chars.indexOf(base64[i]);
  13209. encoded2 = chars.indexOf(base64[i+1]);
  13210. encoded3 = chars.indexOf(base64[i+2]);
  13211. encoded4 = chars.indexOf(base64[i+3]);
  13212. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  13213. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  13214. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  13215. }
  13216. return arraybuffer;
  13217. };
  13218. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  13219. },{}],50:[function(require,module,exports){
  13220. (function (global){
  13221. /**
  13222. * Create a blob builder even when vendor prefixes exist
  13223. */
  13224. var BlobBuilder = global.BlobBuilder
  13225. || global.WebKitBlobBuilder
  13226. || global.MSBlobBuilder
  13227. || global.MozBlobBuilder;
  13228. /**
  13229. * Check if Blob constructor is supported
  13230. */
  13231. var blobSupported = (function() {
  13232. try {
  13233. var b = new Blob(['hi']);
  13234. return b.size == 2;
  13235. } catch(e) {
  13236. return false;
  13237. }
  13238. })();
  13239. /**
  13240. * Check if BlobBuilder is supported
  13241. */
  13242. var blobBuilderSupported = BlobBuilder
  13243. && BlobBuilder.prototype.append
  13244. && BlobBuilder.prototype.getBlob;
  13245. function BlobBuilderConstructor(ary, options) {
  13246. options = options || {};
  13247. var bb = new BlobBuilder();
  13248. for (var i = 0; i < ary.length; i++) {
  13249. bb.append(ary[i]);
  13250. }
  13251. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  13252. };
  13253. module.exports = (function() {
  13254. if (blobSupported) {
  13255. return global.Blob;
  13256. } else if (blobBuilderSupported) {
  13257. return BlobBuilderConstructor;
  13258. } else {
  13259. return undefined;
  13260. }
  13261. })();
  13262. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  13263. },{}],51:[function(require,module,exports){
  13264. // Copyright Joyent, Inc. and other Node contributors.
  13265. //
  13266. // Permission is hereby granted, free of charge, to any person obtaining a
  13267. // copy of this software and associated documentation files (the
  13268. // "Software"), to deal in the Software without restriction, including
  13269. // without limitation the rights to use, copy, modify, merge, publish,
  13270. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13271. // persons to whom the Software is furnished to do so, subject to the
  13272. // following conditions:
  13273. //
  13274. // The above copyright notice and this permission notice shall be included
  13275. // in all copies or substantial portions of the Software.
  13276. //
  13277. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13278. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13279. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13280. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13281. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13282. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13283. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13284. function EventEmitter() {
  13285. this._events = this._events || {};
  13286. this._maxListeners = this._maxListeners || undefined;
  13287. }
  13288. module.exports = EventEmitter;
  13289. // Backwards-compat with node 0.10.x
  13290. EventEmitter.EventEmitter = EventEmitter;
  13291. EventEmitter.prototype._events = undefined;
  13292. EventEmitter.prototype._maxListeners = undefined;
  13293. // By default EventEmitters will print a warning if more than 10 listeners are
  13294. // added to it. This is a useful default which helps finding memory leaks.
  13295. EventEmitter.defaultMaxListeners = 10;
  13296. // Obviously not all Emitters should be limited to 10. This function allows
  13297. // that to be increased. Set to zero for unlimited.
  13298. EventEmitter.prototype.setMaxListeners = function(n) {
  13299. if (!isNumber(n) || n < 0 || isNaN(n))
  13300. throw TypeError('n must be a positive number');
  13301. this._maxListeners = n;
  13302. return this;
  13303. };
  13304. EventEmitter.prototype.emit = function(type) {
  13305. var er, handler, len, args, i, listeners;
  13306. if (!this._events)
  13307. this._events = {};
  13308. // If there is no 'error' event listener then throw.
  13309. if (type === 'error') {
  13310. if (!this._events.error ||
  13311. (isObject(this._events.error) && !this._events.error.length)) {
  13312. er = arguments[1];
  13313. if (er instanceof Error) {
  13314. throw er; // Unhandled 'error' event
  13315. }
  13316. throw TypeError('Uncaught, unspecified "error" event.');
  13317. }
  13318. }
  13319. handler = this._events[type];
  13320. if (isUndefined(handler))
  13321. return false;
  13322. if (isFunction(handler)) {
  13323. switch (arguments.length) {
  13324. // fast cases
  13325. case 1:
  13326. handler.call(this);
  13327. break;
  13328. case 2:
  13329. handler.call(this, arguments[1]);
  13330. break;
  13331. case 3:
  13332. handler.call(this, arguments[1], arguments[2]);
  13333. break;
  13334. // slower
  13335. default:
  13336. len = arguments.length;
  13337. args = new Array(len - 1);
  13338. for (i = 1; i < len; i++)
  13339. args[i - 1] = arguments[i];
  13340. handler.apply(this, args);
  13341. }
  13342. } else if (isObject(handler)) {
  13343. len = arguments.length;
  13344. args = new Array(len - 1);
  13345. for (i = 1; i < len; i++)
  13346. args[i - 1] = arguments[i];
  13347. listeners = handler.slice();
  13348. len = listeners.length;
  13349. for (i = 0; i < len; i++)
  13350. listeners[i].apply(this, args);
  13351. }
  13352. return true;
  13353. };
  13354. EventEmitter.prototype.addListener = function(type, listener) {
  13355. var m;
  13356. if (!isFunction(listener))
  13357. throw TypeError('listener must be a function');
  13358. if (!this._events)
  13359. this._events = {};
  13360. // To avoid recursion in the case that type === "newListener"! Before
  13361. // adding it to the listeners, first emit "newListener".
  13362. if (this._events.newListener)
  13363. this.emit('newListener', type,
  13364. isFunction(listener.listener) ?
  13365. listener.listener : listener);
  13366. if (!this._events[type])
  13367. // Optimize the case of one listener. Don't need the extra array object.
  13368. this._events[type] = listener;
  13369. else if (isObject(this._events[type]))
  13370. // If we've already got an array, just append.
  13371. this._events[type].push(listener);
  13372. else
  13373. // Adding the second element, need to change to array.
  13374. this._events[type] = [this._events[type], listener];
  13375. // Check for listener leak
  13376. if (isObject(this._events[type]) && !this._events[type].warned) {
  13377. var m;
  13378. if (!isUndefined(this._maxListeners)) {
  13379. m = this._maxListeners;
  13380. } else {
  13381. m = EventEmitter.defaultMaxListeners;
  13382. }
  13383. if (m && m > 0 && this._events[type].length > m) {
  13384. this._events[type].warned = true;
  13385. console.error('(node) warning: possible EventEmitter memory ' +
  13386. 'leak detected. %d listeners added. ' +
  13387. 'Use emitter.setMaxListeners() to increase limit.',
  13388. this._events[type].length);
  13389. if (typeof console.trace === 'function') {
  13390. // not supported in IE 10
  13391. console.trace();
  13392. }
  13393. }
  13394. }
  13395. return this;
  13396. };
  13397. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13398. EventEmitter.prototype.once = function(type, listener) {
  13399. if (!isFunction(listener))
  13400. throw TypeError('listener must be a function');
  13401. var fired = false;
  13402. function g() {
  13403. this.removeListener(type, g);
  13404. if (!fired) {
  13405. fired = true;
  13406. listener.apply(this, arguments);
  13407. }
  13408. }
  13409. g.listener = listener;
  13410. this.on(type, g);
  13411. return this;
  13412. };
  13413. // emits a 'removeListener' event iff the listener was removed
  13414. EventEmitter.prototype.removeListener = function(type, listener) {
  13415. var list, position, length, i;
  13416. if (!isFunction(listener))
  13417. throw TypeError('listener must be a function');
  13418. if (!this._events || !this._events[type])
  13419. return this;
  13420. list = this._events[type];
  13421. length = list.length;
  13422. position = -1;
  13423. if (list === listener ||
  13424. (isFunction(list.listener) && list.listener === listener)) {
  13425. delete this._events[type];
  13426. if (this._events.removeListener)
  13427. this.emit('removeListener', type, listener);
  13428. } else if (isObject(list)) {
  13429. for (i = length; i-- > 0;) {
  13430. if (list[i] === listener ||
  13431. (list[i].listener && list[i].listener === listener)) {
  13432. position = i;
  13433. break;
  13434. }
  13435. }
  13436. if (position < 0)
  13437. return this;
  13438. if (list.length === 1) {
  13439. list.length = 0;
  13440. delete this._events[type];
  13441. } else {
  13442. list.splice(position, 1);
  13443. }
  13444. if (this._events.removeListener)
  13445. this.emit('removeListener', type, listener);
  13446. }
  13447. return this;
  13448. };
  13449. EventEmitter.prototype.removeAllListeners = function(type) {
  13450. var key, listeners;
  13451. if (!this._events)
  13452. return this;
  13453. // not listening for removeListener, no need to emit
  13454. if (!this._events.removeListener) {
  13455. if (arguments.length === 0)
  13456. this._events = {};
  13457. else if (this._events[type])
  13458. delete this._events[type];
  13459. return this;
  13460. }
  13461. // emit removeListener for all listeners on all events
  13462. if (arguments.length === 0) {
  13463. for (key in this._events) {
  13464. if (key === 'removeListener') continue;
  13465. this.removeAllListeners(key);
  13466. }
  13467. this.removeAllListeners('removeListener');
  13468. this._events = {};
  13469. return this;
  13470. }
  13471. listeners = this._events[type];
  13472. if (isFunction(listeners)) {
  13473. this.removeListener(type, listeners);
  13474. } else {
  13475. // LIFO order
  13476. while (listeners.length)
  13477. this.removeListener(type, listeners[listeners.length - 1]);
  13478. }
  13479. delete this._events[type];
  13480. return this;
  13481. };
  13482. EventEmitter.prototype.listeners = function(type) {
  13483. var ret;
  13484. if (!this._events || !this._events[type])
  13485. ret = [];
  13486. else if (isFunction(this._events[type]))
  13487. ret = [this._events[type]];
  13488. else
  13489. ret = this._events[type].slice();
  13490. return ret;
  13491. };
  13492. EventEmitter.listenerCount = function(emitter, type) {
  13493. var ret;
  13494. if (!emitter._events || !emitter._events[type])
  13495. ret = 0;
  13496. else if (isFunction(emitter._events[type]))
  13497. ret = 1;
  13498. else
  13499. ret = emitter._events[type].length;
  13500. return ret;
  13501. };
  13502. function isFunction(arg) {
  13503. return typeof arg === 'function';
  13504. }
  13505. function isNumber(arg) {
  13506. return typeof arg === 'number';
  13507. }
  13508. function isObject(arg) {
  13509. return typeof arg === 'object' && arg !== null;
  13510. }
  13511. function isUndefined(arg) {
  13512. return arg === void 0;
  13513. }
  13514. },{}],52:[function(require,module,exports){
  13515. /**
  13516. * Slice reference.
  13517. */
  13518. var slice = [].slice;
  13519. /**
  13520. * Bind `obj` to `fn`.
  13521. *
  13522. * @param {Object} obj
  13523. * @param {Function|String} fn or string
  13524. * @return {Function}
  13525. * @api public
  13526. */
  13527. module.exports = function(obj, fn){
  13528. if ('string' == typeof fn) fn = obj[fn];
  13529. if ('function' != typeof fn) throw new Error('bind() requires a function');
  13530. var args = slice.call(arguments, 2);
  13531. return function(){
  13532. return fn.apply(obj, args.concat(slice.call(arguments)));
  13533. }
  13534. };
  13535. },{}],53:[function(require,module,exports){
  13536. /**
  13537. * Expose `Emitter`.
  13538. */
  13539. module.exports = Emitter;
  13540. /**
  13541. * Initialize a new `Emitter`.
  13542. *
  13543. * @api public
  13544. */
  13545. function Emitter(obj) {
  13546. if (obj) return mixin(obj);
  13547. };
  13548. /**
  13549. * Mixin the emitter properties.
  13550. *
  13551. * @param {Object} obj
  13552. * @return {Object}
  13553. * @api private
  13554. */
  13555. function mixin(obj) {
  13556. for (var key in Emitter.prototype) {
  13557. obj[key] = Emitter.prototype[key];
  13558. }
  13559. return obj;
  13560. }
  13561. /**
  13562. * Listen on the given `event` with `fn`.
  13563. *
  13564. * @param {String} event
  13565. * @param {Function} fn
  13566. * @return {Emitter}
  13567. * @api public
  13568. */
  13569. Emitter.prototype.on =
  13570. Emitter.prototype.addEventListener = function(event, fn){
  13571. this._callbacks = this._callbacks || {};
  13572. (this._callbacks[event] = this._callbacks[event] || [])
  13573. .push(fn);
  13574. return this;
  13575. };
  13576. /**
  13577. * Adds an `event` listener that will be invoked a single
  13578. * time then automatically removed.
  13579. *
  13580. * @param {String} event
  13581. * @param {Function} fn
  13582. * @return {Emitter}
  13583. * @api public
  13584. */
  13585. Emitter.prototype.once = function(event, fn){
  13586. var self = this;
  13587. this._callbacks = this._callbacks || {};
  13588. function on() {
  13589. self.off(event, on);
  13590. fn.apply(this, arguments);
  13591. }
  13592. on.fn = fn;
  13593. this.on(event, on);
  13594. return this;
  13595. };
  13596. /**
  13597. * Remove the given callback for `event` or all
  13598. * registered callbacks.
  13599. *
  13600. * @param {String} event
  13601. * @param {Function} fn
  13602. * @return {Emitter}
  13603. * @api public
  13604. */
  13605. Emitter.prototype.off =
  13606. Emitter.prototype.removeListener =
  13607. Emitter.prototype.removeAllListeners =
  13608. Emitter.prototype.removeEventListener = function(event, fn){
  13609. this._callbacks = this._callbacks || {};
  13610. // all
  13611. if (0 == arguments.length) {
  13612. this._callbacks = {};
  13613. return this;
  13614. }
  13615. // specific event
  13616. var callbacks = this._callbacks[event];
  13617. if (!callbacks) return this;
  13618. // remove all handlers
  13619. if (1 == arguments.length) {
  13620. delete this._callbacks[event];
  13621. return this;
  13622. }
  13623. // remove specific handler
  13624. var cb;
  13625. for (var i = 0; i < callbacks.length; i++) {
  13626. cb = callbacks[i];
  13627. if (cb === fn || cb.fn === fn) {
  13628. callbacks.splice(i, 1);
  13629. break;
  13630. }
  13631. }
  13632. return this;
  13633. };
  13634. /**
  13635. * Emit `event` with the given args.
  13636. *
  13637. * @param {String} event
  13638. * @param {Mixed} ...
  13639. * @return {Emitter}
  13640. */
  13641. Emitter.prototype.emit = function(event){
  13642. this._callbacks = this._callbacks || {};
  13643. var args = [].slice.call(arguments, 1)
  13644. , callbacks = this._callbacks[event];
  13645. if (callbacks) {
  13646. callbacks = callbacks.slice(0);
  13647. for (var i = 0, len = callbacks.length; i < len; ++i) {
  13648. callbacks[i].apply(this, args);
  13649. }
  13650. }
  13651. return this;
  13652. };
  13653. /**
  13654. * Return array of callbacks for `event`.
  13655. *
  13656. * @param {String} event
  13657. * @return {Array}
  13658. * @api public
  13659. */
  13660. Emitter.prototype.listeners = function(event){
  13661. this._callbacks = this._callbacks || {};
  13662. return this._callbacks[event] || [];
  13663. };
  13664. /**
  13665. * Check if this emitter has `event` handlers.
  13666. *
  13667. * @param {String} event
  13668. * @return {Boolean}
  13669. * @api public
  13670. */
  13671. Emitter.prototype.hasListeners = function(event){
  13672. return !! this.listeners(event).length;
  13673. };
  13674. },{}],54:[function(require,module,exports){
  13675. module.exports = function(a, b){
  13676. var fn = function(){};
  13677. fn.prototype = b.prototype;
  13678. a.prototype = new fn;
  13679. a.prototype.constructor = a;
  13680. };
  13681. },{}],55:[function(require,module,exports){
  13682. /**
  13683. * Expose `debug()` as the module.
  13684. */
  13685. module.exports = debug;
  13686. /**
  13687. * Create a debugger with the given `name`.
  13688. *
  13689. * @param {String} name
  13690. * @return {Type}
  13691. * @api public
  13692. */
  13693. function debug(name) {
  13694. if (!debug.enabled(name)) return function(){};
  13695. return function(fmt){
  13696. fmt = coerce(fmt);
  13697. var curr = new Date;
  13698. var ms = curr - (debug[name] || curr);
  13699. debug[name] = curr;
  13700. fmt = name
  13701. + ' '
  13702. + fmt
  13703. + ' +' + debug.humanize(ms);
  13704. // This hackery is required for IE8
  13705. // where `console.log` doesn't have 'apply'
  13706. window.console
  13707. && console.log
  13708. && Function.prototype.apply.call(console.log, console, arguments);
  13709. }
  13710. }
  13711. /**
  13712. * The currently active debug mode names.
  13713. */
  13714. debug.names = [];
  13715. debug.skips = [];
  13716. /**
  13717. * Enables a debug mode by name. This can include modes
  13718. * separated by a colon and wildcards.
  13719. *
  13720. * @param {String} name
  13721. * @api public
  13722. */
  13723. debug.enable = function(name) {
  13724. try {
  13725. localStorage.debug = name;
  13726. } catch(e){}
  13727. var split = (name || '').split(/[\s,]+/)
  13728. , len = split.length;
  13729. for (var i = 0; i < len; i++) {
  13730. name = split[i].replace('*', '.*?');
  13731. if (name[0] === '-') {
  13732. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  13733. }
  13734. else {
  13735. debug.names.push(new RegExp('^' + name + '$'));
  13736. }
  13737. }
  13738. };
  13739. /**
  13740. * Disable debug output.
  13741. *
  13742. * @api public
  13743. */
  13744. debug.disable = function(){
  13745. debug.enable('');
  13746. };
  13747. /**
  13748. * Humanize the given `ms`.
  13749. *
  13750. * @param {Number} m
  13751. * @return {String}
  13752. * @api private
  13753. */
  13754. debug.humanize = function(ms) {
  13755. var sec = 1000
  13756. , min = 60 * 1000
  13757. , hour = 60 * min;
  13758. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  13759. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  13760. if (ms >= sec) return (ms / sec | 0) + 's';
  13761. return ms + 'ms';
  13762. };
  13763. /**
  13764. * Returns true if the given mode name is enabled, false otherwise.
  13765. *
  13766. * @param {String} name
  13767. * @return {Boolean}
  13768. * @api public
  13769. */
  13770. debug.enabled = function(name) {
  13771. for (var i = 0, len = debug.skips.length; i < len; i++) {
  13772. if (debug.skips[i].test(name)) {
  13773. return false;
  13774. }
  13775. }
  13776. for (var i = 0, len = debug.names.length; i < len; i++) {
  13777. if (debug.names[i].test(name)) {
  13778. return true;
  13779. }
  13780. }
  13781. return false;
  13782. };
  13783. /**
  13784. * Coerce `val`.
  13785. */
  13786. function coerce(val) {
  13787. if (val instanceof Error) return val.stack || val.message;
  13788. return val;
  13789. }
  13790. // persist
  13791. try {
  13792. if (window.localStorage) debug.enable(localStorage.debug);
  13793. } catch(e){}
  13794. },{}],56:[function(require,module,exports){
  13795. module.exports = require('./lib/');
  13796. },{"./lib/":57}],57:[function(require,module,exports){
  13797. module.exports = require('./socket');
  13798. /**
  13799. * Exports parser
  13800. *
  13801. * @api public
  13802. *
  13803. */
  13804. module.exports.parser = require('engine.io-parser');
  13805. },{"./socket":58,"engine.io-parser":69}],58:[function(require,module,exports){
  13806. (function (global){
  13807. /**
  13808. * Module dependencies.
  13809. */
  13810. var transports = require('./transports');
  13811. var Emitter = require('component-emitter');
  13812. var debug = require('debug')('engine.io-client:socket');
  13813. var index = require('indexof');
  13814. var parser = require('engine.io-parser');
  13815. var parseuri = require('parseuri');
  13816. var parsejson = require('parsejson');
  13817. var parseqs = require('parseqs');
  13818. /**
  13819. * Module exports.
  13820. */
  13821. module.exports = Socket;
  13822. /**
  13823. * Noop function.
  13824. *
  13825. * @api private
  13826. */
  13827. function noop(){}
  13828. /**
  13829. * Socket constructor.
  13830. *
  13831. * @param {String|Object} uri or options
  13832. * @param {Object} options
  13833. * @api public
  13834. */
  13835. function Socket(uri, opts){
  13836. if (!(this instanceof Socket)) return new Socket(uri, opts);
  13837. opts = opts || {};
  13838. if (uri && 'object' == typeof uri) {
  13839. opts = uri;
  13840. uri = null;
  13841. }
  13842. if (uri) {
  13843. uri = parseuri(uri);
  13844. opts.host = uri.host;
  13845. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  13846. opts.port = uri.port;
  13847. if (uri.query) opts.query = uri.query;
  13848. }
  13849. this.secure = null != opts.secure ? opts.secure :
  13850. (global.location && 'https:' == location.protocol);
  13851. if (opts.host) {
  13852. var pieces = opts.host.split(':');
  13853. opts.hostname = pieces.shift();
  13854. if (pieces.length) {
  13855. opts.port = pieces.pop();
  13856. } else if (!opts.port) {
  13857. // if no port is specified manually, use the protocol default
  13858. opts.port = this.secure ? '443' : '80';
  13859. }
  13860. }
  13861. this.agent = opts.agent || false;
  13862. this.hostname = opts.hostname ||
  13863. (global.location ? location.hostname : 'localhost');
  13864. this.port = opts.port || (global.location && location.port ?
  13865. location.port :
  13866. (this.secure ? 443 : 80));
  13867. this.query = opts.query || {};
  13868. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  13869. this.upgrade = false !== opts.upgrade;
  13870. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  13871. this.forceJSONP = !!opts.forceJSONP;
  13872. this.jsonp = false !== opts.jsonp;
  13873. this.forceBase64 = !!opts.forceBase64;
  13874. this.enablesXDR = !!opts.enablesXDR;
  13875. this.timestampParam = opts.timestampParam || 't';
  13876. this.timestampRequests = opts.timestampRequests;
  13877. this.transports = opts.transports || ['polling', 'websocket'];
  13878. this.readyState = '';
  13879. this.writeBuffer = [];
  13880. this.callbackBuffer = [];
  13881. this.policyPort = opts.policyPort || 843;
  13882. this.rememberUpgrade = opts.rememberUpgrade || false;
  13883. this.binaryType = null;
  13884. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  13885. // SSL options for Node.js client
  13886. this.pfx = opts.pfx || null;
  13887. this.key = opts.key || null;
  13888. this.passphrase = opts.passphrase || null;
  13889. this.cert = opts.cert || null;
  13890. this.ca = opts.ca || null;
  13891. this.ciphers = opts.ciphers || null;
  13892. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  13893. this.open();
  13894. }
  13895. Socket.priorWebsocketSuccess = false;
  13896. /**
  13897. * Mix in `Emitter`.
  13898. */
  13899. Emitter(Socket.prototype);
  13900. /**
  13901. * Protocol version.
  13902. *
  13903. * @api public
  13904. */
  13905. Socket.protocol = parser.protocol; // this is an int
  13906. /**
  13907. * Expose deps for legacy compatibility
  13908. * and standalone browser access.
  13909. */
  13910. Socket.Socket = Socket;
  13911. Socket.Transport = require('./transport');
  13912. Socket.transports = require('./transports');
  13913. Socket.parser = require('engine.io-parser');
  13914. /**
  13915. * Creates transport of the given type.
  13916. *
  13917. * @param {String} transport name
  13918. * @return {Transport}
  13919. * @api private
  13920. */
  13921. Socket.prototype.createTransport = function (name) {
  13922. debug('creating transport "%s"', name);
  13923. var query = clone(this.query);
  13924. // append engine.io protocol identifier
  13925. query.EIO = parser.protocol;
  13926. // transport name
  13927. query.transport = name;
  13928. // session id if we already have one
  13929. if (this.id) query.sid = this.id;
  13930. var transport = new transports[name]({
  13931. agent: this.agent,
  13932. hostname: this.hostname,
  13933. port: this.port,
  13934. secure: this.secure,
  13935. path: this.path,
  13936. query: query,
  13937. forceJSONP: this.forceJSONP,
  13938. jsonp: this.jsonp,
  13939. forceBase64: this.forceBase64,
  13940. enablesXDR: this.enablesXDR,
  13941. timestampRequests: this.timestampRequests,
  13942. timestampParam: this.timestampParam,
  13943. policyPort: this.policyPort,
  13944. socket: this,
  13945. pfx: this.pfx,
  13946. key: this.key,
  13947. passphrase: this.passphrase,
  13948. cert: this.cert,
  13949. ca: this.ca,
  13950. ciphers: this.ciphers,
  13951. rejectUnauthorized: this.rejectUnauthorized
  13952. });
  13953. return transport;
  13954. };
  13955. function clone (obj) {
  13956. var o = {};
  13957. for (var i in obj) {
  13958. if (obj.hasOwnProperty(i)) {
  13959. o[i] = obj[i];
  13960. }
  13961. }
  13962. return o;
  13963. }
  13964. /**
  13965. * Initializes transport to use and starts probe.
  13966. *
  13967. * @api private
  13968. */
  13969. Socket.prototype.open = function () {
  13970. var transport;
  13971. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  13972. transport = 'websocket';
  13973. } else if (0 == this.transports.length) {
  13974. // Emit error on next tick so it can be listened to
  13975. var self = this;
  13976. setTimeout(function() {
  13977. self.emit('error', 'No transports available');
  13978. }, 0);
  13979. return;
  13980. } else {
  13981. transport = this.transports[0];
  13982. }
  13983. this.readyState = 'opening';
  13984. // Retry with the next transport if the transport is disabled (jsonp: false)
  13985. var transport;
  13986. try {
  13987. transport = this.createTransport(transport);
  13988. } catch (e) {
  13989. this.transports.shift();
  13990. this.open();
  13991. return;
  13992. }
  13993. transport.open();
  13994. this.setTransport(transport);
  13995. };
  13996. /**
  13997. * Sets the current transport. Disables the existing one (if any).
  13998. *
  13999. * @api private
  14000. */
  14001. Socket.prototype.setTransport = function(transport){
  14002. debug('setting transport %s', transport.name);
  14003. var self = this;
  14004. if (this.transport) {
  14005. debug('clearing existing transport %s', this.transport.name);
  14006. this.transport.removeAllListeners();
  14007. }
  14008. // set up transport
  14009. this.transport = transport;
  14010. // set up transport listeners
  14011. transport
  14012. .on('drain', function(){
  14013. self.onDrain();
  14014. })
  14015. .on('packet', function(packet){
  14016. self.onPacket(packet);
  14017. })
  14018. .on('error', function(e){
  14019. self.onError(e);
  14020. })
  14021. .on('close', function(){
  14022. self.onClose('transport close');
  14023. });
  14024. };
  14025. /**
  14026. * Probes a transport.
  14027. *
  14028. * @param {String} transport name
  14029. * @api private
  14030. */
  14031. Socket.prototype.probe = function (name) {
  14032. debug('probing transport "%s"', name);
  14033. var transport = this.createTransport(name, { probe: 1 })
  14034. , failed = false
  14035. , self = this;
  14036. Socket.priorWebsocketSuccess = false;
  14037. function onTransportOpen(){
  14038. if (self.onlyBinaryUpgrades) {
  14039. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  14040. failed = failed || upgradeLosesBinary;
  14041. }
  14042. if (failed) return;
  14043. debug('probe transport "%s" opened', name);
  14044. transport.send([{ type: 'ping', data: 'probe' }]);
  14045. transport.once('packet', function (msg) {
  14046. if (failed) return;
  14047. if ('pong' == msg.type && 'probe' == msg.data) {
  14048. debug('probe transport "%s" pong', name);
  14049. self.upgrading = true;
  14050. self.emit('upgrading', transport);
  14051. if (!transport) return;
  14052. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  14053. debug('pausing current transport "%s"', self.transport.name);
  14054. self.transport.pause(function () {
  14055. if (failed) return;
  14056. if ('closed' == self.readyState) return;
  14057. debug('changing transport and sending upgrade packet');
  14058. cleanup();
  14059. self.setTransport(transport);
  14060. transport.send([{ type: 'upgrade' }]);
  14061. self.emit('upgrade', transport);
  14062. transport = null;
  14063. self.upgrading = false;
  14064. self.flush();
  14065. });
  14066. } else {
  14067. debug('probe transport "%s" failed', name);
  14068. var err = new Error('probe error');
  14069. err.transport = transport.name;
  14070. self.emit('upgradeError', err);
  14071. }
  14072. });
  14073. }
  14074. function freezeTransport() {
  14075. if (failed) return;
  14076. // Any callback called by transport should be ignored since now
  14077. failed = true;
  14078. cleanup();
  14079. transport.close();
  14080. transport = null;
  14081. }
  14082. //Handle any error that happens while probing
  14083. function onerror(err) {
  14084. var error = new Error('probe error: ' + err);
  14085. error.transport = transport.name;
  14086. freezeTransport();
  14087. debug('probe transport "%s" failed because of error: %s', name, err);
  14088. self.emit('upgradeError', error);
  14089. }
  14090. function onTransportClose(){
  14091. onerror("transport closed");
  14092. }
  14093. //When the socket is closed while we're probing
  14094. function onclose(){
  14095. onerror("socket closed");
  14096. }
  14097. //When the socket is upgraded while we're probing
  14098. function onupgrade(to){
  14099. if (transport && to.name != transport.name) {
  14100. debug('"%s" works - aborting "%s"', to.name, transport.name);
  14101. freezeTransport();
  14102. }
  14103. }
  14104. //Remove all listeners on the transport and on self
  14105. function cleanup(){
  14106. transport.removeListener('open', onTransportOpen);
  14107. transport.removeListener('error', onerror);
  14108. transport.removeListener('close', onTransportClose);
  14109. self.removeListener('close', onclose);
  14110. self.removeListener('upgrading', onupgrade);
  14111. }
  14112. transport.once('open', onTransportOpen);
  14113. transport.once('error', onerror);
  14114. transport.once('close', onTransportClose);
  14115. this.once('close', onclose);
  14116. this.once('upgrading', onupgrade);
  14117. transport.open();
  14118. };
  14119. /**
  14120. * Called when connection is deemed open.
  14121. *
  14122. * @api public
  14123. */
  14124. Socket.prototype.onOpen = function () {
  14125. debug('socket open');
  14126. this.readyState = 'open';
  14127. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  14128. this.emit('open');
  14129. this.flush();
  14130. // we check for `readyState` in case an `open`
  14131. // listener already closed the socket
  14132. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  14133. debug('starting upgrade probes');
  14134. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  14135. this.probe(this.upgrades[i]);
  14136. }
  14137. }
  14138. };
  14139. /**
  14140. * Handles a packet.
  14141. *
  14142. * @api private
  14143. */
  14144. Socket.prototype.onPacket = function (packet) {
  14145. if ('opening' == this.readyState || 'open' == this.readyState) {
  14146. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  14147. this.emit('packet', packet);
  14148. // Socket is live - any packet counts
  14149. this.emit('heartbeat');
  14150. switch (packet.type) {
  14151. case 'open':
  14152. this.onHandshake(parsejson(packet.data));
  14153. break;
  14154. case 'pong':
  14155. this.setPing();
  14156. break;
  14157. case 'error':
  14158. var err = new Error('server error');
  14159. err.code = packet.data;
  14160. this.emit('error', err);
  14161. break;
  14162. case 'message':
  14163. this.emit('data', packet.data);
  14164. this.emit('message', packet.data);
  14165. break;
  14166. }
  14167. } else {
  14168. debug('packet received with socket readyState "%s"', this.readyState);
  14169. }
  14170. };
  14171. /**
  14172. * Called upon handshake completion.
  14173. *
  14174. * @param {Object} handshake obj
  14175. * @api private
  14176. */
  14177. Socket.prototype.onHandshake = function (data) {
  14178. this.emit('handshake', data);
  14179. this.id = data.sid;
  14180. this.transport.query.sid = data.sid;
  14181. this.upgrades = this.filterUpgrades(data.upgrades);
  14182. this.pingInterval = data.pingInterval;
  14183. this.pingTimeout = data.pingTimeout;
  14184. this.onOpen();
  14185. // In case open handler closes socket
  14186. if ('closed' == this.readyState) return;
  14187. this.setPing();
  14188. // Prolong liveness of socket on heartbeat
  14189. this.removeListener('heartbeat', this.onHeartbeat);
  14190. this.on('heartbeat', this.onHeartbeat);
  14191. };
  14192. /**
  14193. * Resets ping timeout.
  14194. *
  14195. * @api private
  14196. */
  14197. Socket.prototype.onHeartbeat = function (timeout) {
  14198. clearTimeout(this.pingTimeoutTimer);
  14199. var self = this;
  14200. self.pingTimeoutTimer = setTimeout(function () {
  14201. if ('closed' == self.readyState) return;
  14202. self.onClose('ping timeout');
  14203. }, timeout || (self.pingInterval + self.pingTimeout));
  14204. };
  14205. /**
  14206. * Pings server every `this.pingInterval` and expects response
  14207. * within `this.pingTimeout` or closes connection.
  14208. *
  14209. * @api private
  14210. */
  14211. Socket.prototype.setPing = function () {
  14212. var self = this;
  14213. clearTimeout(self.pingIntervalTimer);
  14214. self.pingIntervalTimer = setTimeout(function () {
  14215. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  14216. self.ping();
  14217. self.onHeartbeat(self.pingTimeout);
  14218. }, self.pingInterval);
  14219. };
  14220. /**
  14221. * Sends a ping packet.
  14222. *
  14223. * @api public
  14224. */
  14225. Socket.prototype.ping = function () {
  14226. this.sendPacket('ping');
  14227. };
  14228. /**
  14229. * Called on `drain` event
  14230. *
  14231. * @api private
  14232. */
  14233. Socket.prototype.onDrain = function() {
  14234. for (var i = 0; i < this.prevBufferLen; i++) {
  14235. if (this.callbackBuffer[i]) {
  14236. this.callbackBuffer[i]();
  14237. }
  14238. }
  14239. this.writeBuffer.splice(0, this.prevBufferLen);
  14240. this.callbackBuffer.splice(0, this.prevBufferLen);
  14241. // setting prevBufferLen = 0 is very important
  14242. // for example, when upgrading, upgrade packet is sent over,
  14243. // and a nonzero prevBufferLen could cause problems on `drain`
  14244. this.prevBufferLen = 0;
  14245. if (this.writeBuffer.length == 0) {
  14246. this.emit('drain');
  14247. } else {
  14248. this.flush();
  14249. }
  14250. };
  14251. /**
  14252. * Flush write buffers.
  14253. *
  14254. * @api private
  14255. */
  14256. Socket.prototype.flush = function () {
  14257. if ('closed' != this.readyState && this.transport.writable &&
  14258. !this.upgrading && this.writeBuffer.length) {
  14259. debug('flushing %d packets in socket', this.writeBuffer.length);
  14260. this.transport.send(this.writeBuffer);
  14261. // keep track of current length of writeBuffer
  14262. // splice writeBuffer and callbackBuffer on `drain`
  14263. this.prevBufferLen = this.writeBuffer.length;
  14264. this.emit('flush');
  14265. }
  14266. };
  14267. /**
  14268. * Sends a message.
  14269. *
  14270. * @param {String} message.
  14271. * @param {Function} callback function.
  14272. * @return {Socket} for chaining.
  14273. * @api public
  14274. */
  14275. Socket.prototype.write =
  14276. Socket.prototype.send = function (msg, fn) {
  14277. this.sendPacket('message', msg, fn);
  14278. return this;
  14279. };
  14280. /**
  14281. * Sends a packet.
  14282. *
  14283. * @param {String} packet type.
  14284. * @param {String} data.
  14285. * @param {Function} callback function.
  14286. * @api private
  14287. */
  14288. Socket.prototype.sendPacket = function (type, data, fn) {
  14289. if ('closing' == this.readyState || 'closed' == this.readyState) {
  14290. return;
  14291. }
  14292. var packet = { type: type, data: data };
  14293. this.emit('packetCreate', packet);
  14294. this.writeBuffer.push(packet);
  14295. this.callbackBuffer.push(fn);
  14296. this.flush();
  14297. };
  14298. /**
  14299. * Closes the connection.
  14300. *
  14301. * @api private
  14302. */
  14303. Socket.prototype.close = function () {
  14304. if ('opening' == this.readyState || 'open' == this.readyState) {
  14305. this.readyState = 'closing';
  14306. var self = this;
  14307. function close() {
  14308. self.onClose('forced close');
  14309. debug('socket closing - telling transport to close');
  14310. self.transport.close();
  14311. }
  14312. function cleanupAndClose() {
  14313. self.removeListener('upgrade', cleanupAndClose);
  14314. self.removeListener('upgradeError', cleanupAndClose);
  14315. close();
  14316. }
  14317. function waitForUpgrade() {
  14318. // wait for upgrade to finish since we can't send packets while pausing a transport
  14319. self.once('upgrade', cleanupAndClose);
  14320. self.once('upgradeError', cleanupAndClose);
  14321. }
  14322. if (this.writeBuffer.length) {
  14323. this.once('drain', function() {
  14324. if (this.upgrading) {
  14325. waitForUpgrade();
  14326. } else {
  14327. close();
  14328. }
  14329. });
  14330. } else if (this.upgrading) {
  14331. waitForUpgrade();
  14332. } else {
  14333. close();
  14334. }
  14335. }
  14336. return this;
  14337. };
  14338. /**
  14339. * Called upon transport error
  14340. *
  14341. * @api private
  14342. */
  14343. Socket.prototype.onError = function (err) {
  14344. debug('socket error %j', err);
  14345. Socket.priorWebsocketSuccess = false;
  14346. this.emit('error', err);
  14347. this.onClose('transport error', err);
  14348. };
  14349. /**
  14350. * Called upon transport close.
  14351. *
  14352. * @api private
  14353. */
  14354. Socket.prototype.onClose = function (reason, desc) {
  14355. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  14356. debug('socket close with reason: "%s"', reason);
  14357. var self = this;
  14358. // clear timers
  14359. clearTimeout(this.pingIntervalTimer);
  14360. clearTimeout(this.pingTimeoutTimer);
  14361. // clean buffers in next tick, so developers can still
  14362. // grab the buffers on `close` event
  14363. setTimeout(function() {
  14364. self.writeBuffer = [];
  14365. self.callbackBuffer = [];
  14366. self.prevBufferLen = 0;
  14367. }, 0);
  14368. // stop event from firing again for transport
  14369. this.transport.removeAllListeners('close');
  14370. // ensure transport won't stay open
  14371. this.transport.close();
  14372. // ignore further transport communication
  14373. this.transport.removeAllListeners();
  14374. // set ready state
  14375. this.readyState = 'closed';
  14376. // clear session id
  14377. this.id = null;
  14378. // emit close event
  14379. this.emit('close', reason, desc);
  14380. }
  14381. };
  14382. /**
  14383. * Filters upgrades, returning only those matching client transports.
  14384. *
  14385. * @param {Array} server upgrades
  14386. * @api private
  14387. *
  14388. */
  14389. Socket.prototype.filterUpgrades = function (upgrades) {
  14390. var filteredUpgrades = [];
  14391. for (var i = 0, j = upgrades.length; i<j; i++) {
  14392. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  14393. }
  14394. return filteredUpgrades;
  14395. };
  14396. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14397. },{"./transport":59,"./transports":60,"component-emitter":53,"debug":66,"engine.io-parser":69,"indexof":76,"parsejson":100,"parseqs":101,"parseuri":68}],59:[function(require,module,exports){
  14398. /**
  14399. * Module dependencies.
  14400. */
  14401. var parser = require('engine.io-parser');
  14402. var Emitter = require('component-emitter');
  14403. /**
  14404. * Module exports.
  14405. */
  14406. module.exports = Transport;
  14407. /**
  14408. * Transport abstract constructor.
  14409. *
  14410. * @param {Object} options.
  14411. * @api private
  14412. */
  14413. function Transport (opts) {
  14414. this.path = opts.path;
  14415. this.hostname = opts.hostname;
  14416. this.port = opts.port;
  14417. this.secure = opts.secure;
  14418. this.query = opts.query;
  14419. this.timestampParam = opts.timestampParam;
  14420. this.timestampRequests = opts.timestampRequests;
  14421. this.readyState = '';
  14422. this.agent = opts.agent || false;
  14423. this.socket = opts.socket;
  14424. this.enablesXDR = opts.enablesXDR;
  14425. // SSL options for Node.js client
  14426. this.pfx = opts.pfx;
  14427. this.key = opts.key;
  14428. this.passphrase = opts.passphrase;
  14429. this.cert = opts.cert;
  14430. this.ca = opts.ca;
  14431. this.ciphers = opts.ciphers;
  14432. this.rejectUnauthorized = opts.rejectUnauthorized;
  14433. }
  14434. /**
  14435. * Mix in `Emitter`.
  14436. */
  14437. Emitter(Transport.prototype);
  14438. /**
  14439. * A counter used to prevent collisions in the timestamps used
  14440. * for cache busting.
  14441. */
  14442. Transport.timestamps = 0;
  14443. /**
  14444. * Emits an error.
  14445. *
  14446. * @param {String} str
  14447. * @return {Transport} for chaining
  14448. * @api public
  14449. */
  14450. Transport.prototype.onError = function (msg, desc) {
  14451. var err = new Error(msg);
  14452. err.type = 'TransportError';
  14453. err.description = desc;
  14454. this.emit('error', err);
  14455. return this;
  14456. };
  14457. /**
  14458. * Opens the transport.
  14459. *
  14460. * @api public
  14461. */
  14462. Transport.prototype.open = function () {
  14463. if ('closed' == this.readyState || '' == this.readyState) {
  14464. this.readyState = 'opening';
  14465. this.doOpen();
  14466. }
  14467. return this;
  14468. };
  14469. /**
  14470. * Closes the transport.
  14471. *
  14472. * @api private
  14473. */
  14474. Transport.prototype.close = function () {
  14475. if ('opening' == this.readyState || 'open' == this.readyState) {
  14476. this.doClose();
  14477. this.onClose();
  14478. }
  14479. return this;
  14480. };
  14481. /**
  14482. * Sends multiple packets.
  14483. *
  14484. * @param {Array} packets
  14485. * @api private
  14486. */
  14487. Transport.prototype.send = function(packets){
  14488. if ('open' == this.readyState) {
  14489. this.write(packets);
  14490. } else {
  14491. throw new Error('Transport not open');
  14492. }
  14493. };
  14494. /**
  14495. * Called upon open
  14496. *
  14497. * @api private
  14498. */
  14499. Transport.prototype.onOpen = function () {
  14500. this.readyState = 'open';
  14501. this.writable = true;
  14502. this.emit('open');
  14503. };
  14504. /**
  14505. * Called with data.
  14506. *
  14507. * @param {String} data
  14508. * @api private
  14509. */
  14510. Transport.prototype.onData = function(data){
  14511. var packet = parser.decodePacket(data, this.socket.binaryType);
  14512. this.onPacket(packet);
  14513. };
  14514. /**
  14515. * Called with a decoded packet.
  14516. */
  14517. Transport.prototype.onPacket = function (packet) {
  14518. this.emit('packet', packet);
  14519. };
  14520. /**
  14521. * Called upon close.
  14522. *
  14523. * @api private
  14524. */
  14525. Transport.prototype.onClose = function () {
  14526. this.readyState = 'closed';
  14527. this.emit('close');
  14528. };
  14529. },{"component-emitter":53,"engine.io-parser":69}],60:[function(require,module,exports){
  14530. (function (global){
  14531. /**
  14532. * Module dependencies
  14533. */
  14534. var XMLHttpRequest = require('xmlhttprequest');
  14535. var XHR = require('./polling-xhr');
  14536. var JSONP = require('./polling-jsonp');
  14537. var websocket = require('./websocket');
  14538. /**
  14539. * Export transports.
  14540. */
  14541. exports.polling = polling;
  14542. exports.websocket = websocket;
  14543. /**
  14544. * Polling transport polymorphic constructor.
  14545. * Decides on xhr vs jsonp based on feature detection.
  14546. *
  14547. * @api private
  14548. */
  14549. function polling(opts){
  14550. var xhr;
  14551. var xd = false;
  14552. var xs = false;
  14553. var jsonp = false !== opts.jsonp;
  14554. if (global.location) {
  14555. var isSSL = 'https:' == location.protocol;
  14556. var port = location.port;
  14557. // some user agents have empty `location.port`
  14558. if (!port) {
  14559. port = isSSL ? 443 : 80;
  14560. }
  14561. xd = opts.hostname != location.hostname || port != opts.port;
  14562. xs = opts.secure != isSSL;
  14563. }
  14564. opts.xdomain = xd;
  14565. opts.xscheme = xs;
  14566. xhr = new XMLHttpRequest(opts);
  14567. if ('open' in xhr && !opts.forceJSONP) {
  14568. return new XHR(opts);
  14569. } else {
  14570. if (!jsonp) throw new Error('JSONP disabled');
  14571. return new JSONP(opts);
  14572. }
  14573. }
  14574. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14575. },{"./polling-jsonp":61,"./polling-xhr":62,"./websocket":64,"xmlhttprequest":65}],61:[function(require,module,exports){
  14576. (function (global){
  14577. /**
  14578. * Module requirements.
  14579. */
  14580. var Polling = require('./polling');
  14581. var inherit = require('component-inherit');
  14582. /**
  14583. * Module exports.
  14584. */
  14585. module.exports = JSONPPolling;
  14586. /**
  14587. * Cached regular expressions.
  14588. */
  14589. var rNewline = /\n/g;
  14590. var rEscapedNewline = /\\n/g;
  14591. /**
  14592. * Global JSONP callbacks.
  14593. */
  14594. var callbacks;
  14595. /**
  14596. * Callbacks count.
  14597. */
  14598. var index = 0;
  14599. /**
  14600. * Noop.
  14601. */
  14602. function empty () { }
  14603. /**
  14604. * JSONP Polling constructor.
  14605. *
  14606. * @param {Object} opts.
  14607. * @api public
  14608. */
  14609. function JSONPPolling (opts) {
  14610. Polling.call(this, opts);
  14611. this.query = this.query || {};
  14612. // define global callbacks array if not present
  14613. // we do this here (lazily) to avoid unneeded global pollution
  14614. if (!callbacks) {
  14615. // we need to consider multiple engines in the same page
  14616. if (!global.___eio) global.___eio = [];
  14617. callbacks = global.___eio;
  14618. }
  14619. // callback identifier
  14620. this.index = callbacks.length;
  14621. // add callback to jsonp global
  14622. var self = this;
  14623. callbacks.push(function (msg) {
  14624. self.onData(msg);
  14625. });
  14626. // append to query string
  14627. this.query.j = this.index;
  14628. // prevent spurious errors from being emitted when the window is unloaded
  14629. if (global.document && global.addEventListener) {
  14630. global.addEventListener('beforeunload', function () {
  14631. if (self.script) self.script.onerror = empty;
  14632. }, false);
  14633. }
  14634. }
  14635. /**
  14636. * Inherits from Polling.
  14637. */
  14638. inherit(JSONPPolling, Polling);
  14639. /*
  14640. * JSONP only supports binary as base64 encoded strings
  14641. */
  14642. JSONPPolling.prototype.supportsBinary = false;
  14643. /**
  14644. * Closes the socket.
  14645. *
  14646. * @api private
  14647. */
  14648. JSONPPolling.prototype.doClose = function () {
  14649. if (this.script) {
  14650. this.script.parentNode.removeChild(this.script);
  14651. this.script = null;
  14652. }
  14653. if (this.form) {
  14654. this.form.parentNode.removeChild(this.form);
  14655. this.form = null;
  14656. this.iframe = null;
  14657. }
  14658. Polling.prototype.doClose.call(this);
  14659. };
  14660. /**
  14661. * Starts a poll cycle.
  14662. *
  14663. * @api private
  14664. */
  14665. JSONPPolling.prototype.doPoll = function () {
  14666. var self = this;
  14667. var script = document.createElement('script');
  14668. if (this.script) {
  14669. this.script.parentNode.removeChild(this.script);
  14670. this.script = null;
  14671. }
  14672. script.async = true;
  14673. script.src = this.uri();
  14674. script.onerror = function(e){
  14675. self.onError('jsonp poll error',e);
  14676. };
  14677. var insertAt = document.getElementsByTagName('script')[0];
  14678. insertAt.parentNode.insertBefore(script, insertAt);
  14679. this.script = script;
  14680. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  14681. if (isUAgecko) {
  14682. setTimeout(function () {
  14683. var iframe = document.createElement('iframe');
  14684. document.body.appendChild(iframe);
  14685. document.body.removeChild(iframe);
  14686. }, 100);
  14687. }
  14688. };
  14689. /**
  14690. * Writes with a hidden iframe.
  14691. *
  14692. * @param {String} data to send
  14693. * @param {Function} called upon flush.
  14694. * @api private
  14695. */
  14696. JSONPPolling.prototype.doWrite = function (data, fn) {
  14697. var self = this;
  14698. if (!this.form) {
  14699. var form = document.createElement('form');
  14700. var area = document.createElement('textarea');
  14701. var id = this.iframeId = 'eio_iframe_' + this.index;
  14702. var iframe;
  14703. form.className = 'socketio';
  14704. form.style.position = 'absolute';
  14705. form.style.top = '-1000px';
  14706. form.style.left = '-1000px';
  14707. form.target = id;
  14708. form.method = 'POST';
  14709. form.setAttribute('accept-charset', 'utf-8');
  14710. area.name = 'd';
  14711. form.appendChild(area);
  14712. document.body.appendChild(form);
  14713. this.form = form;
  14714. this.area = area;
  14715. }
  14716. this.form.action = this.uri();
  14717. function complete () {
  14718. initIframe();
  14719. fn();
  14720. }
  14721. function initIframe () {
  14722. if (self.iframe) {
  14723. try {
  14724. self.form.removeChild(self.iframe);
  14725. } catch (e) {
  14726. self.onError('jsonp polling iframe removal error', e);
  14727. }
  14728. }
  14729. try {
  14730. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  14731. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  14732. iframe = document.createElement(html);
  14733. } catch (e) {
  14734. iframe = document.createElement('iframe');
  14735. iframe.name = self.iframeId;
  14736. iframe.src = 'javascript:0';
  14737. }
  14738. iframe.id = self.iframeId;
  14739. self.form.appendChild(iframe);
  14740. self.iframe = iframe;
  14741. }
  14742. initIframe();
  14743. // escape \n to prevent it from being converted into \r\n by some UAs
  14744. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  14745. data = data.replace(rEscapedNewline, '\\\n');
  14746. this.area.value = data.replace(rNewline, '\\n');
  14747. try {
  14748. this.form.submit();
  14749. } catch(e) {}
  14750. if (this.iframe.attachEvent) {
  14751. this.iframe.onreadystatechange = function(){
  14752. if (self.iframe.readyState == 'complete') {
  14753. complete();
  14754. }
  14755. };
  14756. } else {
  14757. this.iframe.onload = complete;
  14758. }
  14759. };
  14760. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14761. },{"./polling":63,"component-inherit":54}],62:[function(require,module,exports){
  14762. (function (global){
  14763. /**
  14764. * Module requirements.
  14765. */
  14766. var XMLHttpRequest = require('xmlhttprequest');
  14767. var Polling = require('./polling');
  14768. var Emitter = require('component-emitter');
  14769. var inherit = require('component-inherit');
  14770. var debug = require('debug')('engine.io-client:polling-xhr');
  14771. /**
  14772. * Module exports.
  14773. */
  14774. module.exports = XHR;
  14775. module.exports.Request = Request;
  14776. /**
  14777. * Empty function
  14778. */
  14779. function empty(){}
  14780. /**
  14781. * XHR Polling constructor.
  14782. *
  14783. * @param {Object} opts
  14784. * @api public
  14785. */
  14786. function XHR(opts){
  14787. Polling.call(this, opts);
  14788. if (global.location) {
  14789. var isSSL = 'https:' == location.protocol;
  14790. var port = location.port;
  14791. // some user agents have empty `location.port`
  14792. if (!port) {
  14793. port = isSSL ? 443 : 80;
  14794. }
  14795. this.xd = opts.hostname != global.location.hostname ||
  14796. port != opts.port;
  14797. this.xs = opts.secure != isSSL;
  14798. }
  14799. }
  14800. /**
  14801. * Inherits from Polling.
  14802. */
  14803. inherit(XHR, Polling);
  14804. /**
  14805. * XHR supports binary
  14806. */
  14807. XHR.prototype.supportsBinary = true;
  14808. /**
  14809. * Creates a request.
  14810. *
  14811. * @param {String} method
  14812. * @api private
  14813. */
  14814. XHR.prototype.request = function(opts){
  14815. opts = opts || {};
  14816. opts.uri = this.uri();
  14817. opts.xd = this.xd;
  14818. opts.xs = this.xs;
  14819. opts.agent = this.agent || false;
  14820. opts.supportsBinary = this.supportsBinary;
  14821. opts.enablesXDR = this.enablesXDR;
  14822. // SSL options for Node.js client
  14823. opts.pfx = this.pfx;
  14824. opts.key = this.key;
  14825. opts.passphrase = this.passphrase;
  14826. opts.cert = this.cert;
  14827. opts.ca = this.ca;
  14828. opts.ciphers = this.ciphers;
  14829. opts.rejectUnauthorized = this.rejectUnauthorized;
  14830. return new Request(opts);
  14831. };
  14832. /**
  14833. * Sends data.
  14834. *
  14835. * @param {String} data to send.
  14836. * @param {Function} called upon flush.
  14837. * @api private
  14838. */
  14839. XHR.prototype.doWrite = function(data, fn){
  14840. var isBinary = typeof data !== 'string' && data !== undefined;
  14841. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  14842. var self = this;
  14843. req.on('success', fn);
  14844. req.on('error', function(err){
  14845. self.onError('xhr post error', err);
  14846. });
  14847. this.sendXhr = req;
  14848. };
  14849. /**
  14850. * Starts a poll cycle.
  14851. *
  14852. * @api private
  14853. */
  14854. XHR.prototype.doPoll = function(){
  14855. debug('xhr poll');
  14856. var req = this.request();
  14857. var self = this;
  14858. req.on('data', function(data){
  14859. self.onData(data);
  14860. });
  14861. req.on('error', function(err){
  14862. self.onError('xhr poll error', err);
  14863. });
  14864. this.pollXhr = req;
  14865. };
  14866. /**
  14867. * Request constructor
  14868. *
  14869. * @param {Object} options
  14870. * @api public
  14871. */
  14872. function Request(opts){
  14873. this.method = opts.method || 'GET';
  14874. this.uri = opts.uri;
  14875. this.xd = !!opts.xd;
  14876. this.xs = !!opts.xs;
  14877. this.async = false !== opts.async;
  14878. this.data = undefined != opts.data ? opts.data : null;
  14879. this.agent = opts.agent;
  14880. this.isBinary = opts.isBinary;
  14881. this.supportsBinary = opts.supportsBinary;
  14882. this.enablesXDR = opts.enablesXDR;
  14883. // SSL options for Node.js client
  14884. this.pfx = opts.pfx;
  14885. this.key = opts.key;
  14886. this.passphrase = opts.passphrase;
  14887. this.cert = opts.cert;
  14888. this.ca = opts.ca;
  14889. this.ciphers = opts.ciphers;
  14890. this.rejectUnauthorized = opts.rejectUnauthorized;
  14891. this.create();
  14892. }
  14893. /**
  14894. * Mix in `Emitter`.
  14895. */
  14896. Emitter(Request.prototype);
  14897. /**
  14898. * Creates the XHR object and sends the request.
  14899. *
  14900. * @api private
  14901. */
  14902. Request.prototype.create = function(){
  14903. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  14904. // SSL options for Node.js client
  14905. opts.pfx = this.pfx;
  14906. opts.key = this.key;
  14907. opts.passphrase = this.passphrase;
  14908. opts.cert = this.cert;
  14909. opts.ca = this.ca;
  14910. opts.ciphers = this.ciphers;
  14911. opts.rejectUnauthorized = this.rejectUnauthorized;
  14912. var xhr = this.xhr = new XMLHttpRequest(opts);
  14913. var self = this;
  14914. try {
  14915. debug('xhr open %s: %s', this.method, this.uri);
  14916. xhr.open(this.method, this.uri, this.async);
  14917. if (this.supportsBinary) {
  14918. // This has to be done after open because Firefox is stupid
  14919. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  14920. xhr.responseType = 'arraybuffer';
  14921. }
  14922. if ('POST' == this.method) {
  14923. try {
  14924. if (this.isBinary) {
  14925. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  14926. } else {
  14927. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  14928. }
  14929. } catch (e) {}
  14930. }
  14931. // ie6 check
  14932. if ('withCredentials' in xhr) {
  14933. xhr.withCredentials = true;
  14934. }
  14935. if (this.hasXDR()) {
  14936. xhr.onload = function(){
  14937. self.onLoad();
  14938. };
  14939. xhr.onerror = function(){
  14940. self.onError(xhr.responseText);
  14941. };
  14942. } else {
  14943. xhr.onreadystatechange = function(){
  14944. if (4 != xhr.readyState) return;
  14945. if (200 == xhr.status || 1223 == xhr.status) {
  14946. self.onLoad();
  14947. } else {
  14948. // make sure the `error` event handler that's user-set
  14949. // does not throw in the same tick and gets caught here
  14950. setTimeout(function(){
  14951. self.onError(xhr.status);
  14952. }, 0);
  14953. }
  14954. };
  14955. }
  14956. debug('xhr data %s', this.data);
  14957. xhr.send(this.data);
  14958. } catch (e) {
  14959. // Need to defer since .create() is called directly fhrom the constructor
  14960. // and thus the 'error' event can only be only bound *after* this exception
  14961. // occurs. Therefore, also, we cannot throw here at all.
  14962. setTimeout(function() {
  14963. self.onError(e);
  14964. }, 0);
  14965. return;
  14966. }
  14967. if (global.document) {
  14968. this.index = Request.requestsCount++;
  14969. Request.requests[this.index] = this;
  14970. }
  14971. };
  14972. /**
  14973. * Called upon successful response.
  14974. *
  14975. * @api private
  14976. */
  14977. Request.prototype.onSuccess = function(){
  14978. this.emit('success');
  14979. this.cleanup();
  14980. };
  14981. /**
  14982. * Called if we have data.
  14983. *
  14984. * @api private
  14985. */
  14986. Request.prototype.onData = function(data){
  14987. this.emit('data', data);
  14988. this.onSuccess();
  14989. };
  14990. /**
  14991. * Called upon error.
  14992. *
  14993. * @api private
  14994. */
  14995. Request.prototype.onError = function(err){
  14996. this.emit('error', err);
  14997. this.cleanup(true);
  14998. };
  14999. /**
  15000. * Cleans up house.
  15001. *
  15002. * @api private
  15003. */
  15004. Request.prototype.cleanup = function(fromError){
  15005. if ('undefined' == typeof this.xhr || null === this.xhr) {
  15006. return;
  15007. }
  15008. // xmlhttprequest
  15009. if (this.hasXDR()) {
  15010. this.xhr.onload = this.xhr.onerror = empty;
  15011. } else {
  15012. this.xhr.onreadystatechange = empty;
  15013. }
  15014. if (fromError) {
  15015. try {
  15016. this.xhr.abort();
  15017. } catch(e) {}
  15018. }
  15019. if (global.document) {
  15020. delete Request.requests[this.index];
  15021. }
  15022. this.xhr = null;
  15023. };
  15024. /**
  15025. * Called upon load.
  15026. *
  15027. * @api private
  15028. */
  15029. Request.prototype.onLoad = function(){
  15030. var data;
  15031. try {
  15032. var contentType;
  15033. try {
  15034. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  15035. } catch (e) {}
  15036. if (contentType === 'application/octet-stream') {
  15037. data = this.xhr.response;
  15038. } else {
  15039. if (!this.supportsBinary) {
  15040. data = this.xhr.responseText;
  15041. } else {
  15042. data = 'ok';
  15043. }
  15044. }
  15045. } catch (e) {
  15046. this.onError(e);
  15047. }
  15048. if (null != data) {
  15049. this.onData(data);
  15050. }
  15051. };
  15052. /**
  15053. * Check if it has XDomainRequest.
  15054. *
  15055. * @api private
  15056. */
  15057. Request.prototype.hasXDR = function(){
  15058. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  15059. };
  15060. /**
  15061. * Aborts the request.
  15062. *
  15063. * @api public
  15064. */
  15065. Request.prototype.abort = function(){
  15066. this.cleanup();
  15067. };
  15068. /**
  15069. * Aborts pending requests when unloading the window. This is needed to prevent
  15070. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  15071. * emitted.
  15072. */
  15073. if (global.document) {
  15074. Request.requestsCount = 0;
  15075. Request.requests = {};
  15076. if (global.attachEvent) {
  15077. global.attachEvent('onunload', unloadHandler);
  15078. } else if (global.addEventListener) {
  15079. global.addEventListener('beforeunload', unloadHandler, false);
  15080. }
  15081. }
  15082. function unloadHandler() {
  15083. for (var i in Request.requests) {
  15084. if (Request.requests.hasOwnProperty(i)) {
  15085. Request.requests[i].abort();
  15086. }
  15087. }
  15088. }
  15089. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  15090. },{"./polling":63,"component-emitter":53,"component-inherit":54,"debug":66,"xmlhttprequest":65}],63:[function(require,module,exports){
  15091. /**
  15092. * Module dependencies.
  15093. */
  15094. var Transport = require('../transport');
  15095. var parseqs = require('parseqs');
  15096. var parser = require('engine.io-parser');
  15097. var inherit = require('component-inherit');
  15098. var debug = require('debug')('engine.io-client:polling');
  15099. /**
  15100. * Module exports.
  15101. */
  15102. module.exports = Polling;
  15103. /**
  15104. * Is XHR2 supported?
  15105. */
  15106. var hasXHR2 = (function() {
  15107. var XMLHttpRequest = require('xmlhttprequest');
  15108. var xhr = new XMLHttpRequest({ xdomain: false });
  15109. return null != xhr.responseType;
  15110. })();
  15111. /**
  15112. * Polling interface.
  15113. *
  15114. * @param {Object} opts
  15115. * @api private
  15116. */
  15117. function Polling(opts){
  15118. var forceBase64 = (opts && opts.forceBase64);
  15119. if (!hasXHR2 || forceBase64) {
  15120. this.supportsBinary = false;
  15121. }
  15122. Transport.call(this, opts);
  15123. }
  15124. /**
  15125. * Inherits from Transport.
  15126. */
  15127. inherit(Polling, Transport);
  15128. /**
  15129. * Transport name.
  15130. */
  15131. Polling.prototype.name = 'polling';
  15132. /**
  15133. * Opens the socket (triggers polling). We write a PING message to determine
  15134. * when the transport is open.
  15135. *
  15136. * @api private
  15137. */
  15138. Polling.prototype.doOpen = function(){
  15139. this.poll();
  15140. };
  15141. /**
  15142. * Pauses polling.
  15143. *
  15144. * @param {Function} callback upon buffers are flushed and transport is paused
  15145. * @api private
  15146. */
  15147. Polling.prototype.pause = function(onPause){
  15148. var pending = 0;
  15149. var self = this;
  15150. this.readyState = 'pausing';
  15151. function pause(){
  15152. debug('paused');
  15153. self.readyState = 'paused';
  15154. onPause();
  15155. }
  15156. if (this.polling || !this.writable) {
  15157. var total = 0;
  15158. if (this.polling) {
  15159. debug('we are currently polling - waiting to pause');
  15160. total++;
  15161. this.once('pollComplete', function(){
  15162. debug('pre-pause polling complete');
  15163. --total || pause();
  15164. });
  15165. }
  15166. if (!this.writable) {
  15167. debug('we are currently writing - waiting to pause');
  15168. total++;
  15169. this.once('drain', function(){
  15170. debug('pre-pause writing complete');
  15171. --total || pause();
  15172. });
  15173. }
  15174. } else {
  15175. pause();
  15176. }
  15177. };
  15178. /**
  15179. * Starts polling cycle.
  15180. *
  15181. * @api public
  15182. */
  15183. Polling.prototype.poll = function(){
  15184. debug('polling');
  15185. this.polling = true;
  15186. this.doPoll();
  15187. this.emit('poll');
  15188. };
  15189. /**
  15190. * Overloads onData to detect payloads.
  15191. *
  15192. * @api private
  15193. */
  15194. Polling.prototype.onData = function(data){
  15195. var self = this;
  15196. debug('polling got data %s', data);
  15197. var callback = function(packet, index, total) {
  15198. // if its the first message we consider the transport open
  15199. if ('opening' == self.readyState) {
  15200. self.onOpen();
  15201. }
  15202. // if its a close packet, we close the ongoing requests
  15203. if ('close' == packet.type) {
  15204. self.onClose();
  15205. return false;
  15206. }
  15207. // otherwise bypass onData and handle the message
  15208. self.onPacket(packet);
  15209. };
  15210. // decode payload
  15211. parser.decodePayload(data, this.socket.binaryType, callback);
  15212. // if an event did not trigger closing
  15213. if ('closed' != this.readyState) {
  15214. // if we got data we're not polling
  15215. this.polling = false;
  15216. this.emit('pollComplete');
  15217. if ('open' == this.readyState) {
  15218. this.poll();
  15219. } else {
  15220. debug('ignoring poll - transport state "%s"', this.readyState);
  15221. }
  15222. }
  15223. };
  15224. /**
  15225. * For polling, send a close packet.
  15226. *
  15227. * @api private
  15228. */
  15229. Polling.prototype.doClose = function(){
  15230. var self = this;
  15231. function close(){
  15232. debug('writing close packet');
  15233. self.write([{ type: 'close' }]);
  15234. }
  15235. if ('open' == this.readyState) {
  15236. debug('transport open - closing');
  15237. close();
  15238. } else {
  15239. // in case we're trying to close while
  15240. // handshaking is in progress (GH-164)
  15241. debug('transport not open - deferring close');
  15242. this.once('open', close);
  15243. }
  15244. };
  15245. /**
  15246. * Writes a packets payload.
  15247. *
  15248. * @param {Array} data packets
  15249. * @param {Function} drain callback
  15250. * @api private
  15251. */
  15252. Polling.prototype.write = function(packets){
  15253. var self = this;
  15254. this.writable = false;
  15255. var callbackfn = function() {
  15256. self.writable = true;
  15257. self.emit('drain');
  15258. };
  15259. var self = this;
  15260. parser.encodePayload(packets, this.supportsBinary, function(data) {
  15261. self.doWrite(data, callbackfn);
  15262. });
  15263. };
  15264. /**
  15265. * Generates uri for connection.
  15266. *
  15267. * @api private
  15268. */
  15269. Polling.prototype.uri = function(){
  15270. var query = this.query || {};
  15271. var schema = this.secure ? 'https' : 'http';
  15272. var port = '';
  15273. // cache busting is forced
  15274. if (false !== this.timestampRequests) {
  15275. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  15276. }
  15277. if (!this.supportsBinary && !query.sid) {
  15278. query.b64 = 1;
  15279. }
  15280. query = parseqs.encode(query);
  15281. // avoid port if default for schema
  15282. if (this.port && (('https' == schema && this.port != 443) ||
  15283. ('http' == schema && this.port != 80))) {
  15284. port = ':' + this.port;
  15285. }
  15286. // prepend ? to query
  15287. if (query.length) {
  15288. query = '?' + query;
  15289. }
  15290. return schema + '://' + this.hostname + port + this.path + query;
  15291. };
  15292. },{"../transport":59,"component-inherit":54,"debug":66,"engine.io-parser":69,"parseqs":101,"xmlhttprequest":65}],64:[function(require,module,exports){
  15293. /**
  15294. * Module dependencies.
  15295. */
  15296. var Transport = require('../transport');
  15297. var parser = require('engine.io-parser');
  15298. var parseqs = require('parseqs');
  15299. var inherit = require('component-inherit');
  15300. var debug = require('debug')('engine.io-client:websocket');
  15301. /**
  15302. * `ws` exposes a WebSocket-compatible interface in
  15303. * Node, or the `WebSocket` or `MozWebSocket` globals
  15304. * in the browser.
  15305. */
  15306. var WebSocket = require('ws');
  15307. /**
  15308. * Module exports.
  15309. */
  15310. module.exports = WS;
  15311. /**
  15312. * WebSocket transport constructor.
  15313. *
  15314. * @api {Object} connection options
  15315. * @api public
  15316. */
  15317. function WS(opts){
  15318. var forceBase64 = (opts && opts.forceBase64);
  15319. if (forceBase64) {
  15320. this.supportsBinary = false;
  15321. }
  15322. Transport.call(this, opts);
  15323. }
  15324. /**
  15325. * Inherits from Transport.
  15326. */
  15327. inherit(WS, Transport);
  15328. /**
  15329. * Transport name.
  15330. *
  15331. * @api public
  15332. */
  15333. WS.prototype.name = 'websocket';
  15334. /*
  15335. * WebSockets support binary
  15336. */
  15337. WS.prototype.supportsBinary = true;
  15338. /**
  15339. * Opens socket.
  15340. *
  15341. * @api private
  15342. */
  15343. WS.prototype.doOpen = function(){
  15344. if (!this.check()) {
  15345. // let probe timeout
  15346. return;
  15347. }
  15348. var self = this;
  15349. var uri = this.uri();
  15350. var protocols = void(0);
  15351. var opts = { agent: this.agent };
  15352. // SSL options for Node.js client
  15353. opts.pfx = this.pfx;
  15354. opts.key = this.key;
  15355. opts.passphrase = this.passphrase;
  15356. opts.cert = this.cert;
  15357. opts.ca = this.ca;
  15358. opts.ciphers = this.ciphers;
  15359. opts.rejectUnauthorized = this.rejectUnauthorized;
  15360. this.ws = new WebSocket(uri, protocols, opts);
  15361. if (this.ws.binaryType === undefined) {
  15362. this.supportsBinary = false;
  15363. }
  15364. this.ws.binaryType = 'arraybuffer';
  15365. this.addEventListeners();
  15366. };
  15367. /**
  15368. * Adds event listeners to the socket
  15369. *
  15370. * @api private
  15371. */
  15372. WS.prototype.addEventListeners = function(){
  15373. var self = this;
  15374. this.ws.onopen = function(){
  15375. self.onOpen();
  15376. };
  15377. this.ws.onclose = function(){
  15378. self.onClose();
  15379. };
  15380. this.ws.onmessage = function(ev){
  15381. self.onData(ev.data);
  15382. };
  15383. this.ws.onerror = function(e){
  15384. self.onError('websocket error', e);
  15385. };
  15386. };
  15387. /**
  15388. * Override `onData` to use a timer on iOS.
  15389. * See: https://gist.github.com/mloughran/2052006
  15390. *
  15391. * @api private
  15392. */
  15393. if ('undefined' != typeof navigator
  15394. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  15395. WS.prototype.onData = function(data){
  15396. var self = this;
  15397. setTimeout(function(){
  15398. Transport.prototype.onData.call(self, data);
  15399. }, 0);
  15400. };
  15401. }
  15402. /**
  15403. * Writes data to socket.
  15404. *
  15405. * @param {Array} array of packets.
  15406. * @api private
  15407. */
  15408. WS.prototype.write = function(packets){
  15409. var self = this;
  15410. this.writable = false;
  15411. // encodePacket efficient as it uses WS framing
  15412. // no need for encodePayload
  15413. for (var i = 0, l = packets.length; i < l; i++) {
  15414. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  15415. //Sometimes the websocket has already been closed but the browser didn't
  15416. //have a chance of informing us about it yet, in that case send will
  15417. //throw an error
  15418. try {
  15419. self.ws.send(data);
  15420. } catch (e){
  15421. debug('websocket closed before onclose event');
  15422. }
  15423. });
  15424. }
  15425. function ondrain() {
  15426. self.writable = true;
  15427. self.emit('drain');
  15428. }
  15429. // fake drain
  15430. // defer to next tick to allow Socket to clear writeBuffer
  15431. setTimeout(ondrain, 0);
  15432. };
  15433. /**
  15434. * Called upon close
  15435. *
  15436. * @api private
  15437. */
  15438. WS.prototype.onClose = function(){
  15439. Transport.prototype.onClose.call(this);
  15440. };
  15441. /**
  15442. * Closes socket.
  15443. *
  15444. * @api private
  15445. */
  15446. WS.prototype.doClose = function(){
  15447. if (typeof this.ws !== 'undefined') {
  15448. this.ws.close();
  15449. }
  15450. };
  15451. /**
  15452. * Generates uri for connection.
  15453. *
  15454. * @api private
  15455. */
  15456. WS.prototype.uri = function(){
  15457. var query = this.query || {};
  15458. var schema = this.secure ? 'wss' : 'ws';
  15459. var port = '';
  15460. // avoid port if default for schema
  15461. if (this.port && (('wss' == schema && this.port != 443)
  15462. || ('ws' == schema && this.port != 80))) {
  15463. port = ':' + this.port;
  15464. }
  15465. // append timestamp to URI
  15466. if (this.timestampRequests) {
  15467. query[this.timestampParam] = +new Date;
  15468. }
  15469. // communicate binary support capabilities
  15470. if (!this.supportsBinary) {
  15471. query.b64 = 1;
  15472. }
  15473. query = parseqs.encode(query);
  15474. // prepend ? to query
  15475. if (query.length) {
  15476. query = '?' + query;
  15477. }
  15478. return schema + '://' + this.hostname + port + this.path + query;
  15479. };
  15480. /**
  15481. * Feature detection for WebSocket.
  15482. *
  15483. * @return {Boolean} whether this transport is available.
  15484. * @api public
  15485. */
  15486. WS.prototype.check = function(){
  15487. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  15488. };
  15489. },{"../transport":59,"component-inherit":54,"debug":66,"engine.io-parser":69,"parseqs":101,"ws":129}],65:[function(require,module,exports){
  15490. // browser shim for xmlhttprequest module
  15491. var hasCORS = require('has-cors');
  15492. module.exports = function(opts) {
  15493. var xdomain = opts.xdomain;
  15494. // scheme must be same when usign XDomainRequest
  15495. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  15496. var xscheme = opts.xscheme;
  15497. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  15498. // https://github.com/Automattic/engine.io-client/pull/217
  15499. var enablesXDR = opts.enablesXDR;
  15500. // XMLHttpRequest can be disabled on IE
  15501. try {
  15502. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  15503. return new XMLHttpRequest();
  15504. }
  15505. } catch (e) { }
  15506. // Use XDomainRequest for IE8 if enablesXDR is true
  15507. // because loading bar keeps flashing when using jsonp-polling
  15508. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  15509. try {
  15510. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  15511. return new XDomainRequest();
  15512. }
  15513. } catch (e) { }
  15514. if (!xdomain) {
  15515. try {
  15516. return new ActiveXObject('Microsoft.XMLHTTP');
  15517. } catch(e) { }
  15518. }
  15519. }
  15520. },{"has-cors":75}],66:[function(require,module,exports){
  15521. /**
  15522. * This is the web browser implementation of `debug()`.
  15523. *
  15524. * Expose `debug()` as the module.
  15525. */
  15526. exports = module.exports = require('./debug');
  15527. exports.log = log;
  15528. exports.formatArgs = formatArgs;
  15529. exports.save = save;
  15530. exports.load = load;
  15531. exports.useColors = useColors;
  15532. /**
  15533. * Colors.
  15534. */
  15535. exports.colors = [
  15536. 'lightseagreen',
  15537. 'forestgreen',
  15538. 'goldenrod',
  15539. 'dodgerblue',
  15540. 'darkorchid',
  15541. 'crimson'
  15542. ];
  15543. /**
  15544. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  15545. * and the Firebug extension (any Firefox version) are known
  15546. * to support "%c" CSS customizations.
  15547. *
  15548. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  15549. */
  15550. function useColors() {
  15551. // is webkit? http://stackoverflow.com/a/16459606/376773
  15552. return ('WebkitAppearance' in document.documentElement.style) ||
  15553. // is firebug? http://stackoverflow.com/a/398120/376773
  15554. (window.console && (console.firebug || (console.exception && console.table))) ||
  15555. // is firefox >= v31?
  15556. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  15557. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  15558. }
  15559. /**
  15560. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  15561. */
  15562. exports.formatters.j = function(v) {
  15563. return JSON.stringify(v);
  15564. };
  15565. /**
  15566. * Colorize log arguments if enabled.
  15567. *
  15568. * @api public
  15569. */
  15570. function formatArgs() {
  15571. var args = arguments;
  15572. var useColors = this.useColors;
  15573. args[0] = (useColors ? '%c' : '')
  15574. + this.namespace
  15575. + (useColors ? ' %c' : ' ')
  15576. + args[0]
  15577. + (useColors ? '%c ' : ' ')
  15578. + '+' + exports.humanize(this.diff);
  15579. if (!useColors) return args;
  15580. var c = 'color: ' + this.color;
  15581. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  15582. // the final "%c" is somewhat tricky, because there could be other
  15583. // arguments passed either before or after the %c, so we need to
  15584. // figure out the correct index to insert the CSS into
  15585. var index = 0;
  15586. var lastC = 0;
  15587. args[0].replace(/%[a-z%]/g, function(match) {
  15588. if ('%%' === match) return;
  15589. index++;
  15590. if ('%c' === match) {
  15591. // we only are interested in the *last* %c
  15592. // (the user may have provided their own)
  15593. lastC = index;
  15594. }
  15595. });
  15596. args.splice(lastC, 0, c);
  15597. return args;
  15598. }
  15599. /**
  15600. * Invokes `console.log()` when available.
  15601. * No-op when `console.log` is not a "function".
  15602. *
  15603. * @api public
  15604. */
  15605. function log() {
  15606. // This hackery is required for IE8,
  15607. // where the `console.log` function doesn't have 'apply'
  15608. return 'object' == typeof console
  15609. && 'function' == typeof console.log
  15610. && Function.prototype.apply.call(console.log, console, arguments);
  15611. }
  15612. /**
  15613. * Save `namespaces`.
  15614. *
  15615. * @param {String} namespaces
  15616. * @api private
  15617. */
  15618. function save(namespaces) {
  15619. try {
  15620. if (null == namespaces) {
  15621. localStorage.removeItem('debug');
  15622. } else {
  15623. localStorage.debug = namespaces;
  15624. }
  15625. } catch(e) {}
  15626. }
  15627. /**
  15628. * Load `namespaces`.
  15629. *
  15630. * @return {String} returns the previously persisted debug modes
  15631. * @api private
  15632. */
  15633. function load() {
  15634. var r;
  15635. try {
  15636. r = localStorage.debug;
  15637. } catch(e) {}
  15638. return r;
  15639. }
  15640. /**
  15641. * Enable namespaces listed in `localStorage.debug` initially.
  15642. */
  15643. exports.enable(load());
  15644. },{"./debug":67}],67:[function(require,module,exports){
  15645. /**
  15646. * This is the common logic for both the Node.js and web browser
  15647. * implementations of `debug()`.
  15648. *
  15649. * Expose `debug()` as the module.
  15650. */
  15651. exports = module.exports = debug;
  15652. exports.coerce = coerce;
  15653. exports.disable = disable;
  15654. exports.enable = enable;
  15655. exports.enabled = enabled;
  15656. exports.humanize = require('ms');
  15657. /**
  15658. * The currently active debug mode names, and names to skip.
  15659. */
  15660. exports.names = [];
  15661. exports.skips = [];
  15662. /**
  15663. * Map of special "%n" handling functions, for the debug "format" argument.
  15664. *
  15665. * Valid key names are a single, lowercased letter, i.e. "n".
  15666. */
  15667. exports.formatters = {};
  15668. /**
  15669. * Previously assigned color.
  15670. */
  15671. var prevColor = 0;
  15672. /**
  15673. * Previous log timestamp.
  15674. */
  15675. var prevTime;
  15676. /**
  15677. * Select a color.
  15678. *
  15679. * @return {Number}
  15680. * @api private
  15681. */
  15682. function selectColor() {
  15683. return exports.colors[prevColor++ % exports.colors.length];
  15684. }
  15685. /**
  15686. * Create a debugger with the given `namespace`.
  15687. *
  15688. * @param {String} namespace
  15689. * @return {Function}
  15690. * @api public
  15691. */
  15692. function debug(namespace) {
  15693. // define the `disabled` version
  15694. function disabled() {
  15695. }
  15696. disabled.enabled = false;
  15697. // define the `enabled` version
  15698. function enabled() {
  15699. var self = enabled;
  15700. // set `diff` timestamp
  15701. var curr = +new Date();
  15702. var ms = curr - (prevTime || curr);
  15703. self.diff = ms;
  15704. self.prev = prevTime;
  15705. self.curr = curr;
  15706. prevTime = curr;
  15707. // add the `color` if not set
  15708. if (null == self.useColors) self.useColors = exports.useColors();
  15709. if (null == self.color && self.useColors) self.color = selectColor();
  15710. var args = Array.prototype.slice.call(arguments);
  15711. args[0] = exports.coerce(args[0]);
  15712. if ('string' !== typeof args[0]) {
  15713. // anything else let's inspect with %o
  15714. args = ['%o'].concat(args);
  15715. }
  15716. // apply any `formatters` transformations
  15717. var index = 0;
  15718. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  15719. // if we encounter an escaped % then don't increase the array index
  15720. if (match === '%%') return match;
  15721. index++;
  15722. var formatter = exports.formatters[format];
  15723. if ('function' === typeof formatter) {
  15724. var val = args[index];
  15725. match = formatter.call(self, val);
  15726. // now we need to remove `args[index]` since it's inlined in the `format`
  15727. args.splice(index, 1);
  15728. index--;
  15729. }
  15730. return match;
  15731. });
  15732. if ('function' === typeof exports.formatArgs) {
  15733. args = exports.formatArgs.apply(self, args);
  15734. }
  15735. var logFn = enabled.log || exports.log || console.log.bind(console);
  15736. logFn.apply(self, args);
  15737. }
  15738. enabled.enabled = true;
  15739. var fn = exports.enabled(namespace) ? enabled : disabled;
  15740. fn.namespace = namespace;
  15741. return fn;
  15742. }
  15743. /**
  15744. * Enables a debug mode by namespaces. This can include modes
  15745. * separated by a colon and wildcards.
  15746. *
  15747. * @param {String} namespaces
  15748. * @api public
  15749. */
  15750. function enable(namespaces) {
  15751. exports.save(namespaces);
  15752. var split = (namespaces || '').split(/[\s,]+/);
  15753. var len = split.length;
  15754. for (var i = 0; i < len; i++) {
  15755. if (!split[i]) continue; // ignore empty strings
  15756. namespaces = split[i].replace(/\*/g, '.*?');
  15757. if (namespaces[0] === '-') {
  15758. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  15759. } else {
  15760. exports.names.push(new RegExp('^' + namespaces + '$'));
  15761. }
  15762. }
  15763. }
  15764. /**
  15765. * Disable debug output.
  15766. *
  15767. * @api public
  15768. */
  15769. function disable() {
  15770. exports.enable('');
  15771. }
  15772. /**
  15773. * Returns true if the given mode name is enabled, false otherwise.
  15774. *
  15775. * @param {String} name
  15776. * @return {Boolean}
  15777. * @api public
  15778. */
  15779. function enabled(name) {
  15780. var i, len;
  15781. for (i = 0, len = exports.skips.length; i < len; i++) {
  15782. if (exports.skips[i].test(name)) {
  15783. return false;
  15784. }
  15785. }
  15786. for (i = 0, len = exports.names.length; i < len; i++) {
  15787. if (exports.names[i].test(name)) {
  15788. return true;
  15789. }
  15790. }
  15791. return false;
  15792. }
  15793. /**
  15794. * Coerce `val`.
  15795. *
  15796. * @param {Mixed} val
  15797. * @return {Mixed}
  15798. * @api private
  15799. */
  15800. function coerce(val) {
  15801. if (val instanceof Error) return val.stack || val.message;
  15802. return val;
  15803. }
  15804. },{"ms":82}],68:[function(require,module,exports){
  15805. /**
  15806. * Parses an URI
  15807. *
  15808. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  15809. * @api private
  15810. */
  15811. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  15812. var parts = [
  15813. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  15814. ];
  15815. module.exports = function parseuri(str) {
  15816. var src = str,
  15817. b = str.indexOf('['),
  15818. e = str.indexOf(']');
  15819. if (b != -1 && e != -1) {
  15820. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  15821. }
  15822. var m = re.exec(str || ''),
  15823. uri = {},
  15824. i = 14;
  15825. while (i--) {
  15826. uri[parts[i]] = m[i] || '';
  15827. }
  15828. if (b != -1 && e != -1) {
  15829. uri.source = src;
  15830. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  15831. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  15832. uri.ipv6uri = true;
  15833. }
  15834. return uri;
  15835. };
  15836. },{}],69:[function(require,module,exports){
  15837. (function (global){
  15838. /**
  15839. * Module dependencies.
  15840. */
  15841. var keys = require('./keys');
  15842. var hasBinary = require('has-binary');
  15843. var sliceBuffer = require('arraybuffer.slice');
  15844. var base64encoder = require('base64-arraybuffer');
  15845. var after = require('after');
  15846. var utf8 = require('utf8');
  15847. /**
  15848. * Check if we are running an android browser. That requires us to use
  15849. * ArrayBuffer with polling transports...
  15850. *
  15851. * http://ghinda.net/jpeg-blob-ajax-android/
  15852. */
  15853. var isAndroid = navigator.userAgent.match(/Android/i);
  15854. /**
  15855. * Check if we are running in PhantomJS.
  15856. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  15857. * https://github.com/ariya/phantomjs/issues/11395
  15858. * @type boolean
  15859. */
  15860. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  15861. /**
  15862. * When true, avoids using Blobs to encode payloads.
  15863. * @type boolean
  15864. */
  15865. var dontSendBlobs = isAndroid || isPhantomJS;
  15866. /**
  15867. * Current protocol version.
  15868. */
  15869. exports.protocol = 3;
  15870. /**
  15871. * Packet types.
  15872. */
  15873. var packets = exports.packets = {
  15874. open: 0 // non-ws
  15875. , close: 1 // non-ws
  15876. , ping: 2
  15877. , pong: 3
  15878. , message: 4
  15879. , upgrade: 5
  15880. , noop: 6
  15881. };
  15882. var packetslist = keys(packets);
  15883. /**
  15884. * Premade error packet.
  15885. */
  15886. var err = { type: 'error', data: 'parser error' };
  15887. /**
  15888. * Create a blob api even for blob builder when vendor prefixes exist
  15889. */
  15890. var Blob = require('blob');
  15891. /**
  15892. * Encodes a packet.
  15893. *
  15894. * <packet type id> [ <data> ]
  15895. *
  15896. * Example:
  15897. *
  15898. * 5hello world
  15899. * 3
  15900. * 4
  15901. *
  15902. * Binary is encoded in an identical principle
  15903. *
  15904. * @api private
  15905. */
  15906. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  15907. if ('function' == typeof supportsBinary) {
  15908. callback = supportsBinary;
  15909. supportsBinary = false;
  15910. }
  15911. if ('function' == typeof utf8encode) {
  15912. callback = utf8encode;
  15913. utf8encode = null;
  15914. }
  15915. var data = (packet.data === undefined)
  15916. ? undefined
  15917. : packet.data.buffer || packet.data;
  15918. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  15919. return encodeArrayBuffer(packet, supportsBinary, callback);
  15920. } else if (Blob && data instanceof global.Blob) {
  15921. return encodeBlob(packet, supportsBinary, callback);
  15922. }
  15923. // might be an object with { base64: true, data: dataAsBase64String }
  15924. if (data && data.base64) {
  15925. return encodeBase64Object(packet, callback);
  15926. }
  15927. // Sending data as a utf-8 string
  15928. var encoded = packets[packet.type];
  15929. // data fragment is optional
  15930. if (undefined !== packet.data) {
  15931. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  15932. }
  15933. return callback('' + encoded);
  15934. };
  15935. function encodeBase64Object(packet, callback) {
  15936. // packet data is an object { base64: true, data: dataAsBase64String }
  15937. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  15938. return callback(message);
  15939. }
  15940. /**
  15941. * Encode packet helpers for binary types
  15942. */
  15943. function encodeArrayBuffer(packet, supportsBinary, callback) {
  15944. if (!supportsBinary) {
  15945. return exports.encodeBase64Packet(packet, callback);
  15946. }
  15947. var data = packet.data;
  15948. var contentArray = new Uint8Array(data);
  15949. var resultBuffer = new Uint8Array(1 + data.byteLength);
  15950. resultBuffer[0] = packets[packet.type];
  15951. for (var i = 0; i < contentArray.length; i++) {
  15952. resultBuffer[i+1] = contentArray[i];
  15953. }
  15954. return callback(resultBuffer.buffer);
  15955. }
  15956. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  15957. if (!supportsBinary) {
  15958. return exports.encodeBase64Packet(packet, callback);
  15959. }
  15960. var fr = new FileReader();
  15961. fr.onload = function() {
  15962. packet.data = fr.result;
  15963. exports.encodePacket(packet, supportsBinary, true, callback);
  15964. };
  15965. return fr.readAsArrayBuffer(packet.data);
  15966. }
  15967. function encodeBlob(packet, supportsBinary, callback) {
  15968. if (!supportsBinary) {
  15969. return exports.encodeBase64Packet(packet, callback);
  15970. }
  15971. if (dontSendBlobs) {
  15972. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  15973. }
  15974. var length = new Uint8Array(1);
  15975. length[0] = packets[packet.type];
  15976. var blob = new Blob([length.buffer, packet.data]);
  15977. return callback(blob);
  15978. }
  15979. /**
  15980. * Encodes a packet with binary data in a base64 string
  15981. *
  15982. * @param {Object} packet, has `type` and `data`
  15983. * @return {String} base64 encoded message
  15984. */
  15985. exports.encodeBase64Packet = function(packet, callback) {
  15986. var message = 'b' + exports.packets[packet.type];
  15987. if (Blob && packet.data instanceof Blob) {
  15988. var fr = new FileReader();
  15989. fr.onload = function() {
  15990. var b64 = fr.result.split(',')[1];
  15991. callback(message + b64);
  15992. };
  15993. return fr.readAsDataURL(packet.data);
  15994. }
  15995. var b64data;
  15996. try {
  15997. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  15998. } catch (e) {
  15999. // iPhone Safari doesn't let you apply with typed arrays
  16000. var typed = new Uint8Array(packet.data);
  16001. var basic = new Array(typed.length);
  16002. for (var i = 0; i < typed.length; i++) {
  16003. basic[i] = typed[i];
  16004. }
  16005. b64data = String.fromCharCode.apply(null, basic);
  16006. }
  16007. message += global.btoa(b64data);
  16008. return callback(message);
  16009. };
  16010. /**
  16011. * Decodes a packet. Changes format to Blob if requested.
  16012. *
  16013. * @return {Object} with `type` and `data` (if any)
  16014. * @api private
  16015. */
  16016. exports.decodePacket = function (data, binaryType, utf8decode) {
  16017. // String data
  16018. if (typeof data == 'string' || data === undefined) {
  16019. if (data.charAt(0) == 'b') {
  16020. return exports.decodeBase64Packet(data.substr(1), binaryType);
  16021. }
  16022. if (utf8decode) {
  16023. try {
  16024. data = utf8.decode(data);
  16025. } catch (e) {
  16026. return err;
  16027. }
  16028. }
  16029. var type = data.charAt(0);
  16030. if (Number(type) != type || !packetslist[type]) {
  16031. return err;
  16032. }
  16033. if (data.length > 1) {
  16034. return { type: packetslist[type], data: data.substring(1) };
  16035. } else {
  16036. return { type: packetslist[type] };
  16037. }
  16038. }
  16039. var asArray = new Uint8Array(data);
  16040. var type = asArray[0];
  16041. var rest = sliceBuffer(data, 1);
  16042. if (Blob && binaryType === 'blob') {
  16043. rest = new Blob([rest]);
  16044. }
  16045. return { type: packetslist[type], data: rest };
  16046. };
  16047. /**
  16048. * Decodes a packet encoded in a base64 string
  16049. *
  16050. * @param {String} base64 encoded message
  16051. * @return {Object} with `type` and `data` (if any)
  16052. */
  16053. exports.decodeBase64Packet = function(msg, binaryType) {
  16054. var type = packetslist[msg.charAt(0)];
  16055. if (!global.ArrayBuffer) {
  16056. return { type: type, data: { base64: true, data: msg.substr(1) } };
  16057. }
  16058. var data = base64encoder.decode(msg.substr(1));
  16059. if (binaryType === 'blob' && Blob) {
  16060. data = new Blob([data]);
  16061. }
  16062. return { type: type, data: data };
  16063. };
  16064. /**
  16065. * Encodes multiple messages (payload).
  16066. *
  16067. * <length>:data
  16068. *
  16069. * Example:
  16070. *
  16071. * 11:hello world2:hi
  16072. *
  16073. * If any contents are binary, they will be encoded as base64 strings. Base64
  16074. * encoded strings are marked with a b before the length specifier
  16075. *
  16076. * @param {Array} packets
  16077. * @api private
  16078. */
  16079. exports.encodePayload = function (packets, supportsBinary, callback) {
  16080. if (typeof supportsBinary == 'function') {
  16081. callback = supportsBinary;
  16082. supportsBinary = null;
  16083. }
  16084. var isBinary = hasBinary(packets);
  16085. if (supportsBinary && isBinary) {
  16086. if (Blob && !dontSendBlobs) {
  16087. return exports.encodePayloadAsBlob(packets, callback);
  16088. }
  16089. return exports.encodePayloadAsArrayBuffer(packets, callback);
  16090. }
  16091. if (!packets.length) {
  16092. return callback('0:');
  16093. }
  16094. function setLengthHeader(message) {
  16095. return message.length + ':' + message;
  16096. }
  16097. function encodeOne(packet, doneCallback) {
  16098. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  16099. doneCallback(null, setLengthHeader(message));
  16100. });
  16101. }
  16102. map(packets, encodeOne, function(err, results) {
  16103. return callback(results.join(''));
  16104. });
  16105. };
  16106. /**
  16107. * Async array map using after
  16108. */
  16109. function map(ary, each, done) {
  16110. var result = new Array(ary.length);
  16111. var next = after(ary.length, done);
  16112. var eachWithIndex = function(i, el, cb) {
  16113. each(el, function(error, msg) {
  16114. result[i] = msg;
  16115. cb(error, result);
  16116. });
  16117. };
  16118. for (var i = 0; i < ary.length; i++) {
  16119. eachWithIndex(i, ary[i], next);
  16120. }
  16121. }
  16122. /*
  16123. * Decodes data when a payload is maybe expected. Possible binary contents are
  16124. * decoded from their base64 representation
  16125. *
  16126. * @param {String} data, callback method
  16127. * @api public
  16128. */
  16129. exports.decodePayload = function (data, binaryType, callback) {
  16130. if (typeof data != 'string') {
  16131. return exports.decodePayloadAsBinary(data, binaryType, callback);
  16132. }
  16133. if (typeof binaryType === 'function') {
  16134. callback = binaryType;
  16135. binaryType = null;
  16136. }
  16137. var packet;
  16138. if (data == '') {
  16139. // parser error - ignoring payload
  16140. return callback(err, 0, 1);
  16141. }
  16142. var length = ''
  16143. , n, msg;
  16144. for (var i = 0, l = data.length; i < l; i++) {
  16145. var chr = data.charAt(i);
  16146. if (':' != chr) {
  16147. length += chr;
  16148. } else {
  16149. if ('' == length || (length != (n = Number(length)))) {
  16150. // parser error - ignoring payload
  16151. return callback(err, 0, 1);
  16152. }
  16153. msg = data.substr(i + 1, n);
  16154. if (length != msg.length) {
  16155. // parser error - ignoring payload
  16156. return callback(err, 0, 1);
  16157. }
  16158. if (msg.length) {
  16159. packet = exports.decodePacket(msg, binaryType, true);
  16160. if (err.type == packet.type && err.data == packet.data) {
  16161. // parser error in individual packet - ignoring payload
  16162. return callback(err, 0, 1);
  16163. }
  16164. var ret = callback(packet, i + n, l);
  16165. if (false === ret) return;
  16166. }
  16167. // advance cursor
  16168. i += n;
  16169. length = '';
  16170. }
  16171. }
  16172. if (length != '') {
  16173. // parser error - ignoring payload
  16174. return callback(err, 0, 1);
  16175. }
  16176. };
  16177. /**
  16178. * Encodes multiple messages (payload) as binary.
  16179. *
  16180. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  16181. * 255><data>
  16182. *
  16183. * Example:
  16184. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  16185. *
  16186. * @param {Array} packets
  16187. * @return {ArrayBuffer} encoded payload
  16188. * @api private
  16189. */
  16190. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  16191. if (!packets.length) {
  16192. return callback(new ArrayBuffer(0));
  16193. }
  16194. function encodeOne(packet, doneCallback) {
  16195. exports.encodePacket(packet, true, true, function(data) {
  16196. return doneCallback(null, data);
  16197. });
  16198. }
  16199. map(packets, encodeOne, function(err, encodedPackets) {
  16200. var totalLength = encodedPackets.reduce(function(acc, p) {
  16201. var len;
  16202. if (typeof p === 'string'){
  16203. len = p.length;
  16204. } else {
  16205. len = p.byteLength;
  16206. }
  16207. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  16208. }, 0);
  16209. var resultArray = new Uint8Array(totalLength);
  16210. var bufferIndex = 0;
  16211. encodedPackets.forEach(function(p) {
  16212. var isString = typeof p === 'string';
  16213. var ab = p;
  16214. if (isString) {
  16215. var view = new Uint8Array(p.length);
  16216. for (var i = 0; i < p.length; i++) {
  16217. view[i] = p.charCodeAt(i);
  16218. }
  16219. ab = view.buffer;
  16220. }
  16221. if (isString) { // not true binary
  16222. resultArray[bufferIndex++] = 0;
  16223. } else { // true binary
  16224. resultArray[bufferIndex++] = 1;
  16225. }
  16226. var lenStr = ab.byteLength.toString();
  16227. for (var i = 0; i < lenStr.length; i++) {
  16228. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  16229. }
  16230. resultArray[bufferIndex++] = 255;
  16231. var view = new Uint8Array(ab);
  16232. for (var i = 0; i < view.length; i++) {
  16233. resultArray[bufferIndex++] = view[i];
  16234. }
  16235. });
  16236. return callback(resultArray.buffer);
  16237. });
  16238. };
  16239. /**
  16240. * Encode as Blob
  16241. */
  16242. exports.encodePayloadAsBlob = function(packets, callback) {
  16243. function encodeOne(packet, doneCallback) {
  16244. exports.encodePacket(packet, true, true, function(encoded) {
  16245. var binaryIdentifier = new Uint8Array(1);
  16246. binaryIdentifier[0] = 1;
  16247. if (typeof encoded === 'string') {
  16248. var view = new Uint8Array(encoded.length);
  16249. for (var i = 0; i < encoded.length; i++) {
  16250. view[i] = encoded.charCodeAt(i);
  16251. }
  16252. encoded = view.buffer;
  16253. binaryIdentifier[0] = 0;
  16254. }
  16255. var len = (encoded instanceof ArrayBuffer)
  16256. ? encoded.byteLength
  16257. : encoded.size;
  16258. var lenStr = len.toString();
  16259. var lengthAry = new Uint8Array(lenStr.length + 1);
  16260. for (var i = 0; i < lenStr.length; i++) {
  16261. lengthAry[i] = parseInt(lenStr[i]);
  16262. }
  16263. lengthAry[lenStr.length] = 255;
  16264. if (Blob) {
  16265. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  16266. doneCallback(null, blob);
  16267. }
  16268. });
  16269. }
  16270. map(packets, encodeOne, function(err, results) {
  16271. return callback(new Blob(results));
  16272. });
  16273. };
  16274. /*
  16275. * Decodes data when a payload is maybe expected. Strings are decoded by
  16276. * interpreting each byte as a key code for entries marked to start with 0. See
  16277. * description of encodePayloadAsBinary
  16278. *
  16279. * @param {ArrayBuffer} data, callback method
  16280. * @api public
  16281. */
  16282. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  16283. if (typeof binaryType === 'function') {
  16284. callback = binaryType;
  16285. binaryType = null;
  16286. }
  16287. var bufferTail = data;
  16288. var buffers = [];
  16289. var numberTooLong = false;
  16290. while (bufferTail.byteLength > 0) {
  16291. var tailArray = new Uint8Array(bufferTail);
  16292. var isString = tailArray[0] === 0;
  16293. var msgLength = '';
  16294. for (var i = 1; ; i++) {
  16295. if (tailArray[i] == 255) break;
  16296. if (msgLength.length > 310) {
  16297. numberTooLong = true;
  16298. break;
  16299. }
  16300. msgLength += tailArray[i];
  16301. }
  16302. if(numberTooLong) return callback(err, 0, 1);
  16303. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  16304. msgLength = parseInt(msgLength);
  16305. var msg = sliceBuffer(bufferTail, 0, msgLength);
  16306. if (isString) {
  16307. try {
  16308. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  16309. } catch (e) {
  16310. // iPhone Safari doesn't let you apply to typed arrays
  16311. var typed = new Uint8Array(msg);
  16312. msg = '';
  16313. for (var i = 0; i < typed.length; i++) {
  16314. msg += String.fromCharCode(typed[i]);
  16315. }
  16316. }
  16317. }
  16318. buffers.push(msg);
  16319. bufferTail = sliceBuffer(bufferTail, msgLength);
  16320. }
  16321. var total = buffers.length;
  16322. buffers.forEach(function(buffer, i) {
  16323. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  16324. });
  16325. };
  16326. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  16327. },{"./keys":70,"after":45,"arraybuffer.slice":46,"base64-arraybuffer":49,"blob":50,"has-binary":71,"utf8":128}],70:[function(require,module,exports){
  16328. /**
  16329. * Gets the keys for an object.
  16330. *
  16331. * @return {Array} keys
  16332. * @api private
  16333. */
  16334. module.exports = Object.keys || function keys (obj){
  16335. var arr = [];
  16336. var has = Object.prototype.hasOwnProperty;
  16337. for (var i in obj) {
  16338. if (has.call(obj, i)) {
  16339. arr.push(i);
  16340. }
  16341. }
  16342. return arr;
  16343. };
  16344. },{}],71:[function(require,module,exports){
  16345. (function (global){
  16346. /*
  16347. * Module requirements.
  16348. */
  16349. var isArray = require('isarray');
  16350. /**
  16351. * Module exports.
  16352. */
  16353. module.exports = hasBinary;
  16354. /**
  16355. * Checks for binary data.
  16356. *
  16357. * Right now only Buffer and ArrayBuffer are supported..
  16358. *
  16359. * @param {Object} anything
  16360. * @api public
  16361. */
  16362. function hasBinary(data) {
  16363. function _hasBinary(obj) {
  16364. if (!obj) return false;
  16365. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  16366. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  16367. (global.Blob && obj instanceof Blob) ||
  16368. (global.File && obj instanceof File)
  16369. ) {
  16370. return true;
  16371. }
  16372. if (isArray(obj)) {
  16373. for (var i = 0; i < obj.length; i++) {
  16374. if (_hasBinary(obj[i])) {
  16375. return true;
  16376. }
  16377. }
  16378. } else if (obj && 'object' == typeof obj) {
  16379. if (obj.toJSON) {
  16380. obj = obj.toJSON();
  16381. }
  16382. for (var key in obj) {
  16383. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  16384. return true;
  16385. }
  16386. }
  16387. }
  16388. return false;
  16389. }
  16390. return _hasBinary(data);
  16391. }
  16392. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  16393. },{"isarray":77}],72:[function(require,module,exports){
  16394. (function (process,global){
  16395. /*!
  16396. * @overview es6-promise - a tiny implementation of Promises/A+.
  16397. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  16398. * @license Licensed under MIT license
  16399. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  16400. * @version 3.0.2
  16401. */
  16402. (function() {
  16403. "use strict";
  16404. function lib$es6$promise$utils$$objectOrFunction(x) {
  16405. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  16406. }
  16407. function lib$es6$promise$utils$$isFunction(x) {
  16408. return typeof x === 'function';
  16409. }
  16410. function lib$es6$promise$utils$$isMaybeThenable(x) {
  16411. return typeof x === 'object' && x !== null;
  16412. }
  16413. var lib$es6$promise$utils$$_isArray;
  16414. if (!Array.isArray) {
  16415. lib$es6$promise$utils$$_isArray = function (x) {
  16416. return Object.prototype.toString.call(x) === '[object Array]';
  16417. };
  16418. } else {
  16419. lib$es6$promise$utils$$_isArray = Array.isArray;
  16420. }
  16421. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  16422. var lib$es6$promise$asap$$len = 0;
  16423. var lib$es6$promise$asap$$toString = {}.toString;
  16424. var lib$es6$promise$asap$$vertxNext;
  16425. var lib$es6$promise$asap$$customSchedulerFn;
  16426. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  16427. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  16428. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  16429. lib$es6$promise$asap$$len += 2;
  16430. if (lib$es6$promise$asap$$len === 2) {
  16431. // If len is 2, that means that we need to schedule an async flush.
  16432. // If additional callbacks are queued before the queue is flushed, they
  16433. // will be processed by this flush that we are scheduling.
  16434. if (lib$es6$promise$asap$$customSchedulerFn) {
  16435. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  16436. } else {
  16437. lib$es6$promise$asap$$scheduleFlush();
  16438. }
  16439. }
  16440. }
  16441. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  16442. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  16443. }
  16444. function lib$es6$promise$asap$$setAsap(asapFn) {
  16445. lib$es6$promise$asap$$asap = asapFn;
  16446. }
  16447. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  16448. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  16449. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  16450. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  16451. // test for web worker but not in IE10
  16452. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  16453. typeof importScripts !== 'undefined' &&
  16454. typeof MessageChannel !== 'undefined';
  16455. // node
  16456. function lib$es6$promise$asap$$useNextTick() {
  16457. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  16458. // see https://github.com/cujojs/when/issues/410 for details
  16459. return function() {
  16460. process.nextTick(lib$es6$promise$asap$$flush);
  16461. };
  16462. }
  16463. // vertx
  16464. function lib$es6$promise$asap$$useVertxTimer() {
  16465. return function() {
  16466. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  16467. };
  16468. }
  16469. function lib$es6$promise$asap$$useMutationObserver() {
  16470. var iterations = 0;
  16471. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  16472. var node = document.createTextNode('');
  16473. observer.observe(node, { characterData: true });
  16474. return function() {
  16475. node.data = (iterations = ++iterations % 2);
  16476. };
  16477. }
  16478. // web worker
  16479. function lib$es6$promise$asap$$useMessageChannel() {
  16480. var channel = new MessageChannel();
  16481. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  16482. return function () {
  16483. channel.port2.postMessage(0);
  16484. };
  16485. }
  16486. function lib$es6$promise$asap$$useSetTimeout() {
  16487. return function() {
  16488. setTimeout(lib$es6$promise$asap$$flush, 1);
  16489. };
  16490. }
  16491. var lib$es6$promise$asap$$queue = new Array(1000);
  16492. function lib$es6$promise$asap$$flush() {
  16493. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  16494. var callback = lib$es6$promise$asap$$queue[i];
  16495. var arg = lib$es6$promise$asap$$queue[i+1];
  16496. callback(arg);
  16497. lib$es6$promise$asap$$queue[i] = undefined;
  16498. lib$es6$promise$asap$$queue[i+1] = undefined;
  16499. }
  16500. lib$es6$promise$asap$$len = 0;
  16501. }
  16502. function lib$es6$promise$asap$$attemptVertx() {
  16503. try {
  16504. var r = require;
  16505. var vertx = r('vertx');
  16506. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  16507. return lib$es6$promise$asap$$useVertxTimer();
  16508. } catch(e) {
  16509. return lib$es6$promise$asap$$useSetTimeout();
  16510. }
  16511. }
  16512. var lib$es6$promise$asap$$scheduleFlush;
  16513. // Decide what async method to use to triggering processing of queued callbacks:
  16514. if (lib$es6$promise$asap$$isNode) {
  16515. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  16516. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  16517. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  16518. } else if (lib$es6$promise$asap$$isWorker) {
  16519. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  16520. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  16521. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  16522. } else {
  16523. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  16524. }
  16525. function lib$es6$promise$$internal$$noop() {}
  16526. var lib$es6$promise$$internal$$PENDING = void 0;
  16527. var lib$es6$promise$$internal$$FULFILLED = 1;
  16528. var lib$es6$promise$$internal$$REJECTED = 2;
  16529. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  16530. function lib$es6$promise$$internal$$selfFulfillment() {
  16531. return new TypeError("You cannot resolve a promise with itself");
  16532. }
  16533. function lib$es6$promise$$internal$$cannotReturnOwn() {
  16534. return new TypeError('A promises callback cannot return that same promise.');
  16535. }
  16536. function lib$es6$promise$$internal$$getThen(promise) {
  16537. try {
  16538. return promise.then;
  16539. } catch(error) {
  16540. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  16541. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  16542. }
  16543. }
  16544. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  16545. try {
  16546. then.call(value, fulfillmentHandler, rejectionHandler);
  16547. } catch(e) {
  16548. return e;
  16549. }
  16550. }
  16551. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  16552. lib$es6$promise$asap$$asap(function(promise) {
  16553. var sealed = false;
  16554. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  16555. if (sealed) { return; }
  16556. sealed = true;
  16557. if (thenable !== value) {
  16558. lib$es6$promise$$internal$$resolve(promise, value);
  16559. } else {
  16560. lib$es6$promise$$internal$$fulfill(promise, value);
  16561. }
  16562. }, function(reason) {
  16563. if (sealed) { return; }
  16564. sealed = true;
  16565. lib$es6$promise$$internal$$reject(promise, reason);
  16566. }, 'Settle: ' + (promise._label || ' unknown promise'));
  16567. if (!sealed && error) {
  16568. sealed = true;
  16569. lib$es6$promise$$internal$$reject(promise, error);
  16570. }
  16571. }, promise);
  16572. }
  16573. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  16574. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  16575. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  16576. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  16577. lib$es6$promise$$internal$$reject(promise, thenable._result);
  16578. } else {
  16579. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  16580. lib$es6$promise$$internal$$resolve(promise, value);
  16581. }, function(reason) {
  16582. lib$es6$promise$$internal$$reject(promise, reason);
  16583. });
  16584. }
  16585. }
  16586. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  16587. if (maybeThenable.constructor === promise.constructor) {
  16588. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  16589. } else {
  16590. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  16591. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  16592. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  16593. } else if (then === undefined) {
  16594. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  16595. } else if (lib$es6$promise$utils$$isFunction(then)) {
  16596. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  16597. } else {
  16598. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  16599. }
  16600. }
  16601. }
  16602. function lib$es6$promise$$internal$$resolve(promise, value) {
  16603. if (promise === value) {
  16604. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  16605. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  16606. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  16607. } else {
  16608. lib$es6$promise$$internal$$fulfill(promise, value);
  16609. }
  16610. }
  16611. function lib$es6$promise$$internal$$publishRejection(promise) {
  16612. if (promise._onerror) {
  16613. promise._onerror(promise._result);
  16614. }
  16615. lib$es6$promise$$internal$$publish(promise);
  16616. }
  16617. function lib$es6$promise$$internal$$fulfill(promise, value) {
  16618. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  16619. promise._result = value;
  16620. promise._state = lib$es6$promise$$internal$$FULFILLED;
  16621. if (promise._subscribers.length !== 0) {
  16622. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  16623. }
  16624. }
  16625. function lib$es6$promise$$internal$$reject(promise, reason) {
  16626. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  16627. promise._state = lib$es6$promise$$internal$$REJECTED;
  16628. promise._result = reason;
  16629. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  16630. }
  16631. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  16632. var subscribers = parent._subscribers;
  16633. var length = subscribers.length;
  16634. parent._onerror = null;
  16635. subscribers[length] = child;
  16636. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  16637. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  16638. if (length === 0 && parent._state) {
  16639. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  16640. }
  16641. }
  16642. function lib$es6$promise$$internal$$publish(promise) {
  16643. var subscribers = promise._subscribers;
  16644. var settled = promise._state;
  16645. if (subscribers.length === 0) { return; }
  16646. var child, callback, detail = promise._result;
  16647. for (var i = 0; i < subscribers.length; i += 3) {
  16648. child = subscribers[i];
  16649. callback = subscribers[i + settled];
  16650. if (child) {
  16651. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  16652. } else {
  16653. callback(detail);
  16654. }
  16655. }
  16656. promise._subscribers.length = 0;
  16657. }
  16658. function lib$es6$promise$$internal$$ErrorObject() {
  16659. this.error = null;
  16660. }
  16661. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  16662. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  16663. try {
  16664. return callback(detail);
  16665. } catch(e) {
  16666. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  16667. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  16668. }
  16669. }
  16670. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  16671. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  16672. value, error, succeeded, failed;
  16673. if (hasCallback) {
  16674. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  16675. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  16676. failed = true;
  16677. error = value.error;
  16678. value = null;
  16679. } else {
  16680. succeeded = true;
  16681. }
  16682. if (promise === value) {
  16683. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  16684. return;
  16685. }
  16686. } else {
  16687. value = detail;
  16688. succeeded = true;
  16689. }
  16690. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  16691. // noop
  16692. } else if (hasCallback && succeeded) {
  16693. lib$es6$promise$$internal$$resolve(promise, value);
  16694. } else if (failed) {
  16695. lib$es6$promise$$internal$$reject(promise, error);
  16696. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  16697. lib$es6$promise$$internal$$fulfill(promise, value);
  16698. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  16699. lib$es6$promise$$internal$$reject(promise, value);
  16700. }
  16701. }
  16702. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  16703. try {
  16704. resolver(function resolvePromise(value){
  16705. lib$es6$promise$$internal$$resolve(promise, value);
  16706. }, function rejectPromise(reason) {
  16707. lib$es6$promise$$internal$$reject(promise, reason);
  16708. });
  16709. } catch(e) {
  16710. lib$es6$promise$$internal$$reject(promise, e);
  16711. }
  16712. }
  16713. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  16714. var enumerator = this;
  16715. enumerator._instanceConstructor = Constructor;
  16716. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  16717. if (enumerator._validateInput(input)) {
  16718. enumerator._input = input;
  16719. enumerator.length = input.length;
  16720. enumerator._remaining = input.length;
  16721. enumerator._init();
  16722. if (enumerator.length === 0) {
  16723. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  16724. } else {
  16725. enumerator.length = enumerator.length || 0;
  16726. enumerator._enumerate();
  16727. if (enumerator._remaining === 0) {
  16728. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  16729. }
  16730. }
  16731. } else {
  16732. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  16733. }
  16734. }
  16735. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  16736. return lib$es6$promise$utils$$isArray(input);
  16737. };
  16738. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  16739. return new Error('Array Methods must be provided an Array');
  16740. };
  16741. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  16742. this._result = new Array(this.length);
  16743. };
  16744. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  16745. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  16746. var enumerator = this;
  16747. var length = enumerator.length;
  16748. var promise = enumerator.promise;
  16749. var input = enumerator._input;
  16750. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  16751. enumerator._eachEntry(input[i], i);
  16752. }
  16753. };
  16754. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  16755. var enumerator = this;
  16756. var c = enumerator._instanceConstructor;
  16757. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  16758. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  16759. entry._onerror = null;
  16760. enumerator._settledAt(entry._state, i, entry._result);
  16761. } else {
  16762. enumerator._willSettleAt(c.resolve(entry), i);
  16763. }
  16764. } else {
  16765. enumerator._remaining--;
  16766. enumerator._result[i] = entry;
  16767. }
  16768. };
  16769. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  16770. var enumerator = this;
  16771. var promise = enumerator.promise;
  16772. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  16773. enumerator._remaining--;
  16774. if (state === lib$es6$promise$$internal$$REJECTED) {
  16775. lib$es6$promise$$internal$$reject(promise, value);
  16776. } else {
  16777. enumerator._result[i] = value;
  16778. }
  16779. }
  16780. if (enumerator._remaining === 0) {
  16781. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  16782. }
  16783. };
  16784. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  16785. var enumerator = this;
  16786. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  16787. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  16788. }, function(reason) {
  16789. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  16790. });
  16791. };
  16792. function lib$es6$promise$promise$all$$all(entries) {
  16793. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  16794. }
  16795. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  16796. function lib$es6$promise$promise$race$$race(entries) {
  16797. /*jshint validthis:true */
  16798. var Constructor = this;
  16799. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  16800. if (!lib$es6$promise$utils$$isArray(entries)) {
  16801. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  16802. return promise;
  16803. }
  16804. var length = entries.length;
  16805. function onFulfillment(value) {
  16806. lib$es6$promise$$internal$$resolve(promise, value);
  16807. }
  16808. function onRejection(reason) {
  16809. lib$es6$promise$$internal$$reject(promise, reason);
  16810. }
  16811. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  16812. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  16813. }
  16814. return promise;
  16815. }
  16816. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  16817. function lib$es6$promise$promise$resolve$$resolve(object) {
  16818. /*jshint validthis:true */
  16819. var Constructor = this;
  16820. if (object && typeof object === 'object' && object.constructor === Constructor) {
  16821. return object;
  16822. }
  16823. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  16824. lib$es6$promise$$internal$$resolve(promise, object);
  16825. return promise;
  16826. }
  16827. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  16828. function lib$es6$promise$promise$reject$$reject(reason) {
  16829. /*jshint validthis:true */
  16830. var Constructor = this;
  16831. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  16832. lib$es6$promise$$internal$$reject(promise, reason);
  16833. return promise;
  16834. }
  16835. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  16836. var lib$es6$promise$promise$$counter = 0;
  16837. function lib$es6$promise$promise$$needsResolver() {
  16838. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  16839. }
  16840. function lib$es6$promise$promise$$needsNew() {
  16841. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  16842. }
  16843. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  16844. /**
  16845. Promise objects represent the eventual result of an asynchronous operation. The
  16846. primary way of interacting with a promise is through its `then` method, which
  16847. registers callbacks to receive either a promise's eventual value or the reason
  16848. why the promise cannot be fulfilled.
  16849. Terminology
  16850. -----------
  16851. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  16852. - `thenable` is an object or function that defines a `then` method.
  16853. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  16854. - `exception` is a value that is thrown using the throw statement.
  16855. - `reason` is a value that indicates why a promise was rejected.
  16856. - `settled` the final resting state of a promise, fulfilled or rejected.
  16857. A promise can be in one of three states: pending, fulfilled, or rejected.
  16858. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  16859. state. Promises that are rejected have a rejection reason and are in the
  16860. rejected state. A fulfillment value is never a thenable.
  16861. Promises can also be said to *resolve* a value. If this value is also a
  16862. promise, then the original promise's settled state will match the value's
  16863. settled state. So a promise that *resolves* a promise that rejects will
  16864. itself reject, and a promise that *resolves* a promise that fulfills will
  16865. itself fulfill.
  16866. Basic Usage:
  16867. ------------
  16868. ```js
  16869. var promise = new Promise(function(resolve, reject) {
  16870. // on success
  16871. resolve(value);
  16872. // on failure
  16873. reject(reason);
  16874. });
  16875. promise.then(function(value) {
  16876. // on fulfillment
  16877. }, function(reason) {
  16878. // on rejection
  16879. });
  16880. ```
  16881. Advanced Usage:
  16882. ---------------
  16883. Promises shine when abstracting away asynchronous interactions such as
  16884. `XMLHttpRequest`s.
  16885. ```js
  16886. function getJSON(url) {
  16887. return new Promise(function(resolve, reject){
  16888. var xhr = new XMLHttpRequest();
  16889. xhr.open('GET', url);
  16890. xhr.onreadystatechange = handler;
  16891. xhr.responseType = 'json';
  16892. xhr.setRequestHeader('Accept', 'application/json');
  16893. xhr.send();
  16894. function handler() {
  16895. if (this.readyState === this.DONE) {
  16896. if (this.status === 200) {
  16897. resolve(this.response);
  16898. } else {
  16899. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  16900. }
  16901. }
  16902. };
  16903. });
  16904. }
  16905. getJSON('/posts.json').then(function(json) {
  16906. // on fulfillment
  16907. }, function(reason) {
  16908. // on rejection
  16909. });
  16910. ```
  16911. Unlike callbacks, promises are great composable primitives.
  16912. ```js
  16913. Promise.all([
  16914. getJSON('/posts'),
  16915. getJSON('/comments')
  16916. ]).then(function(values){
  16917. values[0] // => postsJSON
  16918. values[1] // => commentsJSON
  16919. return values;
  16920. });
  16921. ```
  16922. @class Promise
  16923. @param {function} resolver
  16924. Useful for tooling.
  16925. @constructor
  16926. */
  16927. function lib$es6$promise$promise$$Promise(resolver) {
  16928. this._id = lib$es6$promise$promise$$counter++;
  16929. this._state = undefined;
  16930. this._result = undefined;
  16931. this._subscribers = [];
  16932. if (lib$es6$promise$$internal$$noop !== resolver) {
  16933. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  16934. lib$es6$promise$promise$$needsResolver();
  16935. }
  16936. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  16937. lib$es6$promise$promise$$needsNew();
  16938. }
  16939. lib$es6$promise$$internal$$initializePromise(this, resolver);
  16940. }
  16941. }
  16942. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  16943. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  16944. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  16945. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  16946. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  16947. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  16948. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  16949. lib$es6$promise$promise$$Promise.prototype = {
  16950. constructor: lib$es6$promise$promise$$Promise,
  16951. /**
  16952. The primary way of interacting with a promise is through its `then` method,
  16953. which registers callbacks to receive either a promise's eventual value or the
  16954. reason why the promise cannot be fulfilled.
  16955. ```js
  16956. findUser().then(function(user){
  16957. // user is available
  16958. }, function(reason){
  16959. // user is unavailable, and you are given the reason why
  16960. });
  16961. ```
  16962. Chaining
  16963. --------
  16964. The return value of `then` is itself a promise. This second, 'downstream'
  16965. promise is resolved with the return value of the first promise's fulfillment
  16966. or rejection handler, or rejected if the handler throws an exception.
  16967. ```js
  16968. findUser().then(function (user) {
  16969. return user.name;
  16970. }, function (reason) {
  16971. return 'default name';
  16972. }).then(function (userName) {
  16973. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  16974. // will be `'default name'`
  16975. });
  16976. findUser().then(function (user) {
  16977. throw new Error('Found user, but still unhappy');
  16978. }, function (reason) {
  16979. throw new Error('`findUser` rejected and we're unhappy');
  16980. }).then(function (value) {
  16981. // never reached
  16982. }, function (reason) {
  16983. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  16984. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  16985. });
  16986. ```
  16987. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  16988. ```js
  16989. findUser().then(function (user) {
  16990. throw new PedagogicalException('Upstream error');
  16991. }).then(function (value) {
  16992. // never reached
  16993. }).then(function (value) {
  16994. // never reached
  16995. }, function (reason) {
  16996. // The `PedgagocialException` is propagated all the way down to here
  16997. });
  16998. ```
  16999. Assimilation
  17000. ------------
  17001. Sometimes the value you want to propagate to a downstream promise can only be
  17002. retrieved asynchronously. This can be achieved by returning a promise in the
  17003. fulfillment or rejection handler. The downstream promise will then be pending
  17004. until the returned promise is settled. This is called *assimilation*.
  17005. ```js
  17006. findUser().then(function (user) {
  17007. return findCommentsByAuthor(user);
  17008. }).then(function (comments) {
  17009. // The user's comments are now available
  17010. });
  17011. ```
  17012. If the assimliated promise rejects, then the downstream promise will also reject.
  17013. ```js
  17014. findUser().then(function (user) {
  17015. return findCommentsByAuthor(user);
  17016. }).then(function (comments) {
  17017. // If `findCommentsByAuthor` fulfills, we'll have the value here
  17018. }, function (reason) {
  17019. // If `findCommentsByAuthor` rejects, we'll have the reason here
  17020. });
  17021. ```
  17022. Simple Example
  17023. --------------
  17024. Synchronous Example
  17025. ```javascript
  17026. var result;
  17027. try {
  17028. result = findResult();
  17029. // success
  17030. } catch(reason) {
  17031. // failure
  17032. }
  17033. ```
  17034. Errback Example
  17035. ```js
  17036. findResult(function(result, err){
  17037. if (err) {
  17038. // failure
  17039. } else {
  17040. // success
  17041. }
  17042. });
  17043. ```
  17044. Promise Example;
  17045. ```javascript
  17046. findResult().then(function(result){
  17047. // success
  17048. }, function(reason){
  17049. // failure
  17050. });
  17051. ```
  17052. Advanced Example
  17053. --------------
  17054. Synchronous Example
  17055. ```javascript
  17056. var author, books;
  17057. try {
  17058. author = findAuthor();
  17059. books = findBooksByAuthor(author);
  17060. // success
  17061. } catch(reason) {
  17062. // failure
  17063. }
  17064. ```
  17065. Errback Example
  17066. ```js
  17067. function foundBooks(books) {
  17068. }
  17069. function failure(reason) {
  17070. }
  17071. findAuthor(function(author, err){
  17072. if (err) {
  17073. failure(err);
  17074. // failure
  17075. } else {
  17076. try {
  17077. findBoooksByAuthor(author, function(books, err) {
  17078. if (err) {
  17079. failure(err);
  17080. } else {
  17081. try {
  17082. foundBooks(books);
  17083. } catch(reason) {
  17084. failure(reason);
  17085. }
  17086. }
  17087. });
  17088. } catch(error) {
  17089. failure(err);
  17090. }
  17091. // success
  17092. }
  17093. });
  17094. ```
  17095. Promise Example;
  17096. ```javascript
  17097. findAuthor().
  17098. then(findBooksByAuthor).
  17099. then(function(books){
  17100. // found books
  17101. }).catch(function(reason){
  17102. // something went wrong
  17103. });
  17104. ```
  17105. @method then
  17106. @param {Function} onFulfilled
  17107. @param {Function} onRejected
  17108. Useful for tooling.
  17109. @return {Promise}
  17110. */
  17111. then: function(onFulfillment, onRejection) {
  17112. var parent = this;
  17113. var state = parent._state;
  17114. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  17115. return this;
  17116. }
  17117. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  17118. var result = parent._result;
  17119. if (state) {
  17120. var callback = arguments[state - 1];
  17121. lib$es6$promise$asap$$asap(function(){
  17122. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  17123. });
  17124. } else {
  17125. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  17126. }
  17127. return child;
  17128. },
  17129. /**
  17130. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  17131. as the catch block of a try/catch statement.
  17132. ```js
  17133. function findAuthor(){
  17134. throw new Error('couldn't find that author');
  17135. }
  17136. // synchronous
  17137. try {
  17138. findAuthor();
  17139. } catch(reason) {
  17140. // something went wrong
  17141. }
  17142. // async with promises
  17143. findAuthor().catch(function(reason){
  17144. // something went wrong
  17145. });
  17146. ```
  17147. @method catch
  17148. @param {Function} onRejection
  17149. Useful for tooling.
  17150. @return {Promise}
  17151. */
  17152. 'catch': function(onRejection) {
  17153. return this.then(null, onRejection);
  17154. }
  17155. };
  17156. function lib$es6$promise$polyfill$$polyfill() {
  17157. var local;
  17158. if (typeof global !== 'undefined') {
  17159. local = global;
  17160. } else if (typeof self !== 'undefined') {
  17161. local = self;
  17162. } else {
  17163. try {
  17164. local = Function('return this')();
  17165. } catch (e) {
  17166. throw new Error('polyfill failed because global object is unavailable in this environment');
  17167. }
  17168. }
  17169. var P = local.Promise;
  17170. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  17171. return;
  17172. }
  17173. local.Promise = lib$es6$promise$promise$$default;
  17174. }
  17175. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  17176. var lib$es6$promise$umd$$ES6Promise = {
  17177. 'Promise': lib$es6$promise$promise$$default,
  17178. 'polyfill': lib$es6$promise$polyfill$$default
  17179. };
  17180. /* global define:true module:true window: true */
  17181. if (typeof define === 'function' && define['amd']) {
  17182. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  17183. } else if (typeof module !== 'undefined' && module['exports']) {
  17184. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  17185. } else if (typeof this !== 'undefined') {
  17186. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  17187. }
  17188. lib$es6$promise$polyfill$$default();
  17189. }).call(this);
  17190. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  17191. },{"_process":103}],73:[function(require,module,exports){
  17192. /**
  17193. * Returns `this`. Execute this without a "context" (i.e. without it being
  17194. * attached to an object of the left-hand side), and `this` points to the
  17195. * "global" scope of the current JS execution.
  17196. */
  17197. module.exports = (function () { return this; })();
  17198. },{}],74:[function(require,module,exports){
  17199. (function (global){
  17200. /*
  17201. * Module requirements.
  17202. */
  17203. var isArray = require('isarray');
  17204. /**
  17205. * Module exports.
  17206. */
  17207. module.exports = hasBinary;
  17208. /**
  17209. * Checks for binary data.
  17210. *
  17211. * Right now only Buffer and ArrayBuffer are supported..
  17212. *
  17213. * @param {Object} anything
  17214. * @api public
  17215. */
  17216. function hasBinary(data) {
  17217. function _hasBinary(obj) {
  17218. if (!obj) return false;
  17219. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  17220. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  17221. (global.Blob && obj instanceof Blob) ||
  17222. (global.File && obj instanceof File)
  17223. ) {
  17224. return true;
  17225. }
  17226. if (isArray(obj)) {
  17227. for (var i = 0; i < obj.length; i++) {
  17228. if (_hasBinary(obj[i])) {
  17229. return true;
  17230. }
  17231. }
  17232. } else if (obj && 'object' == typeof obj) {
  17233. if (obj.toJSON) {
  17234. obj = obj.toJSON();
  17235. }
  17236. for (var key in obj) {
  17237. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  17238. return true;
  17239. }
  17240. }
  17241. }
  17242. return false;
  17243. }
  17244. return _hasBinary(data);
  17245. }
  17246. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  17247. },{"isarray":77}],75:[function(require,module,exports){
  17248. /**
  17249. * Module dependencies.
  17250. */
  17251. var global = require('global');
  17252. /**
  17253. * Module exports.
  17254. *
  17255. * Logic borrowed from Modernizr:
  17256. *
  17257. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  17258. */
  17259. try {
  17260. module.exports = 'XMLHttpRequest' in global &&
  17261. 'withCredentials' in new global.XMLHttpRequest();
  17262. } catch (err) {
  17263. // if XMLHttp support is disabled in IE then it will throw
  17264. // when trying to create
  17265. module.exports = false;
  17266. }
  17267. },{"global":73}],76:[function(require,module,exports){
  17268. var indexOf = [].indexOf;
  17269. module.exports = function(arr, obj){
  17270. if (indexOf) return arr.indexOf(obj);
  17271. for (var i = 0; i < arr.length; ++i) {
  17272. if (arr[i] === obj) return i;
  17273. }
  17274. return -1;
  17275. };
  17276. },{}],77:[function(require,module,exports){
  17277. module.exports = Array.isArray || function (arr) {
  17278. return Object.prototype.toString.call(arr) == '[object Array]';
  17279. };
  17280. },{}],78:[function(require,module,exports){
  17281. /* Copyright @ 2015 Atlassian Pty Ltd
  17282. *
  17283. * Licensed under the Apache License, Version 2.0 (the "License");
  17284. * you may not use this file except in compliance with the License.
  17285. * You may obtain a copy of the License at
  17286. *
  17287. * http://www.apache.org/licenses/LICENSE-2.0
  17288. *
  17289. * Unless required by applicable law or agreed to in writing, software
  17290. * distributed under the License is distributed on an "AS IS" BASIS,
  17291. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17292. * See the License for the specific language governing permissions and
  17293. * limitations under the License.
  17294. */
  17295. /**
  17296. * Ordered log levels.
  17297. */
  17298. var levels = {
  17299. "trace": 0,
  17300. "debug": 1,
  17301. "info": 2,
  17302. "log": 3,
  17303. "warn": 4,
  17304. "error": 5
  17305. };
  17306. /**
  17307. * Parses Error's object stack trace and extracts information about the last
  17308. * caller before the log method was called.
  17309. * @returns JS object with info about the caller - method name, file location,
  17310. * line and column.
  17311. */
  17312. function getCallerInfo() {
  17313. var callerInfo = {
  17314. methodName: "",
  17315. fileLocation: "",
  17316. line: null,
  17317. column: null
  17318. };
  17319. //gets the part of the stack without the logger wrappers
  17320. var error = new Error();
  17321. var stack = error.stack? error.stack.split("\n") : [];
  17322. if(!stack || stack.length < 1) {
  17323. return callerInfo;
  17324. }
  17325. var m = null;
  17326. if(stack[3]) {
  17327. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  17328. }
  17329. if(!m || m.length <= 4) {
  17330. //Firefox && Safari
  17331. if(stack[2].indexOf("log@") === 0){
  17332. //Safari
  17333. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  17334. } else {
  17335. //Firefox
  17336. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  17337. }
  17338. return callerInfo;
  17339. }
  17340. callerInfo.methodName = m[1];
  17341. callerInfo.fileLocation = m[2];
  17342. callerInfo.line = m[3];
  17343. callerInfo.column = m[4];
  17344. return callerInfo;
  17345. }
  17346. /**
  17347. * Logs messages using the transports and level from the logger.
  17348. * @param logger a logger instance.
  17349. * @param level the log level of the message. See the levels variable.
  17350. * @param arguments array with arguments that will be logged.
  17351. */
  17352. function log() {
  17353. var logger = arguments[0], level = arguments[1],
  17354. args = Array.prototype.slice.call(arguments, 2);
  17355. if(levels[level] <= logger.level) {
  17356. return;
  17357. }
  17358. var callerInfo = getCallerInfo();
  17359. for(var i = 0; i < logger.transports.length; i++) {
  17360. var t = logger.transports[i];
  17361. var l = t[level];
  17362. if(l && typeof(l) === "function") {
  17363. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  17364. .apply(t, args);
  17365. }
  17366. }
  17367. }
  17368. /**
  17369. *
  17370. * Constructs new logger object.
  17371. * @param level the logging level for the new logger
  17372. * @param id optional identifier for the logger instance.
  17373. * @param transports optional list of handlers(objects) for the logs.
  17374. * The handlers must support - log, warn, error, debug, info, trace.
  17375. * @param format optional (NOT implemented) string.
  17376. */
  17377. function Logger(level, id, transports, format) {
  17378. this.id = id;
  17379. this.format = format;
  17380. if(!this.transports) {
  17381. this.transports = [];
  17382. this.transports.push(Logger.consoleTransport);
  17383. }
  17384. this.level = levels[level];
  17385. var methods = Object.keys(levels);
  17386. for(var i = 0; i < methods.length; i++){
  17387. this[methods[i]] =
  17388. log.bind(null, this, methods[i]);
  17389. }
  17390. }
  17391. /**
  17392. * Sets the log level for the logger.
  17393. * @param level the new log level.
  17394. */
  17395. Logger.prototype.setLevel = function (level) {
  17396. this.level = levels[level];
  17397. };
  17398. module.exports = Logger;
  17399. /**
  17400. * The default transport - console
  17401. */
  17402. Logger.consoleTransport = console;
  17403. /**
  17404. * Enum for the supported log levels.
  17405. */
  17406. Logger.levels = {
  17407. TRACE: "trace",
  17408. DEBUG: "debug",
  17409. INFO: "info",
  17410. LOG: "log",
  17411. WARN: "warn",
  17412. ERROR: "error"
  17413. };
  17414. },{}],79:[function(require,module,exports){
  17415. /* Copyright @ 2015 Atlassian Pty Ltd
  17416. *
  17417. * Licensed under the Apache License, Version 2.0 (the "License");
  17418. * you may not use this file except in compliance with the License.
  17419. * You may obtain a copy of the License at
  17420. *
  17421. * http://www.apache.org/licenses/LICENSE-2.0
  17422. *
  17423. * Unless required by applicable law or agreed to in writing, software
  17424. * distributed under the License is distributed on an "AS IS" BASIS,
  17425. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17426. * See the License for the specific language governing permissions and
  17427. * limitations under the License.
  17428. */
  17429. var Logger = require("./Logger");
  17430. /**
  17431. * Map with the created loggers with ID.
  17432. */
  17433. var idLoggers = {};
  17434. /**
  17435. * Array with the loggers without id.
  17436. */
  17437. var loggers = [];
  17438. /**
  17439. * Log level for the lbrary.
  17440. */
  17441. var curLevel = Logger.levels.TRACE;
  17442. module.exports = {
  17443. /**
  17444. * Creates new logger.
  17445. * @arguments the same as Logger constructor
  17446. */
  17447. getLogger: function(id, transports, format) {
  17448. var logger = new Logger(curLevel, id, transports, format);
  17449. if(id) {
  17450. idLoggers[id] = idLoggers[id] || [];
  17451. idLoggers[id].push(logger);
  17452. } else {
  17453. loggers.push(logger);
  17454. }
  17455. return logger;
  17456. },
  17457. /**
  17458. * Changes the log level for the existing loggers by id.
  17459. * @param level the new log level.
  17460. * @param id if specified the level will be changed only for loggers with the
  17461. * same id. Otherwise the operation will affect all loggers that don't
  17462. * have id.
  17463. */
  17464. setLogLevelById: function(level, id) {
  17465. var l = id? (idLoggers[id] || []) : loggers;
  17466. for(var i = 0; i < l.length; i++) {
  17467. l[i].setLevel(level);
  17468. }
  17469. },
  17470. /**
  17471. * Changes the log level for all existing loggers.
  17472. * @param level the new log level.
  17473. */
  17474. setLogLevel: function (level) {
  17475. curLevel = level;
  17476. var i = 0;
  17477. for(; i < loggers.length; i++) {
  17478. loggers[i].setLevel(level);
  17479. }
  17480. for(var id in idLoggers) {
  17481. var l = idLoggers[id] || [];
  17482. for(i = 0; i < l.length; i++) {
  17483. l[i].setLevel(level);
  17484. }
  17485. }
  17486. },
  17487. /**
  17488. * The supported log levels.
  17489. */
  17490. levels: Logger.levels
  17491. };
  17492. },{"./Logger":78}],80:[function(require,module,exports){
  17493. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  17494. ;(function (window) {
  17495. // Convenience aliases.
  17496. var getClass = {}.toString, isProperty, forEach, undef;
  17497. // Detect the `define` function exposed by asynchronous module loaders. The
  17498. // strict `define` check is necessary for compatibility with `r.js`.
  17499. var isLoader = typeof define === "function" && define.amd;
  17500. // Detect native implementations.
  17501. var nativeJSON = typeof JSON == "object" && JSON;
  17502. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  17503. // available.
  17504. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  17505. if (JSON3 && nativeJSON) {
  17506. // Explicitly delegate to the native `stringify` and `parse`
  17507. // implementations in CommonJS environments.
  17508. JSON3.stringify = nativeJSON.stringify;
  17509. JSON3.parse = nativeJSON.parse;
  17510. } else {
  17511. // Export for web browsers, JavaScript engines, and asynchronous module
  17512. // loaders, using the global `JSON` object if available.
  17513. JSON3 = window.JSON = nativeJSON || {};
  17514. }
  17515. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  17516. var isExtended = new Date(-3509827334573292);
  17517. try {
  17518. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  17519. // results for certain dates in Opera >= 10.53.
  17520. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  17521. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  17522. // but clips the values returned by the date methods to the range of
  17523. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  17524. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  17525. } catch (exception) {}
  17526. // Internal: Determines whether the native `JSON.stringify` and `parse`
  17527. // implementations are spec-compliant. Based on work by Ken Snyder.
  17528. function has(name) {
  17529. if (has[name] !== undef) {
  17530. // Return cached feature test result.
  17531. return has[name];
  17532. }
  17533. var isSupported;
  17534. if (name == "bug-string-char-index") {
  17535. // IE <= 7 doesn't support accessing string characters using square
  17536. // bracket notation. IE 8 only supports this for primitives.
  17537. isSupported = "a"[0] != "a";
  17538. } else if (name == "json") {
  17539. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  17540. // supported.
  17541. isSupported = has("json-stringify") && has("json-parse");
  17542. } else {
  17543. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  17544. // Test `JSON.stringify`.
  17545. if (name == "json-stringify") {
  17546. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  17547. if (stringifySupported) {
  17548. // A test function object with a custom `toJSON` method.
  17549. (value = function () {
  17550. return 1;
  17551. }).toJSON = value;
  17552. try {
  17553. stringifySupported =
  17554. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  17555. // primitives as object literals.
  17556. stringify(0) === "0" &&
  17557. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  17558. // literals.
  17559. stringify(new Number()) === "0" &&
  17560. stringify(new String()) == '""' &&
  17561. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  17562. // does not define a canonical JSON representation (this applies to
  17563. // objects with `toJSON` properties as well, *unless* they are nested
  17564. // within an object or array).
  17565. stringify(getClass) === undef &&
  17566. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  17567. // FF 3.1b3 pass this test.
  17568. stringify(undef) === undef &&
  17569. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  17570. // respectively, if the value is omitted entirely.
  17571. stringify() === undef &&
  17572. // FF 3.1b1, 2 throw an error if the given value is not a number,
  17573. // string, array, object, Boolean, or `null` literal. This applies to
  17574. // objects with custom `toJSON` methods as well, unless they are nested
  17575. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  17576. // methods entirely.
  17577. stringify(value) === "1" &&
  17578. stringify([value]) == "[1]" &&
  17579. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  17580. // `"[null]"`.
  17581. stringify([undef]) == "[null]" &&
  17582. // YUI 3.0.0b1 fails to serialize `null` literals.
  17583. stringify(null) == "null" &&
  17584. // FF 3.1b1, 2 halts serialization if an array contains a function:
  17585. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  17586. // elides non-JSON values from objects and arrays, unless they
  17587. // define custom `toJSON` methods.
  17588. stringify([undef, getClass, null]) == "[null,null,null]" &&
  17589. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  17590. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  17591. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  17592. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  17593. stringify(null, value) === "1" &&
  17594. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  17595. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  17596. // serialize extended years.
  17597. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  17598. // The milliseconds are optional in ES 5, but required in 5.1.
  17599. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  17600. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  17601. // four-digit years instead of six-digit years. Credits: @Yaffle.
  17602. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  17603. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  17604. // values less than 1000. Credits: @Yaffle.
  17605. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  17606. } catch (exception) {
  17607. stringifySupported = false;
  17608. }
  17609. }
  17610. isSupported = stringifySupported;
  17611. }
  17612. // Test `JSON.parse`.
  17613. if (name == "json-parse") {
  17614. var parse = JSON3.parse;
  17615. if (typeof parse == "function") {
  17616. try {
  17617. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  17618. // Conforming implementations should also coerce the initial argument to
  17619. // a string prior to parsing.
  17620. if (parse("0") === 0 && !parse(false)) {
  17621. // Simple parsing test.
  17622. value = parse(serialized);
  17623. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  17624. if (parseSupported) {
  17625. try {
  17626. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  17627. parseSupported = !parse('"\t"');
  17628. } catch (exception) {}
  17629. if (parseSupported) {
  17630. try {
  17631. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  17632. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  17633. // certain octal literals.
  17634. parseSupported = parse("01") !== 1;
  17635. } catch (exception) {}
  17636. }
  17637. if (parseSupported) {
  17638. try {
  17639. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  17640. // points. These environments, along with FF 3.1b1 and 2,
  17641. // also allow trailing commas in JSON objects and arrays.
  17642. parseSupported = parse("1.") !== 1;
  17643. } catch (exception) {}
  17644. }
  17645. }
  17646. }
  17647. } catch (exception) {
  17648. parseSupported = false;
  17649. }
  17650. }
  17651. isSupported = parseSupported;
  17652. }
  17653. }
  17654. return has[name] = !!isSupported;
  17655. }
  17656. if (!has("json")) {
  17657. // Common `[[Class]]` name aliases.
  17658. var functionClass = "[object Function]";
  17659. var dateClass = "[object Date]";
  17660. var numberClass = "[object Number]";
  17661. var stringClass = "[object String]";
  17662. var arrayClass = "[object Array]";
  17663. var booleanClass = "[object Boolean]";
  17664. // Detect incomplete support for accessing string characters by index.
  17665. var charIndexBuggy = has("bug-string-char-index");
  17666. // Define additional utility methods if the `Date` methods are buggy.
  17667. if (!isExtended) {
  17668. var floor = Math.floor;
  17669. // A mapping between the months of the year and the number of days between
  17670. // January 1st and the first of the respective month.
  17671. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  17672. // Internal: Calculates the number of days between the Unix epoch and the
  17673. // first day of the given month.
  17674. var getDay = function (year, month) {
  17675. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  17676. };
  17677. }
  17678. // Internal: Determines if a property is a direct property of the given
  17679. // object. Delegates to the native `Object#hasOwnProperty` method.
  17680. if (!(isProperty = {}.hasOwnProperty)) {
  17681. isProperty = function (property) {
  17682. var members = {}, constructor;
  17683. if ((members.__proto__ = null, members.__proto__ = {
  17684. // The *proto* property cannot be set multiple times in recent
  17685. // versions of Firefox and SeaMonkey.
  17686. "toString": 1
  17687. }, members).toString != getClass) {
  17688. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  17689. // supports the mutable *proto* property.
  17690. isProperty = function (property) {
  17691. // Capture and break the object's prototype chain (see section 8.6.2
  17692. // of the ES 5.1 spec). The parenthesized expression prevents an
  17693. // unsafe transformation by the Closure Compiler.
  17694. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  17695. // Restore the original prototype chain.
  17696. this.__proto__ = original;
  17697. return result;
  17698. };
  17699. } else {
  17700. // Capture a reference to the top-level `Object` constructor.
  17701. constructor = members.constructor;
  17702. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  17703. // other environments.
  17704. isProperty = function (property) {
  17705. var parent = (this.constructor || constructor).prototype;
  17706. return property in this && !(property in parent && this[property] === parent[property]);
  17707. };
  17708. }
  17709. members = null;
  17710. return isProperty.call(this, property);
  17711. };
  17712. }
  17713. // Internal: A set of primitive types used by `isHostType`.
  17714. var PrimitiveTypes = {
  17715. 'boolean': 1,
  17716. 'number': 1,
  17717. 'string': 1,
  17718. 'undefined': 1
  17719. };
  17720. // Internal: Determines if the given object `property` value is a
  17721. // non-primitive.
  17722. var isHostType = function (object, property) {
  17723. var type = typeof object[property];
  17724. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  17725. };
  17726. // Internal: Normalizes the `for...in` iteration algorithm across
  17727. // environments. Each enumerated key is yielded to a `callback` function.
  17728. forEach = function (object, callback) {
  17729. var size = 0, Properties, members, property;
  17730. // Tests for bugs in the current environment's `for...in` algorithm. The
  17731. // `valueOf` property inherits the non-enumerable flag from
  17732. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  17733. (Properties = function () {
  17734. this.valueOf = 0;
  17735. }).prototype.valueOf = 0;
  17736. // Iterate over a new instance of the `Properties` class.
  17737. members = new Properties();
  17738. for (property in members) {
  17739. // Ignore all properties inherited from `Object.prototype`.
  17740. if (isProperty.call(members, property)) {
  17741. size++;
  17742. }
  17743. }
  17744. Properties = members = null;
  17745. // Normalize the iteration algorithm.
  17746. if (!size) {
  17747. // A list of non-enumerable properties inherited from `Object.prototype`.
  17748. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  17749. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  17750. // properties.
  17751. forEach = function (object, callback) {
  17752. var isFunction = getClass.call(object) == functionClass, property, length;
  17753. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  17754. for (property in object) {
  17755. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  17756. // certain conditions; IE does not.
  17757. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  17758. callback(property);
  17759. }
  17760. }
  17761. // Manually invoke the callback for each non-enumerable property.
  17762. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  17763. };
  17764. } else if (size == 2) {
  17765. // Safari <= 2.0.4 enumerates shadowed properties twice.
  17766. forEach = function (object, callback) {
  17767. // Create a set of iterated properties.
  17768. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  17769. for (property in object) {
  17770. // Store each property name to prevent double enumeration. The
  17771. // `prototype` property of functions is not enumerated due to cross-
  17772. // environment inconsistencies.
  17773. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  17774. callback(property);
  17775. }
  17776. }
  17777. };
  17778. } else {
  17779. // No bugs detected; use the standard `for...in` algorithm.
  17780. forEach = function (object, callback) {
  17781. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  17782. for (property in object) {
  17783. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  17784. callback(property);
  17785. }
  17786. }
  17787. // Manually invoke the callback for the `constructor` property due to
  17788. // cross-environment inconsistencies.
  17789. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  17790. callback(property);
  17791. }
  17792. };
  17793. }
  17794. return forEach(object, callback);
  17795. };
  17796. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  17797. // `filter` argument may specify either a function that alters how object and
  17798. // array members are serialized, or an array of strings and numbers that
  17799. // indicates which properties should be serialized. The optional `width`
  17800. // argument may be either a string or number that specifies the indentation
  17801. // level of the output.
  17802. if (!has("json-stringify")) {
  17803. // Internal: A map of control characters and their escaped equivalents.
  17804. var Escapes = {
  17805. 92: "\\\\",
  17806. 34: '\\"',
  17807. 8: "\\b",
  17808. 12: "\\f",
  17809. 10: "\\n",
  17810. 13: "\\r",
  17811. 9: "\\t"
  17812. };
  17813. // Internal: Converts `value` into a zero-padded string such that its
  17814. // length is at least equal to `width`. The `width` must be <= 6.
  17815. var leadingZeroes = "000000";
  17816. var toPaddedString = function (width, value) {
  17817. // The `|| 0` expression is necessary to work around a bug in
  17818. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  17819. return (leadingZeroes + (value || 0)).slice(-width);
  17820. };
  17821. // Internal: Double-quotes a string `value`, replacing all ASCII control
  17822. // characters (characters with code unit values between 0 and 31) with
  17823. // their escaped equivalents. This is an implementation of the
  17824. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  17825. var unicodePrefix = "\\u00";
  17826. var quote = function (value) {
  17827. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  17828. if (isLarge) {
  17829. symbols = value.split("");
  17830. }
  17831. for (; index < length; index++) {
  17832. var charCode = value.charCodeAt(index);
  17833. // If the character is a control character, append its Unicode or
  17834. // shorthand escape sequence; otherwise, append the character as-is.
  17835. switch (charCode) {
  17836. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  17837. result += Escapes[charCode];
  17838. break;
  17839. default:
  17840. if (charCode < 32) {
  17841. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  17842. break;
  17843. }
  17844. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  17845. }
  17846. }
  17847. return result + '"';
  17848. };
  17849. // Internal: Recursively serializes an object. Implements the
  17850. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  17851. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  17852. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  17853. try {
  17854. // Necessary for host object support.
  17855. value = object[property];
  17856. } catch (exception) {}
  17857. if (typeof value == "object" && value) {
  17858. className = getClass.call(value);
  17859. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  17860. if (value > -1 / 0 && value < 1 / 0) {
  17861. // Dates are serialized according to the `Date#toJSON` method
  17862. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  17863. // for the ISO 8601 date time string format.
  17864. if (getDay) {
  17865. // Manually compute the year, month, date, hours, minutes,
  17866. // seconds, and milliseconds if the `getUTC*` methods are
  17867. // buggy. Adapted from @Yaffle's `date-shim` project.
  17868. date = floor(value / 864e5);
  17869. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  17870. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  17871. date = 1 + date - getDay(year, month);
  17872. // The `time` value specifies the time within the day (see ES
  17873. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  17874. // to compute `A modulo B`, as the `%` operator does not
  17875. // correspond to the `modulo` operation for negative numbers.
  17876. time = (value % 864e5 + 864e5) % 864e5;
  17877. // The hours, minutes, seconds, and milliseconds are obtained by
  17878. // decomposing the time within the day. See section 15.9.1.10.
  17879. hours = floor(time / 36e5) % 24;
  17880. minutes = floor(time / 6e4) % 60;
  17881. seconds = floor(time / 1e3) % 60;
  17882. milliseconds = time % 1e3;
  17883. } else {
  17884. year = value.getUTCFullYear();
  17885. month = value.getUTCMonth();
  17886. date = value.getUTCDate();
  17887. hours = value.getUTCHours();
  17888. minutes = value.getUTCMinutes();
  17889. seconds = value.getUTCSeconds();
  17890. milliseconds = value.getUTCMilliseconds();
  17891. }
  17892. // Serialize extended years correctly.
  17893. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  17894. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  17895. // Months, dates, hours, minutes, and seconds should have two
  17896. // digits; milliseconds should have three.
  17897. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  17898. // Milliseconds are optional in ES 5.0, but required in 5.1.
  17899. "." + toPaddedString(3, milliseconds) + "Z";
  17900. } else {
  17901. value = null;
  17902. }
  17903. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  17904. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  17905. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  17906. // ignores all `toJSON` methods on these objects unless they are
  17907. // defined directly on an instance.
  17908. value = value.toJSON(property);
  17909. }
  17910. }
  17911. if (callback) {
  17912. // If a replacement function was provided, call it to obtain the value
  17913. // for serialization.
  17914. value = callback.call(object, property, value);
  17915. }
  17916. if (value === null) {
  17917. return "null";
  17918. }
  17919. className = getClass.call(value);
  17920. if (className == booleanClass) {
  17921. // Booleans are represented literally.
  17922. return "" + value;
  17923. } else if (className == numberClass) {
  17924. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  17925. // `"null"`.
  17926. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  17927. } else if (className == stringClass) {
  17928. // Strings are double-quoted and escaped.
  17929. return quote("" + value);
  17930. }
  17931. // Recursively serialize objects and arrays.
  17932. if (typeof value == "object") {
  17933. // Check for cyclic structures. This is a linear search; performance
  17934. // is inversely proportional to the number of unique nested objects.
  17935. for (length = stack.length; length--;) {
  17936. if (stack[length] === value) {
  17937. // Cyclic structures cannot be serialized by `JSON.stringify`.
  17938. throw TypeError();
  17939. }
  17940. }
  17941. // Add the object to the stack of traversed objects.
  17942. stack.push(value);
  17943. results = [];
  17944. // Save the current indentation level and indent one additional level.
  17945. prefix = indentation;
  17946. indentation += whitespace;
  17947. if (className == arrayClass) {
  17948. // Recursively serialize array elements.
  17949. for (index = 0, length = value.length; index < length; index++) {
  17950. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  17951. results.push(element === undef ? "null" : element);
  17952. }
  17953. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  17954. } else {
  17955. // Recursively serialize object members. Members are selected from
  17956. // either a user-specified list of property names, or the object
  17957. // itself.
  17958. forEach(properties || value, function (property) {
  17959. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  17960. if (element !== undef) {
  17961. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  17962. // is not the empty string, let `member` {quote(property) + ":"}
  17963. // be the concatenation of `member` and the `space` character."
  17964. // The "`space` character" refers to the literal space
  17965. // character, not the `space` {width} argument provided to
  17966. // `JSON.stringify`.
  17967. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  17968. }
  17969. });
  17970. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  17971. }
  17972. // Remove the object from the traversed object stack.
  17973. stack.pop();
  17974. return result;
  17975. }
  17976. };
  17977. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  17978. JSON3.stringify = function (source, filter, width) {
  17979. var whitespace, callback, properties, className;
  17980. if (typeof filter == "function" || typeof filter == "object" && filter) {
  17981. if ((className = getClass.call(filter)) == functionClass) {
  17982. callback = filter;
  17983. } else if (className == arrayClass) {
  17984. // Convert the property names array into a makeshift set.
  17985. properties = {};
  17986. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  17987. }
  17988. }
  17989. if (width) {
  17990. if ((className = getClass.call(width)) == numberClass) {
  17991. // Convert the `width` to an integer and create a string containing
  17992. // `width` number of space characters.
  17993. if ((width -= width % 1) > 0) {
  17994. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  17995. }
  17996. } else if (className == stringClass) {
  17997. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  17998. }
  17999. }
  18000. // Opera <= 7.54u2 discards the values associated with empty string keys
  18001. // (`""`) only if they are used directly within an object member list
  18002. // (e.g., `!("" in { "": 1})`).
  18003. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  18004. };
  18005. }
  18006. // Public: Parses a JSON source string.
  18007. if (!has("json-parse")) {
  18008. var fromCharCode = String.fromCharCode;
  18009. // Internal: A map of escaped control characters and their unescaped
  18010. // equivalents.
  18011. var Unescapes = {
  18012. 92: "\\",
  18013. 34: '"',
  18014. 47: "/",
  18015. 98: "\b",
  18016. 116: "\t",
  18017. 110: "\n",
  18018. 102: "\f",
  18019. 114: "\r"
  18020. };
  18021. // Internal: Stores the parser state.
  18022. var Index, Source;
  18023. // Internal: Resets the parser state and throws a `SyntaxError`.
  18024. var abort = function() {
  18025. Index = Source = null;
  18026. throw SyntaxError();
  18027. };
  18028. // Internal: Returns the next token, or `"$"` if the parser has reached
  18029. // the end of the source string. A token may be a string, number, `null`
  18030. // literal, or Boolean literal.
  18031. var lex = function () {
  18032. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  18033. while (Index < length) {
  18034. charCode = source.charCodeAt(Index);
  18035. switch (charCode) {
  18036. case 9: case 10: case 13: case 32:
  18037. // Skip whitespace tokens, including tabs, carriage returns, line
  18038. // feeds, and space characters.
  18039. Index++;
  18040. break;
  18041. case 123: case 125: case 91: case 93: case 58: case 44:
  18042. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  18043. // the current position.
  18044. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  18045. Index++;
  18046. return value;
  18047. case 34:
  18048. // `"` delimits a JSON string; advance to the next character and
  18049. // begin parsing the string. String tokens are prefixed with the
  18050. // sentinel `@` character to distinguish them from punctuators and
  18051. // end-of-string tokens.
  18052. for (value = "@", Index++; Index < length;) {
  18053. charCode = source.charCodeAt(Index);
  18054. if (charCode < 32) {
  18055. // Unescaped ASCII control characters (those with a code unit
  18056. // less than the space character) are not permitted.
  18057. abort();
  18058. } else if (charCode == 92) {
  18059. // A reverse solidus (`\`) marks the beginning of an escaped
  18060. // control character (including `"`, `\`, and `/`) or Unicode
  18061. // escape sequence.
  18062. charCode = source.charCodeAt(++Index);
  18063. switch (charCode) {
  18064. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  18065. // Revive escaped control characters.
  18066. value += Unescapes[charCode];
  18067. Index++;
  18068. break;
  18069. case 117:
  18070. // `\u` marks the beginning of a Unicode escape sequence.
  18071. // Advance to the first character and validate the
  18072. // four-digit code point.
  18073. begin = ++Index;
  18074. for (position = Index + 4; Index < position; Index++) {
  18075. charCode = source.charCodeAt(Index);
  18076. // A valid sequence comprises four hexdigits (case-
  18077. // insensitive) that form a single hexadecimal value.
  18078. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  18079. // Invalid Unicode escape sequence.
  18080. abort();
  18081. }
  18082. }
  18083. // Revive the escaped character.
  18084. value += fromCharCode("0x" + source.slice(begin, Index));
  18085. break;
  18086. default:
  18087. // Invalid escape sequence.
  18088. abort();
  18089. }
  18090. } else {
  18091. if (charCode == 34) {
  18092. // An unescaped double-quote character marks the end of the
  18093. // string.
  18094. break;
  18095. }
  18096. charCode = source.charCodeAt(Index);
  18097. begin = Index;
  18098. // Optimize for the common case where a string is valid.
  18099. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  18100. charCode = source.charCodeAt(++Index);
  18101. }
  18102. // Append the string as-is.
  18103. value += source.slice(begin, Index);
  18104. }
  18105. }
  18106. if (source.charCodeAt(Index) == 34) {
  18107. // Advance to the next character and return the revived string.
  18108. Index++;
  18109. return value;
  18110. }
  18111. // Unterminated string.
  18112. abort();
  18113. default:
  18114. // Parse numbers and literals.
  18115. begin = Index;
  18116. // Advance past the negative sign, if one is specified.
  18117. if (charCode == 45) {
  18118. isSigned = true;
  18119. charCode = source.charCodeAt(++Index);
  18120. }
  18121. // Parse an integer or floating-point value.
  18122. if (charCode >= 48 && charCode <= 57) {
  18123. // Leading zeroes are interpreted as octal literals.
  18124. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  18125. // Illegal octal literal.
  18126. abort();
  18127. }
  18128. isSigned = false;
  18129. // Parse the integer component.
  18130. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  18131. // Floats cannot contain a leading decimal point; however, this
  18132. // case is already accounted for by the parser.
  18133. if (source.charCodeAt(Index) == 46) {
  18134. position = ++Index;
  18135. // Parse the decimal component.
  18136. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  18137. if (position == Index) {
  18138. // Illegal trailing decimal.
  18139. abort();
  18140. }
  18141. Index = position;
  18142. }
  18143. // Parse exponents. The `e` denoting the exponent is
  18144. // case-insensitive.
  18145. charCode = source.charCodeAt(Index);
  18146. if (charCode == 101 || charCode == 69) {
  18147. charCode = source.charCodeAt(++Index);
  18148. // Skip past the sign following the exponent, if one is
  18149. // specified.
  18150. if (charCode == 43 || charCode == 45) {
  18151. Index++;
  18152. }
  18153. // Parse the exponential component.
  18154. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  18155. if (position == Index) {
  18156. // Illegal empty exponent.
  18157. abort();
  18158. }
  18159. Index = position;
  18160. }
  18161. // Coerce the parsed value to a JavaScript number.
  18162. return +source.slice(begin, Index);
  18163. }
  18164. // A negative sign may only precede numbers.
  18165. if (isSigned) {
  18166. abort();
  18167. }
  18168. // `true`, `false`, and `null` literals.
  18169. if (source.slice(Index, Index + 4) == "true") {
  18170. Index += 4;
  18171. return true;
  18172. } else if (source.slice(Index, Index + 5) == "false") {
  18173. Index += 5;
  18174. return false;
  18175. } else if (source.slice(Index, Index + 4) == "null") {
  18176. Index += 4;
  18177. return null;
  18178. }
  18179. // Unrecognized token.
  18180. abort();
  18181. }
  18182. }
  18183. // Return the sentinel `$` character if the parser has reached the end
  18184. // of the source string.
  18185. return "$";
  18186. };
  18187. // Internal: Parses a JSON `value` token.
  18188. var get = function (value) {
  18189. var results, hasMembers;
  18190. if (value == "$") {
  18191. // Unexpected end of input.
  18192. abort();
  18193. }
  18194. if (typeof value == "string") {
  18195. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  18196. // Remove the sentinel `@` character.
  18197. return value.slice(1);
  18198. }
  18199. // Parse object and array literals.
  18200. if (value == "[") {
  18201. // Parses a JSON array, returning a new JavaScript array.
  18202. results = [];
  18203. for (;; hasMembers || (hasMembers = true)) {
  18204. value = lex();
  18205. // A closing square bracket marks the end of the array literal.
  18206. if (value == "]") {
  18207. break;
  18208. }
  18209. // If the array literal contains elements, the current token
  18210. // should be a comma separating the previous element from the
  18211. // next.
  18212. if (hasMembers) {
  18213. if (value == ",") {
  18214. value = lex();
  18215. if (value == "]") {
  18216. // Unexpected trailing `,` in array literal.
  18217. abort();
  18218. }
  18219. } else {
  18220. // A `,` must separate each array element.
  18221. abort();
  18222. }
  18223. }
  18224. // Elisions and leading commas are not permitted.
  18225. if (value == ",") {
  18226. abort();
  18227. }
  18228. results.push(get(value));
  18229. }
  18230. return results;
  18231. } else if (value == "{") {
  18232. // Parses a JSON object, returning a new JavaScript object.
  18233. results = {};
  18234. for (;; hasMembers || (hasMembers = true)) {
  18235. value = lex();
  18236. // A closing curly brace marks the end of the object literal.
  18237. if (value == "}") {
  18238. break;
  18239. }
  18240. // If the object literal contains members, the current token
  18241. // should be a comma separator.
  18242. if (hasMembers) {
  18243. if (value == ",") {
  18244. value = lex();
  18245. if (value == "}") {
  18246. // Unexpected trailing `,` in object literal.
  18247. abort();
  18248. }
  18249. } else {
  18250. // A `,` must separate each object member.
  18251. abort();
  18252. }
  18253. }
  18254. // Leading commas are not permitted, object property names must be
  18255. // double-quoted strings, and a `:` must separate each property
  18256. // name and value.
  18257. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  18258. abort();
  18259. }
  18260. results[value.slice(1)] = get(lex());
  18261. }
  18262. return results;
  18263. }
  18264. // Unexpected token encountered.
  18265. abort();
  18266. }
  18267. return value;
  18268. };
  18269. // Internal: Updates a traversed object member.
  18270. var update = function(source, property, callback) {
  18271. var element = walk(source, property, callback);
  18272. if (element === undef) {
  18273. delete source[property];
  18274. } else {
  18275. source[property] = element;
  18276. }
  18277. };
  18278. // Internal: Recursively traverses a parsed JSON object, invoking the
  18279. // `callback` function for each value. This is an implementation of the
  18280. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  18281. var walk = function (source, property, callback) {
  18282. var value = source[property], length;
  18283. if (typeof value == "object" && value) {
  18284. // `forEach` can't be used to traverse an array in Opera <= 8.54
  18285. // because its `Object#hasOwnProperty` implementation returns `false`
  18286. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  18287. if (getClass.call(value) == arrayClass) {
  18288. for (length = value.length; length--;) {
  18289. update(value, length, callback);
  18290. }
  18291. } else {
  18292. forEach(value, function (property) {
  18293. update(value, property, callback);
  18294. });
  18295. }
  18296. }
  18297. return callback.call(source, property, value);
  18298. };
  18299. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  18300. JSON3.parse = function (source, callback) {
  18301. var result, value;
  18302. Index = 0;
  18303. Source = "" + source;
  18304. result = get(lex());
  18305. // If a JSON string contains multiple tokens, it is invalid.
  18306. if (lex() != "$") {
  18307. abort();
  18308. }
  18309. // Reset the parser state.
  18310. Index = Source = null;
  18311. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  18312. };
  18313. }
  18314. }
  18315. // Export for asynchronous module loaders.
  18316. if (isLoader) {
  18317. define(function () {
  18318. return JSON3;
  18319. });
  18320. }
  18321. }(this));
  18322. },{}],81:[function(require,module,exports){
  18323. /*
  18324. A JavaScript implementation of the SHA family of hashes, as
  18325. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  18326. as defined in FIPS PUB 198a
  18327. Copyright Brian Turek 2008-2013
  18328. Distributed under the BSD License
  18329. See http://caligatio.github.com/jsSHA/ for more information
  18330. Several functions taken from Paul Johnston
  18331. */
  18332. (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"!==
  18333. 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";
  18334. 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"===
  18335. 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|
  18336. (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,
  18337. 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,
  18338. 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=
  18339. {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):
  18340. 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,
  18341. 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>>>
  18342. 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>>>
  18343. 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>>>
  18344. 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-
  18345. 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,
  18346. 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,
  18347. 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],
  18348. 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),
  18349. 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),
  18350. 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,
  18351. 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,
  18352. 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?
  18353. 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,
  18354. 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);
  18355. },{}],82:[function(require,module,exports){
  18356. /**
  18357. * Helpers.
  18358. */
  18359. var s = 1000;
  18360. var m = s * 60;
  18361. var h = m * 60;
  18362. var d = h * 24;
  18363. var y = d * 365.25;
  18364. /**
  18365. * Parse or format the given `val`.
  18366. *
  18367. * Options:
  18368. *
  18369. * - `long` verbose formatting [false]
  18370. *
  18371. * @param {String|Number} val
  18372. * @param {Object} options
  18373. * @return {String|Number}
  18374. * @api public
  18375. */
  18376. module.exports = function(val, options){
  18377. options = options || {};
  18378. if ('string' == typeof val) return parse(val);
  18379. return options.long
  18380. ? long(val)
  18381. : short(val);
  18382. };
  18383. /**
  18384. * Parse the given `str` and return milliseconds.
  18385. *
  18386. * @param {String} str
  18387. * @return {Number}
  18388. * @api private
  18389. */
  18390. function parse(str) {
  18391. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  18392. if (!match) return;
  18393. var n = parseFloat(match[1]);
  18394. var type = (match[2] || 'ms').toLowerCase();
  18395. switch (type) {
  18396. case 'years':
  18397. case 'year':
  18398. case 'y':
  18399. return n * y;
  18400. case 'days':
  18401. case 'day':
  18402. case 'd':
  18403. return n * d;
  18404. case 'hours':
  18405. case 'hour':
  18406. case 'h':
  18407. return n * h;
  18408. case 'minutes':
  18409. case 'minute':
  18410. case 'm':
  18411. return n * m;
  18412. case 'seconds':
  18413. case 'second':
  18414. case 's':
  18415. return n * s;
  18416. case 'ms':
  18417. return n;
  18418. }
  18419. }
  18420. /**
  18421. * Short format for `ms`.
  18422. *
  18423. * @param {Number} ms
  18424. * @return {String}
  18425. * @api private
  18426. */
  18427. function short(ms) {
  18428. if (ms >= d) return Math.round(ms / d) + 'd';
  18429. if (ms >= h) return Math.round(ms / h) + 'h';
  18430. if (ms >= m) return Math.round(ms / m) + 'm';
  18431. if (ms >= s) return Math.round(ms / s) + 's';
  18432. return ms + 'ms';
  18433. }
  18434. /**
  18435. * Long format for `ms`.
  18436. *
  18437. * @param {Number} ms
  18438. * @return {String}
  18439. * @api private
  18440. */
  18441. function long(ms) {
  18442. return plural(ms, d, 'day')
  18443. || plural(ms, h, 'hour')
  18444. || plural(ms, m, 'minute')
  18445. || plural(ms, s, 'second')
  18446. || ms + ' ms';
  18447. }
  18448. /**
  18449. * Pluralization helper.
  18450. */
  18451. function plural(ms, n, name) {
  18452. if (ms < n) return;
  18453. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  18454. return Math.ceil(ms / n) + ' ' + name + 's';
  18455. }
  18456. },{}],83:[function(require,module,exports){
  18457. /**
  18458. * HOP ref.
  18459. */
  18460. var has = Object.prototype.hasOwnProperty;
  18461. /**
  18462. * Return own keys in `obj`.
  18463. *
  18464. * @param {Object} obj
  18465. * @return {Array}
  18466. * @api public
  18467. */
  18468. exports.keys = Object.keys || function(obj){
  18469. var keys = [];
  18470. for (var key in obj) {
  18471. if (has.call(obj, key)) {
  18472. keys.push(key);
  18473. }
  18474. }
  18475. return keys;
  18476. };
  18477. /**
  18478. * Return own values in `obj`.
  18479. *
  18480. * @param {Object} obj
  18481. * @return {Array}
  18482. * @api public
  18483. */
  18484. exports.values = function(obj){
  18485. var vals = [];
  18486. for (var key in obj) {
  18487. if (has.call(obj, key)) {
  18488. vals.push(obj[key]);
  18489. }
  18490. }
  18491. return vals;
  18492. };
  18493. /**
  18494. * Merge `b` into `a`.
  18495. *
  18496. * @param {Object} a
  18497. * @param {Object} b
  18498. * @return {Object} a
  18499. * @api public
  18500. */
  18501. exports.merge = function(a, b){
  18502. for (var key in b) {
  18503. if (has.call(b, key)) {
  18504. a[key] = b[key];
  18505. }
  18506. }
  18507. return a;
  18508. };
  18509. /**
  18510. * Return length of `obj`.
  18511. *
  18512. * @param {Object} obj
  18513. * @return {Number}
  18514. * @api public
  18515. */
  18516. exports.length = function(obj){
  18517. return exports.keys(obj).length;
  18518. };
  18519. /**
  18520. * Check if `obj` is empty.
  18521. *
  18522. * @param {Object} obj
  18523. * @return {Boolean}
  18524. * @api public
  18525. */
  18526. exports.isEmpty = function(obj){
  18527. return 0 == exports.length(obj);
  18528. };
  18529. },{}],84:[function(require,module,exports){
  18530. // Top level file is just a mixin of submodules & constants
  18531. 'use strict';
  18532. var assign = require('./lib/utils/common').assign;
  18533. var deflate = require('./lib/deflate');
  18534. var inflate = require('./lib/inflate');
  18535. var constants = require('./lib/zlib/constants');
  18536. var pako = {};
  18537. assign(pako, deflate, inflate, constants);
  18538. module.exports = pako;
  18539. },{"./lib/deflate":85,"./lib/inflate":86,"./lib/utils/common":87,"./lib/zlib/constants":90}],85:[function(require,module,exports){
  18540. 'use strict';
  18541. var zlib_deflate = require('./zlib/deflate.js');
  18542. var utils = require('./utils/common');
  18543. var strings = require('./utils/strings');
  18544. var msg = require('./zlib/messages');
  18545. var zstream = require('./zlib/zstream');
  18546. var toString = Object.prototype.toString;
  18547. /* Public constants ==========================================================*/
  18548. /* ===========================================================================*/
  18549. var Z_NO_FLUSH = 0;
  18550. var Z_FINISH = 4;
  18551. var Z_OK = 0;
  18552. var Z_STREAM_END = 1;
  18553. var Z_SYNC_FLUSH = 2;
  18554. var Z_DEFAULT_COMPRESSION = -1;
  18555. var Z_DEFAULT_STRATEGY = 0;
  18556. var Z_DEFLATED = 8;
  18557. /* ===========================================================================*/
  18558. /**
  18559. * class Deflate
  18560. *
  18561. * Generic JS-style wrapper for zlib calls. If you don't need
  18562. * streaming behaviour - use more simple functions: [[deflate]],
  18563. * [[deflateRaw]] and [[gzip]].
  18564. **/
  18565. /* internal
  18566. * Deflate.chunks -> Array
  18567. *
  18568. * Chunks of output data, if [[Deflate#onData]] not overriden.
  18569. **/
  18570. /**
  18571. * Deflate.result -> Uint8Array|Array
  18572. *
  18573. * Compressed result, generated by default [[Deflate#onData]]
  18574. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  18575. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  18576. * push a chunk with explicit flush (call [[Deflate#push]] with
  18577. * `Z_SYNC_FLUSH` param).
  18578. **/
  18579. /**
  18580. * Deflate.err -> Number
  18581. *
  18582. * Error code after deflate finished. 0 (Z_OK) on success.
  18583. * You will not need it in real life, because deflate errors
  18584. * are possible only on wrong options or bad `onData` / `onEnd`
  18585. * custom handlers.
  18586. **/
  18587. /**
  18588. * Deflate.msg -> String
  18589. *
  18590. * Error message, if [[Deflate.err]] != 0
  18591. **/
  18592. /**
  18593. * new Deflate(options)
  18594. * - options (Object): zlib deflate options.
  18595. *
  18596. * Creates new deflator instance with specified params. Throws exception
  18597. * on bad params. Supported options:
  18598. *
  18599. * - `level`
  18600. * - `windowBits`
  18601. * - `memLevel`
  18602. * - `strategy`
  18603. *
  18604. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18605. * for more information on these.
  18606. *
  18607. * Additional options, for internal needs:
  18608. *
  18609. * - `chunkSize` - size of generated data chunks (16K by default)
  18610. * - `raw` (Boolean) - do raw deflate
  18611. * - `gzip` (Boolean) - create gzip wrapper
  18612. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18613. * (each char code [0..255])
  18614. * - `header` (Object) - custom header for gzip
  18615. * - `text` (Boolean) - true if compressed data believed to be text
  18616. * - `time` (Number) - modification time, unix timestamp
  18617. * - `os` (Number) - operation system code
  18618. * - `extra` (Array) - array of bytes with extra data (max 65536)
  18619. * - `name` (String) - file name (binary string)
  18620. * - `comment` (String) - comment (binary string)
  18621. * - `hcrc` (Boolean) - true if header crc should be added
  18622. *
  18623. * ##### Example:
  18624. *
  18625. * ```javascript
  18626. * var pako = require('pako')
  18627. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18628. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18629. *
  18630. * var deflate = new pako.Deflate({ level: 3});
  18631. *
  18632. * deflate.push(chunk1, false);
  18633. * deflate.push(chunk2, true); // true -> last chunk
  18634. *
  18635. * if (deflate.err) { throw new Error(deflate.err); }
  18636. *
  18637. * console.log(deflate.result);
  18638. * ```
  18639. **/
  18640. var Deflate = function(options) {
  18641. this.options = utils.assign({
  18642. level: Z_DEFAULT_COMPRESSION,
  18643. method: Z_DEFLATED,
  18644. chunkSize: 16384,
  18645. windowBits: 15,
  18646. memLevel: 8,
  18647. strategy: Z_DEFAULT_STRATEGY,
  18648. to: ''
  18649. }, options || {});
  18650. var opt = this.options;
  18651. if (opt.raw && (opt.windowBits > 0)) {
  18652. opt.windowBits = -opt.windowBits;
  18653. }
  18654. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  18655. opt.windowBits += 16;
  18656. }
  18657. this.err = 0; // error code, if happens (0 = Z_OK)
  18658. this.msg = ''; // error message
  18659. this.ended = false; // used to avoid multiple onEnd() calls
  18660. this.chunks = []; // chunks of compressed data
  18661. this.strm = new zstream();
  18662. this.strm.avail_out = 0;
  18663. var status = zlib_deflate.deflateInit2(
  18664. this.strm,
  18665. opt.level,
  18666. opt.method,
  18667. opt.windowBits,
  18668. opt.memLevel,
  18669. opt.strategy
  18670. );
  18671. if (status !== Z_OK) {
  18672. throw new Error(msg[status]);
  18673. }
  18674. if (opt.header) {
  18675. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18676. }
  18677. };
  18678. /**
  18679. * Deflate#push(data[, mode]) -> Boolean
  18680. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18681. * converted to utf8 byte sequence.
  18682. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18683. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18684. *
  18685. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18686. * new compressed chunks. Returns `true` on success. The last data block must have
  18687. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  18688. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  18689. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  18690. *
  18691. * On fail call [[Deflate#onEnd]] with error code and return false.
  18692. *
  18693. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18694. * array format is detected automatically). Also, don't skip last param and always
  18695. * use the same type in your code (boolean or number). That will improve JS speed.
  18696. *
  18697. * For regular `Array`-s make sure all elements are [0..255].
  18698. *
  18699. * ##### Example
  18700. *
  18701. * ```javascript
  18702. * push(chunk, false); // push one of data chunks
  18703. * ...
  18704. * push(chunk, true); // push last chunk
  18705. * ```
  18706. **/
  18707. Deflate.prototype.push = function(data, mode) {
  18708. var strm = this.strm;
  18709. var chunkSize = this.options.chunkSize;
  18710. var status, _mode;
  18711. if (this.ended) { return false; }
  18712. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18713. // Convert data if needed
  18714. if (typeof data === 'string') {
  18715. // If we need to compress text, change encoding to utf8.
  18716. strm.input = strings.string2buf(data);
  18717. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18718. strm.input = new Uint8Array(data);
  18719. } else {
  18720. strm.input = data;
  18721. }
  18722. strm.next_in = 0;
  18723. strm.avail_in = strm.input.length;
  18724. do {
  18725. if (strm.avail_out === 0) {
  18726. strm.output = new utils.Buf8(chunkSize);
  18727. strm.next_out = 0;
  18728. strm.avail_out = chunkSize;
  18729. }
  18730. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18731. if (status !== Z_STREAM_END && status !== Z_OK) {
  18732. this.onEnd(status);
  18733. this.ended = true;
  18734. return false;
  18735. }
  18736. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  18737. if (this.options.to === 'string') {
  18738. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18739. } else {
  18740. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18741. }
  18742. }
  18743. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18744. // Finalize on the last chunk.
  18745. if (_mode === Z_FINISH) {
  18746. status = zlib_deflate.deflateEnd(this.strm);
  18747. this.onEnd(status);
  18748. this.ended = true;
  18749. return status === Z_OK;
  18750. }
  18751. // callback interim results if Z_SYNC_FLUSH.
  18752. if (_mode === Z_SYNC_FLUSH) {
  18753. this.onEnd(Z_OK);
  18754. strm.avail_out = 0;
  18755. return true;
  18756. }
  18757. return true;
  18758. };
  18759. /**
  18760. * Deflate#onData(chunk) -> Void
  18761. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18762. * on js engine support. When string output requested, each chunk
  18763. * will be string.
  18764. *
  18765. * By default, stores data blocks in `chunks[]` property and glue
  18766. * those in `onEnd`. Override this handler, if you need another behaviour.
  18767. **/
  18768. Deflate.prototype.onData = function(chunk) {
  18769. this.chunks.push(chunk);
  18770. };
  18771. /**
  18772. * Deflate#onEnd(status) -> Void
  18773. * - status (Number): deflate status. 0 (Z_OK) on success,
  18774. * other if not.
  18775. *
  18776. * Called once after you tell deflate that the input stream is
  18777. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  18778. * or if an error happened. By default - join collected chunks,
  18779. * free memory and fill `results` / `err` properties.
  18780. **/
  18781. Deflate.prototype.onEnd = function(status) {
  18782. // On success - join
  18783. if (status === Z_OK) {
  18784. if (this.options.to === 'string') {
  18785. this.result = this.chunks.join('');
  18786. } else {
  18787. this.result = utils.flattenChunks(this.chunks);
  18788. }
  18789. }
  18790. this.chunks = [];
  18791. this.err = status;
  18792. this.msg = this.strm.msg;
  18793. };
  18794. /**
  18795. * deflate(data[, options]) -> Uint8Array|Array|String
  18796. * - data (Uint8Array|Array|String): input data to compress.
  18797. * - options (Object): zlib deflate options.
  18798. *
  18799. * Compress `data` with deflate alrorythm and `options`.
  18800. *
  18801. * Supported options are:
  18802. *
  18803. * - level
  18804. * - windowBits
  18805. * - memLevel
  18806. * - strategy
  18807. *
  18808. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18809. * for more information on these.
  18810. *
  18811. * Sugar (options):
  18812. *
  18813. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  18814. * negative windowBits implicitly.
  18815. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18816. * (each char code [0..255])
  18817. *
  18818. * ##### Example:
  18819. *
  18820. * ```javascript
  18821. * var pako = require('pako')
  18822. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  18823. *
  18824. * console.log(pako.deflate(data));
  18825. * ```
  18826. **/
  18827. function deflate(input, options) {
  18828. var deflator = new Deflate(options);
  18829. deflator.push(input, true);
  18830. // That will never happens, if you don't cheat with options :)
  18831. if (deflator.err) { throw deflator.msg; }
  18832. return deflator.result;
  18833. }
  18834. /**
  18835. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  18836. * - data (Uint8Array|Array|String): input data to compress.
  18837. * - options (Object): zlib deflate options.
  18838. *
  18839. * The same as [[deflate]], but creates raw data, without wrapper
  18840. * (header and adler32 crc).
  18841. **/
  18842. function deflateRaw(input, options) {
  18843. options = options || {};
  18844. options.raw = true;
  18845. return deflate(input, options);
  18846. }
  18847. /**
  18848. * gzip(data[, options]) -> Uint8Array|Array|String
  18849. * - data (Uint8Array|Array|String): input data to compress.
  18850. * - options (Object): zlib deflate options.
  18851. *
  18852. * The same as [[deflate]], but create gzip wrapper instead of
  18853. * deflate one.
  18854. **/
  18855. function gzip(input, options) {
  18856. options = options || {};
  18857. options.gzip = true;
  18858. return deflate(input, options);
  18859. }
  18860. exports.Deflate = Deflate;
  18861. exports.deflate = deflate;
  18862. exports.deflateRaw = deflateRaw;
  18863. exports.gzip = gzip;
  18864. },{"./utils/common":87,"./utils/strings":88,"./zlib/deflate.js":92,"./zlib/messages":97,"./zlib/zstream":99}],86:[function(require,module,exports){
  18865. 'use strict';
  18866. var zlib_inflate = require('./zlib/inflate.js');
  18867. var utils = require('./utils/common');
  18868. var strings = require('./utils/strings');
  18869. var c = require('./zlib/constants');
  18870. var msg = require('./zlib/messages');
  18871. var zstream = require('./zlib/zstream');
  18872. var gzheader = require('./zlib/gzheader');
  18873. var toString = Object.prototype.toString;
  18874. /**
  18875. * class Inflate
  18876. *
  18877. * Generic JS-style wrapper for zlib calls. If you don't need
  18878. * streaming behaviour - use more simple functions: [[inflate]]
  18879. * and [[inflateRaw]].
  18880. **/
  18881. /* internal
  18882. * inflate.chunks -> Array
  18883. *
  18884. * Chunks of output data, if [[Inflate#onData]] not overriden.
  18885. **/
  18886. /**
  18887. * Inflate.result -> Uint8Array|Array|String
  18888. *
  18889. * Uncompressed result, generated by default [[Inflate#onData]]
  18890. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  18891. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  18892. * push a chunk with explicit flush (call [[Inflate#push]] with
  18893. * `Z_SYNC_FLUSH` param).
  18894. **/
  18895. /**
  18896. * Inflate.err -> Number
  18897. *
  18898. * Error code after inflate finished. 0 (Z_OK) on success.
  18899. * Should be checked if broken data possible.
  18900. **/
  18901. /**
  18902. * Inflate.msg -> String
  18903. *
  18904. * Error message, if [[Inflate.err]] != 0
  18905. **/
  18906. /**
  18907. * new Inflate(options)
  18908. * - options (Object): zlib inflate options.
  18909. *
  18910. * Creates new inflator instance with specified params. Throws exception
  18911. * on bad params. Supported options:
  18912. *
  18913. * - `windowBits`
  18914. *
  18915. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18916. * for more information on these.
  18917. *
  18918. * Additional options, for internal needs:
  18919. *
  18920. * - `chunkSize` - size of generated data chunks (16K by default)
  18921. * - `raw` (Boolean) - do raw inflate
  18922. * - `to` (String) - if equal to 'string', then result will be converted
  18923. * from utf8 to utf16 (javascript) string. When string output requested,
  18924. * chunk length can differ from `chunkSize`, depending on content.
  18925. *
  18926. * By default, when no options set, autodetect deflate/gzip data format via
  18927. * wrapper header.
  18928. *
  18929. * ##### Example:
  18930. *
  18931. * ```javascript
  18932. * var pako = require('pako')
  18933. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18934. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18935. *
  18936. * var inflate = new pako.Inflate({ level: 3});
  18937. *
  18938. * inflate.push(chunk1, false);
  18939. * inflate.push(chunk2, true); // true -> last chunk
  18940. *
  18941. * if (inflate.err) { throw new Error(inflate.err); }
  18942. *
  18943. * console.log(inflate.result);
  18944. * ```
  18945. **/
  18946. var Inflate = function(options) {
  18947. this.options = utils.assign({
  18948. chunkSize: 16384,
  18949. windowBits: 0,
  18950. to: ''
  18951. }, options || {});
  18952. var opt = this.options;
  18953. // Force window size for `raw` data, if not set directly,
  18954. // because we have no header for autodetect.
  18955. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  18956. opt.windowBits = -opt.windowBits;
  18957. if (opt.windowBits === 0) { opt.windowBits = -15; }
  18958. }
  18959. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  18960. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  18961. !(options && options.windowBits)) {
  18962. opt.windowBits += 32;
  18963. }
  18964. // Gzip header has no info about windows size, we can do autodetect only
  18965. // for deflate. So, if window size not set, force it to max when gzip possible
  18966. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  18967. // bit 3 (16) -> gzipped data
  18968. // bit 4 (32) -> autodetect gzip/deflate
  18969. if ((opt.windowBits & 15) === 0) {
  18970. opt.windowBits |= 15;
  18971. }
  18972. }
  18973. this.err = 0; // error code, if happens (0 = Z_OK)
  18974. this.msg = ''; // error message
  18975. this.ended = false; // used to avoid multiple onEnd() calls
  18976. this.chunks = []; // chunks of compressed data
  18977. this.strm = new zstream();
  18978. this.strm.avail_out = 0;
  18979. var status = zlib_inflate.inflateInit2(
  18980. this.strm,
  18981. opt.windowBits
  18982. );
  18983. if (status !== c.Z_OK) {
  18984. throw new Error(msg[status]);
  18985. }
  18986. this.header = new gzheader();
  18987. zlib_inflate.inflateGetHeader(this.strm, this.header);
  18988. };
  18989. /**
  18990. * Inflate#push(data[, mode]) -> Boolean
  18991. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  18992. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18993. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18994. *
  18995. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  18996. * new output chunks. Returns `true` on success. The last data block must have
  18997. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  18998. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  18999. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19000. *
  19001. * On fail call [[Inflate#onEnd]] with error code and return false.
  19002. *
  19003. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19004. * format is detected automatically). Also, don't skip last param and always
  19005. * use the same type in your code (boolean or number). That will improve JS speed.
  19006. *
  19007. * For regular `Array`-s make sure all elements are [0..255].
  19008. *
  19009. * ##### Example
  19010. *
  19011. * ```javascript
  19012. * push(chunk, false); // push one of data chunks
  19013. * ...
  19014. * push(chunk, true); // push last chunk
  19015. * ```
  19016. **/
  19017. Inflate.prototype.push = function(data, mode) {
  19018. var strm = this.strm;
  19019. var chunkSize = this.options.chunkSize;
  19020. var status, _mode;
  19021. var next_out_utf8, tail, utf8str;
  19022. // Flag to properly process Z_BUF_ERROR on testing inflate call
  19023. // when we check that all output data was flushed.
  19024. var allowBufError = false;
  19025. if (this.ended) { return false; }
  19026. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19027. // Convert data if needed
  19028. if (typeof data === 'string') {
  19029. // Only binary strings can be decompressed on practice
  19030. strm.input = strings.binstring2buf(data);
  19031. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19032. strm.input = new Uint8Array(data);
  19033. } else {
  19034. strm.input = data;
  19035. }
  19036. strm.next_in = 0;
  19037. strm.avail_in = strm.input.length;
  19038. do {
  19039. if (strm.avail_out === 0) {
  19040. strm.output = new utils.Buf8(chunkSize);
  19041. strm.next_out = 0;
  19042. strm.avail_out = chunkSize;
  19043. }
  19044. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19045. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  19046. status = c.Z_OK;
  19047. allowBufError = false;
  19048. }
  19049. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19050. this.onEnd(status);
  19051. this.ended = true;
  19052. return false;
  19053. }
  19054. if (strm.next_out) {
  19055. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19056. if (this.options.to === 'string') {
  19057. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19058. tail = strm.next_out - next_out_utf8;
  19059. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19060. // move tail
  19061. strm.next_out = tail;
  19062. strm.avail_out = chunkSize - tail;
  19063. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19064. this.onData(utf8str);
  19065. } else {
  19066. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19067. }
  19068. }
  19069. }
  19070. // When no more input data, we should check that internal inflate buffers
  19071. // are flushed. The only way to do it when avail_out = 0 - run one more
  19072. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  19073. // Here we set flag to process this error properly.
  19074. //
  19075. // NOTE. Deflate does not return error in this case and does not needs such
  19076. // logic.
  19077. if (strm.avail_in === 0 && strm.avail_out === 0) {
  19078. allowBufError = true;
  19079. }
  19080. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  19081. if (status === c.Z_STREAM_END) {
  19082. _mode = c.Z_FINISH;
  19083. }
  19084. // Finalize on the last chunk.
  19085. if (_mode === c.Z_FINISH) {
  19086. status = zlib_inflate.inflateEnd(this.strm);
  19087. this.onEnd(status);
  19088. this.ended = true;
  19089. return status === c.Z_OK;
  19090. }
  19091. // callback interim results if Z_SYNC_FLUSH.
  19092. if (_mode === c.Z_SYNC_FLUSH) {
  19093. this.onEnd(c.Z_OK);
  19094. strm.avail_out = 0;
  19095. return true;
  19096. }
  19097. return true;
  19098. };
  19099. /**
  19100. * Inflate#onData(chunk) -> Void
  19101. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19102. * on js engine support. When string output requested, each chunk
  19103. * will be string.
  19104. *
  19105. * By default, stores data blocks in `chunks[]` property and glue
  19106. * those in `onEnd`. Override this handler, if you need another behaviour.
  19107. **/
  19108. Inflate.prototype.onData = function(chunk) {
  19109. this.chunks.push(chunk);
  19110. };
  19111. /**
  19112. * Inflate#onEnd(status) -> Void
  19113. * - status (Number): inflate status. 0 (Z_OK) on success,
  19114. * other if not.
  19115. *
  19116. * Called either after you tell inflate that the input stream is
  19117. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19118. * or if an error happened. By default - join collected chunks,
  19119. * free memory and fill `results` / `err` properties.
  19120. **/
  19121. Inflate.prototype.onEnd = function(status) {
  19122. // On success - join
  19123. if (status === c.Z_OK) {
  19124. if (this.options.to === 'string') {
  19125. // Glue & convert here, until we teach pako to send
  19126. // utf8 alligned strings to onData
  19127. this.result = this.chunks.join('');
  19128. } else {
  19129. this.result = utils.flattenChunks(this.chunks);
  19130. }
  19131. }
  19132. this.chunks = [];
  19133. this.err = status;
  19134. this.msg = this.strm.msg;
  19135. };
  19136. /**
  19137. * inflate(data[, options]) -> Uint8Array|Array|String
  19138. * - data (Uint8Array|Array|String): input data to decompress.
  19139. * - options (Object): zlib inflate options.
  19140. *
  19141. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19142. * format via wrapper header by default. That's why we don't provide
  19143. * separate `ungzip` method.
  19144. *
  19145. * Supported options are:
  19146. *
  19147. * - windowBits
  19148. *
  19149. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19150. * for more information.
  19151. *
  19152. * Sugar (options):
  19153. *
  19154. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19155. * negative windowBits implicitly.
  19156. * - `to` (String) - if equal to 'string', then result will be converted
  19157. * from utf8 to utf16 (javascript) string. When string output requested,
  19158. * chunk length can differ from `chunkSize`, depending on content.
  19159. *
  19160. *
  19161. * ##### Example:
  19162. *
  19163. * ```javascript
  19164. * var pako = require('pako')
  19165. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19166. * , output;
  19167. *
  19168. * try {
  19169. * output = pako.inflate(input);
  19170. * } catch (err)
  19171. * console.log(err);
  19172. * }
  19173. * ```
  19174. **/
  19175. function inflate(input, options) {
  19176. var inflator = new Inflate(options);
  19177. inflator.push(input, true);
  19178. // That will never happens, if you don't cheat with options :)
  19179. if (inflator.err) { throw inflator.msg; }
  19180. return inflator.result;
  19181. }
  19182. /**
  19183. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19184. * - data (Uint8Array|Array|String): input data to decompress.
  19185. * - options (Object): zlib inflate options.
  19186. *
  19187. * The same as [[inflate]], but creates raw data, without wrapper
  19188. * (header and adler32 crc).
  19189. **/
  19190. function inflateRaw(input, options) {
  19191. options = options || {};
  19192. options.raw = true;
  19193. return inflate(input, options);
  19194. }
  19195. /**
  19196. * ungzip(data[, options]) -> Uint8Array|Array|String
  19197. * - data (Uint8Array|Array|String): input data to decompress.
  19198. * - options (Object): zlib inflate options.
  19199. *
  19200. * Just shortcut to [[inflate]], because it autodetects format
  19201. * by header.content. Done for convenience.
  19202. **/
  19203. exports.Inflate = Inflate;
  19204. exports.inflate = inflate;
  19205. exports.inflateRaw = inflateRaw;
  19206. exports.ungzip = inflate;
  19207. },{"./utils/common":87,"./utils/strings":88,"./zlib/constants":90,"./zlib/gzheader":93,"./zlib/inflate.js":95,"./zlib/messages":97,"./zlib/zstream":99}],87:[function(require,module,exports){
  19208. 'use strict';
  19209. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19210. (typeof Uint16Array !== 'undefined') &&
  19211. (typeof Int32Array !== 'undefined');
  19212. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19213. var sources = Array.prototype.slice.call(arguments, 1);
  19214. while (sources.length) {
  19215. var source = sources.shift();
  19216. if (!source) { continue; }
  19217. if (typeof source !== 'object') {
  19218. throw new TypeError(source + 'must be non-object');
  19219. }
  19220. for (var p in source) {
  19221. if (source.hasOwnProperty(p)) {
  19222. obj[p] = source[p];
  19223. }
  19224. }
  19225. }
  19226. return obj;
  19227. };
  19228. // reduce buffer size, avoiding mem copy
  19229. exports.shrinkBuf = function (buf, size) {
  19230. if (buf.length === size) { return buf; }
  19231. if (buf.subarray) { return buf.subarray(0, size); }
  19232. buf.length = size;
  19233. return buf;
  19234. };
  19235. var fnTyped = {
  19236. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19237. if (src.subarray && dest.subarray) {
  19238. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19239. return;
  19240. }
  19241. // Fallback to ordinary array
  19242. for (var i=0; i<len; i++) {
  19243. dest[dest_offs + i] = src[src_offs + i];
  19244. }
  19245. },
  19246. // Join array of chunks to single array.
  19247. flattenChunks: function(chunks) {
  19248. var i, l, len, pos, chunk, result;
  19249. // calculate data length
  19250. len = 0;
  19251. for (i=0, l=chunks.length; i<l; i++) {
  19252. len += chunks[i].length;
  19253. }
  19254. // join chunks
  19255. result = new Uint8Array(len);
  19256. pos = 0;
  19257. for (i=0, l=chunks.length; i<l; i++) {
  19258. chunk = chunks[i];
  19259. result.set(chunk, pos);
  19260. pos += chunk.length;
  19261. }
  19262. return result;
  19263. }
  19264. };
  19265. var fnUntyped = {
  19266. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19267. for (var i=0; i<len; i++) {
  19268. dest[dest_offs + i] = src[src_offs + i];
  19269. }
  19270. },
  19271. // Join array of chunks to single array.
  19272. flattenChunks: function(chunks) {
  19273. return [].concat.apply([], chunks);
  19274. }
  19275. };
  19276. // Enable/Disable typed arrays use, for testing
  19277. //
  19278. exports.setTyped = function (on) {
  19279. if (on) {
  19280. exports.Buf8 = Uint8Array;
  19281. exports.Buf16 = Uint16Array;
  19282. exports.Buf32 = Int32Array;
  19283. exports.assign(exports, fnTyped);
  19284. } else {
  19285. exports.Buf8 = Array;
  19286. exports.Buf16 = Array;
  19287. exports.Buf32 = Array;
  19288. exports.assign(exports, fnUntyped);
  19289. }
  19290. };
  19291. exports.setTyped(TYPED_OK);
  19292. },{}],88:[function(require,module,exports){
  19293. // String encode/decode helpers
  19294. 'use strict';
  19295. var utils = require('./common');
  19296. // Quick check if we can use fast array to bin string conversion
  19297. //
  19298. // - apply(Array) can fail on Android 2.2
  19299. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19300. //
  19301. var STR_APPLY_OK = true;
  19302. var STR_APPLY_UIA_OK = true;
  19303. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19304. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19305. // Table with utf8 lengths (calculated by first byte of sequence)
  19306. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19307. // because max possible codepoint is 0x10ffff
  19308. var _utf8len = new utils.Buf8(256);
  19309. for (var q=0; q<256; q++) {
  19310. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  19311. }
  19312. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19313. // convert string to array (typed, when possible)
  19314. exports.string2buf = function (str) {
  19315. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19316. // count binary size
  19317. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19318. c = str.charCodeAt(m_pos);
  19319. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19320. c2 = str.charCodeAt(m_pos+1);
  19321. if ((c2 & 0xfc00) === 0xdc00) {
  19322. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19323. m_pos++;
  19324. }
  19325. }
  19326. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19327. }
  19328. // allocate buffer
  19329. buf = new utils.Buf8(buf_len);
  19330. // convert
  19331. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19332. c = str.charCodeAt(m_pos);
  19333. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19334. c2 = str.charCodeAt(m_pos+1);
  19335. if ((c2 & 0xfc00) === 0xdc00) {
  19336. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19337. m_pos++;
  19338. }
  19339. }
  19340. if (c < 0x80) {
  19341. /* one byte */
  19342. buf[i++] = c;
  19343. } else if (c < 0x800) {
  19344. /* two bytes */
  19345. buf[i++] = 0xC0 | (c >>> 6);
  19346. buf[i++] = 0x80 | (c & 0x3f);
  19347. } else if (c < 0x10000) {
  19348. /* three bytes */
  19349. buf[i++] = 0xE0 | (c >>> 12);
  19350. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19351. buf[i++] = 0x80 | (c & 0x3f);
  19352. } else {
  19353. /* four bytes */
  19354. buf[i++] = 0xf0 | (c >>> 18);
  19355. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19356. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19357. buf[i++] = 0x80 | (c & 0x3f);
  19358. }
  19359. }
  19360. return buf;
  19361. };
  19362. // Helper (used in 2 places)
  19363. function buf2binstring(buf, len) {
  19364. // use fallback for big arrays to avoid stack overflow
  19365. if (len < 65537) {
  19366. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19367. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19368. }
  19369. }
  19370. var result = '';
  19371. for (var i=0; i < len; i++) {
  19372. result += String.fromCharCode(buf[i]);
  19373. }
  19374. return result;
  19375. }
  19376. // Convert byte array to binary string
  19377. exports.buf2binstring = function(buf) {
  19378. return buf2binstring(buf, buf.length);
  19379. };
  19380. // Convert binary string (typed, when possible)
  19381. exports.binstring2buf = function(str) {
  19382. var buf = new utils.Buf8(str.length);
  19383. for (var i=0, len=buf.length; i < len; i++) {
  19384. buf[i] = str.charCodeAt(i);
  19385. }
  19386. return buf;
  19387. };
  19388. // convert array to string
  19389. exports.buf2string = function (buf, max) {
  19390. var i, out, c, c_len;
  19391. var len = max || buf.length;
  19392. // Reserve max possible length (2 words per char)
  19393. // NB: by unknown reasons, Array is significantly faster for
  19394. // String.fromCharCode.apply than Uint16Array.
  19395. var utf16buf = new Array(len*2);
  19396. for (out=0, i=0; i<len;) {
  19397. c = buf[i++];
  19398. // quick process ascii
  19399. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19400. c_len = _utf8len[c];
  19401. // skip 5 & 6 byte codes
  19402. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19403. // apply mask on first byte
  19404. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19405. // join the rest
  19406. while (c_len > 1 && i < len) {
  19407. c = (c << 6) | (buf[i++] & 0x3f);
  19408. c_len--;
  19409. }
  19410. // terminated by end of string?
  19411. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19412. if (c < 0x10000) {
  19413. utf16buf[out++] = c;
  19414. } else {
  19415. c -= 0x10000;
  19416. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19417. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19418. }
  19419. }
  19420. return buf2binstring(utf16buf, out);
  19421. };
  19422. // Calculate max possible position in utf8 buffer,
  19423. // that will not break sequence. If that's not possible
  19424. // - (very small limits) return max size as is.
  19425. //
  19426. // buf[] - utf8 bytes array
  19427. // max - length limit (mandatory);
  19428. exports.utf8border = function(buf, max) {
  19429. var pos;
  19430. max = max || buf.length;
  19431. if (max > buf.length) { max = buf.length; }
  19432. // go back from last position, until start of sequence found
  19433. pos = max-1;
  19434. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  19435. // Fuckup - very small and broken sequence,
  19436. // return max, because we should return something anyway.
  19437. if (pos < 0) { return max; }
  19438. // If we came to start of buffer - that means vuffer is too small,
  19439. // return max too.
  19440. if (pos === 0) { return max; }
  19441. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  19442. };
  19443. },{"./common":87}],89:[function(require,module,exports){
  19444. 'use strict';
  19445. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  19446. // It doesn't worth to make additional optimizationa as in original.
  19447. // Small size is preferable.
  19448. function adler32(adler, buf, len, pos) {
  19449. var s1 = (adler & 0xffff) |0,
  19450. s2 = ((adler >>> 16) & 0xffff) |0,
  19451. n = 0;
  19452. while (len !== 0) {
  19453. // Set limit ~ twice less than 5552, to keep
  19454. // s2 in 31-bits, because we force signed ints.
  19455. // in other case %= will fail.
  19456. n = len > 2000 ? 2000 : len;
  19457. len -= n;
  19458. do {
  19459. s1 = (s1 + buf[pos++]) |0;
  19460. s2 = (s2 + s1) |0;
  19461. } while (--n);
  19462. s1 %= 65521;
  19463. s2 %= 65521;
  19464. }
  19465. return (s1 | (s2 << 16)) |0;
  19466. }
  19467. module.exports = adler32;
  19468. },{}],90:[function(require,module,exports){
  19469. module.exports = {
  19470. /* Allowed flush values; see deflate() and inflate() below for details */
  19471. Z_NO_FLUSH: 0,
  19472. Z_PARTIAL_FLUSH: 1,
  19473. Z_SYNC_FLUSH: 2,
  19474. Z_FULL_FLUSH: 3,
  19475. Z_FINISH: 4,
  19476. Z_BLOCK: 5,
  19477. Z_TREES: 6,
  19478. /* Return codes for the compression/decompression functions. Negative values
  19479. * are errors, positive values are used for special but normal events.
  19480. */
  19481. Z_OK: 0,
  19482. Z_STREAM_END: 1,
  19483. Z_NEED_DICT: 2,
  19484. Z_ERRNO: -1,
  19485. Z_STREAM_ERROR: -2,
  19486. Z_DATA_ERROR: -3,
  19487. //Z_MEM_ERROR: -4,
  19488. Z_BUF_ERROR: -5,
  19489. //Z_VERSION_ERROR: -6,
  19490. /* compression levels */
  19491. Z_NO_COMPRESSION: 0,
  19492. Z_BEST_SPEED: 1,
  19493. Z_BEST_COMPRESSION: 9,
  19494. Z_DEFAULT_COMPRESSION: -1,
  19495. Z_FILTERED: 1,
  19496. Z_HUFFMAN_ONLY: 2,
  19497. Z_RLE: 3,
  19498. Z_FIXED: 4,
  19499. Z_DEFAULT_STRATEGY: 0,
  19500. /* Possible values of the data_type field (though see inflate()) */
  19501. Z_BINARY: 0,
  19502. Z_TEXT: 1,
  19503. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  19504. Z_UNKNOWN: 2,
  19505. /* The deflate compression method */
  19506. Z_DEFLATED: 8
  19507. //Z_NULL: null // Use -1 or null inline, depending on var type
  19508. };
  19509. },{}],91:[function(require,module,exports){
  19510. 'use strict';
  19511. // Note: we can't get significant speed boost here.
  19512. // So write code to minimize size - no pregenerated tables
  19513. // and array tools dependencies.
  19514. // Use ordinary array, since untyped makes no boost here
  19515. function makeTable() {
  19516. var c, table = [];
  19517. for (var n =0; n < 256; n++) {
  19518. c = n;
  19519. for (var k =0; k < 8; k++) {
  19520. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  19521. }
  19522. table[n] = c;
  19523. }
  19524. return table;
  19525. }
  19526. // Create table on load. Just 255 signed longs. Not a problem.
  19527. var crcTable = makeTable();
  19528. function crc32(crc, buf, len, pos) {
  19529. var t = crcTable,
  19530. end = pos + len;
  19531. crc = crc ^ (-1);
  19532. for (var i = pos; i < end; i++) {
  19533. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  19534. }
  19535. return (crc ^ (-1)); // >>> 0;
  19536. }
  19537. module.exports = crc32;
  19538. },{}],92:[function(require,module,exports){
  19539. 'use strict';
  19540. var utils = require('../utils/common');
  19541. var trees = require('./trees');
  19542. var adler32 = require('./adler32');
  19543. var crc32 = require('./crc32');
  19544. var msg = require('./messages');
  19545. /* Public constants ==========================================================*/
  19546. /* ===========================================================================*/
  19547. /* Allowed flush values; see deflate() and inflate() below for details */
  19548. var Z_NO_FLUSH = 0;
  19549. var Z_PARTIAL_FLUSH = 1;
  19550. //var Z_SYNC_FLUSH = 2;
  19551. var Z_FULL_FLUSH = 3;
  19552. var Z_FINISH = 4;
  19553. var Z_BLOCK = 5;
  19554. //var Z_TREES = 6;
  19555. /* Return codes for the compression/decompression functions. Negative values
  19556. * are errors, positive values are used for special but normal events.
  19557. */
  19558. var Z_OK = 0;
  19559. var Z_STREAM_END = 1;
  19560. //var Z_NEED_DICT = 2;
  19561. //var Z_ERRNO = -1;
  19562. var Z_STREAM_ERROR = -2;
  19563. var Z_DATA_ERROR = -3;
  19564. //var Z_MEM_ERROR = -4;
  19565. var Z_BUF_ERROR = -5;
  19566. //var Z_VERSION_ERROR = -6;
  19567. /* compression levels */
  19568. //var Z_NO_COMPRESSION = 0;
  19569. //var Z_BEST_SPEED = 1;
  19570. //var Z_BEST_COMPRESSION = 9;
  19571. var Z_DEFAULT_COMPRESSION = -1;
  19572. var Z_FILTERED = 1;
  19573. var Z_HUFFMAN_ONLY = 2;
  19574. var Z_RLE = 3;
  19575. var Z_FIXED = 4;
  19576. var Z_DEFAULT_STRATEGY = 0;
  19577. /* Possible values of the data_type field (though see inflate()) */
  19578. //var Z_BINARY = 0;
  19579. //var Z_TEXT = 1;
  19580. //var Z_ASCII = 1; // = Z_TEXT
  19581. var Z_UNKNOWN = 2;
  19582. /* The deflate compression method */
  19583. var Z_DEFLATED = 8;
  19584. /*============================================================================*/
  19585. var MAX_MEM_LEVEL = 9;
  19586. /* Maximum value for memLevel in deflateInit2 */
  19587. var MAX_WBITS = 15;
  19588. /* 32K LZ77 window */
  19589. var DEF_MEM_LEVEL = 8;
  19590. var LENGTH_CODES = 29;
  19591. /* number of length codes, not counting the special END_BLOCK code */
  19592. var LITERALS = 256;
  19593. /* number of literal bytes 0..255 */
  19594. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19595. /* number of Literal or Length codes, including the END_BLOCK code */
  19596. var D_CODES = 30;
  19597. /* number of distance codes */
  19598. var BL_CODES = 19;
  19599. /* number of codes used to transfer the bit lengths */
  19600. var HEAP_SIZE = 2*L_CODES + 1;
  19601. /* maximum heap size */
  19602. var MAX_BITS = 15;
  19603. /* All codes must not exceed MAX_BITS bits */
  19604. var MIN_MATCH = 3;
  19605. var MAX_MATCH = 258;
  19606. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  19607. var PRESET_DICT = 0x20;
  19608. var INIT_STATE = 42;
  19609. var EXTRA_STATE = 69;
  19610. var NAME_STATE = 73;
  19611. var COMMENT_STATE = 91;
  19612. var HCRC_STATE = 103;
  19613. var BUSY_STATE = 113;
  19614. var FINISH_STATE = 666;
  19615. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  19616. var BS_BLOCK_DONE = 2; /* block flush performed */
  19617. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  19618. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  19619. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  19620. function err(strm, errorCode) {
  19621. strm.msg = msg[errorCode];
  19622. return errorCode;
  19623. }
  19624. function rank(f) {
  19625. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  19626. }
  19627. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19628. /* =========================================================================
  19629. * Flush as much pending output as possible. All deflate() output goes
  19630. * through this function so some applications may wish to modify it
  19631. * to avoid allocating a large strm->output buffer and copying into it.
  19632. * (See also read_buf()).
  19633. */
  19634. function flush_pending(strm) {
  19635. var s = strm.state;
  19636. //_tr_flush_bits(s);
  19637. var len = s.pending;
  19638. if (len > strm.avail_out) {
  19639. len = strm.avail_out;
  19640. }
  19641. if (len === 0) { return; }
  19642. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  19643. strm.next_out += len;
  19644. s.pending_out += len;
  19645. strm.total_out += len;
  19646. strm.avail_out -= len;
  19647. s.pending -= len;
  19648. if (s.pending === 0) {
  19649. s.pending_out = 0;
  19650. }
  19651. }
  19652. function flush_block_only (s, last) {
  19653. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  19654. s.block_start = s.strstart;
  19655. flush_pending(s.strm);
  19656. }
  19657. function put_byte(s, b) {
  19658. s.pending_buf[s.pending++] = b;
  19659. }
  19660. /* =========================================================================
  19661. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  19662. * IN assertion: the stream state is correct and there is enough room in
  19663. * pending_buf.
  19664. */
  19665. function putShortMSB(s, b) {
  19666. // put_byte(s, (Byte)(b >> 8));
  19667. // put_byte(s, (Byte)(b & 0xff));
  19668. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  19669. s.pending_buf[s.pending++] = b & 0xff;
  19670. }
  19671. /* ===========================================================================
  19672. * Read a new buffer from the current input stream, update the adler32
  19673. * and total number of bytes read. All deflate() input goes through
  19674. * this function so some applications may wish to modify it to avoid
  19675. * allocating a large strm->input buffer and copying from it.
  19676. * (See also flush_pending()).
  19677. */
  19678. function read_buf(strm, buf, start, size) {
  19679. var len = strm.avail_in;
  19680. if (len > size) { len = size; }
  19681. if (len === 0) { return 0; }
  19682. strm.avail_in -= len;
  19683. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  19684. if (strm.state.wrap === 1) {
  19685. strm.adler = adler32(strm.adler, buf, len, start);
  19686. }
  19687. else if (strm.state.wrap === 2) {
  19688. strm.adler = crc32(strm.adler, buf, len, start);
  19689. }
  19690. strm.next_in += len;
  19691. strm.total_in += len;
  19692. return len;
  19693. }
  19694. /* ===========================================================================
  19695. * Set match_start to the longest match starting at the given string and
  19696. * return its length. Matches shorter or equal to prev_length are discarded,
  19697. * in which case the result is equal to prev_length and match_start is
  19698. * garbage.
  19699. * IN assertions: cur_match is the head of the hash chain for the current
  19700. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  19701. * OUT assertion: the match length is not greater than s->lookahead.
  19702. */
  19703. function longest_match(s, cur_match) {
  19704. var chain_length = s.max_chain_length; /* max hash chain length */
  19705. var scan = s.strstart; /* current string */
  19706. var match; /* matched string */
  19707. var len; /* length of current match */
  19708. var best_len = s.prev_length; /* best match length so far */
  19709. var nice_match = s.nice_match; /* stop if match long enough */
  19710. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19711. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19712. var _win = s.window; // shortcut
  19713. var wmask = s.w_mask;
  19714. var prev = s.prev;
  19715. /* Stop when cur_match becomes <= limit. To simplify the code,
  19716. * we prevent matches with the string of window index 0.
  19717. */
  19718. var strend = s.strstart + MAX_MATCH;
  19719. var scan_end1 = _win[scan + best_len - 1];
  19720. var scan_end = _win[scan + best_len];
  19721. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19722. * It is easy to get rid of this optimization if necessary.
  19723. */
  19724. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19725. /* Do not waste too much time if we already have a good match: */
  19726. if (s.prev_length >= s.good_match) {
  19727. chain_length >>= 2;
  19728. }
  19729. /* Do not look for matches beyond the end of the input. This is necessary
  19730. * to make deflate deterministic.
  19731. */
  19732. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19733. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19734. do {
  19735. // Assert(cur_match < s->strstart, "no future");
  19736. match = cur_match;
  19737. /* Skip to next match if the match length cannot increase
  19738. * or if the match length is less than 2. Note that the checks below
  19739. * for insufficient lookahead only occur occasionally for performance
  19740. * reasons. Therefore uninitialized memory will be accessed, and
  19741. * conditional jumps will be made that depend on those values.
  19742. * However the length of the match is limited to the lookahead, so
  19743. * the output of deflate is not affected by the uninitialized values.
  19744. */
  19745. if (_win[match + best_len] !== scan_end ||
  19746. _win[match + best_len - 1] !== scan_end1 ||
  19747. _win[match] !== _win[scan] ||
  19748. _win[++match] !== _win[scan + 1]) {
  19749. continue;
  19750. }
  19751. /* The check at best_len-1 can be removed because it will be made
  19752. * again later. (This heuristic is not always a win.)
  19753. * It is not necessary to compare scan[2] and match[2] since they
  19754. * are always equal when the other bytes match, given that
  19755. * the hash keys are equal and that HASH_BITS >= 8.
  19756. */
  19757. scan += 2;
  19758. match++;
  19759. // Assert(*scan == *match, "match[2]?");
  19760. /* We check for insufficient lookahead only every 8th comparison;
  19761. * the 256th check will be made at strstart+258.
  19762. */
  19763. do {
  19764. /*jshint noempty:false*/
  19765. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19766. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19767. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19768. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19769. scan < strend);
  19770. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19771. len = MAX_MATCH - (strend - scan);
  19772. scan = strend - MAX_MATCH;
  19773. if (len > best_len) {
  19774. s.match_start = cur_match;
  19775. best_len = len;
  19776. if (len >= nice_match) {
  19777. break;
  19778. }
  19779. scan_end1 = _win[scan + best_len - 1];
  19780. scan_end = _win[scan + best_len];
  19781. }
  19782. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19783. if (best_len <= s.lookahead) {
  19784. return best_len;
  19785. }
  19786. return s.lookahead;
  19787. }
  19788. /* ===========================================================================
  19789. * Fill the window when the lookahead becomes insufficient.
  19790. * Updates strstart and lookahead.
  19791. *
  19792. * IN assertion: lookahead < MIN_LOOKAHEAD
  19793. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  19794. * At least one byte has been read, or avail_in == 0; reads are
  19795. * performed for at least two bytes (required for the zip translate_eol
  19796. * option -- not supported here).
  19797. */
  19798. function fill_window(s) {
  19799. var _w_size = s.w_size;
  19800. var p, n, m, more, str;
  19801. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  19802. do {
  19803. more = s.window_size - s.lookahead - s.strstart;
  19804. // JS ints have 32 bit, block below not needed
  19805. /* Deal with !@#$% 64K limit: */
  19806. //if (sizeof(int) <= 2) {
  19807. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  19808. // more = wsize;
  19809. //
  19810. // } else if (more == (unsigned)(-1)) {
  19811. // /* Very unlikely, but possible on 16 bit machine if
  19812. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  19813. // */
  19814. // more--;
  19815. // }
  19816. //}
  19817. /* If the window is almost full and there is insufficient lookahead,
  19818. * move the upper half to the lower one to make room in the upper half.
  19819. */
  19820. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  19821. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  19822. s.match_start -= _w_size;
  19823. s.strstart -= _w_size;
  19824. /* we now have strstart >= MAX_DIST */
  19825. s.block_start -= _w_size;
  19826. /* Slide the hash table (could be avoided with 32 bit values
  19827. at the expense of memory usage). We slide even when level == 0
  19828. to keep the hash table consistent if we switch back to level > 0
  19829. later. (Using level 0 permanently is not an optimal usage of
  19830. zlib, so we don't care about this pathological case.)
  19831. */
  19832. n = s.hash_size;
  19833. p = n;
  19834. do {
  19835. m = s.head[--p];
  19836. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  19837. } while (--n);
  19838. n = _w_size;
  19839. p = n;
  19840. do {
  19841. m = s.prev[--p];
  19842. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  19843. /* If n is not on any hash chain, prev[n] is garbage but
  19844. * its value will never be used.
  19845. */
  19846. } while (--n);
  19847. more += _w_size;
  19848. }
  19849. if (s.strm.avail_in === 0) {
  19850. break;
  19851. }
  19852. /* If there was no sliding:
  19853. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  19854. * more == window_size - lookahead - strstart
  19855. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  19856. * => more >= window_size - 2*WSIZE + 2
  19857. * In the BIG_MEM or MMAP case (not yet supported),
  19858. * window_size == input_size + MIN_LOOKAHEAD &&
  19859. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  19860. * Otherwise, window_size == 2*WSIZE so more >= 2.
  19861. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  19862. */
  19863. //Assert(more >= 2, "more < 2");
  19864. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  19865. s.lookahead += n;
  19866. /* Initialize the hash value now that we have some input: */
  19867. if (s.lookahead + s.insert >= MIN_MATCH) {
  19868. str = s.strstart - s.insert;
  19869. s.ins_h = s.window[str];
  19870. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  19871. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  19872. //#if MIN_MATCH != 3
  19873. // Call update_hash() MIN_MATCH-3 more times
  19874. //#endif
  19875. while (s.insert) {
  19876. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  19877. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  19878. s.prev[str & s.w_mask] = s.head[s.ins_h];
  19879. s.head[s.ins_h] = str;
  19880. str++;
  19881. s.insert--;
  19882. if (s.lookahead + s.insert < MIN_MATCH) {
  19883. break;
  19884. }
  19885. }
  19886. }
  19887. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  19888. * but this is not important since only literal bytes will be emitted.
  19889. */
  19890. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  19891. /* If the WIN_INIT bytes after the end of the current data have never been
  19892. * written, then zero those bytes in order to avoid memory check reports of
  19893. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  19894. * the longest match routines. Update the high water mark for the next
  19895. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  19896. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  19897. */
  19898. // if (s.high_water < s.window_size) {
  19899. // var curr = s.strstart + s.lookahead;
  19900. // var init = 0;
  19901. //
  19902. // if (s.high_water < curr) {
  19903. // /* Previous high water mark below current data -- zero WIN_INIT
  19904. // * bytes or up to end of window, whichever is less.
  19905. // */
  19906. // init = s.window_size - curr;
  19907. // if (init > WIN_INIT)
  19908. // init = WIN_INIT;
  19909. // zmemzero(s->window + curr, (unsigned)init);
  19910. // s->high_water = curr + init;
  19911. // }
  19912. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  19913. // /* High water mark at or above current data, but below current data
  19914. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  19915. // * to end of window, whichever is less.
  19916. // */
  19917. // init = (ulg)curr + WIN_INIT - s->high_water;
  19918. // if (init > s->window_size - s->high_water)
  19919. // init = s->window_size - s->high_water;
  19920. // zmemzero(s->window + s->high_water, (unsigned)init);
  19921. // s->high_water += init;
  19922. // }
  19923. // }
  19924. //
  19925. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  19926. // "not enough room for search");
  19927. }
  19928. /* ===========================================================================
  19929. * Copy without compression as much as possible from the input stream, return
  19930. * the current block state.
  19931. * This function does not insert new strings in the dictionary since
  19932. * uncompressible data is probably not useful. This function is used
  19933. * only for the level=0 compression option.
  19934. * NOTE: this function should be optimized to avoid extra copying from
  19935. * window to pending_buf.
  19936. */
  19937. function deflate_stored(s, flush) {
  19938. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  19939. * to pending_buf_size, and each stored block has a 5 byte header:
  19940. */
  19941. var max_block_size = 0xffff;
  19942. if (max_block_size > s.pending_buf_size - 5) {
  19943. max_block_size = s.pending_buf_size - 5;
  19944. }
  19945. /* Copy as much as possible from input to output: */
  19946. for (;;) {
  19947. /* Fill the window as much as possible: */
  19948. if (s.lookahead <= 1) {
  19949. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  19950. // s->block_start >= (long)s->w_size, "slide too late");
  19951. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  19952. // s.block_start >= s.w_size)) {
  19953. // throw new Error("slide too late");
  19954. // }
  19955. fill_window(s);
  19956. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  19957. return BS_NEED_MORE;
  19958. }
  19959. if (s.lookahead === 0) {
  19960. break;
  19961. }
  19962. /* flush the current block */
  19963. }
  19964. //Assert(s->block_start >= 0L, "block gone");
  19965. // if (s.block_start < 0) throw new Error("block gone");
  19966. s.strstart += s.lookahead;
  19967. s.lookahead = 0;
  19968. /* Emit a stored block if pending_buf will be full: */
  19969. var max_start = s.block_start + max_block_size;
  19970. if (s.strstart === 0 || s.strstart >= max_start) {
  19971. /* strstart == 0 is possible when wraparound on 16-bit machine */
  19972. s.lookahead = s.strstart - max_start;
  19973. s.strstart = max_start;
  19974. /*** FLUSH_BLOCK(s, 0); ***/
  19975. flush_block_only(s, false);
  19976. if (s.strm.avail_out === 0) {
  19977. return BS_NEED_MORE;
  19978. }
  19979. /***/
  19980. }
  19981. /* Flush if we may have to slide, otherwise block_start may become
  19982. * negative and the data will be gone:
  19983. */
  19984. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  19985. /*** FLUSH_BLOCK(s, 0); ***/
  19986. flush_block_only(s, false);
  19987. if (s.strm.avail_out === 0) {
  19988. return BS_NEED_MORE;
  19989. }
  19990. /***/
  19991. }
  19992. }
  19993. s.insert = 0;
  19994. if (flush === Z_FINISH) {
  19995. /*** FLUSH_BLOCK(s, 1); ***/
  19996. flush_block_only(s, true);
  19997. if (s.strm.avail_out === 0) {
  19998. return BS_FINISH_STARTED;
  19999. }
  20000. /***/
  20001. return BS_FINISH_DONE;
  20002. }
  20003. if (s.strstart > s.block_start) {
  20004. /*** FLUSH_BLOCK(s, 0); ***/
  20005. flush_block_only(s, false);
  20006. if (s.strm.avail_out === 0) {
  20007. return BS_NEED_MORE;
  20008. }
  20009. /***/
  20010. }
  20011. return BS_NEED_MORE;
  20012. }
  20013. /* ===========================================================================
  20014. * Compress as much as possible from the input stream, return the current
  20015. * block state.
  20016. * This function does not perform lazy evaluation of matches and inserts
  20017. * new strings in the dictionary only for unmatched strings or for short
  20018. * matches. It is used only for the fast compression options.
  20019. */
  20020. function deflate_fast(s, flush) {
  20021. var hash_head; /* head of the hash chain */
  20022. var bflush; /* set if current block must be flushed */
  20023. for (;;) {
  20024. /* Make sure that we always have enough lookahead, except
  20025. * at the end of the input file. We need MAX_MATCH bytes
  20026. * for the next match, plus MIN_MATCH bytes to insert the
  20027. * string following the next match.
  20028. */
  20029. if (s.lookahead < MIN_LOOKAHEAD) {
  20030. fill_window(s);
  20031. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20032. return BS_NEED_MORE;
  20033. }
  20034. if (s.lookahead === 0) {
  20035. break; /* flush the current block */
  20036. }
  20037. }
  20038. /* Insert the string window[strstart .. strstart+2] in the
  20039. * dictionary, and set hash_head to the head of the hash chain:
  20040. */
  20041. hash_head = 0/*NIL*/;
  20042. if (s.lookahead >= MIN_MATCH) {
  20043. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20044. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20045. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20046. s.head[s.ins_h] = s.strstart;
  20047. /***/
  20048. }
  20049. /* Find the longest match, discarding those <= prev_length.
  20050. * At this point we have always match_length < MIN_MATCH
  20051. */
  20052. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20053. /* To simplify the code, we prevent matches with the string
  20054. * of window index 0 (in particular we have to avoid a match
  20055. * of the string with itself at the start of the input file).
  20056. */
  20057. s.match_length = longest_match(s, hash_head);
  20058. /* longest_match() sets match_start */
  20059. }
  20060. if (s.match_length >= MIN_MATCH) {
  20061. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20062. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20063. s.match_length - MIN_MATCH, bflush); ***/
  20064. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20065. s.lookahead -= s.match_length;
  20066. /* Insert new strings in the hash table only if the match length
  20067. * is not too large. This saves time but degrades compression.
  20068. */
  20069. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20070. s.match_length--; /* string at strstart already in table */
  20071. do {
  20072. s.strstart++;
  20073. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20074. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20075. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20076. s.head[s.ins_h] = s.strstart;
  20077. /***/
  20078. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20079. * always MIN_MATCH bytes ahead.
  20080. */
  20081. } while (--s.match_length !== 0);
  20082. s.strstart++;
  20083. } else
  20084. {
  20085. s.strstart += s.match_length;
  20086. s.match_length = 0;
  20087. s.ins_h = s.window[s.strstart];
  20088. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20089. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20090. //#if MIN_MATCH != 3
  20091. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20092. //#endif
  20093. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20094. * matter since it will be recomputed at next deflate call.
  20095. */
  20096. }
  20097. } else {
  20098. /* No match, output a literal byte */
  20099. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20100. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20101. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20102. s.lookahead--;
  20103. s.strstart++;
  20104. }
  20105. if (bflush) {
  20106. /*** FLUSH_BLOCK(s, 0); ***/
  20107. flush_block_only(s, false);
  20108. if (s.strm.avail_out === 0) {
  20109. return BS_NEED_MORE;
  20110. }
  20111. /***/
  20112. }
  20113. }
  20114. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20115. if (flush === Z_FINISH) {
  20116. /*** FLUSH_BLOCK(s, 1); ***/
  20117. flush_block_only(s, true);
  20118. if (s.strm.avail_out === 0) {
  20119. return BS_FINISH_STARTED;
  20120. }
  20121. /***/
  20122. return BS_FINISH_DONE;
  20123. }
  20124. if (s.last_lit) {
  20125. /*** FLUSH_BLOCK(s, 0); ***/
  20126. flush_block_only(s, false);
  20127. if (s.strm.avail_out === 0) {
  20128. return BS_NEED_MORE;
  20129. }
  20130. /***/
  20131. }
  20132. return BS_BLOCK_DONE;
  20133. }
  20134. /* ===========================================================================
  20135. * Same as above, but achieves better compression. We use a lazy
  20136. * evaluation for matches: a match is finally adopted only if there is
  20137. * no better match at the next window position.
  20138. */
  20139. function deflate_slow(s, flush) {
  20140. var hash_head; /* head of hash chain */
  20141. var bflush; /* set if current block must be flushed */
  20142. var max_insert;
  20143. /* Process the input block. */
  20144. for (;;) {
  20145. /* Make sure that we always have enough lookahead, except
  20146. * at the end of the input file. We need MAX_MATCH bytes
  20147. * for the next match, plus MIN_MATCH bytes to insert the
  20148. * string following the next match.
  20149. */
  20150. if (s.lookahead < MIN_LOOKAHEAD) {
  20151. fill_window(s);
  20152. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20153. return BS_NEED_MORE;
  20154. }
  20155. if (s.lookahead === 0) { break; } /* flush the current block */
  20156. }
  20157. /* Insert the string window[strstart .. strstart+2] in the
  20158. * dictionary, and set hash_head to the head of the hash chain:
  20159. */
  20160. hash_head = 0/*NIL*/;
  20161. if (s.lookahead >= MIN_MATCH) {
  20162. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20163. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20164. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20165. s.head[s.ins_h] = s.strstart;
  20166. /***/
  20167. }
  20168. /* Find the longest match, discarding those <= prev_length.
  20169. */
  20170. s.prev_length = s.match_length;
  20171. s.prev_match = s.match_start;
  20172. s.match_length = MIN_MATCH-1;
  20173. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20174. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20175. /* To simplify the code, we prevent matches with the string
  20176. * of window index 0 (in particular we have to avoid a match
  20177. * of the string with itself at the start of the input file).
  20178. */
  20179. s.match_length = longest_match(s, hash_head);
  20180. /* longest_match() sets match_start */
  20181. if (s.match_length <= 5 &&
  20182. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20183. /* If prev_match is also MIN_MATCH, match_start is garbage
  20184. * but we will ignore the current match anyway.
  20185. */
  20186. s.match_length = MIN_MATCH-1;
  20187. }
  20188. }
  20189. /* If there was a match at the previous step and the current
  20190. * match is not better, output the previous match:
  20191. */
  20192. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20193. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20194. /* Do not insert strings in hash table beyond this. */
  20195. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20196. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20197. s.prev_length - MIN_MATCH, bflush);***/
  20198. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20199. /* Insert in hash table all strings up to the end of the match.
  20200. * strstart-1 and strstart are already inserted. If there is not
  20201. * enough lookahead, the last two strings are not inserted in
  20202. * the hash table.
  20203. */
  20204. s.lookahead -= s.prev_length-1;
  20205. s.prev_length -= 2;
  20206. do {
  20207. if (++s.strstart <= max_insert) {
  20208. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20209. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20210. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20211. s.head[s.ins_h] = s.strstart;
  20212. /***/
  20213. }
  20214. } while (--s.prev_length !== 0);
  20215. s.match_available = 0;
  20216. s.match_length = MIN_MATCH-1;
  20217. s.strstart++;
  20218. if (bflush) {
  20219. /*** FLUSH_BLOCK(s, 0); ***/
  20220. flush_block_only(s, false);
  20221. if (s.strm.avail_out === 0) {
  20222. return BS_NEED_MORE;
  20223. }
  20224. /***/
  20225. }
  20226. } else if (s.match_available) {
  20227. /* If there was no match at the previous position, output a
  20228. * single literal. If there was a match but the current match
  20229. * is longer, truncate the previous match to a single literal.
  20230. */
  20231. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20232. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20233. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20234. if (bflush) {
  20235. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20236. flush_block_only(s, false);
  20237. /***/
  20238. }
  20239. s.strstart++;
  20240. s.lookahead--;
  20241. if (s.strm.avail_out === 0) {
  20242. return BS_NEED_MORE;
  20243. }
  20244. } else {
  20245. /* There is no previous match to compare with, wait for
  20246. * the next step to decide.
  20247. */
  20248. s.match_available = 1;
  20249. s.strstart++;
  20250. s.lookahead--;
  20251. }
  20252. }
  20253. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20254. if (s.match_available) {
  20255. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20256. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20257. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20258. s.match_available = 0;
  20259. }
  20260. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20261. if (flush === Z_FINISH) {
  20262. /*** FLUSH_BLOCK(s, 1); ***/
  20263. flush_block_only(s, true);
  20264. if (s.strm.avail_out === 0) {
  20265. return BS_FINISH_STARTED;
  20266. }
  20267. /***/
  20268. return BS_FINISH_DONE;
  20269. }
  20270. if (s.last_lit) {
  20271. /*** FLUSH_BLOCK(s, 0); ***/
  20272. flush_block_only(s, false);
  20273. if (s.strm.avail_out === 0) {
  20274. return BS_NEED_MORE;
  20275. }
  20276. /***/
  20277. }
  20278. return BS_BLOCK_DONE;
  20279. }
  20280. /* ===========================================================================
  20281. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20282. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20283. * deflate switches away from Z_RLE.)
  20284. */
  20285. function deflate_rle(s, flush) {
  20286. var bflush; /* set if current block must be flushed */
  20287. var prev; /* byte at distance one to match */
  20288. var scan, strend; /* scan goes up to strend for length of run */
  20289. var _win = s.window;
  20290. for (;;) {
  20291. /* Make sure that we always have enough lookahead, except
  20292. * at the end of the input file. We need MAX_MATCH bytes
  20293. * for the longest run, plus one for the unrolled loop.
  20294. */
  20295. if (s.lookahead <= MAX_MATCH) {
  20296. fill_window(s);
  20297. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20298. return BS_NEED_MORE;
  20299. }
  20300. if (s.lookahead === 0) { break; } /* flush the current block */
  20301. }
  20302. /* See how many times the previous byte repeats */
  20303. s.match_length = 0;
  20304. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20305. scan = s.strstart - 1;
  20306. prev = _win[scan];
  20307. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20308. strend = s.strstart + MAX_MATCH;
  20309. do {
  20310. /*jshint noempty:false*/
  20311. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20312. prev === _win[++scan] && prev === _win[++scan] &&
  20313. prev === _win[++scan] && prev === _win[++scan] &&
  20314. prev === _win[++scan] && prev === _win[++scan] &&
  20315. scan < strend);
  20316. s.match_length = MAX_MATCH - (strend - scan);
  20317. if (s.match_length > s.lookahead) {
  20318. s.match_length = s.lookahead;
  20319. }
  20320. }
  20321. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20322. }
  20323. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20324. if (s.match_length >= MIN_MATCH) {
  20325. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20326. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20327. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20328. s.lookahead -= s.match_length;
  20329. s.strstart += s.match_length;
  20330. s.match_length = 0;
  20331. } else {
  20332. /* No match, output a literal byte */
  20333. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20334. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20335. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20336. s.lookahead--;
  20337. s.strstart++;
  20338. }
  20339. if (bflush) {
  20340. /*** FLUSH_BLOCK(s, 0); ***/
  20341. flush_block_only(s, false);
  20342. if (s.strm.avail_out === 0) {
  20343. return BS_NEED_MORE;
  20344. }
  20345. /***/
  20346. }
  20347. }
  20348. s.insert = 0;
  20349. if (flush === Z_FINISH) {
  20350. /*** FLUSH_BLOCK(s, 1); ***/
  20351. flush_block_only(s, true);
  20352. if (s.strm.avail_out === 0) {
  20353. return BS_FINISH_STARTED;
  20354. }
  20355. /***/
  20356. return BS_FINISH_DONE;
  20357. }
  20358. if (s.last_lit) {
  20359. /*** FLUSH_BLOCK(s, 0); ***/
  20360. flush_block_only(s, false);
  20361. if (s.strm.avail_out === 0) {
  20362. return BS_NEED_MORE;
  20363. }
  20364. /***/
  20365. }
  20366. return BS_BLOCK_DONE;
  20367. }
  20368. /* ===========================================================================
  20369. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20370. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20371. */
  20372. function deflate_huff(s, flush) {
  20373. var bflush; /* set if current block must be flushed */
  20374. for (;;) {
  20375. /* Make sure that we have a literal to write. */
  20376. if (s.lookahead === 0) {
  20377. fill_window(s);
  20378. if (s.lookahead === 0) {
  20379. if (flush === Z_NO_FLUSH) {
  20380. return BS_NEED_MORE;
  20381. }
  20382. break; /* flush the current block */
  20383. }
  20384. }
  20385. /* Output a literal byte */
  20386. s.match_length = 0;
  20387. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20388. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20389. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20390. s.lookahead--;
  20391. s.strstart++;
  20392. if (bflush) {
  20393. /*** FLUSH_BLOCK(s, 0); ***/
  20394. flush_block_only(s, false);
  20395. if (s.strm.avail_out === 0) {
  20396. return BS_NEED_MORE;
  20397. }
  20398. /***/
  20399. }
  20400. }
  20401. s.insert = 0;
  20402. if (flush === Z_FINISH) {
  20403. /*** FLUSH_BLOCK(s, 1); ***/
  20404. flush_block_only(s, true);
  20405. if (s.strm.avail_out === 0) {
  20406. return BS_FINISH_STARTED;
  20407. }
  20408. /***/
  20409. return BS_FINISH_DONE;
  20410. }
  20411. if (s.last_lit) {
  20412. /*** FLUSH_BLOCK(s, 0); ***/
  20413. flush_block_only(s, false);
  20414. if (s.strm.avail_out === 0) {
  20415. return BS_NEED_MORE;
  20416. }
  20417. /***/
  20418. }
  20419. return BS_BLOCK_DONE;
  20420. }
  20421. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20422. * the desired pack level (0..9). The values given below have been tuned to
  20423. * exclude worst case performance for pathological files. Better values may be
  20424. * found for specific files.
  20425. */
  20426. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20427. this.good_length = good_length;
  20428. this.max_lazy = max_lazy;
  20429. this.nice_length = nice_length;
  20430. this.max_chain = max_chain;
  20431. this.func = func;
  20432. };
  20433. var configuration_table;
  20434. configuration_table = [
  20435. /* good lazy nice chain */
  20436. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  20437. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  20438. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  20439. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  20440. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  20441. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  20442. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  20443. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  20444. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  20445. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  20446. ];
  20447. /* ===========================================================================
  20448. * Initialize the "longest match" routines for a new zlib stream
  20449. */
  20450. function lm_init(s) {
  20451. s.window_size = 2 * s.w_size;
  20452. /*** CLEAR_HASH(s); ***/
  20453. zero(s.head); // Fill with NIL (= 0);
  20454. /* Set the default configuration parameters:
  20455. */
  20456. s.max_lazy_match = configuration_table[s.level].max_lazy;
  20457. s.good_match = configuration_table[s.level].good_length;
  20458. s.nice_match = configuration_table[s.level].nice_length;
  20459. s.max_chain_length = configuration_table[s.level].max_chain;
  20460. s.strstart = 0;
  20461. s.block_start = 0;
  20462. s.lookahead = 0;
  20463. s.insert = 0;
  20464. s.match_length = s.prev_length = MIN_MATCH - 1;
  20465. s.match_available = 0;
  20466. s.ins_h = 0;
  20467. }
  20468. function DeflateState() {
  20469. this.strm = null; /* pointer back to this zlib stream */
  20470. this.status = 0; /* as the name implies */
  20471. this.pending_buf = null; /* output still pending */
  20472. this.pending_buf_size = 0; /* size of pending_buf */
  20473. this.pending_out = 0; /* next pending byte to output to the stream */
  20474. this.pending = 0; /* nb of bytes in the pending buffer */
  20475. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20476. this.gzhead = null; /* gzip header information to write */
  20477. this.gzindex = 0; /* where in extra, name, or comment */
  20478. this.method = Z_DEFLATED; /* can only be DEFLATED */
  20479. this.last_flush = -1; /* value of flush param for previous deflate call */
  20480. this.w_size = 0; /* LZ77 window size (32K by default) */
  20481. this.w_bits = 0; /* log2(w_size) (8..16) */
  20482. this.w_mask = 0; /* w_size - 1 */
  20483. this.window = null;
  20484. /* Sliding window. Input bytes are read into the second half of the window,
  20485. * and move to the first half later to keep a dictionary of at least wSize
  20486. * bytes. With this organization, matches are limited to a distance of
  20487. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  20488. * performed with a length multiple of the block size.
  20489. */
  20490. this.window_size = 0;
  20491. /* Actual size of window: 2*wSize, except when the user input buffer
  20492. * is directly used as sliding window.
  20493. */
  20494. this.prev = null;
  20495. /* Link to older string with same hash index. To limit the size of this
  20496. * array to 64K, this link is maintained only for the last 32K strings.
  20497. * An index in this array is thus a window index modulo 32K.
  20498. */
  20499. this.head = null; /* Heads of the hash chains or NIL. */
  20500. this.ins_h = 0; /* hash index of string to be inserted */
  20501. this.hash_size = 0; /* number of elements in hash table */
  20502. this.hash_bits = 0; /* log2(hash_size) */
  20503. this.hash_mask = 0; /* hash_size-1 */
  20504. this.hash_shift = 0;
  20505. /* Number of bits by which ins_h must be shifted at each input
  20506. * step. It must be such that after MIN_MATCH steps, the oldest
  20507. * byte no longer takes part in the hash key, that is:
  20508. * hash_shift * MIN_MATCH >= hash_bits
  20509. */
  20510. this.block_start = 0;
  20511. /* Window position at the beginning of the current output block. Gets
  20512. * negative when the window is moved backwards.
  20513. */
  20514. this.match_length = 0; /* length of best match */
  20515. this.prev_match = 0; /* previous match */
  20516. this.match_available = 0; /* set if previous match exists */
  20517. this.strstart = 0; /* start of string to insert */
  20518. this.match_start = 0; /* start of matching string */
  20519. this.lookahead = 0; /* number of valid bytes ahead in window */
  20520. this.prev_length = 0;
  20521. /* Length of the best match at previous step. Matches not greater than this
  20522. * are discarded. This is used in the lazy match evaluation.
  20523. */
  20524. this.max_chain_length = 0;
  20525. /* To speed up deflation, hash chains are never searched beyond this
  20526. * length. A higher limit improves compression ratio but degrades the
  20527. * speed.
  20528. */
  20529. this.max_lazy_match = 0;
  20530. /* Attempt to find a better match only when the current match is strictly
  20531. * smaller than this value. This mechanism is used only for compression
  20532. * levels >= 4.
  20533. */
  20534. // That's alias to max_lazy_match, don't use directly
  20535. //this.max_insert_length = 0;
  20536. /* Insert new strings in the hash table only if the match length is not
  20537. * greater than this length. This saves time but degrades compression.
  20538. * max_insert_length is used only for compression levels <= 3.
  20539. */
  20540. this.level = 0; /* compression level (1..9) */
  20541. this.strategy = 0; /* favor or force Huffman coding*/
  20542. this.good_match = 0;
  20543. /* Use a faster search when the previous match is longer than this */
  20544. this.nice_match = 0; /* Stop searching when current match exceeds this */
  20545. /* used by trees.c: */
  20546. /* Didn't use ct_data typedef below to suppress compiler warning */
  20547. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  20548. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  20549. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  20550. // Use flat array of DOUBLE size, with interleaved fata,
  20551. // because JS does not support effective
  20552. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  20553. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  20554. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  20555. zero(this.dyn_ltree);
  20556. zero(this.dyn_dtree);
  20557. zero(this.bl_tree);
  20558. this.l_desc = null; /* desc. for literal tree */
  20559. this.d_desc = null; /* desc. for distance tree */
  20560. this.bl_desc = null; /* desc. for bit length tree */
  20561. //ush bl_count[MAX_BITS+1];
  20562. this.bl_count = new utils.Buf16(MAX_BITS+1);
  20563. /* number of codes at each bit length for an optimal tree */
  20564. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  20565. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  20566. zero(this.heap);
  20567. this.heap_len = 0; /* number of elements in the heap */
  20568. this.heap_max = 0; /* element of largest frequency */
  20569. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  20570. * The same heap array is used to build all trees.
  20571. */
  20572. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  20573. zero(this.depth);
  20574. /* Depth of each subtree used as tie breaker for trees of equal frequency
  20575. */
  20576. this.l_buf = 0; /* buffer index for literals or lengths */
  20577. this.lit_bufsize = 0;
  20578. /* Size of match buffer for literals/lengths. There are 4 reasons for
  20579. * limiting lit_bufsize to 64K:
  20580. * - frequencies can be kept in 16 bit counters
  20581. * - if compression is not successful for the first block, all input
  20582. * data is still in the window so we can still emit a stored block even
  20583. * when input comes from standard input. (This can also be done for
  20584. * all blocks if lit_bufsize is not greater than 32K.)
  20585. * - if compression is not successful for a file smaller than 64K, we can
  20586. * even emit a stored file instead of a stored block (saving 5 bytes).
  20587. * This is applicable only for zip (not gzip or zlib).
  20588. * - creating new Huffman trees less frequently may not provide fast
  20589. * adaptation to changes in the input data statistics. (Take for
  20590. * example a binary file with poorly compressible code followed by
  20591. * a highly compressible string table.) Smaller buffer sizes give
  20592. * fast adaptation but have of course the overhead of transmitting
  20593. * trees more frequently.
  20594. * - I can't count above 4
  20595. */
  20596. this.last_lit = 0; /* running index in l_buf */
  20597. this.d_buf = 0;
  20598. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  20599. * the same number of elements. To use different lengths, an extra flag
  20600. * array would be necessary.
  20601. */
  20602. this.opt_len = 0; /* bit length of current block with optimal trees */
  20603. this.static_len = 0; /* bit length of current block with static trees */
  20604. this.matches = 0; /* number of string matches in current block */
  20605. this.insert = 0; /* bytes at end of window left to insert */
  20606. this.bi_buf = 0;
  20607. /* Output buffer. bits are inserted starting at the bottom (least
  20608. * significant bits).
  20609. */
  20610. this.bi_valid = 0;
  20611. /* Number of valid bits in bi_buf. All bits above the last valid bit
  20612. * are always zero.
  20613. */
  20614. // Used for window memory init. We safely ignore it for JS. That makes
  20615. // sense only for pointers and memory check tools.
  20616. //this.high_water = 0;
  20617. /* High water mark offset in window for initialized bytes -- bytes above
  20618. * this are set to zero in order to avoid memory check warnings when
  20619. * longest match routines access bytes past the input. This is then
  20620. * updated to the new high water mark.
  20621. */
  20622. }
  20623. function deflateResetKeep(strm) {
  20624. var s;
  20625. if (!strm || !strm.state) {
  20626. return err(strm, Z_STREAM_ERROR);
  20627. }
  20628. strm.total_in = strm.total_out = 0;
  20629. strm.data_type = Z_UNKNOWN;
  20630. s = strm.state;
  20631. s.pending = 0;
  20632. s.pending_out = 0;
  20633. if (s.wrap < 0) {
  20634. s.wrap = -s.wrap;
  20635. /* was made negative by deflate(..., Z_FINISH); */
  20636. }
  20637. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  20638. strm.adler = (s.wrap === 2) ?
  20639. 0 // crc32(0, Z_NULL, 0)
  20640. :
  20641. 1; // adler32(0, Z_NULL, 0)
  20642. s.last_flush = Z_NO_FLUSH;
  20643. trees._tr_init(s);
  20644. return Z_OK;
  20645. }
  20646. function deflateReset(strm) {
  20647. var ret = deflateResetKeep(strm);
  20648. if (ret === Z_OK) {
  20649. lm_init(strm.state);
  20650. }
  20651. return ret;
  20652. }
  20653. function deflateSetHeader(strm, head) {
  20654. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20655. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  20656. strm.state.gzhead = head;
  20657. return Z_OK;
  20658. }
  20659. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  20660. if (!strm) { // === Z_NULL
  20661. return Z_STREAM_ERROR;
  20662. }
  20663. var wrap = 1;
  20664. if (level === Z_DEFAULT_COMPRESSION) {
  20665. level = 6;
  20666. }
  20667. if (windowBits < 0) { /* suppress zlib wrapper */
  20668. wrap = 0;
  20669. windowBits = -windowBits;
  20670. }
  20671. else if (windowBits > 15) {
  20672. wrap = 2; /* write gzip wrapper instead */
  20673. windowBits -= 16;
  20674. }
  20675. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  20676. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  20677. strategy < 0 || strategy > Z_FIXED) {
  20678. return err(strm, Z_STREAM_ERROR);
  20679. }
  20680. if (windowBits === 8) {
  20681. windowBits = 9;
  20682. }
  20683. /* until 256-byte window bug fixed */
  20684. var s = new DeflateState();
  20685. strm.state = s;
  20686. s.strm = strm;
  20687. s.wrap = wrap;
  20688. s.gzhead = null;
  20689. s.w_bits = windowBits;
  20690. s.w_size = 1 << s.w_bits;
  20691. s.w_mask = s.w_size - 1;
  20692. s.hash_bits = memLevel + 7;
  20693. s.hash_size = 1 << s.hash_bits;
  20694. s.hash_mask = s.hash_size - 1;
  20695. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  20696. s.window = new utils.Buf8(s.w_size * 2);
  20697. s.head = new utils.Buf16(s.hash_size);
  20698. s.prev = new utils.Buf16(s.w_size);
  20699. // Don't need mem init magic for JS.
  20700. //s.high_water = 0; /* nothing written to s->window yet */
  20701. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  20702. s.pending_buf_size = s.lit_bufsize * 4;
  20703. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  20704. s.d_buf = s.lit_bufsize >> 1;
  20705. s.l_buf = (1 + 2) * s.lit_bufsize;
  20706. s.level = level;
  20707. s.strategy = strategy;
  20708. s.method = method;
  20709. return deflateReset(strm);
  20710. }
  20711. function deflateInit(strm, level) {
  20712. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20713. }
  20714. function deflate(strm, flush) {
  20715. var old_flush, s;
  20716. var beg, val; // for gzip header write only
  20717. if (!strm || !strm.state ||
  20718. flush > Z_BLOCK || flush < 0) {
  20719. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20720. }
  20721. s = strm.state;
  20722. if (!strm.output ||
  20723. (!strm.input && strm.avail_in !== 0) ||
  20724. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20725. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20726. }
  20727. s.strm = strm; /* just in case */
  20728. old_flush = s.last_flush;
  20729. s.last_flush = flush;
  20730. /* Write the header */
  20731. if (s.status === INIT_STATE) {
  20732. if (s.wrap === 2) { // GZIP header
  20733. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20734. put_byte(s, 31);
  20735. put_byte(s, 139);
  20736. put_byte(s, 8);
  20737. if (!s.gzhead) { // s->gzhead == Z_NULL
  20738. put_byte(s, 0);
  20739. put_byte(s, 0);
  20740. put_byte(s, 0);
  20741. put_byte(s, 0);
  20742. put_byte(s, 0);
  20743. put_byte(s, s.level === 9 ? 2 :
  20744. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20745. 4 : 0));
  20746. put_byte(s, OS_CODE);
  20747. s.status = BUSY_STATE;
  20748. }
  20749. else {
  20750. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20751. (s.gzhead.hcrc ? 2 : 0) +
  20752. (!s.gzhead.extra ? 0 : 4) +
  20753. (!s.gzhead.name ? 0 : 8) +
  20754. (!s.gzhead.comment ? 0 : 16)
  20755. );
  20756. put_byte(s, s.gzhead.time & 0xff);
  20757. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20758. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20759. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20760. put_byte(s, s.level === 9 ? 2 :
  20761. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20762. 4 : 0));
  20763. put_byte(s, s.gzhead.os & 0xff);
  20764. if (s.gzhead.extra && s.gzhead.extra.length) {
  20765. put_byte(s, s.gzhead.extra.length & 0xff);
  20766. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20767. }
  20768. if (s.gzhead.hcrc) {
  20769. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20770. }
  20771. s.gzindex = 0;
  20772. s.status = EXTRA_STATE;
  20773. }
  20774. }
  20775. else // DEFLATE header
  20776. {
  20777. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20778. var level_flags = -1;
  20779. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20780. level_flags = 0;
  20781. } else if (s.level < 6) {
  20782. level_flags = 1;
  20783. } else if (s.level === 6) {
  20784. level_flags = 2;
  20785. } else {
  20786. level_flags = 3;
  20787. }
  20788. header |= (level_flags << 6);
  20789. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20790. header += 31 - (header % 31);
  20791. s.status = BUSY_STATE;
  20792. putShortMSB(s, header);
  20793. /* Save the adler32 of the preset dictionary: */
  20794. if (s.strstart !== 0) {
  20795. putShortMSB(s, strm.adler >>> 16);
  20796. putShortMSB(s, strm.adler & 0xffff);
  20797. }
  20798. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  20799. }
  20800. }
  20801. //#ifdef GZIP
  20802. if (s.status === EXTRA_STATE) {
  20803. if (s.gzhead.extra/* != Z_NULL*/) {
  20804. beg = s.pending; /* start of bytes to update crc */
  20805. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  20806. if (s.pending === s.pending_buf_size) {
  20807. if (s.gzhead.hcrc && s.pending > beg) {
  20808. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20809. }
  20810. flush_pending(strm);
  20811. beg = s.pending;
  20812. if (s.pending === s.pending_buf_size) {
  20813. break;
  20814. }
  20815. }
  20816. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  20817. s.gzindex++;
  20818. }
  20819. if (s.gzhead.hcrc && s.pending > beg) {
  20820. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20821. }
  20822. if (s.gzindex === s.gzhead.extra.length) {
  20823. s.gzindex = 0;
  20824. s.status = NAME_STATE;
  20825. }
  20826. }
  20827. else {
  20828. s.status = NAME_STATE;
  20829. }
  20830. }
  20831. if (s.status === NAME_STATE) {
  20832. if (s.gzhead.name/* != Z_NULL*/) {
  20833. beg = s.pending; /* start of bytes to update crc */
  20834. //int val;
  20835. do {
  20836. if (s.pending === s.pending_buf_size) {
  20837. if (s.gzhead.hcrc && s.pending > beg) {
  20838. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20839. }
  20840. flush_pending(strm);
  20841. beg = s.pending;
  20842. if (s.pending === s.pending_buf_size) {
  20843. val = 1;
  20844. break;
  20845. }
  20846. }
  20847. // JS specific: little magic to add zero terminator to end of string
  20848. if (s.gzindex < s.gzhead.name.length) {
  20849. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  20850. } else {
  20851. val = 0;
  20852. }
  20853. put_byte(s, val);
  20854. } while (val !== 0);
  20855. if (s.gzhead.hcrc && s.pending > beg) {
  20856. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20857. }
  20858. if (val === 0) {
  20859. s.gzindex = 0;
  20860. s.status = COMMENT_STATE;
  20861. }
  20862. }
  20863. else {
  20864. s.status = COMMENT_STATE;
  20865. }
  20866. }
  20867. if (s.status === COMMENT_STATE) {
  20868. if (s.gzhead.comment/* != Z_NULL*/) {
  20869. beg = s.pending; /* start of bytes to update crc */
  20870. //int val;
  20871. do {
  20872. if (s.pending === s.pending_buf_size) {
  20873. if (s.gzhead.hcrc && s.pending > beg) {
  20874. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20875. }
  20876. flush_pending(strm);
  20877. beg = s.pending;
  20878. if (s.pending === s.pending_buf_size) {
  20879. val = 1;
  20880. break;
  20881. }
  20882. }
  20883. // JS specific: little magic to add zero terminator to end of string
  20884. if (s.gzindex < s.gzhead.comment.length) {
  20885. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  20886. } else {
  20887. val = 0;
  20888. }
  20889. put_byte(s, val);
  20890. } while (val !== 0);
  20891. if (s.gzhead.hcrc && s.pending > beg) {
  20892. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  20893. }
  20894. if (val === 0) {
  20895. s.status = HCRC_STATE;
  20896. }
  20897. }
  20898. else {
  20899. s.status = HCRC_STATE;
  20900. }
  20901. }
  20902. if (s.status === HCRC_STATE) {
  20903. if (s.gzhead.hcrc) {
  20904. if (s.pending + 2 > s.pending_buf_size) {
  20905. flush_pending(strm);
  20906. }
  20907. if (s.pending + 2 <= s.pending_buf_size) {
  20908. put_byte(s, strm.adler & 0xff);
  20909. put_byte(s, (strm.adler >> 8) & 0xff);
  20910. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20911. s.status = BUSY_STATE;
  20912. }
  20913. }
  20914. else {
  20915. s.status = BUSY_STATE;
  20916. }
  20917. }
  20918. //#endif
  20919. /* Flush as much pending output as possible */
  20920. if (s.pending !== 0) {
  20921. flush_pending(strm);
  20922. if (strm.avail_out === 0) {
  20923. /* Since avail_out is 0, deflate will be called again with
  20924. * more output space, but possibly with both pending and
  20925. * avail_in equal to zero. There won't be anything to do,
  20926. * but this is not an error situation so make sure we
  20927. * return OK instead of BUF_ERROR at next call of deflate:
  20928. */
  20929. s.last_flush = -1;
  20930. return Z_OK;
  20931. }
  20932. /* Make sure there is something to do and avoid duplicate consecutive
  20933. * flushes. For repeated and useless calls with Z_FINISH, we keep
  20934. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  20935. */
  20936. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  20937. flush !== Z_FINISH) {
  20938. return err(strm, Z_BUF_ERROR);
  20939. }
  20940. /* User must not provide more input after the first FINISH: */
  20941. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  20942. return err(strm, Z_BUF_ERROR);
  20943. }
  20944. /* Start a new block or continue the current one.
  20945. */
  20946. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  20947. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  20948. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  20949. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  20950. configuration_table[s.level].func(s, flush));
  20951. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  20952. s.status = FINISH_STATE;
  20953. }
  20954. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  20955. if (strm.avail_out === 0) {
  20956. s.last_flush = -1;
  20957. /* avoid BUF_ERROR next call, see above */
  20958. }
  20959. return Z_OK;
  20960. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  20961. * of deflate should use the same flush parameter to make sure
  20962. * that the flush is complete. So we don't have to output an
  20963. * empty block here, this will be done at next call. This also
  20964. * ensures that for a very small output buffer, we emit at most
  20965. * one empty block.
  20966. */
  20967. }
  20968. if (bstate === BS_BLOCK_DONE) {
  20969. if (flush === Z_PARTIAL_FLUSH) {
  20970. trees._tr_align(s);
  20971. }
  20972. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  20973. trees._tr_stored_block(s, 0, 0, false);
  20974. /* For a full flush, this empty block will be recognized
  20975. * as a special marker by inflate_sync().
  20976. */
  20977. if (flush === Z_FULL_FLUSH) {
  20978. /*** CLEAR_HASH(s); ***/ /* forget history */
  20979. zero(s.head); // Fill with NIL (= 0);
  20980. if (s.lookahead === 0) {
  20981. s.strstart = 0;
  20982. s.block_start = 0;
  20983. s.insert = 0;
  20984. }
  20985. }
  20986. }
  20987. flush_pending(strm);
  20988. if (strm.avail_out === 0) {
  20989. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  20990. return Z_OK;
  20991. }
  20992. }
  20993. }
  20994. //Assert(strm->avail_out > 0, "bug2");
  20995. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  20996. if (flush !== Z_FINISH) { return Z_OK; }
  20997. if (s.wrap <= 0) { return Z_STREAM_END; }
  20998. /* Write the trailer */
  20999. if (s.wrap === 2) {
  21000. put_byte(s, strm.adler & 0xff);
  21001. put_byte(s, (strm.adler >> 8) & 0xff);
  21002. put_byte(s, (strm.adler >> 16) & 0xff);
  21003. put_byte(s, (strm.adler >> 24) & 0xff);
  21004. put_byte(s, strm.total_in & 0xff);
  21005. put_byte(s, (strm.total_in >> 8) & 0xff);
  21006. put_byte(s, (strm.total_in >> 16) & 0xff);
  21007. put_byte(s, (strm.total_in >> 24) & 0xff);
  21008. }
  21009. else
  21010. {
  21011. putShortMSB(s, strm.adler >>> 16);
  21012. putShortMSB(s, strm.adler & 0xffff);
  21013. }
  21014. flush_pending(strm);
  21015. /* If avail_out is zero, the application will call deflate again
  21016. * to flush the rest.
  21017. */
  21018. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21019. /* write the trailer only once! */
  21020. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21021. }
  21022. function deflateEnd(strm) {
  21023. var status;
  21024. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21025. return Z_STREAM_ERROR;
  21026. }
  21027. status = strm.state.status;
  21028. if (status !== INIT_STATE &&
  21029. status !== EXTRA_STATE &&
  21030. status !== NAME_STATE &&
  21031. status !== COMMENT_STATE &&
  21032. status !== HCRC_STATE &&
  21033. status !== BUSY_STATE &&
  21034. status !== FINISH_STATE
  21035. ) {
  21036. return err(strm, Z_STREAM_ERROR);
  21037. }
  21038. strm.state = null;
  21039. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21040. }
  21041. /* =========================================================================
  21042. * Copy the source state to the destination state
  21043. */
  21044. //function deflateCopy(dest, source) {
  21045. //
  21046. //}
  21047. exports.deflateInit = deflateInit;
  21048. exports.deflateInit2 = deflateInit2;
  21049. exports.deflateReset = deflateReset;
  21050. exports.deflateResetKeep = deflateResetKeep;
  21051. exports.deflateSetHeader = deflateSetHeader;
  21052. exports.deflate = deflate;
  21053. exports.deflateEnd = deflateEnd;
  21054. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21055. /* Not implemented
  21056. exports.deflateBound = deflateBound;
  21057. exports.deflateCopy = deflateCopy;
  21058. exports.deflateSetDictionary = deflateSetDictionary;
  21059. exports.deflateParams = deflateParams;
  21060. exports.deflatePending = deflatePending;
  21061. exports.deflatePrime = deflatePrime;
  21062. exports.deflateTune = deflateTune;
  21063. */
  21064. },{"../utils/common":87,"./adler32":89,"./crc32":91,"./messages":97,"./trees":98}],93:[function(require,module,exports){
  21065. 'use strict';
  21066. function GZheader() {
  21067. /* true if compressed data believed to be text */
  21068. this.text = 0;
  21069. /* modification time */
  21070. this.time = 0;
  21071. /* extra flags (not used when writing a gzip file) */
  21072. this.xflags = 0;
  21073. /* operating system */
  21074. this.os = 0;
  21075. /* pointer to extra field or Z_NULL if none */
  21076. this.extra = null;
  21077. /* extra field length (valid if extra != Z_NULL) */
  21078. this.extra_len = 0; // Actually, we don't need it in JS,
  21079. // but leave for few code modifications
  21080. //
  21081. // Setup limits is not necessary because in js we should not preallocate memory
  21082. // for inflate use constant limit in 65536 bytes
  21083. //
  21084. /* space at extra (only when reading header) */
  21085. // this.extra_max = 0;
  21086. /* pointer to zero-terminated file name or Z_NULL */
  21087. this.name = '';
  21088. /* space at name (only when reading header) */
  21089. // this.name_max = 0;
  21090. /* pointer to zero-terminated comment or Z_NULL */
  21091. this.comment = '';
  21092. /* space at comment (only when reading header) */
  21093. // this.comm_max = 0;
  21094. /* true if there was or will be a header crc */
  21095. this.hcrc = 0;
  21096. /* true when done reading gzip header (not used when writing a gzip file) */
  21097. this.done = false;
  21098. }
  21099. module.exports = GZheader;
  21100. },{}],94:[function(require,module,exports){
  21101. 'use strict';
  21102. // See state defs from inflate.js
  21103. var BAD = 30; /* got a data error -- remain here until reset */
  21104. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21105. /*
  21106. Decode literal, length, and distance codes and write out the resulting
  21107. literal and match bytes until either not enough input or output is
  21108. available, an end-of-block is encountered, or a data error is encountered.
  21109. When large enough input and output buffers are supplied to inflate(), for
  21110. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21111. inflate execution time is spent in this routine.
  21112. Entry assumptions:
  21113. state.mode === LEN
  21114. strm.avail_in >= 6
  21115. strm.avail_out >= 258
  21116. start >= strm.avail_out
  21117. state.bits < 8
  21118. On return, state.mode is one of:
  21119. LEN -- ran out of enough output space or enough available input
  21120. TYPE -- reached end of block code, inflate() to interpret next block
  21121. BAD -- error in block data
  21122. Notes:
  21123. - The maximum input bits used by a length/distance pair is 15 bits for the
  21124. length code, 5 bits for the length extra, 15 bits for the distance code,
  21125. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21126. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21127. checking for available input while decoding.
  21128. - The maximum bytes that a single length/distance pair can output is 258
  21129. bytes, which is the maximum length that can be coded. inflate_fast()
  21130. requires strm.avail_out >= 258 for each loop to avoid checking for
  21131. output space.
  21132. */
  21133. module.exports = function inflate_fast(strm, start) {
  21134. var state;
  21135. var _in; /* local strm.input */
  21136. var last; /* have enough input while in < last */
  21137. var _out; /* local strm.output */
  21138. var beg; /* inflate()'s initial strm.output */
  21139. var end; /* while out < end, enough space available */
  21140. //#ifdef INFLATE_STRICT
  21141. var dmax; /* maximum distance from zlib header */
  21142. //#endif
  21143. var wsize; /* window size or zero if not using window */
  21144. var whave; /* valid bytes in the window */
  21145. var wnext; /* window write index */
  21146. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  21147. var s_window; /* allocated sliding window, if wsize != 0 */
  21148. var hold; /* local strm.hold */
  21149. var bits; /* local strm.bits */
  21150. var lcode; /* local strm.lencode */
  21151. var dcode; /* local strm.distcode */
  21152. var lmask; /* mask for first level of length codes */
  21153. var dmask; /* mask for first level of distance codes */
  21154. var here; /* retrieved table entry */
  21155. var op; /* code bits, operation, extra bits, or */
  21156. /* window position, window bytes to copy */
  21157. var len; /* match length, unused bytes */
  21158. var dist; /* match distance */
  21159. var from; /* where to copy match from */
  21160. var from_source;
  21161. var input, output; // JS specific, because we have no pointers
  21162. /* copy state to local variables */
  21163. state = strm.state;
  21164. //here = state.here;
  21165. _in = strm.next_in;
  21166. input = strm.input;
  21167. last = _in + (strm.avail_in - 5);
  21168. _out = strm.next_out;
  21169. output = strm.output;
  21170. beg = _out - (start - strm.avail_out);
  21171. end = _out + (strm.avail_out - 257);
  21172. //#ifdef INFLATE_STRICT
  21173. dmax = state.dmax;
  21174. //#endif
  21175. wsize = state.wsize;
  21176. whave = state.whave;
  21177. wnext = state.wnext;
  21178. s_window = state.window;
  21179. hold = state.hold;
  21180. bits = state.bits;
  21181. lcode = state.lencode;
  21182. dcode = state.distcode;
  21183. lmask = (1 << state.lenbits) - 1;
  21184. dmask = (1 << state.distbits) - 1;
  21185. /* decode literals and length/distances until end-of-block or not enough
  21186. input data or output space */
  21187. top:
  21188. do {
  21189. if (bits < 15) {
  21190. hold += input[_in++] << bits;
  21191. bits += 8;
  21192. hold += input[_in++] << bits;
  21193. bits += 8;
  21194. }
  21195. here = lcode[hold & lmask];
  21196. dolen:
  21197. for (;;) { // Goto emulation
  21198. op = here >>> 24/*here.bits*/;
  21199. hold >>>= op;
  21200. bits -= op;
  21201. op = (here >>> 16) & 0xff/*here.op*/;
  21202. if (op === 0) { /* literal */
  21203. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21204. // "inflate: literal '%c'\n" :
  21205. // "inflate: literal 0x%02x\n", here.val));
  21206. output[_out++] = here & 0xffff/*here.val*/;
  21207. }
  21208. else if (op & 16) { /* length base */
  21209. len = here & 0xffff/*here.val*/;
  21210. op &= 15; /* number of extra bits */
  21211. if (op) {
  21212. if (bits < op) {
  21213. hold += input[_in++] << bits;
  21214. bits += 8;
  21215. }
  21216. len += hold & ((1 << op) - 1);
  21217. hold >>>= op;
  21218. bits -= op;
  21219. }
  21220. //Tracevv((stderr, "inflate: length %u\n", len));
  21221. if (bits < 15) {
  21222. hold += input[_in++] << bits;
  21223. bits += 8;
  21224. hold += input[_in++] << bits;
  21225. bits += 8;
  21226. }
  21227. here = dcode[hold & dmask];
  21228. dodist:
  21229. for (;;) { // goto emulation
  21230. op = here >>> 24/*here.bits*/;
  21231. hold >>>= op;
  21232. bits -= op;
  21233. op = (here >>> 16) & 0xff/*here.op*/;
  21234. if (op & 16) { /* distance base */
  21235. dist = here & 0xffff/*here.val*/;
  21236. op &= 15; /* number of extra bits */
  21237. if (bits < op) {
  21238. hold += input[_in++] << bits;
  21239. bits += 8;
  21240. if (bits < op) {
  21241. hold += input[_in++] << bits;
  21242. bits += 8;
  21243. }
  21244. }
  21245. dist += hold & ((1 << op) - 1);
  21246. //#ifdef INFLATE_STRICT
  21247. if (dist > dmax) {
  21248. strm.msg = 'invalid distance too far back';
  21249. state.mode = BAD;
  21250. break top;
  21251. }
  21252. //#endif
  21253. hold >>>= op;
  21254. bits -= op;
  21255. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21256. op = _out - beg; /* max distance in output */
  21257. if (dist > op) { /* see if copy from window */
  21258. op = dist - op; /* distance back in window */
  21259. if (op > whave) {
  21260. if (state.sane) {
  21261. strm.msg = 'invalid distance too far back';
  21262. state.mode = BAD;
  21263. break top;
  21264. }
  21265. // (!) This block is disabled in zlib defailts,
  21266. // don't enable it for binary compatibility
  21267. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21268. // if (len <= op - whave) {
  21269. // do {
  21270. // output[_out++] = 0;
  21271. // } while (--len);
  21272. // continue top;
  21273. // }
  21274. // len -= op - whave;
  21275. // do {
  21276. // output[_out++] = 0;
  21277. // } while (--op > whave);
  21278. // if (op === 0) {
  21279. // from = _out - dist;
  21280. // do {
  21281. // output[_out++] = output[from++];
  21282. // } while (--len);
  21283. // continue top;
  21284. // }
  21285. //#endif
  21286. }
  21287. from = 0; // window index
  21288. from_source = s_window;
  21289. if (wnext === 0) { /* very common case */
  21290. from += wsize - op;
  21291. if (op < len) { /* some from window */
  21292. len -= op;
  21293. do {
  21294. output[_out++] = s_window[from++];
  21295. } while (--op);
  21296. from = _out - dist; /* rest from output */
  21297. from_source = output;
  21298. }
  21299. }
  21300. else if (wnext < op) { /* wrap around window */
  21301. from += wsize + wnext - op;
  21302. op -= wnext;
  21303. if (op < len) { /* some from end of window */
  21304. len -= op;
  21305. do {
  21306. output[_out++] = s_window[from++];
  21307. } while (--op);
  21308. from = 0;
  21309. if (wnext < len) { /* some from start of window */
  21310. op = wnext;
  21311. len -= op;
  21312. do {
  21313. output[_out++] = s_window[from++];
  21314. } while (--op);
  21315. from = _out - dist; /* rest from output */
  21316. from_source = output;
  21317. }
  21318. }
  21319. }
  21320. else { /* contiguous in window */
  21321. from += wnext - op;
  21322. if (op < len) { /* some from window */
  21323. len -= op;
  21324. do {
  21325. output[_out++] = s_window[from++];
  21326. } while (--op);
  21327. from = _out - dist; /* rest from output */
  21328. from_source = output;
  21329. }
  21330. }
  21331. while (len > 2) {
  21332. output[_out++] = from_source[from++];
  21333. output[_out++] = from_source[from++];
  21334. output[_out++] = from_source[from++];
  21335. len -= 3;
  21336. }
  21337. if (len) {
  21338. output[_out++] = from_source[from++];
  21339. if (len > 1) {
  21340. output[_out++] = from_source[from++];
  21341. }
  21342. }
  21343. }
  21344. else {
  21345. from = _out - dist; /* copy direct from output */
  21346. do { /* minimum length is three */
  21347. output[_out++] = output[from++];
  21348. output[_out++] = output[from++];
  21349. output[_out++] = output[from++];
  21350. len -= 3;
  21351. } while (len > 2);
  21352. if (len) {
  21353. output[_out++] = output[from++];
  21354. if (len > 1) {
  21355. output[_out++] = output[from++];
  21356. }
  21357. }
  21358. }
  21359. }
  21360. else if ((op & 64) === 0) { /* 2nd level distance code */
  21361. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21362. continue dodist;
  21363. }
  21364. else {
  21365. strm.msg = 'invalid distance code';
  21366. state.mode = BAD;
  21367. break top;
  21368. }
  21369. break; // need to emulate goto via "continue"
  21370. }
  21371. }
  21372. else if ((op & 64) === 0) { /* 2nd level length code */
  21373. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21374. continue dolen;
  21375. }
  21376. else if (op & 32) { /* end-of-block */
  21377. //Tracevv((stderr, "inflate: end of block\n"));
  21378. state.mode = TYPE;
  21379. break top;
  21380. }
  21381. else {
  21382. strm.msg = 'invalid literal/length code';
  21383. state.mode = BAD;
  21384. break top;
  21385. }
  21386. break; // need to emulate goto via "continue"
  21387. }
  21388. } while (_in < last && _out < end);
  21389. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21390. len = bits >> 3;
  21391. _in -= len;
  21392. bits -= len << 3;
  21393. hold &= (1 << bits) - 1;
  21394. /* update state and return */
  21395. strm.next_in = _in;
  21396. strm.next_out = _out;
  21397. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21398. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21399. state.hold = hold;
  21400. state.bits = bits;
  21401. return;
  21402. };
  21403. },{}],95:[function(require,module,exports){
  21404. 'use strict';
  21405. var utils = require('../utils/common');
  21406. var adler32 = require('./adler32');
  21407. var crc32 = require('./crc32');
  21408. var inflate_fast = require('./inffast');
  21409. var inflate_table = require('./inftrees');
  21410. var CODES = 0;
  21411. var LENS = 1;
  21412. var DISTS = 2;
  21413. /* Public constants ==========================================================*/
  21414. /* ===========================================================================*/
  21415. /* Allowed flush values; see deflate() and inflate() below for details */
  21416. //var Z_NO_FLUSH = 0;
  21417. //var Z_PARTIAL_FLUSH = 1;
  21418. //var Z_SYNC_FLUSH = 2;
  21419. //var Z_FULL_FLUSH = 3;
  21420. var Z_FINISH = 4;
  21421. var Z_BLOCK = 5;
  21422. var Z_TREES = 6;
  21423. /* Return codes for the compression/decompression functions. Negative values
  21424. * are errors, positive values are used for special but normal events.
  21425. */
  21426. var Z_OK = 0;
  21427. var Z_STREAM_END = 1;
  21428. var Z_NEED_DICT = 2;
  21429. //var Z_ERRNO = -1;
  21430. var Z_STREAM_ERROR = -2;
  21431. var Z_DATA_ERROR = -3;
  21432. var Z_MEM_ERROR = -4;
  21433. var Z_BUF_ERROR = -5;
  21434. //var Z_VERSION_ERROR = -6;
  21435. /* The deflate compression method */
  21436. var Z_DEFLATED = 8;
  21437. /* STATES ====================================================================*/
  21438. /* ===========================================================================*/
  21439. var HEAD = 1; /* i: waiting for magic header */
  21440. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  21441. var TIME = 3; /* i: waiting for modification time (gzip) */
  21442. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  21443. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  21444. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  21445. var NAME = 7; /* i: waiting for end of file name (gzip) */
  21446. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  21447. var HCRC = 9; /* i: waiting for header crc (gzip) */
  21448. var DICTID = 10; /* i: waiting for dictionary check value */
  21449. var DICT = 11; /* waiting for inflateSetDictionary() call */
  21450. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21451. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  21452. var STORED = 14; /* i: waiting for stored size (length and complement) */
  21453. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  21454. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  21455. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  21456. var LENLENS = 18; /* i: waiting for code length code lengths */
  21457. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  21458. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  21459. var LEN = 21; /* i: waiting for length/lit/eob code */
  21460. var LENEXT = 22; /* i: waiting for length extra bits */
  21461. var DIST = 23; /* i: waiting for distance code */
  21462. var DISTEXT = 24; /* i: waiting for distance extra bits */
  21463. var MATCH = 25; /* o: waiting for output space to copy string */
  21464. var LIT = 26; /* o: waiting for output space to write literal */
  21465. var CHECK = 27; /* i: waiting for 32-bit check value */
  21466. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  21467. var DONE = 29; /* finished check, done -- remain here until reset */
  21468. var BAD = 30; /* got a data error -- remain here until reset */
  21469. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  21470. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  21471. /* ===========================================================================*/
  21472. var ENOUGH_LENS = 852;
  21473. var ENOUGH_DISTS = 592;
  21474. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21475. var MAX_WBITS = 15;
  21476. /* 32K LZ77 window */
  21477. var DEF_WBITS = MAX_WBITS;
  21478. function ZSWAP32(q) {
  21479. return (((q >>> 24) & 0xff) +
  21480. ((q >>> 8) & 0xff00) +
  21481. ((q & 0xff00) << 8) +
  21482. ((q & 0xff) << 24));
  21483. }
  21484. function InflateState() {
  21485. this.mode = 0; /* current inflate mode */
  21486. this.last = false; /* true if processing last block */
  21487. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21488. this.havedict = false; /* true if dictionary provided */
  21489. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  21490. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  21491. this.check = 0; /* protected copy of check value */
  21492. this.total = 0; /* protected copy of output count */
  21493. // TODO: may be {}
  21494. this.head = null; /* where to save gzip header information */
  21495. /* sliding window */
  21496. this.wbits = 0; /* log base 2 of requested window size */
  21497. this.wsize = 0; /* window size or zero if not using window */
  21498. this.whave = 0; /* valid bytes in the window */
  21499. this.wnext = 0; /* window write index */
  21500. this.window = null; /* allocated sliding window, if needed */
  21501. /* bit accumulator */
  21502. this.hold = 0; /* input bit accumulator */
  21503. this.bits = 0; /* number of bits in "in" */
  21504. /* for string and stored block copying */
  21505. this.length = 0; /* literal or length of data to copy */
  21506. this.offset = 0; /* distance back to copy string from */
  21507. /* for table and code decoding */
  21508. this.extra = 0; /* extra bits needed */
  21509. /* fixed and dynamic code tables */
  21510. this.lencode = null; /* starting table for length/literal codes */
  21511. this.distcode = null; /* starting table for distance codes */
  21512. this.lenbits = 0; /* index bits for lencode */
  21513. this.distbits = 0; /* index bits for distcode */
  21514. /* dynamic table building */
  21515. this.ncode = 0; /* number of code length code lengths */
  21516. this.nlen = 0; /* number of length code lengths */
  21517. this.ndist = 0; /* number of distance code lengths */
  21518. this.have = 0; /* number of code lengths in lens[] */
  21519. this.next = null; /* next available space in codes[] */
  21520. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  21521. this.work = new utils.Buf16(288); /* work area for code table building */
  21522. /*
  21523. because we don't have pointers in js, we use lencode and distcode directly
  21524. as buffers so we don't need codes
  21525. */
  21526. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  21527. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  21528. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  21529. this.sane = 0; /* if false, allow invalid distance too far */
  21530. this.back = 0; /* bits back of last unprocessed length/lit */
  21531. this.was = 0; /* initial length of match */
  21532. }
  21533. function inflateResetKeep(strm) {
  21534. var state;
  21535. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21536. state = strm.state;
  21537. strm.total_in = strm.total_out = state.total = 0;
  21538. strm.msg = ''; /*Z_NULL*/
  21539. if (state.wrap) { /* to support ill-conceived Java test suite */
  21540. strm.adler = state.wrap & 1;
  21541. }
  21542. state.mode = HEAD;
  21543. state.last = 0;
  21544. state.havedict = 0;
  21545. state.dmax = 32768;
  21546. state.head = null/*Z_NULL*/;
  21547. state.hold = 0;
  21548. state.bits = 0;
  21549. //state.lencode = state.distcode = state.next = state.codes;
  21550. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  21551. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  21552. state.sane = 1;
  21553. state.back = -1;
  21554. //Tracev((stderr, "inflate: reset\n"));
  21555. return Z_OK;
  21556. }
  21557. function inflateReset(strm) {
  21558. var state;
  21559. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21560. state = strm.state;
  21561. state.wsize = 0;
  21562. state.whave = 0;
  21563. state.wnext = 0;
  21564. return inflateResetKeep(strm);
  21565. }
  21566. function inflateReset2(strm, windowBits) {
  21567. var wrap;
  21568. var state;
  21569. /* get the state */
  21570. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21571. state = strm.state;
  21572. /* extract wrap request from windowBits parameter */
  21573. if (windowBits < 0) {
  21574. wrap = 0;
  21575. windowBits = -windowBits;
  21576. }
  21577. else {
  21578. wrap = (windowBits >> 4) + 1;
  21579. if (windowBits < 48) {
  21580. windowBits &= 15;
  21581. }
  21582. }
  21583. /* set number of window bits, free window if different */
  21584. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  21585. return Z_STREAM_ERROR;
  21586. }
  21587. if (state.window !== null && state.wbits !== windowBits) {
  21588. state.window = null;
  21589. }
  21590. /* update state and reset the rest of it */
  21591. state.wrap = wrap;
  21592. state.wbits = windowBits;
  21593. return inflateReset(strm);
  21594. }
  21595. function inflateInit2(strm, windowBits) {
  21596. var ret;
  21597. var state;
  21598. if (!strm) { return Z_STREAM_ERROR; }
  21599. //strm.msg = Z_NULL; /* in case we return an error */
  21600. state = new InflateState();
  21601. //if (state === Z_NULL) return Z_MEM_ERROR;
  21602. //Tracev((stderr, "inflate: allocated\n"));
  21603. strm.state = state;
  21604. state.window = null/*Z_NULL*/;
  21605. ret = inflateReset2(strm, windowBits);
  21606. if (ret !== Z_OK) {
  21607. strm.state = null/*Z_NULL*/;
  21608. }
  21609. return ret;
  21610. }
  21611. function inflateInit(strm) {
  21612. return inflateInit2(strm, DEF_WBITS);
  21613. }
  21614. /*
  21615. Return state with length and distance decoding tables and index sizes set to
  21616. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  21617. If BUILDFIXED is defined, then instead this routine builds the tables the
  21618. first time it's called, and returns those tables the first time and
  21619. thereafter. This reduces the size of the code by about 2K bytes, in
  21620. exchange for a little execution time. However, BUILDFIXED should not be
  21621. used for threaded applications, since the rewriting of the tables and virgin
  21622. may not be thread-safe.
  21623. */
  21624. var virgin = true;
  21625. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  21626. function fixedtables(state) {
  21627. /* build fixed huffman tables if first call (may not be thread safe) */
  21628. if (virgin) {
  21629. var sym;
  21630. lenfix = new utils.Buf32(512);
  21631. distfix = new utils.Buf32(32);
  21632. /* literal/length table */
  21633. sym = 0;
  21634. while (sym < 144) { state.lens[sym++] = 8; }
  21635. while (sym < 256) { state.lens[sym++] = 9; }
  21636. while (sym < 280) { state.lens[sym++] = 7; }
  21637. while (sym < 288) { state.lens[sym++] = 8; }
  21638. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  21639. /* distance table */
  21640. sym = 0;
  21641. while (sym < 32) { state.lens[sym++] = 5; }
  21642. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  21643. /* do this just once */
  21644. virgin = false;
  21645. }
  21646. state.lencode = lenfix;
  21647. state.lenbits = 9;
  21648. state.distcode = distfix;
  21649. state.distbits = 5;
  21650. }
  21651. /*
  21652. Update the window with the last wsize (normally 32K) bytes written before
  21653. returning. If window does not exist yet, create it. This is only called
  21654. when a window is already in use, or when output has been written during this
  21655. inflate call, but the end of the deflate stream has not been reached yet.
  21656. It is also called to create a window for dictionary data when a dictionary
  21657. is loaded.
  21658. Providing output buffers larger than 32K to inflate() should provide a speed
  21659. advantage, since only the last 32K of output is copied to the sliding window
  21660. upon return from inflate(), and since all distances after the first 32K of
  21661. output will fall in the output data, making match copies simpler and faster.
  21662. The advantage may be dependent on the size of the processor's data caches.
  21663. */
  21664. function updatewindow(strm, src, end, copy) {
  21665. var dist;
  21666. var state = strm.state;
  21667. /* if it hasn't been done already, allocate space for the window */
  21668. if (state.window === null) {
  21669. state.wsize = 1 << state.wbits;
  21670. state.wnext = 0;
  21671. state.whave = 0;
  21672. state.window = new utils.Buf8(state.wsize);
  21673. }
  21674. /* copy state->wsize or less output bytes into the circular window */
  21675. if (copy >= state.wsize) {
  21676. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  21677. state.wnext = 0;
  21678. state.whave = state.wsize;
  21679. }
  21680. else {
  21681. dist = state.wsize - state.wnext;
  21682. if (dist > copy) {
  21683. dist = copy;
  21684. }
  21685. //zmemcpy(state->window + state->wnext, end - copy, dist);
  21686. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  21687. copy -= dist;
  21688. if (copy) {
  21689. //zmemcpy(state->window, end - copy, copy);
  21690. utils.arraySet(state.window,src, end - copy, copy, 0);
  21691. state.wnext = copy;
  21692. state.whave = state.wsize;
  21693. }
  21694. else {
  21695. state.wnext += dist;
  21696. if (state.wnext === state.wsize) { state.wnext = 0; }
  21697. if (state.whave < state.wsize) { state.whave += dist; }
  21698. }
  21699. }
  21700. return 0;
  21701. }
  21702. function inflate(strm, flush) {
  21703. var state;
  21704. var input, output; // input/output buffers
  21705. var next; /* next input INDEX */
  21706. var put; /* next output INDEX */
  21707. var have, left; /* available input and output */
  21708. var hold; /* bit buffer */
  21709. var bits; /* bits in bit buffer */
  21710. var _in, _out; /* save starting available input and output */
  21711. var copy; /* number of stored or match bytes to copy */
  21712. var from; /* where to copy match bytes from */
  21713. var from_source;
  21714. var here = 0; /* current decoding table entry */
  21715. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21716. //var last; /* parent table entry */
  21717. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21718. var len; /* length to copy for repeats, bits to drop */
  21719. var ret; /* return code */
  21720. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21721. var opts;
  21722. var n; // temporary var for NEED_BITS
  21723. var order = /* permutation of code lengths */
  21724. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21725. if (!strm || !strm.state || !strm.output ||
  21726. (!strm.input && strm.avail_in !== 0)) {
  21727. return Z_STREAM_ERROR;
  21728. }
  21729. state = strm.state;
  21730. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21731. //--- LOAD() ---
  21732. put = strm.next_out;
  21733. output = strm.output;
  21734. left = strm.avail_out;
  21735. next = strm.next_in;
  21736. input = strm.input;
  21737. have = strm.avail_in;
  21738. hold = state.hold;
  21739. bits = state.bits;
  21740. //---
  21741. _in = have;
  21742. _out = left;
  21743. ret = Z_OK;
  21744. inf_leave: // goto emulation
  21745. for (;;) {
  21746. switch (state.mode) {
  21747. case HEAD:
  21748. if (state.wrap === 0) {
  21749. state.mode = TYPEDO;
  21750. break;
  21751. }
  21752. //=== NEEDBITS(16);
  21753. while (bits < 16) {
  21754. if (have === 0) { break inf_leave; }
  21755. have--;
  21756. hold += input[next++] << bits;
  21757. bits += 8;
  21758. }
  21759. //===//
  21760. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21761. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21762. //=== CRC2(state.check, hold);
  21763. hbuf[0] = hold & 0xff;
  21764. hbuf[1] = (hold >>> 8) & 0xff;
  21765. state.check = crc32(state.check, hbuf, 2, 0);
  21766. //===//
  21767. //=== INITBITS();
  21768. hold = 0;
  21769. bits = 0;
  21770. //===//
  21771. state.mode = FLAGS;
  21772. break;
  21773. }
  21774. state.flags = 0; /* expect zlib header */
  21775. if (state.head) {
  21776. state.head.done = false;
  21777. }
  21778. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21779. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21780. strm.msg = 'incorrect header check';
  21781. state.mode = BAD;
  21782. break;
  21783. }
  21784. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21785. strm.msg = 'unknown compression method';
  21786. state.mode = BAD;
  21787. break;
  21788. }
  21789. //--- DROPBITS(4) ---//
  21790. hold >>>= 4;
  21791. bits -= 4;
  21792. //---//
  21793. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  21794. if (state.wbits === 0) {
  21795. state.wbits = len;
  21796. }
  21797. else if (len > state.wbits) {
  21798. strm.msg = 'invalid window size';
  21799. state.mode = BAD;
  21800. break;
  21801. }
  21802. state.dmax = 1 << len;
  21803. //Tracev((stderr, "inflate: zlib header ok\n"));
  21804. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  21805. state.mode = hold & 0x200 ? DICTID : TYPE;
  21806. //=== INITBITS();
  21807. hold = 0;
  21808. bits = 0;
  21809. //===//
  21810. break;
  21811. case FLAGS:
  21812. //=== NEEDBITS(16); */
  21813. while (bits < 16) {
  21814. if (have === 0) { break inf_leave; }
  21815. have--;
  21816. hold += input[next++] << bits;
  21817. bits += 8;
  21818. }
  21819. //===//
  21820. state.flags = hold;
  21821. if ((state.flags & 0xff) !== Z_DEFLATED) {
  21822. strm.msg = 'unknown compression method';
  21823. state.mode = BAD;
  21824. break;
  21825. }
  21826. if (state.flags & 0xe000) {
  21827. strm.msg = 'unknown header flags set';
  21828. state.mode = BAD;
  21829. break;
  21830. }
  21831. if (state.head) {
  21832. state.head.text = ((hold >> 8) & 1);
  21833. }
  21834. if (state.flags & 0x0200) {
  21835. //=== CRC2(state.check, hold);
  21836. hbuf[0] = hold & 0xff;
  21837. hbuf[1] = (hold >>> 8) & 0xff;
  21838. state.check = crc32(state.check, hbuf, 2, 0);
  21839. //===//
  21840. }
  21841. //=== INITBITS();
  21842. hold = 0;
  21843. bits = 0;
  21844. //===//
  21845. state.mode = TIME;
  21846. /* falls through */
  21847. case TIME:
  21848. //=== NEEDBITS(32); */
  21849. while (bits < 32) {
  21850. if (have === 0) { break inf_leave; }
  21851. have--;
  21852. hold += input[next++] << bits;
  21853. bits += 8;
  21854. }
  21855. //===//
  21856. if (state.head) {
  21857. state.head.time = hold;
  21858. }
  21859. if (state.flags & 0x0200) {
  21860. //=== CRC4(state.check, hold)
  21861. hbuf[0] = hold & 0xff;
  21862. hbuf[1] = (hold >>> 8) & 0xff;
  21863. hbuf[2] = (hold >>> 16) & 0xff;
  21864. hbuf[3] = (hold >>> 24) & 0xff;
  21865. state.check = crc32(state.check, hbuf, 4, 0);
  21866. //===
  21867. }
  21868. //=== INITBITS();
  21869. hold = 0;
  21870. bits = 0;
  21871. //===//
  21872. state.mode = OS;
  21873. /* falls through */
  21874. case OS:
  21875. //=== NEEDBITS(16); */
  21876. while (bits < 16) {
  21877. if (have === 0) { break inf_leave; }
  21878. have--;
  21879. hold += input[next++] << bits;
  21880. bits += 8;
  21881. }
  21882. //===//
  21883. if (state.head) {
  21884. state.head.xflags = (hold & 0xff);
  21885. state.head.os = (hold >> 8);
  21886. }
  21887. if (state.flags & 0x0200) {
  21888. //=== CRC2(state.check, hold);
  21889. hbuf[0] = hold & 0xff;
  21890. hbuf[1] = (hold >>> 8) & 0xff;
  21891. state.check = crc32(state.check, hbuf, 2, 0);
  21892. //===//
  21893. }
  21894. //=== INITBITS();
  21895. hold = 0;
  21896. bits = 0;
  21897. //===//
  21898. state.mode = EXLEN;
  21899. /* falls through */
  21900. case EXLEN:
  21901. if (state.flags & 0x0400) {
  21902. //=== NEEDBITS(16); */
  21903. while (bits < 16) {
  21904. if (have === 0) { break inf_leave; }
  21905. have--;
  21906. hold += input[next++] << bits;
  21907. bits += 8;
  21908. }
  21909. //===//
  21910. state.length = hold;
  21911. if (state.head) {
  21912. state.head.extra_len = hold;
  21913. }
  21914. if (state.flags & 0x0200) {
  21915. //=== CRC2(state.check, hold);
  21916. hbuf[0] = hold & 0xff;
  21917. hbuf[1] = (hold >>> 8) & 0xff;
  21918. state.check = crc32(state.check, hbuf, 2, 0);
  21919. //===//
  21920. }
  21921. //=== INITBITS();
  21922. hold = 0;
  21923. bits = 0;
  21924. //===//
  21925. }
  21926. else if (state.head) {
  21927. state.head.extra = null/*Z_NULL*/;
  21928. }
  21929. state.mode = EXTRA;
  21930. /* falls through */
  21931. case EXTRA:
  21932. if (state.flags & 0x0400) {
  21933. copy = state.length;
  21934. if (copy > have) { copy = have; }
  21935. if (copy) {
  21936. if (state.head) {
  21937. len = state.head.extra_len - state.length;
  21938. if (!state.head.extra) {
  21939. // Use untyped array for more conveniend processing later
  21940. state.head.extra = new Array(state.head.extra_len);
  21941. }
  21942. utils.arraySet(
  21943. state.head.extra,
  21944. input,
  21945. next,
  21946. // extra field is limited to 65536 bytes
  21947. // - no need for additional size check
  21948. copy,
  21949. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  21950. len
  21951. );
  21952. //zmemcpy(state.head.extra + len, next,
  21953. // len + copy > state.head.extra_max ?
  21954. // state.head.extra_max - len : copy);
  21955. }
  21956. if (state.flags & 0x0200) {
  21957. state.check = crc32(state.check, input, copy, next);
  21958. }
  21959. have -= copy;
  21960. next += copy;
  21961. state.length -= copy;
  21962. }
  21963. if (state.length) { break inf_leave; }
  21964. }
  21965. state.length = 0;
  21966. state.mode = NAME;
  21967. /* falls through */
  21968. case NAME:
  21969. if (state.flags & 0x0800) {
  21970. if (have === 0) { break inf_leave; }
  21971. copy = 0;
  21972. do {
  21973. // TODO: 2 or 1 bytes?
  21974. len = input[next + copy++];
  21975. /* use constant limit because in js we should not preallocate memory */
  21976. if (state.head && len &&
  21977. (state.length < 65536 /*state.head.name_max*/)) {
  21978. state.head.name += String.fromCharCode(len);
  21979. }
  21980. } while (len && copy < have);
  21981. if (state.flags & 0x0200) {
  21982. state.check = crc32(state.check, input, copy, next);
  21983. }
  21984. have -= copy;
  21985. next += copy;
  21986. if (len) { break inf_leave; }
  21987. }
  21988. else if (state.head) {
  21989. state.head.name = null;
  21990. }
  21991. state.length = 0;
  21992. state.mode = COMMENT;
  21993. /* falls through */
  21994. case COMMENT:
  21995. if (state.flags & 0x1000) {
  21996. if (have === 0) { break inf_leave; }
  21997. copy = 0;
  21998. do {
  21999. len = input[next + copy++];
  22000. /* use constant limit because in js we should not preallocate memory */
  22001. if (state.head && len &&
  22002. (state.length < 65536 /*state.head.comm_max*/)) {
  22003. state.head.comment += String.fromCharCode(len);
  22004. }
  22005. } while (len && copy < have);
  22006. if (state.flags & 0x0200) {
  22007. state.check = crc32(state.check, input, copy, next);
  22008. }
  22009. have -= copy;
  22010. next += copy;
  22011. if (len) { break inf_leave; }
  22012. }
  22013. else if (state.head) {
  22014. state.head.comment = null;
  22015. }
  22016. state.mode = HCRC;
  22017. /* falls through */
  22018. case HCRC:
  22019. if (state.flags & 0x0200) {
  22020. //=== NEEDBITS(16); */
  22021. while (bits < 16) {
  22022. if (have === 0) { break inf_leave; }
  22023. have--;
  22024. hold += input[next++] << bits;
  22025. bits += 8;
  22026. }
  22027. //===//
  22028. if (hold !== (state.check & 0xffff)) {
  22029. strm.msg = 'header crc mismatch';
  22030. state.mode = BAD;
  22031. break;
  22032. }
  22033. //=== INITBITS();
  22034. hold = 0;
  22035. bits = 0;
  22036. //===//
  22037. }
  22038. if (state.head) {
  22039. state.head.hcrc = ((state.flags >> 9) & 1);
  22040. state.head.done = true;
  22041. }
  22042. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22043. state.mode = TYPE;
  22044. break;
  22045. case DICTID:
  22046. //=== NEEDBITS(32); */
  22047. while (bits < 32) {
  22048. if (have === 0) { break inf_leave; }
  22049. have--;
  22050. hold += input[next++] << bits;
  22051. bits += 8;
  22052. }
  22053. //===//
  22054. strm.adler = state.check = ZSWAP32(hold);
  22055. //=== INITBITS();
  22056. hold = 0;
  22057. bits = 0;
  22058. //===//
  22059. state.mode = DICT;
  22060. /* falls through */
  22061. case DICT:
  22062. if (state.havedict === 0) {
  22063. //--- RESTORE() ---
  22064. strm.next_out = put;
  22065. strm.avail_out = left;
  22066. strm.next_in = next;
  22067. strm.avail_in = have;
  22068. state.hold = hold;
  22069. state.bits = bits;
  22070. //---
  22071. return Z_NEED_DICT;
  22072. }
  22073. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22074. state.mode = TYPE;
  22075. /* falls through */
  22076. case TYPE:
  22077. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22078. /* falls through */
  22079. case TYPEDO:
  22080. if (state.last) {
  22081. //--- BYTEBITS() ---//
  22082. hold >>>= bits & 7;
  22083. bits -= bits & 7;
  22084. //---//
  22085. state.mode = CHECK;
  22086. break;
  22087. }
  22088. //=== NEEDBITS(3); */
  22089. while (bits < 3) {
  22090. if (have === 0) { break inf_leave; }
  22091. have--;
  22092. hold += input[next++] << bits;
  22093. bits += 8;
  22094. }
  22095. //===//
  22096. state.last = (hold & 0x01)/*BITS(1)*/;
  22097. //--- DROPBITS(1) ---//
  22098. hold >>>= 1;
  22099. bits -= 1;
  22100. //---//
  22101. switch ((hold & 0x03)/*BITS(2)*/) {
  22102. case 0: /* stored block */
  22103. //Tracev((stderr, "inflate: stored block%s\n",
  22104. // state.last ? " (last)" : ""));
  22105. state.mode = STORED;
  22106. break;
  22107. case 1: /* fixed block */
  22108. fixedtables(state);
  22109. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22110. // state.last ? " (last)" : ""));
  22111. state.mode = LEN_; /* decode codes */
  22112. if (flush === Z_TREES) {
  22113. //--- DROPBITS(2) ---//
  22114. hold >>>= 2;
  22115. bits -= 2;
  22116. //---//
  22117. break inf_leave;
  22118. }
  22119. break;
  22120. case 2: /* dynamic block */
  22121. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22122. // state.last ? " (last)" : ""));
  22123. state.mode = TABLE;
  22124. break;
  22125. case 3:
  22126. strm.msg = 'invalid block type';
  22127. state.mode = BAD;
  22128. }
  22129. //--- DROPBITS(2) ---//
  22130. hold >>>= 2;
  22131. bits -= 2;
  22132. //---//
  22133. break;
  22134. case STORED:
  22135. //--- BYTEBITS() ---// /* go to byte boundary */
  22136. hold >>>= bits & 7;
  22137. bits -= bits & 7;
  22138. //---//
  22139. //=== NEEDBITS(32); */
  22140. while (bits < 32) {
  22141. if (have === 0) { break inf_leave; }
  22142. have--;
  22143. hold += input[next++] << bits;
  22144. bits += 8;
  22145. }
  22146. //===//
  22147. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22148. strm.msg = 'invalid stored block lengths';
  22149. state.mode = BAD;
  22150. break;
  22151. }
  22152. state.length = hold & 0xffff;
  22153. //Tracev((stderr, "inflate: stored length %u\n",
  22154. // state.length));
  22155. //=== INITBITS();
  22156. hold = 0;
  22157. bits = 0;
  22158. //===//
  22159. state.mode = COPY_;
  22160. if (flush === Z_TREES) { break inf_leave; }
  22161. /* falls through */
  22162. case COPY_:
  22163. state.mode = COPY;
  22164. /* falls through */
  22165. case COPY:
  22166. copy = state.length;
  22167. if (copy) {
  22168. if (copy > have) { copy = have; }
  22169. if (copy > left) { copy = left; }
  22170. if (copy === 0) { break inf_leave; }
  22171. //--- zmemcpy(put, next, copy); ---
  22172. utils.arraySet(output, input, next, copy, put);
  22173. //---//
  22174. have -= copy;
  22175. next += copy;
  22176. left -= copy;
  22177. put += copy;
  22178. state.length -= copy;
  22179. break;
  22180. }
  22181. //Tracev((stderr, "inflate: stored end\n"));
  22182. state.mode = TYPE;
  22183. break;
  22184. case TABLE:
  22185. //=== NEEDBITS(14); */
  22186. while (bits < 14) {
  22187. if (have === 0) { break inf_leave; }
  22188. have--;
  22189. hold += input[next++] << bits;
  22190. bits += 8;
  22191. }
  22192. //===//
  22193. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22194. //--- DROPBITS(5) ---//
  22195. hold >>>= 5;
  22196. bits -= 5;
  22197. //---//
  22198. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22199. //--- DROPBITS(5) ---//
  22200. hold >>>= 5;
  22201. bits -= 5;
  22202. //---//
  22203. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22204. //--- DROPBITS(4) ---//
  22205. hold >>>= 4;
  22206. bits -= 4;
  22207. //---//
  22208. //#ifndef PKZIP_BUG_WORKAROUND
  22209. if (state.nlen > 286 || state.ndist > 30) {
  22210. strm.msg = 'too many length or distance symbols';
  22211. state.mode = BAD;
  22212. break;
  22213. }
  22214. //#endif
  22215. //Tracev((stderr, "inflate: table sizes ok\n"));
  22216. state.have = 0;
  22217. state.mode = LENLENS;
  22218. /* falls through */
  22219. case LENLENS:
  22220. while (state.have < state.ncode) {
  22221. //=== NEEDBITS(3);
  22222. while (bits < 3) {
  22223. if (have === 0) { break inf_leave; }
  22224. have--;
  22225. hold += input[next++] << bits;
  22226. bits += 8;
  22227. }
  22228. //===//
  22229. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22230. //--- DROPBITS(3) ---//
  22231. hold >>>= 3;
  22232. bits -= 3;
  22233. //---//
  22234. }
  22235. while (state.have < 19) {
  22236. state.lens[order[state.have++]] = 0;
  22237. }
  22238. // We have separate tables & no pointers. 2 commented lines below not needed.
  22239. //state.next = state.codes;
  22240. //state.lencode = state.next;
  22241. // Switch to use dynamic table
  22242. state.lencode = state.lendyn;
  22243. state.lenbits = 7;
  22244. opts = {bits: state.lenbits};
  22245. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22246. state.lenbits = opts.bits;
  22247. if (ret) {
  22248. strm.msg = 'invalid code lengths set';
  22249. state.mode = BAD;
  22250. break;
  22251. }
  22252. //Tracev((stderr, "inflate: code lengths ok\n"));
  22253. state.have = 0;
  22254. state.mode = CODELENS;
  22255. /* falls through */
  22256. case CODELENS:
  22257. while (state.have < state.nlen + state.ndist) {
  22258. for (;;) {
  22259. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22260. here_bits = here >>> 24;
  22261. here_op = (here >>> 16) & 0xff;
  22262. here_val = here & 0xffff;
  22263. if ((here_bits) <= bits) { break; }
  22264. //--- PULLBYTE() ---//
  22265. if (have === 0) { break inf_leave; }
  22266. have--;
  22267. hold += input[next++] << bits;
  22268. bits += 8;
  22269. //---//
  22270. }
  22271. if (here_val < 16) {
  22272. //--- DROPBITS(here.bits) ---//
  22273. hold >>>= here_bits;
  22274. bits -= here_bits;
  22275. //---//
  22276. state.lens[state.have++] = here_val;
  22277. }
  22278. else {
  22279. if (here_val === 16) {
  22280. //=== NEEDBITS(here.bits + 2);
  22281. n = here_bits + 2;
  22282. while (bits < n) {
  22283. if (have === 0) { break inf_leave; }
  22284. have--;
  22285. hold += input[next++] << bits;
  22286. bits += 8;
  22287. }
  22288. //===//
  22289. //--- DROPBITS(here.bits) ---//
  22290. hold >>>= here_bits;
  22291. bits -= here_bits;
  22292. //---//
  22293. if (state.have === 0) {
  22294. strm.msg = 'invalid bit length repeat';
  22295. state.mode = BAD;
  22296. break;
  22297. }
  22298. len = state.lens[state.have - 1];
  22299. copy = 3 + (hold & 0x03);//BITS(2);
  22300. //--- DROPBITS(2) ---//
  22301. hold >>>= 2;
  22302. bits -= 2;
  22303. //---//
  22304. }
  22305. else if (here_val === 17) {
  22306. //=== NEEDBITS(here.bits + 3);
  22307. n = here_bits + 3;
  22308. while (bits < n) {
  22309. if (have === 0) { break inf_leave; }
  22310. have--;
  22311. hold += input[next++] << bits;
  22312. bits += 8;
  22313. }
  22314. //===//
  22315. //--- DROPBITS(here.bits) ---//
  22316. hold >>>= here_bits;
  22317. bits -= here_bits;
  22318. //---//
  22319. len = 0;
  22320. copy = 3 + (hold & 0x07);//BITS(3);
  22321. //--- DROPBITS(3) ---//
  22322. hold >>>= 3;
  22323. bits -= 3;
  22324. //---//
  22325. }
  22326. else {
  22327. //=== NEEDBITS(here.bits + 7);
  22328. n = here_bits + 7;
  22329. while (bits < n) {
  22330. if (have === 0) { break inf_leave; }
  22331. have--;
  22332. hold += input[next++] << bits;
  22333. bits += 8;
  22334. }
  22335. //===//
  22336. //--- DROPBITS(here.bits) ---//
  22337. hold >>>= here_bits;
  22338. bits -= here_bits;
  22339. //---//
  22340. len = 0;
  22341. copy = 11 + (hold & 0x7f);//BITS(7);
  22342. //--- DROPBITS(7) ---//
  22343. hold >>>= 7;
  22344. bits -= 7;
  22345. //---//
  22346. }
  22347. if (state.have + copy > state.nlen + state.ndist) {
  22348. strm.msg = 'invalid bit length repeat';
  22349. state.mode = BAD;
  22350. break;
  22351. }
  22352. while (copy--) {
  22353. state.lens[state.have++] = len;
  22354. }
  22355. }
  22356. }
  22357. /* handle error breaks in while */
  22358. if (state.mode === BAD) { break; }
  22359. /* check for end-of-block code (better have one) */
  22360. if (state.lens[256] === 0) {
  22361. strm.msg = 'invalid code -- missing end-of-block';
  22362. state.mode = BAD;
  22363. break;
  22364. }
  22365. /* build code tables -- note: do not change the lenbits or distbits
  22366. values here (9 and 6) without reading the comments in inftrees.h
  22367. concerning the ENOUGH constants, which depend on those values */
  22368. state.lenbits = 9;
  22369. opts = {bits: state.lenbits};
  22370. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22371. // We have separate tables & no pointers. 2 commented lines below not needed.
  22372. // state.next_index = opts.table_index;
  22373. state.lenbits = opts.bits;
  22374. // state.lencode = state.next;
  22375. if (ret) {
  22376. strm.msg = 'invalid literal/lengths set';
  22377. state.mode = BAD;
  22378. break;
  22379. }
  22380. state.distbits = 6;
  22381. //state.distcode.copy(state.codes);
  22382. // Switch to use dynamic table
  22383. state.distcode = state.distdyn;
  22384. opts = {bits: state.distbits};
  22385. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22386. // We have separate tables & no pointers. 2 commented lines below not needed.
  22387. // state.next_index = opts.table_index;
  22388. state.distbits = opts.bits;
  22389. // state.distcode = state.next;
  22390. if (ret) {
  22391. strm.msg = 'invalid distances set';
  22392. state.mode = BAD;
  22393. break;
  22394. }
  22395. //Tracev((stderr, 'inflate: codes ok\n'));
  22396. state.mode = LEN_;
  22397. if (flush === Z_TREES) { break inf_leave; }
  22398. /* falls through */
  22399. case LEN_:
  22400. state.mode = LEN;
  22401. /* falls through */
  22402. case LEN:
  22403. if (have >= 6 && left >= 258) {
  22404. //--- RESTORE() ---
  22405. strm.next_out = put;
  22406. strm.avail_out = left;
  22407. strm.next_in = next;
  22408. strm.avail_in = have;
  22409. state.hold = hold;
  22410. state.bits = bits;
  22411. //---
  22412. inflate_fast(strm, _out);
  22413. //--- LOAD() ---
  22414. put = strm.next_out;
  22415. output = strm.output;
  22416. left = strm.avail_out;
  22417. next = strm.next_in;
  22418. input = strm.input;
  22419. have = strm.avail_in;
  22420. hold = state.hold;
  22421. bits = state.bits;
  22422. //---
  22423. if (state.mode === TYPE) {
  22424. state.back = -1;
  22425. }
  22426. break;
  22427. }
  22428. state.back = 0;
  22429. for (;;) {
  22430. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22431. here_bits = here >>> 24;
  22432. here_op = (here >>> 16) & 0xff;
  22433. here_val = here & 0xffff;
  22434. if (here_bits <= bits) { break; }
  22435. //--- PULLBYTE() ---//
  22436. if (have === 0) { break inf_leave; }
  22437. have--;
  22438. hold += input[next++] << bits;
  22439. bits += 8;
  22440. //---//
  22441. }
  22442. if (here_op && (here_op & 0xf0) === 0) {
  22443. last_bits = here_bits;
  22444. last_op = here_op;
  22445. last_val = here_val;
  22446. for (;;) {
  22447. here = state.lencode[last_val +
  22448. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22449. here_bits = here >>> 24;
  22450. here_op = (here >>> 16) & 0xff;
  22451. here_val = here & 0xffff;
  22452. if ((last_bits + here_bits) <= bits) { break; }
  22453. //--- PULLBYTE() ---//
  22454. if (have === 0) { break inf_leave; }
  22455. have--;
  22456. hold += input[next++] << bits;
  22457. bits += 8;
  22458. //---//
  22459. }
  22460. //--- DROPBITS(last.bits) ---//
  22461. hold >>>= last_bits;
  22462. bits -= last_bits;
  22463. //---//
  22464. state.back += last_bits;
  22465. }
  22466. //--- DROPBITS(here.bits) ---//
  22467. hold >>>= here_bits;
  22468. bits -= here_bits;
  22469. //---//
  22470. state.back += here_bits;
  22471. state.length = here_val;
  22472. if (here_op === 0) {
  22473. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22474. // "inflate: literal '%c'\n" :
  22475. // "inflate: literal 0x%02x\n", here.val));
  22476. state.mode = LIT;
  22477. break;
  22478. }
  22479. if (here_op & 32) {
  22480. //Tracevv((stderr, "inflate: end of block\n"));
  22481. state.back = -1;
  22482. state.mode = TYPE;
  22483. break;
  22484. }
  22485. if (here_op & 64) {
  22486. strm.msg = 'invalid literal/length code';
  22487. state.mode = BAD;
  22488. break;
  22489. }
  22490. state.extra = here_op & 15;
  22491. state.mode = LENEXT;
  22492. /* falls through */
  22493. case LENEXT:
  22494. if (state.extra) {
  22495. //=== NEEDBITS(state.extra);
  22496. n = state.extra;
  22497. while (bits < n) {
  22498. if (have === 0) { break inf_leave; }
  22499. have--;
  22500. hold += input[next++] << bits;
  22501. bits += 8;
  22502. }
  22503. //===//
  22504. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22505. //--- DROPBITS(state.extra) ---//
  22506. hold >>>= state.extra;
  22507. bits -= state.extra;
  22508. //---//
  22509. state.back += state.extra;
  22510. }
  22511. //Tracevv((stderr, "inflate: length %u\n", state.length));
  22512. state.was = state.length;
  22513. state.mode = DIST;
  22514. /* falls through */
  22515. case DIST:
  22516. for (;;) {
  22517. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  22518. here_bits = here >>> 24;
  22519. here_op = (here >>> 16) & 0xff;
  22520. here_val = here & 0xffff;
  22521. if ((here_bits) <= bits) { break; }
  22522. //--- PULLBYTE() ---//
  22523. if (have === 0) { break inf_leave; }
  22524. have--;
  22525. hold += input[next++] << bits;
  22526. bits += 8;
  22527. //---//
  22528. }
  22529. if ((here_op & 0xf0) === 0) {
  22530. last_bits = here_bits;
  22531. last_op = here_op;
  22532. last_val = here_val;
  22533. for (;;) {
  22534. here = state.distcode[last_val +
  22535. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22536. here_bits = here >>> 24;
  22537. here_op = (here >>> 16) & 0xff;
  22538. here_val = here & 0xffff;
  22539. if ((last_bits + here_bits) <= bits) { break; }
  22540. //--- PULLBYTE() ---//
  22541. if (have === 0) { break inf_leave; }
  22542. have--;
  22543. hold += input[next++] << bits;
  22544. bits += 8;
  22545. //---//
  22546. }
  22547. //--- DROPBITS(last.bits) ---//
  22548. hold >>>= last_bits;
  22549. bits -= last_bits;
  22550. //---//
  22551. state.back += last_bits;
  22552. }
  22553. //--- DROPBITS(here.bits) ---//
  22554. hold >>>= here_bits;
  22555. bits -= here_bits;
  22556. //---//
  22557. state.back += here_bits;
  22558. if (here_op & 64) {
  22559. strm.msg = 'invalid distance code';
  22560. state.mode = BAD;
  22561. break;
  22562. }
  22563. state.offset = here_val;
  22564. state.extra = (here_op) & 15;
  22565. state.mode = DISTEXT;
  22566. /* falls through */
  22567. case DISTEXT:
  22568. if (state.extra) {
  22569. //=== NEEDBITS(state.extra);
  22570. n = state.extra;
  22571. while (bits < n) {
  22572. if (have === 0) { break inf_leave; }
  22573. have--;
  22574. hold += input[next++] << bits;
  22575. bits += 8;
  22576. }
  22577. //===//
  22578. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22579. //--- DROPBITS(state.extra) ---//
  22580. hold >>>= state.extra;
  22581. bits -= state.extra;
  22582. //---//
  22583. state.back += state.extra;
  22584. }
  22585. //#ifdef INFLATE_STRICT
  22586. if (state.offset > state.dmax) {
  22587. strm.msg = 'invalid distance too far back';
  22588. state.mode = BAD;
  22589. break;
  22590. }
  22591. //#endif
  22592. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  22593. state.mode = MATCH;
  22594. /* falls through */
  22595. case MATCH:
  22596. if (left === 0) { break inf_leave; }
  22597. copy = _out - left;
  22598. if (state.offset > copy) { /* copy from window */
  22599. copy = state.offset - copy;
  22600. if (copy > state.whave) {
  22601. if (state.sane) {
  22602. strm.msg = 'invalid distance too far back';
  22603. state.mode = BAD;
  22604. break;
  22605. }
  22606. // (!) This block is disabled in zlib defailts,
  22607. // don't enable it for binary compatibility
  22608. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22609. // Trace((stderr, "inflate.c too far\n"));
  22610. // copy -= state.whave;
  22611. // if (copy > state.length) { copy = state.length; }
  22612. // if (copy > left) { copy = left; }
  22613. // left -= copy;
  22614. // state.length -= copy;
  22615. // do {
  22616. // output[put++] = 0;
  22617. // } while (--copy);
  22618. // if (state.length === 0) { state.mode = LEN; }
  22619. // break;
  22620. //#endif
  22621. }
  22622. if (copy > state.wnext) {
  22623. copy -= state.wnext;
  22624. from = state.wsize - copy;
  22625. }
  22626. else {
  22627. from = state.wnext - copy;
  22628. }
  22629. if (copy > state.length) { copy = state.length; }
  22630. from_source = state.window;
  22631. }
  22632. else { /* copy from output */
  22633. from_source = output;
  22634. from = put - state.offset;
  22635. copy = state.length;
  22636. }
  22637. if (copy > left) { copy = left; }
  22638. left -= copy;
  22639. state.length -= copy;
  22640. do {
  22641. output[put++] = from_source[from++];
  22642. } while (--copy);
  22643. if (state.length === 0) { state.mode = LEN; }
  22644. break;
  22645. case LIT:
  22646. if (left === 0) { break inf_leave; }
  22647. output[put++] = state.length;
  22648. left--;
  22649. state.mode = LEN;
  22650. break;
  22651. case CHECK:
  22652. if (state.wrap) {
  22653. //=== NEEDBITS(32);
  22654. while (bits < 32) {
  22655. if (have === 0) { break inf_leave; }
  22656. have--;
  22657. // Use '|' insdead of '+' to make sure that result is signed
  22658. hold |= input[next++] << bits;
  22659. bits += 8;
  22660. }
  22661. //===//
  22662. _out -= left;
  22663. strm.total_out += _out;
  22664. state.total += _out;
  22665. if (_out) {
  22666. strm.adler = state.check =
  22667. /*UPDATE(state.check, put - _out, _out);*/
  22668. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  22669. }
  22670. _out = left;
  22671. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  22672. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  22673. strm.msg = 'incorrect data check';
  22674. state.mode = BAD;
  22675. break;
  22676. }
  22677. //=== INITBITS();
  22678. hold = 0;
  22679. bits = 0;
  22680. //===//
  22681. //Tracev((stderr, "inflate: check matches trailer\n"));
  22682. }
  22683. state.mode = LENGTH;
  22684. /* falls through */
  22685. case LENGTH:
  22686. if (state.wrap && state.flags) {
  22687. //=== NEEDBITS(32);
  22688. while (bits < 32) {
  22689. if (have === 0) { break inf_leave; }
  22690. have--;
  22691. hold += input[next++] << bits;
  22692. bits += 8;
  22693. }
  22694. //===//
  22695. if (hold !== (state.total & 0xffffffff)) {
  22696. strm.msg = 'incorrect length check';
  22697. state.mode = BAD;
  22698. break;
  22699. }
  22700. //=== INITBITS();
  22701. hold = 0;
  22702. bits = 0;
  22703. //===//
  22704. //Tracev((stderr, "inflate: length matches trailer\n"));
  22705. }
  22706. state.mode = DONE;
  22707. /* falls through */
  22708. case DONE:
  22709. ret = Z_STREAM_END;
  22710. break inf_leave;
  22711. case BAD:
  22712. ret = Z_DATA_ERROR;
  22713. break inf_leave;
  22714. case MEM:
  22715. return Z_MEM_ERROR;
  22716. case SYNC:
  22717. /* falls through */
  22718. default:
  22719. return Z_STREAM_ERROR;
  22720. }
  22721. }
  22722. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22723. /*
  22724. Return from inflate(), updating the total counts and the check value.
  22725. If there was no progress during the inflate() call, return a buffer
  22726. error. Call updatewindow() to create and/or update the window state.
  22727. Note: a memory error from inflate() is non-recoverable.
  22728. */
  22729. //--- RESTORE() ---
  22730. strm.next_out = put;
  22731. strm.avail_out = left;
  22732. strm.next_in = next;
  22733. strm.avail_in = have;
  22734. state.hold = hold;
  22735. state.bits = bits;
  22736. //---
  22737. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22738. (state.mode < CHECK || flush !== Z_FINISH))) {
  22739. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22740. state.mode = MEM;
  22741. return Z_MEM_ERROR;
  22742. }
  22743. }
  22744. _in -= strm.avail_in;
  22745. _out -= strm.avail_out;
  22746. strm.total_in += _in;
  22747. strm.total_out += _out;
  22748. state.total += _out;
  22749. if (state.wrap && _out) {
  22750. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22751. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22752. }
  22753. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22754. (state.mode === TYPE ? 128 : 0) +
  22755. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22756. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22757. ret = Z_BUF_ERROR;
  22758. }
  22759. return ret;
  22760. }
  22761. function inflateEnd(strm) {
  22762. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22763. return Z_STREAM_ERROR;
  22764. }
  22765. var state = strm.state;
  22766. if (state.window) {
  22767. state.window = null;
  22768. }
  22769. strm.state = null;
  22770. return Z_OK;
  22771. }
  22772. function inflateGetHeader(strm, head) {
  22773. var state;
  22774. /* check state */
  22775. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22776. state = strm.state;
  22777. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22778. /* save header structure */
  22779. state.head = head;
  22780. head.done = false;
  22781. return Z_OK;
  22782. }
  22783. exports.inflateReset = inflateReset;
  22784. exports.inflateReset2 = inflateReset2;
  22785. exports.inflateResetKeep = inflateResetKeep;
  22786. exports.inflateInit = inflateInit;
  22787. exports.inflateInit2 = inflateInit2;
  22788. exports.inflate = inflate;
  22789. exports.inflateEnd = inflateEnd;
  22790. exports.inflateGetHeader = inflateGetHeader;
  22791. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22792. /* Not implemented
  22793. exports.inflateCopy = inflateCopy;
  22794. exports.inflateGetDictionary = inflateGetDictionary;
  22795. exports.inflateMark = inflateMark;
  22796. exports.inflatePrime = inflatePrime;
  22797. exports.inflateSetDictionary = inflateSetDictionary;
  22798. exports.inflateSync = inflateSync;
  22799. exports.inflateSyncPoint = inflateSyncPoint;
  22800. exports.inflateUndermine = inflateUndermine;
  22801. */
  22802. },{"../utils/common":87,"./adler32":89,"./crc32":91,"./inffast":94,"./inftrees":96}],96:[function(require,module,exports){
  22803. 'use strict';
  22804. var utils = require('../utils/common');
  22805. var MAXBITS = 15;
  22806. var ENOUGH_LENS = 852;
  22807. var ENOUGH_DISTS = 592;
  22808. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22809. var CODES = 0;
  22810. var LENS = 1;
  22811. var DISTS = 2;
  22812. var lbase = [ /* Length codes 257..285 base */
  22813. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  22814. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  22815. ];
  22816. var lext = [ /* Length codes 257..285 extra */
  22817. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  22818. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  22819. ];
  22820. var dbase = [ /* Distance codes 0..29 base */
  22821. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  22822. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  22823. 8193, 12289, 16385, 24577, 0, 0
  22824. ];
  22825. var dext = [ /* Distance codes 0..29 extra */
  22826. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  22827. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  22828. 28, 28, 29, 29, 64, 64
  22829. ];
  22830. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  22831. {
  22832. var bits = opts.bits;
  22833. //here = opts.here; /* table entry for duplication */
  22834. var len = 0; /* a code's length in bits */
  22835. var sym = 0; /* index of code symbols */
  22836. var min = 0, max = 0; /* minimum and maximum code lengths */
  22837. var root = 0; /* number of index bits for root table */
  22838. var curr = 0; /* number of index bits for current table */
  22839. var drop = 0; /* code bits to drop for sub-table */
  22840. var left = 0; /* number of prefix codes available */
  22841. var used = 0; /* code entries in table used */
  22842. var huff = 0; /* Huffman code */
  22843. var incr; /* for incrementing code, index */
  22844. var fill; /* index for replicating entries */
  22845. var low; /* low bits for current root entry */
  22846. var mask; /* mask for low root bits */
  22847. var next; /* next available space in table */
  22848. var base = null; /* base value table to use */
  22849. var base_index = 0;
  22850. // var shoextra; /* extra bits table to use */
  22851. var end; /* use base and extra for symbol > end */
  22852. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  22853. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  22854. var extra = null;
  22855. var extra_index = 0;
  22856. var here_bits, here_op, here_val;
  22857. /*
  22858. Process a set of code lengths to create a canonical Huffman code. The
  22859. code lengths are lens[0..codes-1]. Each length corresponds to the
  22860. symbols 0..codes-1. The Huffman code is generated by first sorting the
  22861. symbols by length from short to long, and retaining the symbol order
  22862. for codes with equal lengths. Then the code starts with all zero bits
  22863. for the first code of the shortest length, and the codes are integer
  22864. increments for the same length, and zeros are appended as the length
  22865. increases. For the deflate format, these bits are stored backwards
  22866. from their more natural integer increment ordering, and so when the
  22867. decoding tables are built in the large loop below, the integer codes
  22868. are incremented backwards.
  22869. This routine assumes, but does not check, that all of the entries in
  22870. lens[] are in the range 0..MAXBITS. The caller must assure this.
  22871. 1..MAXBITS is interpreted as that code length. zero means that that
  22872. symbol does not occur in this code.
  22873. The codes are sorted by computing a count of codes for each length,
  22874. creating from that a table of starting indices for each length in the
  22875. sorted table, and then entering the symbols in order in the sorted
  22876. table. The sorted table is work[], with that space being provided by
  22877. the caller.
  22878. The length counts are used for other purposes as well, i.e. finding
  22879. the minimum and maximum length codes, determining if there are any
  22880. codes at all, checking for a valid set of lengths, and looking ahead
  22881. at length counts to determine sub-table sizes when building the
  22882. decoding tables.
  22883. */
  22884. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  22885. for (len = 0; len <= MAXBITS; len++) {
  22886. count[len] = 0;
  22887. }
  22888. for (sym = 0; sym < codes; sym++) {
  22889. count[lens[lens_index + sym]]++;
  22890. }
  22891. /* bound code lengths, force root to be within code lengths */
  22892. root = bits;
  22893. for (max = MAXBITS; max >= 1; max--) {
  22894. if (count[max] !== 0) { break; }
  22895. }
  22896. if (root > max) {
  22897. root = max;
  22898. }
  22899. if (max === 0) { /* no symbols to code at all */
  22900. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  22901. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  22902. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  22903. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22904. //table.op[opts.table_index] = 64;
  22905. //table.bits[opts.table_index] = 1;
  22906. //table.val[opts.table_index++] = 0;
  22907. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  22908. opts.bits = 1;
  22909. return 0; /* no symbols, but wait for decoding to report error */
  22910. }
  22911. for (min = 1; min < max; min++) {
  22912. if (count[min] !== 0) { break; }
  22913. }
  22914. if (root < min) {
  22915. root = min;
  22916. }
  22917. /* check for an over-subscribed or incomplete set of lengths */
  22918. left = 1;
  22919. for (len = 1; len <= MAXBITS; len++) {
  22920. left <<= 1;
  22921. left -= count[len];
  22922. if (left < 0) {
  22923. return -1;
  22924. } /* over-subscribed */
  22925. }
  22926. if (left > 0 && (type === CODES || max !== 1)) {
  22927. return -1; /* incomplete set */
  22928. }
  22929. /* generate offsets into symbol table for each length for sorting */
  22930. offs[1] = 0;
  22931. for (len = 1; len < MAXBITS; len++) {
  22932. offs[len + 1] = offs[len] + count[len];
  22933. }
  22934. /* sort symbols by length, by symbol order within each length */
  22935. for (sym = 0; sym < codes; sym++) {
  22936. if (lens[lens_index + sym] !== 0) {
  22937. work[offs[lens[lens_index + sym]]++] = sym;
  22938. }
  22939. }
  22940. /*
  22941. Create and fill in decoding tables. In this loop, the table being
  22942. filled is at next and has curr index bits. The code being used is huff
  22943. with length len. That code is converted to an index by dropping drop
  22944. bits off of the bottom. For codes where len is less than drop + curr,
  22945. those top drop + curr - len bits are incremented through all values to
  22946. fill the table with replicated entries.
  22947. root is the number of index bits for the root table. When len exceeds
  22948. root, sub-tables are created pointed to by the root entry with an index
  22949. of the low root bits of huff. This is saved in low to check for when a
  22950. new sub-table should be started. drop is zero when the root table is
  22951. being filled, and drop is root when sub-tables are being filled.
  22952. When a new sub-table is needed, it is necessary to look ahead in the
  22953. code lengths to determine what size sub-table is needed. The length
  22954. counts are used for this, and so count[] is decremented as codes are
  22955. entered in the tables.
  22956. used keeps track of how many table entries have been allocated from the
  22957. provided *table space. It is checked for LENS and DIST tables against
  22958. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  22959. the initial root table size constants. See the comments in inftrees.h
  22960. for more information.
  22961. sym increments through all symbols, and the loop terminates when
  22962. all codes of length max, i.e. all codes, have been processed. This
  22963. routine permits incomplete codes, so another loop after this one fills
  22964. in the rest of the decoding tables with invalid code markers.
  22965. */
  22966. /* set up for code type */
  22967. // poor man optimization - use if-else instead of switch,
  22968. // to avoid deopts in old v8
  22969. if (type === CODES) {
  22970. base = extra = work; /* dummy value--not used */
  22971. end = 19;
  22972. } else if (type === LENS) {
  22973. base = lbase;
  22974. base_index -= 257;
  22975. extra = lext;
  22976. extra_index -= 257;
  22977. end = 256;
  22978. } else { /* DISTS */
  22979. base = dbase;
  22980. extra = dext;
  22981. end = -1;
  22982. }
  22983. /* initialize opts for loop */
  22984. huff = 0; /* starting code */
  22985. sym = 0; /* starting code symbol */
  22986. len = min; /* starting code length */
  22987. next = table_index; /* current table to fill in */
  22988. curr = root; /* current table index bits */
  22989. drop = 0; /* current bits to drop from code for index */
  22990. low = -1; /* trigger new sub-table when len > root */
  22991. used = 1 << root; /* use root table entries */
  22992. mask = used - 1; /* mask for comparing low */
  22993. /* check available table space */
  22994. if ((type === LENS && used > ENOUGH_LENS) ||
  22995. (type === DISTS && used > ENOUGH_DISTS)) {
  22996. return 1;
  22997. }
  22998. var i=0;
  22999. /* process all codes and make table entries */
  23000. for (;;) {
  23001. i++;
  23002. /* create table entry */
  23003. here_bits = len - drop;
  23004. if (work[sym] < end) {
  23005. here_op = 0;
  23006. here_val = work[sym];
  23007. }
  23008. else if (work[sym] > end) {
  23009. here_op = extra[extra_index + work[sym]];
  23010. here_val = base[base_index + work[sym]];
  23011. }
  23012. else {
  23013. here_op = 32 + 64; /* end of block */
  23014. here_val = 0;
  23015. }
  23016. /* replicate for those indices with low len bits equal to huff */
  23017. incr = 1 << (len - drop);
  23018. fill = 1 << curr;
  23019. min = fill; /* save offset to next table */
  23020. do {
  23021. fill -= incr;
  23022. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23023. } while (fill !== 0);
  23024. /* backwards increment the len-bit code huff */
  23025. incr = 1 << (len - 1);
  23026. while (huff & incr) {
  23027. incr >>= 1;
  23028. }
  23029. if (incr !== 0) {
  23030. huff &= incr - 1;
  23031. huff += incr;
  23032. } else {
  23033. huff = 0;
  23034. }
  23035. /* go to next symbol, update count, len */
  23036. sym++;
  23037. if (--count[len] === 0) {
  23038. if (len === max) { break; }
  23039. len = lens[lens_index + work[sym]];
  23040. }
  23041. /* create new sub-table if needed */
  23042. if (len > root && (huff & mask) !== low) {
  23043. /* if first time, transition to sub-tables */
  23044. if (drop === 0) {
  23045. drop = root;
  23046. }
  23047. /* increment past last table */
  23048. next += min; /* here min is 1 << curr */
  23049. /* determine length of next table */
  23050. curr = len - drop;
  23051. left = 1 << curr;
  23052. while (curr + drop < max) {
  23053. left -= count[curr + drop];
  23054. if (left <= 0) { break; }
  23055. curr++;
  23056. left <<= 1;
  23057. }
  23058. /* check for enough space */
  23059. used += 1 << curr;
  23060. if ((type === LENS && used > ENOUGH_LENS) ||
  23061. (type === DISTS && used > ENOUGH_DISTS)) {
  23062. return 1;
  23063. }
  23064. /* point entry in root table to sub-table */
  23065. low = huff & mask;
  23066. /*table.op[low] = curr;
  23067. table.bits[low] = root;
  23068. table.val[low] = next - opts.table_index;*/
  23069. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23070. }
  23071. }
  23072. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23073. at most one remaining entry, since if the code is incomplete, the
  23074. maximum code length that was allowed to get this far is one bit) */
  23075. if (huff !== 0) {
  23076. //table.op[next + huff] = 64; /* invalid code marker */
  23077. //table.bits[next + huff] = len - drop;
  23078. //table.val[next + huff] = 0;
  23079. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23080. }
  23081. /* set return parameters */
  23082. //opts.table_index += used;
  23083. opts.bits = root;
  23084. return 0;
  23085. };
  23086. },{"../utils/common":87}],97:[function(require,module,exports){
  23087. 'use strict';
  23088. module.exports = {
  23089. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23090. '1': 'stream end', /* Z_STREAM_END 1 */
  23091. '0': '', /* Z_OK 0 */
  23092. '-1': 'file error', /* Z_ERRNO (-1) */
  23093. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23094. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23095. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23096. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23097. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23098. };
  23099. },{}],98:[function(require,module,exports){
  23100. 'use strict';
  23101. var utils = require('../utils/common');
  23102. /* Public constants ==========================================================*/
  23103. /* ===========================================================================*/
  23104. //var Z_FILTERED = 1;
  23105. //var Z_HUFFMAN_ONLY = 2;
  23106. //var Z_RLE = 3;
  23107. var Z_FIXED = 4;
  23108. //var Z_DEFAULT_STRATEGY = 0;
  23109. /* Possible values of the data_type field (though see inflate()) */
  23110. var Z_BINARY = 0;
  23111. var Z_TEXT = 1;
  23112. //var Z_ASCII = 1; // = Z_TEXT
  23113. var Z_UNKNOWN = 2;
  23114. /*============================================================================*/
  23115. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23116. // From zutil.h
  23117. var STORED_BLOCK = 0;
  23118. var STATIC_TREES = 1;
  23119. var DYN_TREES = 2;
  23120. /* The three kinds of block type */
  23121. var MIN_MATCH = 3;
  23122. var MAX_MATCH = 258;
  23123. /* The minimum and maximum match lengths */
  23124. // From deflate.h
  23125. /* ===========================================================================
  23126. * Internal compression state.
  23127. */
  23128. var LENGTH_CODES = 29;
  23129. /* number of length codes, not counting the special END_BLOCK code */
  23130. var LITERALS = 256;
  23131. /* number of literal bytes 0..255 */
  23132. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23133. /* number of Literal or Length codes, including the END_BLOCK code */
  23134. var D_CODES = 30;
  23135. /* number of distance codes */
  23136. var BL_CODES = 19;
  23137. /* number of codes used to transfer the bit lengths */
  23138. var HEAP_SIZE = 2*L_CODES + 1;
  23139. /* maximum heap size */
  23140. var MAX_BITS = 15;
  23141. /* All codes must not exceed MAX_BITS bits */
  23142. var Buf_size = 16;
  23143. /* size of bit buffer in bi_buf */
  23144. /* ===========================================================================
  23145. * Constants
  23146. */
  23147. var MAX_BL_BITS = 7;
  23148. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23149. var END_BLOCK = 256;
  23150. /* end of block literal code */
  23151. var REP_3_6 = 16;
  23152. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23153. var REPZ_3_10 = 17;
  23154. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23155. var REPZ_11_138 = 18;
  23156. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23157. var extra_lbits = /* extra bits for each length code */
  23158. [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];
  23159. var extra_dbits = /* extra bits for each distance code */
  23160. [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];
  23161. var extra_blbits = /* extra bits for each bit length code */
  23162. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23163. var bl_order =
  23164. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23165. /* The lengths of the bit length codes are sent in order of decreasing
  23166. * probability, to avoid transmitting the lengths for unused bit length codes.
  23167. */
  23168. /* ===========================================================================
  23169. * Local data. These are initialized only once.
  23170. */
  23171. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23172. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23173. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23174. var static_ltree = new Array((L_CODES+2) * 2);
  23175. zero(static_ltree);
  23176. /* The static literal tree. Since the bit lengths are imposed, there is no
  23177. * need for the L_CODES extra codes used during heap construction. However
  23178. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23179. * below).
  23180. */
  23181. var static_dtree = new Array(D_CODES * 2);
  23182. zero(static_dtree);
  23183. /* The static distance tree. (Actually a trivial tree since all codes use
  23184. * 5 bits.)
  23185. */
  23186. var _dist_code = new Array(DIST_CODE_LEN);
  23187. zero(_dist_code);
  23188. /* Distance codes. The first 256 values correspond to the distances
  23189. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23190. * the 15 bit distances.
  23191. */
  23192. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23193. zero(_length_code);
  23194. /* length code for each normalized match length (0 == MIN_MATCH) */
  23195. var base_length = new Array(LENGTH_CODES);
  23196. zero(base_length);
  23197. /* First normalized length for each code (0 = MIN_MATCH) */
  23198. var base_dist = new Array(D_CODES);
  23199. zero(base_dist);
  23200. /* First normalized distance for each code (0 = distance of 1) */
  23201. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23202. this.static_tree = static_tree; /* static tree or NULL */
  23203. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23204. this.extra_base = extra_base; /* base index for extra_bits */
  23205. this.elems = elems; /* max number of elements in the tree */
  23206. this.max_length = max_length; /* max bit length for the codes */
  23207. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23208. this.has_stree = static_tree && static_tree.length;
  23209. };
  23210. var static_l_desc;
  23211. var static_d_desc;
  23212. var static_bl_desc;
  23213. var TreeDesc = function(dyn_tree, stat_desc) {
  23214. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23215. this.max_code = 0; /* largest code with non zero frequency */
  23216. this.stat_desc = stat_desc; /* the corresponding static tree */
  23217. };
  23218. function d_code(dist) {
  23219. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23220. }
  23221. /* ===========================================================================
  23222. * Output a short LSB first on the stream.
  23223. * IN assertion: there is enough room in pendingBuf.
  23224. */
  23225. function put_short (s, w) {
  23226. // put_byte(s, (uch)((w) & 0xff));
  23227. // put_byte(s, (uch)((ush)(w) >> 8));
  23228. s.pending_buf[s.pending++] = (w) & 0xff;
  23229. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23230. }
  23231. /* ===========================================================================
  23232. * Send a value on a given number of bits.
  23233. * IN assertion: length <= 16 and value fits in length bits.
  23234. */
  23235. function send_bits(s, value, length) {
  23236. if (s.bi_valid > (Buf_size - length)) {
  23237. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23238. put_short(s, s.bi_buf);
  23239. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23240. s.bi_valid += length - Buf_size;
  23241. } else {
  23242. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23243. s.bi_valid += length;
  23244. }
  23245. }
  23246. function send_code(s, c, tree) {
  23247. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23248. }
  23249. /* ===========================================================================
  23250. * Reverse the first len bits of a code, using straightforward code (a faster
  23251. * method would use a table)
  23252. * IN assertion: 1 <= len <= 15
  23253. */
  23254. function bi_reverse(code, len) {
  23255. var res = 0;
  23256. do {
  23257. res |= code & 1;
  23258. code >>>= 1;
  23259. res <<= 1;
  23260. } while (--len > 0);
  23261. return res >>> 1;
  23262. }
  23263. /* ===========================================================================
  23264. * Flush the bit buffer, keeping at most 7 bits in it.
  23265. */
  23266. function bi_flush(s) {
  23267. if (s.bi_valid === 16) {
  23268. put_short(s, s.bi_buf);
  23269. s.bi_buf = 0;
  23270. s.bi_valid = 0;
  23271. } else if (s.bi_valid >= 8) {
  23272. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23273. s.bi_buf >>= 8;
  23274. s.bi_valid -= 8;
  23275. }
  23276. }
  23277. /* ===========================================================================
  23278. * Compute the optimal bit lengths for a tree and update the total bit length
  23279. * for the current block.
  23280. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23281. * above are the tree nodes sorted by increasing frequency.
  23282. * OUT assertions: the field len is set to the optimal bit length, the
  23283. * array bl_count contains the frequencies for each bit length.
  23284. * The length opt_len is updated; static_len is also updated if stree is
  23285. * not null.
  23286. */
  23287. function gen_bitlen(s, desc)
  23288. // deflate_state *s;
  23289. // tree_desc *desc; /* the tree descriptor */
  23290. {
  23291. var tree = desc.dyn_tree;
  23292. var max_code = desc.max_code;
  23293. var stree = desc.stat_desc.static_tree;
  23294. var has_stree = desc.stat_desc.has_stree;
  23295. var extra = desc.stat_desc.extra_bits;
  23296. var base = desc.stat_desc.extra_base;
  23297. var max_length = desc.stat_desc.max_length;
  23298. var h; /* heap index */
  23299. var n, m; /* iterate over the tree elements */
  23300. var bits; /* bit length */
  23301. var xbits; /* extra bits */
  23302. var f; /* frequency */
  23303. var overflow = 0; /* number of elements with bit length too large */
  23304. for (bits = 0; bits <= MAX_BITS; bits++) {
  23305. s.bl_count[bits] = 0;
  23306. }
  23307. /* In a first pass, compute the optimal bit lengths (which may
  23308. * overflow in the case of the bit length tree).
  23309. */
  23310. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23311. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23312. n = s.heap[h];
  23313. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23314. if (bits > max_length) {
  23315. bits = max_length;
  23316. overflow++;
  23317. }
  23318. tree[n*2 + 1]/*.Len*/ = bits;
  23319. /* We overwrite tree[n].Dad which is no longer needed */
  23320. if (n > max_code) { continue; } /* not a leaf node */
  23321. s.bl_count[bits]++;
  23322. xbits = 0;
  23323. if (n >= base) {
  23324. xbits = extra[n-base];
  23325. }
  23326. f = tree[n * 2]/*.Freq*/;
  23327. s.opt_len += f * (bits + xbits);
  23328. if (has_stree) {
  23329. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23330. }
  23331. }
  23332. if (overflow === 0) { return; }
  23333. // Trace((stderr,"\nbit length overflow\n"));
  23334. /* This happens for example on obj2 and pic of the Calgary corpus */
  23335. /* Find the first bit length which could increase: */
  23336. do {
  23337. bits = max_length-1;
  23338. while (s.bl_count[bits] === 0) { bits--; }
  23339. s.bl_count[bits]--; /* move one leaf down the tree */
  23340. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23341. s.bl_count[max_length]--;
  23342. /* The brother of the overflow item also moves one step up,
  23343. * but this does not affect bl_count[max_length]
  23344. */
  23345. overflow -= 2;
  23346. } while (overflow > 0);
  23347. /* Now recompute all bit lengths, scanning in increasing frequency.
  23348. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23349. * lengths instead of fixing only the wrong ones. This idea is taken
  23350. * from 'ar' written by Haruhiko Okumura.)
  23351. */
  23352. for (bits = max_length; bits !== 0; bits--) {
  23353. n = s.bl_count[bits];
  23354. while (n !== 0) {
  23355. m = s.heap[--h];
  23356. if (m > max_code) { continue; }
  23357. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23358. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23359. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23360. tree[m*2 + 1]/*.Len*/ = bits;
  23361. }
  23362. n--;
  23363. }
  23364. }
  23365. }
  23366. /* ===========================================================================
  23367. * Generate the codes for a given tree and bit counts (which need not be
  23368. * optimal).
  23369. * IN assertion: the array bl_count contains the bit length statistics for
  23370. * the given tree and the field len is set for all tree elements.
  23371. * OUT assertion: the field code is set for all tree elements of non
  23372. * zero code length.
  23373. */
  23374. function gen_codes(tree, max_code, bl_count)
  23375. // ct_data *tree; /* the tree to decorate */
  23376. // int max_code; /* largest code with non zero frequency */
  23377. // ushf *bl_count; /* number of codes at each bit length */
  23378. {
  23379. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23380. var code = 0; /* running code value */
  23381. var bits; /* bit index */
  23382. var n; /* code index */
  23383. /* The distribution counts are first used to generate the code values
  23384. * without bit reversal.
  23385. */
  23386. for (bits = 1; bits <= MAX_BITS; bits++) {
  23387. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23388. }
  23389. /* Check that the bit counts in bl_count are consistent. The last code
  23390. * must be all ones.
  23391. */
  23392. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23393. // "inconsistent bit counts");
  23394. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23395. for (n = 0; n <= max_code; n++) {
  23396. var len = tree[n*2 + 1]/*.Len*/;
  23397. if (len === 0) { continue; }
  23398. /* Now reverse the bits */
  23399. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23400. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23401. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23402. }
  23403. }
  23404. /* ===========================================================================
  23405. * Initialize the various 'constant' tables.
  23406. */
  23407. function tr_static_init() {
  23408. var n; /* iterates over tree elements */
  23409. var bits; /* bit counter */
  23410. var length; /* length value */
  23411. var code; /* code value */
  23412. var dist; /* distance index */
  23413. var bl_count = new Array(MAX_BITS+1);
  23414. /* number of codes at each bit length for an optimal tree */
  23415. // do check in _tr_init()
  23416. //if (static_init_done) return;
  23417. /* For some embedded targets, global variables are not initialized: */
  23418. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23419. static_l_desc.static_tree = static_ltree;
  23420. static_l_desc.extra_bits = extra_lbits;
  23421. static_d_desc.static_tree = static_dtree;
  23422. static_d_desc.extra_bits = extra_dbits;
  23423. static_bl_desc.extra_bits = extra_blbits;
  23424. #endif*/
  23425. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23426. length = 0;
  23427. for (code = 0; code < LENGTH_CODES-1; code++) {
  23428. base_length[code] = length;
  23429. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23430. _length_code[length++] = code;
  23431. }
  23432. }
  23433. //Assert (length == 256, "tr_static_init: length != 256");
  23434. /* Note that the length 255 (match length 258) can be represented
  23435. * in two different ways: code 284 + 5 bits or code 285, so we
  23436. * overwrite length_code[255] to use the best encoding:
  23437. */
  23438. _length_code[length-1] = code;
  23439. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  23440. dist = 0;
  23441. for (code = 0 ; code < 16; code++) {
  23442. base_dist[code] = dist;
  23443. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  23444. _dist_code[dist++] = code;
  23445. }
  23446. }
  23447. //Assert (dist == 256, "tr_static_init: dist != 256");
  23448. dist >>= 7; /* from now on, all distances are divided by 128 */
  23449. for (; code < D_CODES; code++) {
  23450. base_dist[code] = dist << 7;
  23451. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  23452. _dist_code[256 + dist++] = code;
  23453. }
  23454. }
  23455. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  23456. /* Construct the codes of the static literal tree */
  23457. for (bits = 0; bits <= MAX_BITS; bits++) {
  23458. bl_count[bits] = 0;
  23459. }
  23460. n = 0;
  23461. while (n <= 143) {
  23462. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23463. n++;
  23464. bl_count[8]++;
  23465. }
  23466. while (n <= 255) {
  23467. static_ltree[n*2 + 1]/*.Len*/ = 9;
  23468. n++;
  23469. bl_count[9]++;
  23470. }
  23471. while (n <= 279) {
  23472. static_ltree[n*2 + 1]/*.Len*/ = 7;
  23473. n++;
  23474. bl_count[7]++;
  23475. }
  23476. while (n <= 287) {
  23477. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23478. n++;
  23479. bl_count[8]++;
  23480. }
  23481. /* Codes 286 and 287 do not exist, but we must include them in the
  23482. * tree construction to get a canonical Huffman tree (longest code
  23483. * all ones)
  23484. */
  23485. gen_codes(static_ltree, L_CODES+1, bl_count);
  23486. /* The static distance tree is trivial: */
  23487. for (n = 0; n < D_CODES; n++) {
  23488. static_dtree[n*2 + 1]/*.Len*/ = 5;
  23489. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  23490. }
  23491. // Now data ready and we can init static trees
  23492. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  23493. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  23494. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  23495. //static_init_done = true;
  23496. }
  23497. /* ===========================================================================
  23498. * Initialize a new block.
  23499. */
  23500. function init_block(s) {
  23501. var n; /* iterates over tree elements */
  23502. /* Initialize the trees. */
  23503. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  23504. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  23505. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  23506. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  23507. s.opt_len = s.static_len = 0;
  23508. s.last_lit = s.matches = 0;
  23509. }
  23510. /* ===========================================================================
  23511. * Flush the bit buffer and align the output on a byte boundary
  23512. */
  23513. function bi_windup(s)
  23514. {
  23515. if (s.bi_valid > 8) {
  23516. put_short(s, s.bi_buf);
  23517. } else if (s.bi_valid > 0) {
  23518. //put_byte(s, (Byte)s->bi_buf);
  23519. s.pending_buf[s.pending++] = s.bi_buf;
  23520. }
  23521. s.bi_buf = 0;
  23522. s.bi_valid = 0;
  23523. }
  23524. /* ===========================================================================
  23525. * Copy a stored block, storing first the length and its
  23526. * one's complement if requested.
  23527. */
  23528. function copy_block(s, buf, len, header)
  23529. //DeflateState *s;
  23530. //charf *buf; /* the input data */
  23531. //unsigned len; /* its length */
  23532. //int header; /* true if block header must be written */
  23533. {
  23534. bi_windup(s); /* align on byte boundary */
  23535. if (header) {
  23536. put_short(s, len);
  23537. put_short(s, ~len);
  23538. }
  23539. // while (len--) {
  23540. // put_byte(s, *buf++);
  23541. // }
  23542. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  23543. s.pending += len;
  23544. }
  23545. /* ===========================================================================
  23546. * Compares to subtrees, using the tree depth as tie breaker when
  23547. * the subtrees have equal frequency. This minimizes the worst case length.
  23548. */
  23549. function smaller(tree, n, m, depth) {
  23550. var _n2 = n*2;
  23551. var _m2 = m*2;
  23552. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  23553. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  23554. }
  23555. /* ===========================================================================
  23556. * Restore the heap property by moving down the tree starting at node k,
  23557. * exchanging a node with the smallest of its two sons if necessary, stopping
  23558. * when the heap property is re-established (each father smaller than its
  23559. * two sons).
  23560. */
  23561. function pqdownheap(s, tree, k)
  23562. // deflate_state *s;
  23563. // ct_data *tree; /* the tree to restore */
  23564. // int k; /* node to move down */
  23565. {
  23566. var v = s.heap[k];
  23567. var j = k << 1; /* left son of k */
  23568. while (j <= s.heap_len) {
  23569. /* Set j to the smallest of the two sons: */
  23570. if (j < s.heap_len &&
  23571. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  23572. j++;
  23573. }
  23574. /* Exit if v is smaller than both sons */
  23575. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  23576. /* Exchange v with the smallest son */
  23577. s.heap[k] = s.heap[j];
  23578. k = j;
  23579. /* And continue down the tree, setting j to the left son of k */
  23580. j <<= 1;
  23581. }
  23582. s.heap[k] = v;
  23583. }
  23584. // inlined manually
  23585. // var SMALLEST = 1;
  23586. /* ===========================================================================
  23587. * Send the block data compressed using the given Huffman trees
  23588. */
  23589. function compress_block(s, ltree, dtree)
  23590. // deflate_state *s;
  23591. // const ct_data *ltree; /* literal tree */
  23592. // const ct_data *dtree; /* distance tree */
  23593. {
  23594. var dist; /* distance of matched string */
  23595. var lc; /* match length or unmatched char (if dist == 0) */
  23596. var lx = 0; /* running index in l_buf */
  23597. var code; /* the code to send */
  23598. var extra; /* number of extra bits to send */
  23599. if (s.last_lit !== 0) {
  23600. do {
  23601. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  23602. lc = s.pending_buf[s.l_buf + lx];
  23603. lx++;
  23604. if (dist === 0) {
  23605. send_code(s, lc, ltree); /* send a literal byte */
  23606. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  23607. } else {
  23608. /* Here, lc is the match length - MIN_MATCH */
  23609. code = _length_code[lc];
  23610. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  23611. extra = extra_lbits[code];
  23612. if (extra !== 0) {
  23613. lc -= base_length[code];
  23614. send_bits(s, lc, extra); /* send the extra length bits */
  23615. }
  23616. dist--; /* dist is now the match distance - 1 */
  23617. code = d_code(dist);
  23618. //Assert (code < D_CODES, "bad d_code");
  23619. send_code(s, code, dtree); /* send the distance code */
  23620. extra = extra_dbits[code];
  23621. if (extra !== 0) {
  23622. dist -= base_dist[code];
  23623. send_bits(s, dist, extra); /* send the extra distance bits */
  23624. }
  23625. } /* literal or match pair ? */
  23626. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  23627. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  23628. // "pendingBuf overflow");
  23629. } while (lx < s.last_lit);
  23630. }
  23631. send_code(s, END_BLOCK, ltree);
  23632. }
  23633. /* ===========================================================================
  23634. * Construct one Huffman tree and assigns the code bit strings and lengths.
  23635. * Update the total bit length for the current block.
  23636. * IN assertion: the field freq is set for all tree elements.
  23637. * OUT assertions: the fields len and code are set to the optimal bit length
  23638. * and corresponding code. The length opt_len is updated; static_len is
  23639. * also updated if stree is not null. The field max_code is set.
  23640. */
  23641. function build_tree(s, desc)
  23642. // deflate_state *s;
  23643. // tree_desc *desc; /* the tree descriptor */
  23644. {
  23645. var tree = desc.dyn_tree;
  23646. var stree = desc.stat_desc.static_tree;
  23647. var has_stree = desc.stat_desc.has_stree;
  23648. var elems = desc.stat_desc.elems;
  23649. var n, m; /* iterate over heap elements */
  23650. var max_code = -1; /* largest code with non zero frequency */
  23651. var node; /* new node being created */
  23652. /* Construct the initial heap, with least frequent element in
  23653. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  23654. * heap[0] is not used.
  23655. */
  23656. s.heap_len = 0;
  23657. s.heap_max = HEAP_SIZE;
  23658. for (n = 0; n < elems; n++) {
  23659. if (tree[n * 2]/*.Freq*/ !== 0) {
  23660. s.heap[++s.heap_len] = max_code = n;
  23661. s.depth[n] = 0;
  23662. } else {
  23663. tree[n*2 + 1]/*.Len*/ = 0;
  23664. }
  23665. }
  23666. /* The pkzip format requires that at least one distance code exists,
  23667. * and that at least one bit should be sent even if there is only one
  23668. * possible code. So to avoid special checks later on we force at least
  23669. * two codes of non zero frequency.
  23670. */
  23671. while (s.heap_len < 2) {
  23672. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  23673. tree[node * 2]/*.Freq*/ = 1;
  23674. s.depth[node] = 0;
  23675. s.opt_len--;
  23676. if (has_stree) {
  23677. s.static_len -= stree[node*2 + 1]/*.Len*/;
  23678. }
  23679. /* node is 0 or 1 so it does not have extra bits */
  23680. }
  23681. desc.max_code = max_code;
  23682. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  23683. * establish sub-heaps of increasing lengths:
  23684. */
  23685. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  23686. /* Construct the Huffman tree by repeatedly combining the least two
  23687. * frequent nodes.
  23688. */
  23689. node = elems; /* next internal node of the tree */
  23690. do {
  23691. //pqremove(s, tree, n); /* n = node of least frequency */
  23692. /*** pqremove ***/
  23693. n = s.heap[1/*SMALLEST*/];
  23694. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  23695. pqdownheap(s, tree, 1/*SMALLEST*/);
  23696. /***/
  23697. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  23698. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  23699. s.heap[--s.heap_max] = m;
  23700. /* Create a new node father of n and m */
  23701. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  23702. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  23703. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  23704. /* and insert the new node in the heap */
  23705. s.heap[1/*SMALLEST*/] = node++;
  23706. pqdownheap(s, tree, 1/*SMALLEST*/);
  23707. } while (s.heap_len >= 2);
  23708. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  23709. /* At this point, the fields freq and dad are set. We can now
  23710. * generate the bit lengths.
  23711. */
  23712. gen_bitlen(s, desc);
  23713. /* The field len is now set, we can generate the bit codes */
  23714. gen_codes(tree, max_code, s.bl_count);
  23715. }
  23716. /* ===========================================================================
  23717. * Scan a literal or distance tree to determine the frequencies of the codes
  23718. * in the bit length tree.
  23719. */
  23720. function scan_tree(s, tree, max_code)
  23721. // deflate_state *s;
  23722. // ct_data *tree; /* the tree to be scanned */
  23723. // int max_code; /* and its largest code of non zero frequency */
  23724. {
  23725. var n; /* iterates over all tree elements */
  23726. var prevlen = -1; /* last emitted length */
  23727. var curlen; /* length of current code */
  23728. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23729. var count = 0; /* repeat count of the current code */
  23730. var max_count = 7; /* max repeat count */
  23731. var min_count = 4; /* min repeat count */
  23732. if (nextlen === 0) {
  23733. max_count = 138;
  23734. min_count = 3;
  23735. }
  23736. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23737. for (n = 0; n <= max_code; n++) {
  23738. curlen = nextlen;
  23739. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23740. if (++count < max_count && curlen === nextlen) {
  23741. continue;
  23742. } else if (count < min_count) {
  23743. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23744. } else if (curlen !== 0) {
  23745. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23746. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23747. } else if (count <= 10) {
  23748. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23749. } else {
  23750. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23751. }
  23752. count = 0;
  23753. prevlen = curlen;
  23754. if (nextlen === 0) {
  23755. max_count = 138;
  23756. min_count = 3;
  23757. } else if (curlen === nextlen) {
  23758. max_count = 6;
  23759. min_count = 3;
  23760. } else {
  23761. max_count = 7;
  23762. min_count = 4;
  23763. }
  23764. }
  23765. }
  23766. /* ===========================================================================
  23767. * Send a literal or distance tree in compressed form, using the codes in
  23768. * bl_tree.
  23769. */
  23770. function send_tree(s, tree, max_code)
  23771. // deflate_state *s;
  23772. // ct_data *tree; /* the tree to be scanned */
  23773. // int max_code; /* and its largest code of non zero frequency */
  23774. {
  23775. var n; /* iterates over all tree elements */
  23776. var prevlen = -1; /* last emitted length */
  23777. var curlen; /* length of current code */
  23778. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23779. var count = 0; /* repeat count of the current code */
  23780. var max_count = 7; /* max repeat count */
  23781. var min_count = 4; /* min repeat count */
  23782. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23783. if (nextlen === 0) {
  23784. max_count = 138;
  23785. min_count = 3;
  23786. }
  23787. for (n = 0; n <= max_code; n++) {
  23788. curlen = nextlen;
  23789. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23790. if (++count < max_count && curlen === nextlen) {
  23791. continue;
  23792. } else if (count < min_count) {
  23793. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  23794. } else if (curlen !== 0) {
  23795. if (curlen !== prevlen) {
  23796. send_code(s, curlen, s.bl_tree);
  23797. count--;
  23798. }
  23799. //Assert(count >= 3 && count <= 6, " 3_6?");
  23800. send_code(s, REP_3_6, s.bl_tree);
  23801. send_bits(s, count-3, 2);
  23802. } else if (count <= 10) {
  23803. send_code(s, REPZ_3_10, s.bl_tree);
  23804. send_bits(s, count-3, 3);
  23805. } else {
  23806. send_code(s, REPZ_11_138, s.bl_tree);
  23807. send_bits(s, count-11, 7);
  23808. }
  23809. count = 0;
  23810. prevlen = curlen;
  23811. if (nextlen === 0) {
  23812. max_count = 138;
  23813. min_count = 3;
  23814. } else if (curlen === nextlen) {
  23815. max_count = 6;
  23816. min_count = 3;
  23817. } else {
  23818. max_count = 7;
  23819. min_count = 4;
  23820. }
  23821. }
  23822. }
  23823. /* ===========================================================================
  23824. * Construct the Huffman tree for the bit lengths and return the index in
  23825. * bl_order of the last bit length code to send.
  23826. */
  23827. function build_bl_tree(s) {
  23828. var max_blindex; /* index of last bit length code of non zero freq */
  23829. /* Determine the bit length frequencies for literal and distance trees */
  23830. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  23831. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  23832. /* Build the bit length tree: */
  23833. build_tree(s, s.bl_desc);
  23834. /* opt_len now includes the length of the tree representations, except
  23835. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  23836. */
  23837. /* Determine the number of bit length codes to send. The pkzip format
  23838. * requires that at least 4 bit length codes be sent. (appnote.txt says
  23839. * 3 but the actual value used is 4.)
  23840. */
  23841. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  23842. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  23843. break;
  23844. }
  23845. }
  23846. /* Update opt_len to include the bit length tree and counts */
  23847. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  23848. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  23849. // s->opt_len, s->static_len));
  23850. return max_blindex;
  23851. }
  23852. /* ===========================================================================
  23853. * Send the header for a block using dynamic Huffman trees: the counts, the
  23854. * lengths of the bit length codes, the literal tree and the distance tree.
  23855. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  23856. */
  23857. function send_all_trees(s, lcodes, dcodes, blcodes)
  23858. // deflate_state *s;
  23859. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  23860. {
  23861. var rank; /* index in bl_order */
  23862. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  23863. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  23864. // "too many codes");
  23865. //Tracev((stderr, "\nbl counts: "));
  23866. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  23867. send_bits(s, dcodes-1, 5);
  23868. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  23869. for (rank = 0; rank < blcodes; rank++) {
  23870. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  23871. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  23872. }
  23873. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  23874. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  23875. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  23876. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  23877. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  23878. }
  23879. /* ===========================================================================
  23880. * Check if the data type is TEXT or BINARY, using the following algorithm:
  23881. * - TEXT if the two conditions below are satisfied:
  23882. * a) There are no non-portable control characters belonging to the
  23883. * "black list" (0..6, 14..25, 28..31).
  23884. * b) There is at least one printable character belonging to the
  23885. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  23886. * - BINARY otherwise.
  23887. * - The following partially-portable control characters form a
  23888. * "gray list" that is ignored in this detection algorithm:
  23889. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  23890. * IN assertion: the fields Freq of dyn_ltree are set.
  23891. */
  23892. function detect_data_type(s) {
  23893. /* black_mask is the bit mask of black-listed bytes
  23894. * set bits 0..6, 14..25, and 28..31
  23895. * 0xf3ffc07f = binary 11110011111111111100000001111111
  23896. */
  23897. var black_mask = 0xf3ffc07f;
  23898. var n;
  23899. /* Check for non-textual ("black-listed") bytes. */
  23900. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  23901. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  23902. return Z_BINARY;
  23903. }
  23904. }
  23905. /* Check for textual ("white-listed") bytes. */
  23906. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  23907. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  23908. return Z_TEXT;
  23909. }
  23910. for (n = 32; n < LITERALS; n++) {
  23911. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  23912. return Z_TEXT;
  23913. }
  23914. }
  23915. /* There are no "black-listed" or "white-listed" bytes:
  23916. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  23917. */
  23918. return Z_BINARY;
  23919. }
  23920. var static_init_done = false;
  23921. /* ===========================================================================
  23922. * Initialize the tree data structures for a new zlib stream.
  23923. */
  23924. function _tr_init(s)
  23925. {
  23926. if (!static_init_done) {
  23927. tr_static_init();
  23928. static_init_done = true;
  23929. }
  23930. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  23931. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  23932. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  23933. s.bi_buf = 0;
  23934. s.bi_valid = 0;
  23935. /* Initialize the first block of the first file: */
  23936. init_block(s);
  23937. }
  23938. /* ===========================================================================
  23939. * Send a stored block
  23940. */
  23941. function _tr_stored_block(s, buf, stored_len, last)
  23942. //DeflateState *s;
  23943. //charf *buf; /* input block */
  23944. //ulg stored_len; /* length of input block */
  23945. //int last; /* one if this is the last block for a file */
  23946. {
  23947. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  23948. copy_block(s, buf, stored_len, true); /* with header */
  23949. }
  23950. /* ===========================================================================
  23951. * Send one empty static block to give enough lookahead for inflate.
  23952. * This takes 10 bits, of which 7 may remain in the bit buffer.
  23953. */
  23954. function _tr_align(s) {
  23955. send_bits(s, STATIC_TREES<<1, 3);
  23956. send_code(s, END_BLOCK, static_ltree);
  23957. bi_flush(s);
  23958. }
  23959. /* ===========================================================================
  23960. * Determine the best encoding for the current block: dynamic trees, static
  23961. * trees or store, and output the encoded block to the zip file.
  23962. */
  23963. function _tr_flush_block(s, buf, stored_len, last)
  23964. //DeflateState *s;
  23965. //charf *buf; /* input block, or NULL if too old */
  23966. //ulg stored_len; /* length of input block */
  23967. //int last; /* one if this is the last block for a file */
  23968. {
  23969. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  23970. var max_blindex = 0; /* index of last bit length code of non zero freq */
  23971. /* Build the Huffman trees unless a stored block is forced */
  23972. if (s.level > 0) {
  23973. /* Check if the file is binary or text */
  23974. if (s.strm.data_type === Z_UNKNOWN) {
  23975. s.strm.data_type = detect_data_type(s);
  23976. }
  23977. /* Construct the literal and distance trees */
  23978. build_tree(s, s.l_desc);
  23979. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  23980. // s->static_len));
  23981. build_tree(s, s.d_desc);
  23982. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  23983. // s->static_len));
  23984. /* At this point, opt_len and static_len are the total bit lengths of
  23985. * the compressed block data, excluding the tree representations.
  23986. */
  23987. /* Build the bit length tree for the above two trees, and get the index
  23988. * in bl_order of the last bit length code to send.
  23989. */
  23990. max_blindex = build_bl_tree(s);
  23991. /* Determine the best encoding. Compute the block lengths in bytes. */
  23992. opt_lenb = (s.opt_len+3+7) >>> 3;
  23993. static_lenb = (s.static_len+3+7) >>> 3;
  23994. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  23995. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  23996. // s->last_lit));
  23997. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  23998. } else {
  23999. // Assert(buf != (char*)0, "lost buf");
  24000. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24001. }
  24002. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24003. /* 4: two words for the lengths */
  24004. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24005. * Otherwise we can't have processed more than WSIZE input bytes since
  24006. * the last block flush, because compression would have been
  24007. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24008. * transform a block into a stored block.
  24009. */
  24010. _tr_stored_block(s, buf, stored_len, last);
  24011. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24012. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24013. compress_block(s, static_ltree, static_dtree);
  24014. } else {
  24015. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24016. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24017. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24018. }
  24019. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24020. /* The above check is made mod 2^32, for files larger than 512 MB
  24021. * and uLong implemented on 32 bits.
  24022. */
  24023. init_block(s);
  24024. if (last) {
  24025. bi_windup(s);
  24026. }
  24027. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24028. // s->compressed_len-7*last));
  24029. }
  24030. /* ===========================================================================
  24031. * Save the match info and tally the frequency counts. Return true if
  24032. * the current block must be flushed.
  24033. */
  24034. function _tr_tally(s, dist, lc)
  24035. // deflate_state *s;
  24036. // unsigned dist; /* distance of matched string */
  24037. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24038. {
  24039. //var out_length, in_length, dcode;
  24040. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24041. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24042. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24043. s.last_lit++;
  24044. if (dist === 0) {
  24045. /* lc is the unmatched char */
  24046. s.dyn_ltree[lc*2]/*.Freq*/++;
  24047. } else {
  24048. s.matches++;
  24049. /* Here, lc is the match length - MIN_MATCH */
  24050. dist--; /* dist = match distance - 1 */
  24051. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24052. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24053. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24054. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24055. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24056. }
  24057. // (!) This block is disabled in zlib defailts,
  24058. // don't enable it for binary compatibility
  24059. //#ifdef TRUNCATE_BLOCK
  24060. // /* Try to guess if it is profitable to stop the current block here */
  24061. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24062. // /* Compute an upper bound for the compressed length */
  24063. // out_length = s.last_lit*8;
  24064. // in_length = s.strstart - s.block_start;
  24065. //
  24066. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24067. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24068. // }
  24069. // out_length >>>= 3;
  24070. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24071. // // s->last_lit, in_length, out_length,
  24072. // // 100L - out_length*100L/in_length));
  24073. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24074. // return true;
  24075. // }
  24076. // }
  24077. //#endif
  24078. return (s.last_lit === s.lit_bufsize-1);
  24079. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24080. * on 16 bit machines and because stored blocks are restricted to
  24081. * 64K-1 bytes.
  24082. */
  24083. }
  24084. exports._tr_init = _tr_init;
  24085. exports._tr_stored_block = _tr_stored_block;
  24086. exports._tr_flush_block = _tr_flush_block;
  24087. exports._tr_tally = _tr_tally;
  24088. exports._tr_align = _tr_align;
  24089. },{"../utils/common":87}],99:[function(require,module,exports){
  24090. 'use strict';
  24091. function ZStream() {
  24092. /* next input byte */
  24093. this.input = null; // JS specific, because we have no pointers
  24094. this.next_in = 0;
  24095. /* number of bytes available at input */
  24096. this.avail_in = 0;
  24097. /* total number of input bytes read so far */
  24098. this.total_in = 0;
  24099. /* next output byte should be put there */
  24100. this.output = null; // JS specific, because we have no pointers
  24101. this.next_out = 0;
  24102. /* remaining free space at output */
  24103. this.avail_out = 0;
  24104. /* total number of bytes output so far */
  24105. this.total_out = 0;
  24106. /* last error message, NULL if no error */
  24107. this.msg = ''/*Z_NULL*/;
  24108. /* not visible by applications */
  24109. this.state = null;
  24110. /* best guess about the data type: binary or text */
  24111. this.data_type = 2/*Z_UNKNOWN*/;
  24112. /* adler32 value of the uncompressed data */
  24113. this.adler = 0;
  24114. }
  24115. module.exports = ZStream;
  24116. },{}],100:[function(require,module,exports){
  24117. (function (global){
  24118. /**
  24119. * JSON parse.
  24120. *
  24121. * @see Based on jQuery#parseJSON (MIT) and JSON2
  24122. * @api private
  24123. */
  24124. var rvalidchars = /^[\],:{}\s]*$/;
  24125. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  24126. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  24127. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  24128. var rtrimLeft = /^\s+/;
  24129. var rtrimRight = /\s+$/;
  24130. module.exports = function parsejson(data) {
  24131. if ('string' != typeof data || !data) {
  24132. return null;
  24133. }
  24134. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  24135. // Attempt to parse using the native JSON parser first
  24136. if (global.JSON && JSON.parse) {
  24137. return JSON.parse(data);
  24138. }
  24139. if (rvalidchars.test(data.replace(rvalidescape, '@')
  24140. .replace(rvalidtokens, ']')
  24141. .replace(rvalidbraces, ''))) {
  24142. return (new Function('return ' + data))();
  24143. }
  24144. };
  24145. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24146. },{}],101:[function(require,module,exports){
  24147. /**
  24148. * Compiles a querystring
  24149. * Returns string representation of the object
  24150. *
  24151. * @param {Object}
  24152. * @api private
  24153. */
  24154. exports.encode = function (obj) {
  24155. var str = '';
  24156. for (var i in obj) {
  24157. if (obj.hasOwnProperty(i)) {
  24158. if (str.length) str += '&';
  24159. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  24160. }
  24161. }
  24162. return str;
  24163. };
  24164. /**
  24165. * Parses a simple querystring into an object
  24166. *
  24167. * @param {String} qs
  24168. * @api private
  24169. */
  24170. exports.decode = function(qs){
  24171. var qry = {};
  24172. var pairs = qs.split('&');
  24173. for (var i = 0, l = pairs.length; i < l; i++) {
  24174. var pair = pairs[i].split('=');
  24175. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  24176. }
  24177. return qry;
  24178. };
  24179. },{}],102:[function(require,module,exports){
  24180. /**
  24181. * Parses an URI
  24182. *
  24183. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  24184. * @api private
  24185. */
  24186. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  24187. var parts = [
  24188. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  24189. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  24190. ];
  24191. module.exports = function parseuri(str) {
  24192. var m = re.exec(str || '')
  24193. , uri = {}
  24194. , i = 14;
  24195. while (i--) {
  24196. uri[parts[i]] = m[i] || '';
  24197. }
  24198. return uri;
  24199. };
  24200. },{}],103:[function(require,module,exports){
  24201. // shim for using process in browser
  24202. var process = module.exports = {};
  24203. var queue = [];
  24204. var draining = false;
  24205. var currentQueue;
  24206. var queueIndex = -1;
  24207. function cleanUpNextTick() {
  24208. draining = false;
  24209. if (currentQueue.length) {
  24210. queue = currentQueue.concat(queue);
  24211. } else {
  24212. queueIndex = -1;
  24213. }
  24214. if (queue.length) {
  24215. drainQueue();
  24216. }
  24217. }
  24218. function drainQueue() {
  24219. if (draining) {
  24220. return;
  24221. }
  24222. var timeout = setTimeout(cleanUpNextTick);
  24223. draining = true;
  24224. var len = queue.length;
  24225. while(len) {
  24226. currentQueue = queue;
  24227. queue = [];
  24228. while (++queueIndex < len) {
  24229. if (currentQueue) {
  24230. currentQueue[queueIndex].run();
  24231. }
  24232. }
  24233. queueIndex = -1;
  24234. len = queue.length;
  24235. }
  24236. currentQueue = null;
  24237. draining = false;
  24238. clearTimeout(timeout);
  24239. }
  24240. process.nextTick = function (fun) {
  24241. var args = new Array(arguments.length - 1);
  24242. if (arguments.length > 1) {
  24243. for (var i = 1; i < arguments.length; i++) {
  24244. args[i - 1] = arguments[i];
  24245. }
  24246. }
  24247. queue.push(new Item(fun, args));
  24248. if (queue.length === 1 && !draining) {
  24249. setTimeout(drainQueue, 0);
  24250. }
  24251. };
  24252. // v8 likes predictible objects
  24253. function Item(fun, array) {
  24254. this.fun = fun;
  24255. this.array = array;
  24256. }
  24257. Item.prototype.run = function () {
  24258. this.fun.apply(null, this.array);
  24259. };
  24260. process.title = 'browser';
  24261. process.browser = true;
  24262. process.env = {};
  24263. process.argv = [];
  24264. process.version = ''; // empty string to avoid regexp issues
  24265. process.versions = {};
  24266. function noop() {}
  24267. process.on = noop;
  24268. process.addListener = noop;
  24269. process.once = noop;
  24270. process.off = noop;
  24271. process.removeListener = noop;
  24272. process.removeAllListeners = noop;
  24273. process.emit = noop;
  24274. process.binding = function (name) {
  24275. throw new Error('process.binding is not supported');
  24276. };
  24277. process.cwd = function () { return '/' };
  24278. process.chdir = function (dir) {
  24279. throw new Error('process.chdir is not supported');
  24280. };
  24281. process.umask = function() { return 0; };
  24282. },{}],104:[function(require,module,exports){
  24283. /* Copyright @ 2015 Atlassian Pty Ltd
  24284. *
  24285. * Licensed under the Apache License, Version 2.0 (the "License");
  24286. * you may not use this file except in compliance with the License.
  24287. * You may obtain a copy of the License at
  24288. *
  24289. * http://www.apache.org/licenses/LICENSE-2.0
  24290. *
  24291. * Unless required by applicable law or agreed to in writing, software
  24292. * distributed under the License is distributed on an "AS IS" BASIS,
  24293. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24294. * See the License for the specific language governing permissions and
  24295. * limitations under the License.
  24296. */
  24297. module.exports = function arrayEquals(array) {
  24298. // if the other array is a falsy value, return
  24299. if (!array)
  24300. return false;
  24301. // compare lengths - can save a lot of time
  24302. if (this.length != array.length)
  24303. return false;
  24304. for (var i = 0, l = this.length; i < l; i++) {
  24305. // Check if we have nested arrays
  24306. if (this[i] instanceof Array && array[i] instanceof Array) {
  24307. // recurse into the nested arrays
  24308. if (!arrayEquals.apply(this[i], [array[i]]))
  24309. return false;
  24310. } else if (this[i] != array[i]) {
  24311. // Warning - two different object instances will never be equal:
  24312. // {x:20} != {x:20}
  24313. return false;
  24314. }
  24315. }
  24316. return true;
  24317. };
  24318. },{}],105:[function(require,module,exports){
  24319. /* Copyright @ 2015 Atlassian Pty Ltd
  24320. *
  24321. * Licensed under the Apache License, Version 2.0 (the "License");
  24322. * you may not use this file except in compliance with the License.
  24323. * You may obtain a copy of the License at
  24324. *
  24325. * http://www.apache.org/licenses/LICENSE-2.0
  24326. *
  24327. * Unless required by applicable law or agreed to in writing, software
  24328. * distributed under the License is distributed on an "AS IS" BASIS,
  24329. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24330. * See the License for the specific language governing permissions and
  24331. * limitations under the License.
  24332. */
  24333. exports.Interop = require('./interop');
  24334. },{"./interop":106}],106:[function(require,module,exports){
  24335. /* Copyright @ 2015 Atlassian Pty Ltd
  24336. *
  24337. * Licensed under the Apache License, Version 2.0 (the "License");
  24338. * you may not use this file except in compliance with the License.
  24339. * You may obtain a copy of the License at
  24340. *
  24341. * http://www.apache.org/licenses/LICENSE-2.0
  24342. *
  24343. * Unless required by applicable law or agreed to in writing, software
  24344. * distributed under the License is distributed on an "AS IS" BASIS,
  24345. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24346. * See the License for the specific language governing permissions and
  24347. * limitations under the License.
  24348. */
  24349. /* global RTCSessionDescription */
  24350. /* jshint -W097 */
  24351. "use strict";
  24352. var transform = require('./transform');
  24353. var arrayEquals = require('./array-equals');
  24354. function Interop() {
  24355. /**
  24356. * This map holds the most recent Unified Plan offer/answer SDP that was
  24357. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24358. * the SDP string as values.
  24359. *
  24360. * @type {{}}
  24361. */
  24362. this.cache = {};
  24363. }
  24364. module.exports = Interop;
  24365. /**
  24366. * Returns the index of the first m-line with the given media type and with a
  24367. * direction which allows sending, in the last Unified Plan description with
  24368. * type "answer" converted to Plan B. Returns {null} if there is no saved
  24369. * answer, or if none of its m-lines with the given type allow sending.
  24370. * @param type the media type ("audio" or "video").
  24371. * @returns {*}
  24372. */
  24373. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  24374. if (!this.cache.answer) {
  24375. return null;
  24376. }
  24377. var session = transform.parse(this.cache.answer);
  24378. if (session && session.media && Array.isArray(session.media)){
  24379. for (var i = 0; i < session.media.length; i++) {
  24380. if (session.media[i].type == type &&
  24381. (!session.media[i].direction /* default to sendrecv */ ||
  24382. session.media[i].direction === 'sendrecv' ||
  24383. session.media[i].direction === 'sendonly')){
  24384. return i;
  24385. }
  24386. }
  24387. }
  24388. return null;
  24389. };
  24390. /**
  24391. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24392. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24393. * application.
  24394. *
  24395. * @param desc
  24396. * @returns {*}
  24397. */
  24398. Interop.prototype.toPlanB = function(desc) {
  24399. var self = this;
  24400. //#region Preliminary input validation.
  24401. if (typeof desc !== 'object' || desc === null ||
  24402. typeof desc.sdp !== 'string') {
  24403. console.warn('An empty description was passed as an argument.');
  24404. return desc;
  24405. }
  24406. // Objectify the SDP for easier manipulation.
  24407. var session = transform.parse(desc.sdp);
  24408. // If the SDP contains no media, there's nothing to transform.
  24409. if (typeof session.media === 'undefined' ||
  24410. !Array.isArray(session.media) || session.media.length === 0) {
  24411. console.warn('The description has no media.');
  24412. return desc;
  24413. }
  24414. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24415. // SDP has a video, an audio and a data "channel" at most.
  24416. if (session.media.length <= 3 && session.media.every(function(m) {
  24417. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24418. })) {
  24419. console.warn('This description does not look like Unified Plan.');
  24420. return desc;
  24421. }
  24422. //#endregion
  24423. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  24424. var sdp = desc.sdp;
  24425. var rewrite = false;
  24426. for (var i = 0; i < session.media.length; i++) {
  24427. var uLine = session.media[i];
  24428. uLine.rtp.forEach(function(rtp) {
  24429. if (rtp.codec === 'NULL')
  24430. {
  24431. rewrite = true;
  24432. var offer = transform.parse(self.cache['offer']);
  24433. rtp.codec = offer.media[i].rtp[0].codec;
  24434. }
  24435. });
  24436. };
  24437. if (rewrite) {
  24438. sdp = transform.write(session);
  24439. }
  24440. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24441. // -> Unified Plan transformation.
  24442. this.cache[desc.type] = sdp;
  24443. //#region Convert from Unified Plan to Plan B.
  24444. // We rebuild the session.media array.
  24445. var media = session.media;
  24446. session.media = [];
  24447. // Associative array that maps channel types to channel objects for fast
  24448. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24449. // obj.
  24450. var type2bl = {};
  24451. // Used to build the group:BUNDLE value after the channels construction
  24452. // loop.
  24453. var types = [];
  24454. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24455. media.forEach(function(uLine) {
  24456. // rtcp-mux is required in the Plan B SDP.
  24457. if ((typeof uLine.rtcpMux !== 'string' ||
  24458. uLine.rtcpMux !== 'rtcp-mux') &&
  24459. uLine.direction !== 'inactive') {
  24460. throw new Error('Cannot convert to Plan B because m-lines ' +
  24461. 'without the rtcp-mux attribute were found.');
  24462. }
  24463. if (uLine.type === 'application') {
  24464. session.media.push(uLine);
  24465. types.push(uLine.mid);
  24466. return;
  24467. }
  24468. // If we don't have a channel for this uLine.type, then use this
  24469. // uLine as the channel basis.
  24470. if (typeof type2bl[uLine.type] === 'undefined') {
  24471. type2bl[uLine.type] = uLine;
  24472. }
  24473. // Add sources to the channel and handle a=msid.
  24474. if (typeof uLine.sources === 'object') {
  24475. Object.keys(uLine.sources).forEach(function(ssrc) {
  24476. if (typeof type2bl[uLine.type].sources !== 'object')
  24477. type2bl[uLine.type].sources = {};
  24478. // Assign the sources to the channel.
  24479. type2bl[uLine.type].sources[ssrc] =
  24480. uLine.sources[ssrc];
  24481. if (typeof uLine.msid !== 'undefined') {
  24482. // In Plan B the msid is an SSRC attribute. Also, we don't
  24483. // care about the obsolete label and mslabel attributes.
  24484. //
  24485. // Note that it is not guaranteed that the uLine will
  24486. // have an msid. recvonly channels in particular don't have
  24487. // one.
  24488. type2bl[uLine.type].sources[ssrc].msid =
  24489. uLine.msid;
  24490. }
  24491. // NOTE ssrcs in ssrc groups will share msids, as
  24492. // draft-uberti-rtcweb-plan-00 mandates.
  24493. });
  24494. }
  24495. // Add ssrc groups to the channel.
  24496. if (typeof uLine.ssrcGroups !== 'undefined' &&
  24497. Array.isArray(uLine.ssrcGroups)) {
  24498. // Create the ssrcGroups array, if it's not defined.
  24499. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  24500. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  24501. type2bl[uLine.type].ssrcGroups = [];
  24502. }
  24503. type2bl[uLine.type].ssrcGroups =
  24504. type2bl[uLine.type].ssrcGroups.concat(
  24505. uLine.ssrcGroups);
  24506. }
  24507. if (type2bl[uLine.type] === uLine) {
  24508. // Copy ICE related stuff from the principal media line.
  24509. uLine.candidates = media[0].candidates;
  24510. uLine.iceUfrag = media[0].iceUfrag;
  24511. uLine.icePwd = media[0].icePwd;
  24512. uLine.fingerprint = media[0].fingerprint;
  24513. // Plan B mids are in ['audio', 'video', 'data']
  24514. uLine.mid = uLine.type;
  24515. // Plan B doesn't support/need the bundle-only attribute.
  24516. delete uLine.bundleOnly;
  24517. // In Plan B the msid is an SSRC attribute.
  24518. delete uLine.msid;
  24519. // Used to build the group:BUNDLE value after this loop.
  24520. types.push(uLine.type);
  24521. // Add the channel to the new media array.
  24522. session.media.push(uLine);
  24523. }
  24524. });
  24525. // We regenerate the BUNDLE group with the new mids.
  24526. session.groups.some(function(group) {
  24527. if (group.type === 'BUNDLE') {
  24528. group.mids = types.join(' ');
  24529. return true;
  24530. }
  24531. });
  24532. // msid semantic
  24533. session.msidSemantic = {
  24534. semantic: 'WMS',
  24535. token: '*'
  24536. };
  24537. var resStr = transform.write(session);
  24538. return new RTCSessionDescription({
  24539. type: desc.type,
  24540. sdp: resStr
  24541. });
  24542. //#endregion
  24543. };
  24544. /**
  24545. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24546. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24547. * to FF.
  24548. *
  24549. * @param desc
  24550. * @returns {*}
  24551. */
  24552. Interop.prototype.toUnifiedPlan = function(desc) {
  24553. var self = this;
  24554. //#region Preliminary input validation.
  24555. if (typeof desc !== 'object' || desc === null ||
  24556. typeof desc.sdp !== 'string') {
  24557. console.warn('An empty description was passed as an argument.');
  24558. return desc;
  24559. }
  24560. var session = transform.parse(desc.sdp);
  24561. // If the SDP contains no media, there's nothing to transform.
  24562. if (typeof session.media === 'undefined' ||
  24563. !Array.isArray(session.media) || session.media.length === 0) {
  24564. console.warn('The description has no media.');
  24565. return desc;
  24566. }
  24567. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  24568. // a video, an audio and a data "channel" at most.
  24569. if (session.media.length > 3 || !session.media.every(function(m) {
  24570. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24571. })) {
  24572. console.warn('This description does not look like Plan B.');
  24573. return desc;
  24574. }
  24575. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  24576. var mids = [];
  24577. session.media.forEach(function(m) {
  24578. mids.push(m.mid);
  24579. });
  24580. var hasBundle = false;
  24581. if (typeof session.groups !== 'undefined' &&
  24582. Array.isArray(session.groups)) {
  24583. hasBundle = session.groups.every(function(g) {
  24584. return g.type !== 'BUNDLE' ||
  24585. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  24586. });
  24587. }
  24588. if (!hasBundle) {
  24589. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  24590. " are not bundled were found.");
  24591. }
  24592. //#endregion
  24593. //#region Convert from Plan B to Unified Plan.
  24594. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  24595. // rebuild an equivalent Unified Plan offer/answer.
  24596. //
  24597. // For example, if this is a local answer (in Unified Plan style) that we
  24598. // convert to Plan B prior to handing it over to the application (the
  24599. // PeerConnection wrapper called us, for instance, after a successful
  24600. // createAnswer), we want to remember the m-line at which we've seen the
  24601. // (local) SSRC. That's because when the application wants to do call the
  24602. // SLD method, forcing us to do the inverse transformation (from Plan B to
  24603. // Unified Plan), we need to know to which m-line to assign the (local)
  24604. // SSRC. We also need to know all the other m-lines that the original
  24605. // answer had and include them in the transformed answer as well.
  24606. //
  24607. // Another example is if this is a remote offer that we convert to Plan B
  24608. // prior to giving it to the application, we want to remember the mid at
  24609. // which we've seen the (remote) SSRC.
  24610. //
  24611. // In the iteration that follows, we use the cached Unified Plan (if it
  24612. // exists) to assign mids to ssrcs.
  24613. var cached;
  24614. if (typeof this.cache[desc.type] !== 'undefined') {
  24615. cached = transform.parse(this.cache[desc.type]);
  24616. }
  24617. var recvonlySsrcs = {
  24618. audio: {},
  24619. video: {}
  24620. };
  24621. // A helper map that sends mids to m-line objects. We use it later to
  24622. // rebuild the Unified Plan style session.media array.
  24623. var mid2ul = {};
  24624. session.media.forEach(function(bLine) {
  24625. if ((typeof bLine.rtcpMux !== 'string' ||
  24626. bLine.rtcpMux !== 'rtcp-mux') &&
  24627. bLine.direction !== 'inactive') {
  24628. throw new Error("Cannot convert to Unified Plan because m-lines " +
  24629. "without the rtcp-mux attribute were found.");
  24630. }
  24631. if (bLine.type === 'application') {
  24632. mid2ul[bLine.mid] = bLine;
  24633. return;
  24634. }
  24635. // With rtcp-mux and bundle all the channels should have the same ICE
  24636. // stuff.
  24637. var sources = bLine.sources;
  24638. var ssrcGroups = bLine.ssrcGroups;
  24639. var candidates = bLine.candidates;
  24640. var iceUfrag = bLine.iceUfrag;
  24641. var icePwd = bLine.icePwd;
  24642. var fingerprint = bLine.fingerprint;
  24643. var port = bLine.port;
  24644. // We'll use the "bLine" object as a prototype for each new "mLine"
  24645. // that we create, but first we need to clean it up a bit.
  24646. delete bLine.sources;
  24647. delete bLine.ssrcGroups;
  24648. delete bLine.candidates;
  24649. delete bLine.iceUfrag;
  24650. delete bLine.icePwd;
  24651. delete bLine.fingerprint;
  24652. delete bLine.port;
  24653. delete bLine.mid;
  24654. // inverted ssrc group map
  24655. var ssrc2group = {};
  24656. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  24657. ssrcGroups.forEach(function (ssrcGroup) {
  24658. // TODO(gp) find out how to receive simulcast with FF. For the
  24659. // time being, hide it.
  24660. if (ssrcGroup.semantics === 'SIM') {
  24661. return;
  24662. }
  24663. // XXX This might brake if an SSRC is in more than one group
  24664. // for some reason.
  24665. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24666. Array.isArray(ssrcGroup.ssrcs)) {
  24667. ssrcGroup.ssrcs.forEach(function (ssrc) {
  24668. if (typeof ssrc2group[ssrc] === 'undefined') {
  24669. ssrc2group[ssrc] = [];
  24670. }
  24671. ssrc2group[ssrc].push(ssrcGroup);
  24672. });
  24673. }
  24674. });
  24675. }
  24676. // ssrc to m-line index.
  24677. var ssrc2ml = {};
  24678. if (typeof sources === 'object') {
  24679. // Explode the Plan B channel sources with one m-line per source.
  24680. Object.keys(sources).forEach(function(ssrc) {
  24681. // The (unified) m-line for this SSRC. We either create it from
  24682. // scratch or, if it's a grouped SSRC, we re-use a related
  24683. // mline. In other words, if the source is grouped with another
  24684. // source, put the two together in the same m-line.
  24685. var uLine;
  24686. // We assume here that we are the answerer in the O/A, so any
  24687. // offers which we translate come from the remote side, while
  24688. // answers are local. So the check below is to make that we
  24689. // handle receive-only SSRCs in a special way only if they come
  24690. // from the remote side.
  24691. if (desc.type==='offer') {
  24692. // We want to detect SSRCs which are used by a remote peer
  24693. // in an m-line with direction=recvonly (i.e. they are
  24694. // being used for RTCP only).
  24695. // This information would have gotten lost if the remote
  24696. // peer used Unified Plan and their local description was
  24697. // translated to Plan B. So we use the lack of an MSID
  24698. // attribute to deduce a "receive only" SSRC.
  24699. if (!sources[ssrc].msid) {
  24700. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  24701. // Receive-only SSRCs must not create new m-lines. We
  24702. // will assign them to an existing m-line later.
  24703. return;
  24704. }
  24705. }
  24706. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  24707. Array.isArray(ssrc2group[ssrc])) {
  24708. ssrc2group[ssrc].some(function (ssrcGroup) {
  24709. // ssrcGroup.ssrcs *is* an Array, no need to check
  24710. // again here.
  24711. return ssrcGroup.ssrcs.some(function (related) {
  24712. if (typeof ssrc2ml[related] === 'object') {
  24713. uLine = ssrc2ml[related];
  24714. return true;
  24715. }
  24716. });
  24717. });
  24718. }
  24719. if (typeof uLine === 'object') {
  24720. // the m-line already exists. Just add the source.
  24721. uLine.sources[ssrc] = sources[ssrc];
  24722. delete sources[ssrc].msid;
  24723. } else {
  24724. // Use the "bLine" as a prototype for the "uLine".
  24725. uLine = Object.create(bLine);
  24726. ssrc2ml[ssrc] = uLine;
  24727. if (typeof sources[ssrc].msid !== 'undefined') {
  24728. // Assign the msid of the source to the m-line. Note
  24729. // that it is not guaranteed that the source will have
  24730. // msid. In particular "recvonly" sources don't have an
  24731. // msid. Note that "recvonly" is a term only defined
  24732. // for m-lines.
  24733. uLine.msid = sources[ssrc].msid;
  24734. uLine.direction = 'sendrecv';
  24735. delete sources[ssrc].msid;
  24736. }
  24737. // We assign one SSRC per media line.
  24738. uLine.sources = {};
  24739. uLine.sources[ssrc] = sources[ssrc];
  24740. uLine.ssrcGroups = ssrc2group[ssrc];
  24741. // Use the cached Unified Plan SDP (if it exists) to assign
  24742. // SSRCs to mids.
  24743. if (typeof cached !== 'undefined' &&
  24744. typeof cached.media !== 'undefined' &&
  24745. Array.isArray(cached.media)) {
  24746. cached.media.forEach(function (m) {
  24747. if (typeof m.sources === 'object') {
  24748. Object.keys(m.sources).forEach(function (s) {
  24749. if (s === ssrc) {
  24750. uLine.mid = m.mid;
  24751. }
  24752. });
  24753. }
  24754. });
  24755. }
  24756. if (typeof uLine.mid === 'undefined') {
  24757. // If this is an SSRC that we see for the first time
  24758. // assign it a new mid. This is typically the case when
  24759. // this method is called to transform a remote
  24760. // description for the first time or when there is a
  24761. // new SSRC in the remote description because a new
  24762. // peer has joined the conference. Local SSRCs should
  24763. // have already been added to the map in the toPlanB
  24764. // method.
  24765. //
  24766. // Because FF generates answers in Unified Plan style,
  24767. // we MUST already have a cached answer with all the
  24768. // local SSRCs mapped to some m-line/mid.
  24769. if (desc.type === 'answer') {
  24770. throw new Error("An unmapped SSRC was found.");
  24771. }
  24772. uLine.mid = [bLine.type, '-', ssrc].join('');
  24773. }
  24774. // Include the candidates in the 1st media line.
  24775. uLine.candidates = candidates;
  24776. uLine.iceUfrag = iceUfrag;
  24777. uLine.icePwd = icePwd;
  24778. uLine.fingerprint = fingerprint;
  24779. uLine.port = port;
  24780. mid2ul[uLine.mid] = uLine;
  24781. }
  24782. });
  24783. }
  24784. });
  24785. // Rebuild the media array in the right order and add the missing mLines
  24786. // (missing from the Plan B SDP).
  24787. session.media = [];
  24788. mids = []; // reuse
  24789. if (desc.type === 'answer') {
  24790. // The media lines in the answer must match the media lines in the
  24791. // offer. The order is important too. Here we assume that Firefox is
  24792. // the answerer, so we merely have to use the reconstructed (unified)
  24793. // answer to update the cached (unified) answer accordingly.
  24794. //
  24795. // In the general case, one would have to use the cached (unified)
  24796. // offer to find the m-lines that are missing from the reconstructed
  24797. // answer, potentially grabbing them from the cached (unified) answer.
  24798. // One has to be careful with this approach because inactive m-lines do
  24799. // not always have an mid, making it tricky (impossible?) to find where
  24800. // exactly and which m-lines are missing from the reconstructed answer.
  24801. for (var i = 0; i < cached.media.length; i++) {
  24802. var uLine = cached.media[i];
  24803. if (typeof mid2ul[uLine.mid] === 'undefined') {
  24804. // The mid isn't in the reconstructed (unified) answer.
  24805. // This is either a (unified) m-line containing a remote
  24806. // track only, or a (unified) m-line containing a remote
  24807. // track and a local track that has been removed.
  24808. // In either case, it MUST exist in the cached
  24809. // (unified) answer.
  24810. //
  24811. // In case this is a removed local track, clean-up
  24812. // the (unified) m-line and make sure it's 'recvonly' or
  24813. // 'inactive'.
  24814. delete uLine.msid;
  24815. delete uLine.sources;
  24816. delete uLine.ssrcGroups;
  24817. if (!uLine.direction
  24818. || uLine.direction === 'sendrecv')
  24819. uLine.direction = 'recvonly';
  24820. else if (uLine.direction === 'sendonly')
  24821. uLine.direction = 'inactive';
  24822. } else {
  24823. // This is an (unified) m-line/channel that contains a local
  24824. // track (sendrecv or sendonly channel) or it's a unified
  24825. // recvonly m-line/channel. In either case, since we're
  24826. // going from PlanB -> Unified Plan this m-line MUST
  24827. // exist in the cached answer.
  24828. }
  24829. session.media.push(uLine);
  24830. if (typeof uLine.mid === 'string') {
  24831. // inactive lines don't/may not have an mid.
  24832. mids.push(uLine.mid);
  24833. }
  24834. }
  24835. } else {
  24836. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  24837. // under any circumstances. If we are no longer interested in sending a
  24838. // track, we just remove the msid and ssrc attributes and set it to
  24839. // either a=recvonly (as the reofferer, we must use recvonly if the
  24840. // other side was previously sending on the m-section, but we can also
  24841. // leave the possibility open if it wasn't previously in use), or
  24842. // a=inactive.
  24843. if (typeof cached !== 'undefined' &&
  24844. typeof cached.media !== 'undefined' &&
  24845. Array.isArray(cached.media)) {
  24846. cached.media.forEach(function(uLine) {
  24847. mids.push(uLine.mid);
  24848. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  24849. session.media.push(mid2ul[uLine.mid]);
  24850. } else {
  24851. delete uLine.msid;
  24852. delete uLine.sources;
  24853. delete uLine.ssrcGroups;
  24854. if (!uLine.direction
  24855. || uLine.direction === 'sendrecv')
  24856. uLine.direction = 'recvonly';
  24857. if (!uLine.direction
  24858. || uLine.direction === 'sendonly')
  24859. uLine.direction = 'inactive';
  24860. session.media.push(uLine);
  24861. }
  24862. });
  24863. }
  24864. // Add all the remaining (new) m-lines of the transformed SDP.
  24865. Object.keys(mid2ul).forEach(function(mid) {
  24866. if (mids.indexOf(mid) === -1) {
  24867. mids.push(mid);
  24868. if (mid2ul[mid].direction === 'recvonly') {
  24869. // This is a remote recvonly channel. Add its SSRC to the
  24870. // appropriate sendrecv or sendonly channel.
  24871. // TODO(gp) what if we don't have sendrecv/sendonly
  24872. // channel?
  24873. session.media.some(function (uLine) {
  24874. if ((uLine.direction === 'sendrecv' ||
  24875. uLine.direction === 'sendonly') &&
  24876. uLine.type === mid2ul[mid].type) {
  24877. // mid2ul[mid] shouldn't have any ssrc-groups
  24878. Object.keys(mid2ul[mid].sources).forEach(
  24879. function (ssrc) {
  24880. uLine.sources[ssrc] =
  24881. mid2ul[mid].sources[ssrc];
  24882. });
  24883. return true;
  24884. }
  24885. });
  24886. } else {
  24887. session.media.push(mid2ul[mid]);
  24888. }
  24889. }
  24890. });
  24891. }
  24892. // After we have constructed the Plan Unified m-lines we can figure out
  24893. // where (in which m-line) to place the 'recvonly SSRCs'.
  24894. // Note: we assume here that we are the answerer in the O/A, so any offers
  24895. // which we translate come from the remote side, while answers are local
  24896. // (and so our last local description is cached as an 'answer').
  24897. ["audio", "video"].forEach(function (type) {
  24898. if (!session || !session.media || !Array.isArray(session.media))
  24899. return;
  24900. var idx = null;
  24901. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  24902. idx = self.getFirstSendingIndexFromAnswer(type);
  24903. if (idx === null){
  24904. // If this is the first offer we receive, we don't have a
  24905. // cached answer. Assume that we will be sending media using
  24906. // the first m-line for each media type.
  24907. for (var i = 0; i < session.media.length; i++) {
  24908. if (session.media[i].type === type) {
  24909. idx = i;
  24910. break;
  24911. }
  24912. }
  24913. }
  24914. }
  24915. if (idx && session.media.length > idx) {
  24916. var mLine = session.media[idx];
  24917. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  24918. if (mLine.sources && mLine.sources[ssrc]) {
  24919. console.warn("Replacing an existing SSRC.");
  24920. }
  24921. if (!mLine.sources) {
  24922. mLine.sources = {};
  24923. }
  24924. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  24925. });
  24926. }
  24927. });
  24928. // We regenerate the BUNDLE group (since we regenerated the mids)
  24929. session.groups.some(function(group) {
  24930. if (group.type === 'BUNDLE') {
  24931. group.mids = mids.join(' ');
  24932. return true;
  24933. }
  24934. });
  24935. // msid semantic
  24936. session.msidSemantic = {
  24937. semantic: 'WMS',
  24938. token: '*'
  24939. };
  24940. var resStr = transform.write(session);
  24941. // Cache the transformed SDP (Unified Plan) for later re-use in this
  24942. // function.
  24943. this.cache[desc.type] = resStr;
  24944. return new RTCSessionDescription({
  24945. type: desc.type,
  24946. sdp: resStr
  24947. });
  24948. //#endregion
  24949. };
  24950. },{"./array-equals":104,"./transform":107}],107:[function(require,module,exports){
  24951. /* Copyright @ 2015 Atlassian Pty Ltd
  24952. *
  24953. * Licensed under the Apache License, Version 2.0 (the "License");
  24954. * you may not use this file except in compliance with the License.
  24955. * You may obtain a copy of the License at
  24956. *
  24957. * http://www.apache.org/licenses/LICENSE-2.0
  24958. *
  24959. * Unless required by applicable law or agreed to in writing, software
  24960. * distributed under the License is distributed on an "AS IS" BASIS,
  24961. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24962. * See the License for the specific language governing permissions and
  24963. * limitations under the License.
  24964. */
  24965. var transform = require('sdp-transform');
  24966. exports.write = function(session, opts) {
  24967. if (typeof session !== 'undefined' &&
  24968. typeof session.media !== 'undefined' &&
  24969. Array.isArray(session.media)) {
  24970. session.media.forEach(function (mLine) {
  24971. // expand sources to ssrcs
  24972. if (typeof mLine.sources !== 'undefined' &&
  24973. Object.keys(mLine.sources).length !== 0) {
  24974. mLine.ssrcs = [];
  24975. Object.keys(mLine.sources).forEach(function (ssrc) {
  24976. var source = mLine.sources[ssrc];
  24977. Object.keys(source).forEach(function (attribute) {
  24978. mLine.ssrcs.push({
  24979. id: ssrc,
  24980. attribute: attribute,
  24981. value: source[attribute]
  24982. });
  24983. });
  24984. });
  24985. delete mLine.sources;
  24986. }
  24987. // join ssrcs in ssrc groups
  24988. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24989. Array.isArray(mLine.ssrcGroups)) {
  24990. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24991. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24992. Array.isArray(ssrcGroup.ssrcs)) {
  24993. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24994. }
  24995. });
  24996. }
  24997. });
  24998. }
  24999. // join group mids
  25000. if (typeof session !== 'undefined' &&
  25001. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25002. session.groups.forEach(function (g) {
  25003. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25004. g.mids = g.mids.join(' ');
  25005. }
  25006. });
  25007. }
  25008. return transform.write(session, opts);
  25009. };
  25010. exports.parse = function(sdp) {
  25011. var session = transform.parse(sdp);
  25012. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25013. Array.isArray(session.media)) {
  25014. session.media.forEach(function (mLine) {
  25015. // group sources attributes by ssrc
  25016. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25017. mLine.sources = {};
  25018. mLine.ssrcs.forEach(function (ssrc) {
  25019. if (!mLine.sources[ssrc.id])
  25020. mLine.sources[ssrc.id] = {};
  25021. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25022. });
  25023. delete mLine.ssrcs;
  25024. }
  25025. // split ssrcs in ssrc groups
  25026. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25027. Array.isArray(mLine.ssrcGroups)) {
  25028. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25029. if (typeof ssrcGroup.ssrcs === 'string') {
  25030. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25031. }
  25032. });
  25033. }
  25034. });
  25035. }
  25036. // split group mids
  25037. if (typeof session !== 'undefined' &&
  25038. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25039. session.groups.forEach(function (g) {
  25040. if (typeof g.mids === 'string') {
  25041. g.mids = g.mids.split(' ');
  25042. }
  25043. });
  25044. }
  25045. return session;
  25046. };
  25047. },{"sdp-transform":109}],108:[function(require,module,exports){
  25048. var grammar = module.exports = {
  25049. v: [{
  25050. name: 'version',
  25051. reg: /^(\d*)$/
  25052. }],
  25053. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25054. // NB: sessionId will be a String in most cases because it is huge
  25055. name: 'origin',
  25056. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25057. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25058. format: "%s %s %d %s IP%d %s"
  25059. }],
  25060. // default parsing of these only (though some of these feel outdated)
  25061. s: [{ name: 'name' }],
  25062. i: [{ name: 'description' }],
  25063. u: [{ name: 'uri' }],
  25064. e: [{ name: 'email' }],
  25065. p: [{ name: 'phone' }],
  25066. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25067. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25068. //k: [{}], // outdated thing ignored
  25069. t: [{ //t=0 0
  25070. name: 'timing',
  25071. reg: /^(\d*) (\d*)/,
  25072. names: ['start', 'stop'],
  25073. format: "%d %d"
  25074. }],
  25075. c: [{ //c=IN IP4 10.47.197.26
  25076. name: 'connection',
  25077. reg: /^IN IP(\d) (\S*)/,
  25078. names: ['version', 'ip'],
  25079. format: "IN IP%d %s"
  25080. }],
  25081. b: [{ //b=AS:4000
  25082. push: 'bandwidth',
  25083. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25084. names: ['type', 'limit'],
  25085. format: "%s:%s"
  25086. }],
  25087. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25088. // NB: special - pushes to session
  25089. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25090. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25091. names: ['type', 'port', 'protocol', 'payloads'],
  25092. format: "%s %d %s %s"
  25093. }],
  25094. a: [
  25095. { //a=rtpmap:110 opus/48000/2
  25096. push: 'rtp',
  25097. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  25098. names: ['payload', 'codec', 'rate', 'encoding'],
  25099. format: function (o) {
  25100. return (o.encoding) ?
  25101. "rtpmap:%d %s/%s/%s":
  25102. o.rate ?
  25103. "rtpmap:%d %s/%s":
  25104. "rtpmap:%d %s";
  25105. }
  25106. },
  25107. {
  25108. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25109. //a=fmtp:111 minptime=10; useinbandfec=1
  25110. push: 'fmtp',
  25111. reg: /^fmtp:(\d*) ([\S| ]*)/,
  25112. names: ['payload', 'config'],
  25113. format: "fmtp:%d %s"
  25114. },
  25115. { //a=control:streamid=0
  25116. name: 'control',
  25117. reg: /^control:(.*)/,
  25118. format: "control:%s"
  25119. },
  25120. { //a=rtcp:65179 IN IP4 193.84.77.194
  25121. name: 'rtcp',
  25122. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25123. names: ['port', 'netType', 'ipVer', 'address'],
  25124. format: function (o) {
  25125. return (o.address != null) ?
  25126. "rtcp:%d %s IP%d %s":
  25127. "rtcp:%d";
  25128. }
  25129. },
  25130. { //a=rtcp-fb:98 trr-int 100
  25131. push: 'rtcpFbTrrInt',
  25132. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25133. names: ['payload', 'value'],
  25134. format: "rtcp-fb:%d trr-int %d"
  25135. },
  25136. { //a=rtcp-fb:98 nack rpsi
  25137. push: 'rtcpFb',
  25138. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25139. names: ['payload', 'type', 'subtype'],
  25140. format: function (o) {
  25141. return (o.subtype != null) ?
  25142. "rtcp-fb:%s %s %s":
  25143. "rtcp-fb:%s %s";
  25144. }
  25145. },
  25146. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25147. //a=extmap:1/recvonly URI-gps-string
  25148. push: 'ext',
  25149. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25150. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25151. format: function (o) {
  25152. return (o.config != null) ?
  25153. "extmap:%s %s %s":
  25154. "extmap:%s %s";
  25155. }
  25156. },
  25157. {
  25158. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25159. push: 'crypto',
  25160. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25161. names: ['id', 'suite', 'config', 'sessionConfig'],
  25162. format: function (o) {
  25163. return (o.sessionConfig != null) ?
  25164. "crypto:%d %s %s %s":
  25165. "crypto:%d %s %s";
  25166. }
  25167. },
  25168. { //a=setup:actpass
  25169. name: 'setup',
  25170. reg: /^setup:(\w*)/,
  25171. format: "setup:%s"
  25172. },
  25173. { //a=mid:1
  25174. name: 'mid',
  25175. reg: /^mid:([^\s]*)/,
  25176. format: "mid:%s"
  25177. },
  25178. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25179. name: 'msid',
  25180. reg: /^msid:(.*)/,
  25181. format: "msid:%s"
  25182. },
  25183. { //a=ptime:20
  25184. name: 'ptime',
  25185. reg: /^ptime:(\d*)/,
  25186. format: "ptime:%d"
  25187. },
  25188. { //a=maxptime:60
  25189. name: 'maxptime',
  25190. reg: /^maxptime:(\d*)/,
  25191. format: "maxptime:%d"
  25192. },
  25193. { //a=sendrecv
  25194. name: 'direction',
  25195. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25196. },
  25197. { //a=ice-lite
  25198. name: 'icelite',
  25199. reg: /^(ice-lite)/
  25200. },
  25201. { //a=ice-ufrag:F7gI
  25202. name: 'iceUfrag',
  25203. reg: /^ice-ufrag:(\S*)/,
  25204. format: "ice-ufrag:%s"
  25205. },
  25206. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25207. name: 'icePwd',
  25208. reg: /^ice-pwd:(\S*)/,
  25209. format: "ice-pwd:%s"
  25210. },
  25211. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25212. name: 'fingerprint',
  25213. reg: /^fingerprint:(\S*) (\S*)/,
  25214. names: ['type', 'hash'],
  25215. format: "fingerprint:%s %s"
  25216. },
  25217. {
  25218. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25219. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25220. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25221. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  25222. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  25223. push:'candidates',
  25224. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  25225. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  25226. format: function (o) {
  25227. var str = "candidate:%s %d %s %d %s %d typ %s";
  25228. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25229. // NB: candidate has three optional chunks, so %void middles one if it's missing
  25230. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  25231. if (o.generation != null) {
  25232. str += " generation %d";
  25233. }
  25234. return str;
  25235. }
  25236. },
  25237. { //a=end-of-candidates (keep after the candidates line for readability)
  25238. name: 'endOfCandidates',
  25239. reg: /^(end-of-candidates)/
  25240. },
  25241. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25242. name: 'remoteCandidates',
  25243. reg: /^remote-candidates:(.*)/,
  25244. format: "remote-candidates:%s"
  25245. },
  25246. { //a=ice-options:google-ice
  25247. name: 'iceOptions',
  25248. reg: /^ice-options:(\S*)/,
  25249. format: "ice-options:%s"
  25250. },
  25251. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25252. push: "ssrcs",
  25253. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25254. names: ['id', 'attribute', 'value'],
  25255. format: "ssrc:%d %s:%s"
  25256. },
  25257. { //a=ssrc-group:FEC 1 2
  25258. push: "ssrcGroups",
  25259. reg: /^ssrc-group:(\w*) (.*)/,
  25260. names: ['semantics', 'ssrcs'],
  25261. format: "ssrc-group:%s %s"
  25262. },
  25263. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25264. name: "msidSemantic",
  25265. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25266. names: ['semantic', 'token'],
  25267. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25268. },
  25269. { //a=group:BUNDLE audio video
  25270. push: 'groups',
  25271. reg: /^group:(\w*) (.*)/,
  25272. names: ['type', 'mids'],
  25273. format: "group:%s %s"
  25274. },
  25275. { //a=rtcp-mux
  25276. name: 'rtcpMux',
  25277. reg: /^(rtcp-mux)/
  25278. },
  25279. { //a=rtcp-rsize
  25280. name: 'rtcpRsize',
  25281. reg: /^(rtcp-rsize)/
  25282. },
  25283. { // any a= that we don't understand is kepts verbatim on media.invalid
  25284. push: 'invalid',
  25285. names: ["value"]
  25286. }
  25287. ]
  25288. };
  25289. // set sensible defaults to avoid polluting the grammar with boring details
  25290. Object.keys(grammar).forEach(function (key) {
  25291. var objs = grammar[key];
  25292. objs.forEach(function (obj) {
  25293. if (!obj.reg) {
  25294. obj.reg = /(.*)/;
  25295. }
  25296. if (!obj.format) {
  25297. obj.format = "%s";
  25298. }
  25299. });
  25300. });
  25301. },{}],109:[function(require,module,exports){
  25302. var parser = require('./parser');
  25303. var writer = require('./writer');
  25304. exports.write = writer;
  25305. exports.parse = parser.parse;
  25306. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25307. exports.parsePayloads = parser.parsePayloads;
  25308. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25309. },{"./parser":110,"./writer":111}],110:[function(require,module,exports){
  25310. var toIntIfInt = function (v) {
  25311. return String(Number(v)) === v ? Number(v) : v;
  25312. };
  25313. var attachProperties = function (match, location, names, rawName) {
  25314. if (rawName && !names) {
  25315. location[rawName] = toIntIfInt(match[1]);
  25316. }
  25317. else {
  25318. for (var i = 0; i < names.length; i += 1) {
  25319. if (match[i+1] != null) {
  25320. location[names[i]] = toIntIfInt(match[i+1]);
  25321. }
  25322. }
  25323. }
  25324. };
  25325. var parseReg = function (obj, location, content) {
  25326. var needsBlank = obj.name && obj.names;
  25327. if (obj.push && !location[obj.push]) {
  25328. location[obj.push] = [];
  25329. }
  25330. else if (needsBlank && !location[obj.name]) {
  25331. location[obj.name] = {};
  25332. }
  25333. var keyLocation = obj.push ?
  25334. {} : // blank object that will be pushed
  25335. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25336. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25337. if (obj.push) {
  25338. location[obj.push].push(keyLocation);
  25339. }
  25340. };
  25341. var grammar = require('./grammar');
  25342. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25343. exports.parse = function (sdp) {
  25344. var session = {}
  25345. , media = []
  25346. , location = session; // points at where properties go under (one of the above)
  25347. // parse lines we understand
  25348. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25349. var type = l[0];
  25350. var content = l.slice(2);
  25351. if (type === 'm') {
  25352. media.push({rtp: [], fmtp: []});
  25353. location = media[media.length-1]; // point at latest media line
  25354. }
  25355. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25356. var obj = grammar[type][j];
  25357. if (obj.reg.test(content)) {
  25358. return parseReg(obj, location, content);
  25359. }
  25360. }
  25361. });
  25362. session.media = media; // link it up
  25363. return session;
  25364. };
  25365. var fmtpReducer = function (acc, expr) {
  25366. var s = expr.split('=');
  25367. if (s.length === 2) {
  25368. acc[s[0]] = toIntIfInt(s[1]);
  25369. }
  25370. return acc;
  25371. };
  25372. exports.parseFmtpConfig = function (str) {
  25373. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  25374. };
  25375. exports.parsePayloads = function (str) {
  25376. return str.split(' ').map(Number);
  25377. };
  25378. exports.parseRemoteCandidates = function (str) {
  25379. var candidates = [];
  25380. var parts = str.split(' ').map(toIntIfInt);
  25381. for (var i = 0; i < parts.length; i += 3) {
  25382. candidates.push({
  25383. component: parts[i],
  25384. ip: parts[i + 1],
  25385. port: parts[i + 2]
  25386. });
  25387. }
  25388. return candidates;
  25389. };
  25390. },{"./grammar":108}],111:[function(require,module,exports){
  25391. var grammar = require('./grammar');
  25392. // customized util.format - discards excess arguments and can void middle ones
  25393. var formatRegExp = /%[sdv%]/g;
  25394. var format = function (formatStr) {
  25395. var i = 1;
  25396. var args = arguments;
  25397. var len = args.length;
  25398. return formatStr.replace(formatRegExp, function (x) {
  25399. if (i >= len) {
  25400. return x; // missing argument
  25401. }
  25402. var arg = args[i];
  25403. i += 1;
  25404. switch (x) {
  25405. case '%%':
  25406. return '%';
  25407. case '%s':
  25408. return String(arg);
  25409. case '%d':
  25410. return Number(arg);
  25411. case '%v':
  25412. return '';
  25413. }
  25414. });
  25415. // NB: we discard excess arguments - they are typically undefined from makeLine
  25416. };
  25417. var makeLine = function (type, obj, location) {
  25418. var str = obj.format instanceof Function ?
  25419. (obj.format(obj.push ? location : location[obj.name])) :
  25420. obj.format;
  25421. var args = [type + '=' + str];
  25422. if (obj.names) {
  25423. for (var i = 0; i < obj.names.length; i += 1) {
  25424. var n = obj.names[i];
  25425. if (obj.name) {
  25426. args.push(location[obj.name][n]);
  25427. }
  25428. else { // for mLine and push attributes
  25429. args.push(location[obj.names[i]]);
  25430. }
  25431. }
  25432. }
  25433. else {
  25434. args.push(location[obj.name]);
  25435. }
  25436. return format.apply(null, args);
  25437. };
  25438. // RFC specified order
  25439. // TODO: extend this with all the rest
  25440. var defaultOuterOrder = [
  25441. 'v', 'o', 's', 'i',
  25442. 'u', 'e', 'p', 'c',
  25443. 'b', 't', 'r', 'z', 'a'
  25444. ];
  25445. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25446. module.exports = function (session, opts) {
  25447. opts = opts || {};
  25448. // ensure certain properties exist
  25449. if (session.version == null) {
  25450. session.version = 0; // "v=0" must be there (only defined version atm)
  25451. }
  25452. if (session.name == null) {
  25453. session.name = " "; // "s= " must be there if no meaningful name set
  25454. }
  25455. session.media.forEach(function (mLine) {
  25456. if (mLine.payloads == null) {
  25457. mLine.payloads = "";
  25458. }
  25459. });
  25460. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25461. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25462. var sdp = [];
  25463. // loop through outerOrder for matching properties on session
  25464. outerOrder.forEach(function (type) {
  25465. grammar[type].forEach(function (obj) {
  25466. if (obj.name in session && session[obj.name] != null) {
  25467. sdp.push(makeLine(type, obj, session));
  25468. }
  25469. else if (obj.push in session && session[obj.push] != null) {
  25470. session[obj.push].forEach(function (el) {
  25471. sdp.push(makeLine(type, obj, el));
  25472. });
  25473. }
  25474. });
  25475. });
  25476. // then for each media line, follow the innerOrder
  25477. session.media.forEach(function (mLine) {
  25478. sdp.push(makeLine('m', grammar.m[0], mLine));
  25479. innerOrder.forEach(function (type) {
  25480. grammar[type].forEach(function (obj) {
  25481. if (obj.name in mLine && mLine[obj.name] != null) {
  25482. sdp.push(makeLine(type, obj, mLine));
  25483. }
  25484. else if (obj.push in mLine && mLine[obj.push] != null) {
  25485. mLine[obj.push].forEach(function (el) {
  25486. sdp.push(makeLine(type, obj, el));
  25487. });
  25488. }
  25489. });
  25490. });
  25491. });
  25492. return sdp.join('\r\n') + '\r\n';
  25493. };
  25494. },{"./grammar":108}],112:[function(require,module,exports){
  25495. /* Copyright @ 2015 Atlassian Pty Ltd
  25496. *
  25497. * Licensed under the Apache License, Version 2.0 (the "License");
  25498. * you may not use this file except in compliance with the License.
  25499. * You may obtain a copy of the License at
  25500. *
  25501. * http://www.apache.org/licenses/LICENSE-2.0
  25502. *
  25503. * Unless required by applicable law or agreed to in writing, software
  25504. * distributed under the License is distributed on an "AS IS" BASIS,
  25505. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25506. * See the License for the specific language governing permissions and
  25507. * limitations under the License.
  25508. */
  25509. var transform = require('sdp-transform');
  25510. var transformUtils = require('./transform-utils');
  25511. var parseSsrcs = transformUtils.parseSsrcs;
  25512. var writeSsrcs = transformUtils.writeSsrcs;
  25513. //region Constants
  25514. var DEFAULT_NUM_OF_LAYERS = 3;
  25515. //endregion
  25516. //region Ctor
  25517. function Simulcast(options) {
  25518. this.options = options ? options : {};
  25519. if (!this.options.numOfLayers) {
  25520. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25521. }
  25522. this.layers = [];
  25523. }
  25524. //endregion
  25525. //region Stateless private utility functions
  25526. /**
  25527. * Returns a random integer between min (included) and max (excluded)
  25528. * Using Math.round() gives a non-uniform distribution!
  25529. * @returns {number}
  25530. */
  25531. function generateSSRC() {
  25532. var min = 0, max = 0xffffffff;
  25533. return Math.floor(Math.random() * (max - min)) + min;
  25534. };
  25535. function processVideo(session, action) {
  25536. if (session == null || !Array.isArray(session.media)) {
  25537. return;
  25538. }
  25539. session.media.forEach(function (mLine) {
  25540. if (mLine.type === 'video') {
  25541. action(mLine);
  25542. }
  25543. });
  25544. }
  25545. function validateDescription(desc)
  25546. {
  25547. return desc && desc != null
  25548. && desc.type && desc.type != ''
  25549. && desc.sdp && desc.sdp != '';
  25550. }
  25551. function explodeRemoteSimulcast(mLine) {
  25552. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25553. return;
  25554. }
  25555. var sources = parseSsrcs(mLine);
  25556. var order = [];
  25557. // Find the SIM group and explode its sources.
  25558. var j = mLine.ssrcGroups.length;
  25559. while (j--) {
  25560. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25561. continue;
  25562. }
  25563. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25564. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25565. var ssrc = simulcastSsrcs[i];
  25566. order.push(ssrc);
  25567. var parts = sources[ssrc].msid.split(' ');
  25568. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25569. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25570. // Remove all the groups that this SSRC participates in.
  25571. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25572. if (relatedGroup.semantics === 'SIM') {
  25573. return;
  25574. }
  25575. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25576. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25577. return;
  25578. }
  25579. // Nuke all the related SSRCs.
  25580. relatedSsrcs.forEach(function (relatedSSRC) {
  25581. sources[relatedSSRC].msid = sources[ssrc].msid;
  25582. sources[relatedSSRC].cname = sources[ssrc].cname;
  25583. if (relatedSSRC !== ssrc) {
  25584. order.push(relatedSSRC);
  25585. }
  25586. });
  25587. // Schedule the related group for nuking.
  25588. })
  25589. }
  25590. mLine.ssrcs = writeSsrcs(sources, order);
  25591. mLine.ssrcGroups.splice(j, 1);
  25592. };
  25593. }
  25594. function implodeRemoteSimulcast(mLine) {
  25595. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25596. console.info('Halt: There are no SSRC groups in the remote ' +
  25597. 'description.');
  25598. return;
  25599. }
  25600. var sources = parseSsrcs(mLine);
  25601. // Find the SIM group and nuke it.
  25602. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  25603. if (simulcastGroup.semantics !== 'SIM') {
  25604. return;
  25605. }
  25606. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  25607. // Schedule the SIM group for nuking.
  25608. simulcastGroup.nuke = true;
  25609. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25610. // Nuke all the higher layer SSRCs.
  25611. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25612. var ssrc = simulcastSsrcs[i];
  25613. delete sources[ssrc];
  25614. // Remove all the groups that this SSRC participates in.
  25615. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25616. if (relatedGroup.semantics === 'SIM') {
  25617. return;
  25618. }
  25619. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25620. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25621. return;
  25622. }
  25623. // Nuke all the related SSRCs.
  25624. relatedSsrcs.forEach(function (relatedSSRC) {
  25625. delete sources[relatedSSRC];
  25626. });
  25627. // Schedule the related group for nuking.
  25628. relatedGroup.nuke = true;
  25629. })
  25630. }
  25631. return;
  25632. });
  25633. mLine.ssrcs = writeSsrcs(sources);
  25634. // Nuke all the scheduled groups.
  25635. var i = mLine.ssrcGroups.length;
  25636. while (i--) {
  25637. if (mLine.ssrcGroups[i].nuke) {
  25638. mLine.ssrcGroups.splice(i, 1);
  25639. }
  25640. }
  25641. }
  25642. function removeGoogConference(mLine) {
  25643. if (!mLine || !Array.isArray(mLine.invalid)) {
  25644. return;
  25645. }
  25646. var i = mLine.invalid.length;
  25647. while (i--) {
  25648. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25649. mLine.invalid.splice(i, 1);
  25650. }
  25651. }
  25652. }
  25653. function assertGoogConference(mLine) {
  25654. if (!mLine) {
  25655. return;
  25656. }
  25657. if (!Array.isArray(mLine.invalid)) {
  25658. mLine.invalid = [];
  25659. }
  25660. if (!mLine.invalid.some(
  25661. function (i) { return i.value === 'x-google-flag:conference' })) {
  25662. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25663. }
  25664. }
  25665. //endregion
  25666. //region "Private" functions
  25667. /**
  25668. *
  25669. * @param mLine
  25670. * @private
  25671. */
  25672. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  25673. if (!mLine || mLine.type !== 'video') {
  25674. return;
  25675. }
  25676. var sources = parseSsrcs(mLine);
  25677. if (Object.keys(sources).length === 0) {
  25678. // no sources, disable simulcast.
  25679. if (this.layers.length !== 0) {
  25680. this.layers = [];
  25681. }
  25682. return;
  25683. }
  25684. // find the base layer (we'll reuse its msid and cname).
  25685. var baseLayerSSRC = Object.keys(sources)[0];
  25686. var baseLayer = sources[baseLayerSSRC];
  25687. // todo(gp) handle screen sharing.
  25688. // check if base CNAME has changed and reinitialise layers.
  25689. if (this.layers.length > 0
  25690. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  25691. this.layers = [];
  25692. }
  25693. // (re)initialise layers
  25694. if (this.layers.length < 1) {
  25695. // first push the base layer.
  25696. this.layers.push({
  25697. ssrc: baseLayerSSRC,
  25698. msid: baseLayer.msid,
  25699. cname: baseLayer.cname
  25700. });
  25701. var rtx = false; // RFC 4588
  25702. if (Array.isArray(mLine.rtp)) {
  25703. rtx = mLine.rtp.some(
  25704. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  25705. }
  25706. if (rtx) {
  25707. this.layers[0].rtx = generateSSRC();
  25708. }
  25709. // now push additional layers.
  25710. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  25711. var layer = { ssrc: generateSSRC() };
  25712. if (rtx) {
  25713. layer.rtx = generateSSRC();
  25714. }
  25715. this.layers.push(layer);
  25716. }
  25717. }
  25718. };
  25719. /**
  25720. *
  25721. * @param mLine
  25722. * @private
  25723. */
  25724. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  25725. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  25726. var sources = {};
  25727. var msid = this.layers[0].msid;
  25728. var cname = this.layers[0].cname;
  25729. var simulcastSsrcs = [];
  25730. var ssrcGroups = [];
  25731. for (var i = 0; i < this.layers.length; i++) {
  25732. var layer = this.layers[i];
  25733. sources[layer.ssrc] = { msid: msid, cname: cname };
  25734. simulcastSsrcs.push(layer.ssrc);
  25735. if (layer.rtx) {
  25736. sources[layer.rtx] = {
  25737. msid: msid,
  25738. cname: cname
  25739. }
  25740. ssrcGroups.push({
  25741. semantics: 'FID',
  25742. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  25743. });
  25744. }
  25745. }
  25746. ssrcGroups.push({
  25747. semantics: 'SIM',
  25748. ssrcs: simulcastSsrcs.join(' ')
  25749. });
  25750. mLine.ssrcGroups = ssrcGroups;
  25751. mLine.ssrcs = writeSsrcs(sources);
  25752. }
  25753. }
  25754. //endregion
  25755. //region "Public" functions
  25756. Simulcast.prototype.isSupported = function () {
  25757. return window.chrome;
  25758. // TODO this needs improvements. For example I doubt that Chrome in Android
  25759. // has simulcast support. Also, only recent versions of Chromium have native
  25760. // simulcast support.
  25761. }
  25762. /**
  25763. *
  25764. * @param desc
  25765. * @returns {RTCSessionDescription}
  25766. */
  25767. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  25768. if (!validateDescription(desc)) {
  25769. return desc;
  25770. }
  25771. var session = transform.parse(desc.sdp);
  25772. var self = this;
  25773. processVideo(session, function (mLine) {
  25774. // Handle simulcast reception.
  25775. if (self.options.explodeRemoteSimulcast) {
  25776. explodeRemoteSimulcast(mLine);
  25777. } else {
  25778. implodeRemoteSimulcast(mLine);
  25779. }
  25780. // If native simulcast is enabled, we must append the x-goog-conference
  25781. // attribute to the SDP.
  25782. if (self.layers.length < 1) {
  25783. removeGoogConference(mLine);
  25784. } else {
  25785. assertGoogConference(mLine);
  25786. }
  25787. });
  25788. return new RTCSessionDescription({
  25789. type: desc.type,
  25790. sdp: transform.write(session)
  25791. });
  25792. };
  25793. /**
  25794. *
  25795. * @param desc
  25796. * @returns {RTCSessionDescription}
  25797. */
  25798. Simulcast.prototype.mungeLocalDescription = function (desc) {
  25799. if (!validateDescription(desc) || !this.isSupported()) {
  25800. return desc;
  25801. }
  25802. var session = transform.parse(desc.sdp);
  25803. var self = this;
  25804. processVideo(session, function (mLine) {
  25805. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  25806. {
  25807. return;
  25808. }
  25809. // Initialize native simulcast layers, if not already done.
  25810. self._maybeInitializeLayers(mLine);
  25811. // Update the SDP with the simulcast layers.
  25812. self._restoreSimulcastView(mLine);
  25813. });
  25814. return new RTCSessionDescription({
  25815. type: desc.type,
  25816. sdp: transform.write(session)
  25817. });
  25818. };
  25819. //endregion
  25820. module.exports = Simulcast;
  25821. },{"./transform-utils":113,"sdp-transform":115}],113:[function(require,module,exports){
  25822. /* Copyright @ 2015 Atlassian Pty Ltd
  25823. *
  25824. * Licensed under the Apache License, Version 2.0 (the "License");
  25825. * you may not use this file except in compliance with the License.
  25826. * You may obtain a copy of the License at
  25827. *
  25828. * http://www.apache.org/licenses/LICENSE-2.0
  25829. *
  25830. * Unless required by applicable law or agreed to in writing, software
  25831. * distributed under the License is distributed on an "AS IS" BASIS,
  25832. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  25833. * See the License for the specific language governing permissions and
  25834. * limitations under the License.
  25835. */
  25836. exports.writeSsrcs = function(sources, order) {
  25837. var ssrcs = [];
  25838. // expand sources to ssrcs
  25839. if (typeof sources !== 'undefined' &&
  25840. Object.keys(sources).length !== 0) {
  25841. if (Array.isArray(order)) {
  25842. for (var i = 0; i < order.length; i++) {
  25843. var ssrc = order[i];
  25844. var source = sources[ssrc];
  25845. Object.keys(source).forEach(function (attribute) {
  25846. ssrcs.push({
  25847. id: ssrc,
  25848. attribute: attribute,
  25849. value: source[attribute]
  25850. });
  25851. });
  25852. }
  25853. } else {
  25854. Object.keys(sources).forEach(function (ssrc) {
  25855. var source = sources[ssrc];
  25856. Object.keys(source).forEach(function (attribute) {
  25857. ssrcs.push({
  25858. id: ssrc,
  25859. attribute: attribute,
  25860. value: source[attribute]
  25861. });
  25862. });
  25863. });
  25864. }
  25865. }
  25866. return ssrcs;
  25867. };
  25868. exports.parseSsrcs = function (mLine) {
  25869. var sources = {};
  25870. // group sources attributes by ssrc.
  25871. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25872. mLine.ssrcs.forEach(function (ssrc) {
  25873. if (!sources[ssrc.id])
  25874. sources[ssrc.id] = {};
  25875. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25876. });
  25877. }
  25878. return sources;
  25879. };
  25880. },{}],114:[function(require,module,exports){
  25881. arguments[4][108][0].apply(exports,arguments)
  25882. },{"dup":108}],115:[function(require,module,exports){
  25883. arguments[4][109][0].apply(exports,arguments)
  25884. },{"./parser":116,"./writer":117,"dup":109}],116:[function(require,module,exports){
  25885. arguments[4][110][0].apply(exports,arguments)
  25886. },{"./grammar":114,"dup":110}],117:[function(require,module,exports){
  25887. arguments[4][111][0].apply(exports,arguments)
  25888. },{"./grammar":114,"dup":111}],118:[function(require,module,exports){
  25889. module.exports = require('./lib/');
  25890. },{"./lib/":119}],119:[function(require,module,exports){
  25891. /**
  25892. * Module dependencies.
  25893. */
  25894. var url = require('./url');
  25895. var parser = require('socket.io-parser');
  25896. var Manager = require('./manager');
  25897. var debug = require('debug')('socket.io-client');
  25898. /**
  25899. * Module exports.
  25900. */
  25901. module.exports = exports = lookup;
  25902. /**
  25903. * Managers cache.
  25904. */
  25905. var cache = exports.managers = {};
  25906. /**
  25907. * Looks up an existing `Manager` for multiplexing.
  25908. * If the user summons:
  25909. *
  25910. * `io('http://localhost/a');`
  25911. * `io('http://localhost/b');`
  25912. *
  25913. * We reuse the existing instance based on same scheme/port/host,
  25914. * and we initialize sockets for each namespace.
  25915. *
  25916. * @api public
  25917. */
  25918. function lookup(uri, opts) {
  25919. if (typeof uri == 'object') {
  25920. opts = uri;
  25921. uri = undefined;
  25922. }
  25923. opts = opts || {};
  25924. var parsed = url(uri);
  25925. var source = parsed.source;
  25926. var id = parsed.id;
  25927. var io;
  25928. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  25929. debug('ignoring socket cache for %s', source);
  25930. io = Manager(source, opts);
  25931. } else {
  25932. if (!cache[id]) {
  25933. debug('new io instance for %s', source);
  25934. cache[id] = Manager(source, opts);
  25935. }
  25936. io = cache[id];
  25937. }
  25938. return io.socket(parsed.path);
  25939. }
  25940. /**
  25941. * Protocol version.
  25942. *
  25943. * @api public
  25944. */
  25945. exports.protocol = parser.protocol;
  25946. /**
  25947. * `connect`.
  25948. *
  25949. * @param {String} uri
  25950. * @api public
  25951. */
  25952. exports.connect = lookup;
  25953. /**
  25954. * Expose constructors for standalone build.
  25955. *
  25956. * @api public
  25957. */
  25958. exports.Manager = require('./manager');
  25959. exports.Socket = require('./socket');
  25960. },{"./manager":120,"./socket":122,"./url":123,"debug":55,"socket.io-parser":125}],120:[function(require,module,exports){
  25961. /**
  25962. * Module dependencies.
  25963. */
  25964. var url = require('./url');
  25965. var eio = require('engine.io-client');
  25966. var Socket = require('./socket');
  25967. var Emitter = require('component-emitter');
  25968. var parser = require('socket.io-parser');
  25969. var on = require('./on');
  25970. var bind = require('component-bind');
  25971. var object = require('object-component');
  25972. var debug = require('debug')('socket.io-client:manager');
  25973. var indexOf = require('indexof');
  25974. var Backoff = require('backo2');
  25975. /**
  25976. * Module exports
  25977. */
  25978. module.exports = Manager;
  25979. /**
  25980. * `Manager` constructor.
  25981. *
  25982. * @param {String} engine instance or engine uri/opts
  25983. * @param {Object} options
  25984. * @api public
  25985. */
  25986. function Manager(uri, opts){
  25987. if (!(this instanceof Manager)) return new Manager(uri, opts);
  25988. if (uri && ('object' == typeof uri)) {
  25989. opts = uri;
  25990. uri = undefined;
  25991. }
  25992. opts = opts || {};
  25993. opts.path = opts.path || '/socket.io';
  25994. this.nsps = {};
  25995. this.subs = [];
  25996. this.opts = opts;
  25997. this.reconnection(opts.reconnection !== false);
  25998. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  25999. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  26000. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  26001. this.randomizationFactor(opts.randomizationFactor || 0.5);
  26002. this.backoff = new Backoff({
  26003. min: this.reconnectionDelay(),
  26004. max: this.reconnectionDelayMax(),
  26005. jitter: this.randomizationFactor()
  26006. });
  26007. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  26008. this.readyState = 'closed';
  26009. this.uri = uri;
  26010. this.connected = [];
  26011. this.encoding = false;
  26012. this.packetBuffer = [];
  26013. this.encoder = new parser.Encoder();
  26014. this.decoder = new parser.Decoder();
  26015. this.autoConnect = opts.autoConnect !== false;
  26016. if (this.autoConnect) this.open();
  26017. }
  26018. /**
  26019. * Propagate given event to sockets and emit on `this`
  26020. *
  26021. * @api private
  26022. */
  26023. Manager.prototype.emitAll = function() {
  26024. this.emit.apply(this, arguments);
  26025. for (var nsp in this.nsps) {
  26026. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  26027. }
  26028. };
  26029. /**
  26030. * Update `socket.id` of all sockets
  26031. *
  26032. * @api private
  26033. */
  26034. Manager.prototype.updateSocketIds = function(){
  26035. for (var nsp in this.nsps) {
  26036. this.nsps[nsp].id = this.engine.id;
  26037. }
  26038. };
  26039. /**
  26040. * Mix in `Emitter`.
  26041. */
  26042. Emitter(Manager.prototype);
  26043. /**
  26044. * Sets the `reconnection` config.
  26045. *
  26046. * @param {Boolean} true/false if it should automatically reconnect
  26047. * @return {Manager} self or value
  26048. * @api public
  26049. */
  26050. Manager.prototype.reconnection = function(v){
  26051. if (!arguments.length) return this._reconnection;
  26052. this._reconnection = !!v;
  26053. return this;
  26054. };
  26055. /**
  26056. * Sets the reconnection attempts config.
  26057. *
  26058. * @param {Number} max reconnection attempts before giving up
  26059. * @return {Manager} self or value
  26060. * @api public
  26061. */
  26062. Manager.prototype.reconnectionAttempts = function(v){
  26063. if (!arguments.length) return this._reconnectionAttempts;
  26064. this._reconnectionAttempts = v;
  26065. return this;
  26066. };
  26067. /**
  26068. * Sets the delay between reconnections.
  26069. *
  26070. * @param {Number} delay
  26071. * @return {Manager} self or value
  26072. * @api public
  26073. */
  26074. Manager.prototype.reconnectionDelay = function(v){
  26075. if (!arguments.length) return this._reconnectionDelay;
  26076. this._reconnectionDelay = v;
  26077. this.backoff && this.backoff.setMin(v);
  26078. return this;
  26079. };
  26080. Manager.prototype.randomizationFactor = function(v){
  26081. if (!arguments.length) return this._randomizationFactor;
  26082. this._randomizationFactor = v;
  26083. this.backoff && this.backoff.setJitter(v);
  26084. return this;
  26085. };
  26086. /**
  26087. * Sets the maximum delay between reconnections.
  26088. *
  26089. * @param {Number} delay
  26090. * @return {Manager} self or value
  26091. * @api public
  26092. */
  26093. Manager.prototype.reconnectionDelayMax = function(v){
  26094. if (!arguments.length) return this._reconnectionDelayMax;
  26095. this._reconnectionDelayMax = v;
  26096. this.backoff && this.backoff.setMax(v);
  26097. return this;
  26098. };
  26099. /**
  26100. * Sets the connection timeout. `false` to disable
  26101. *
  26102. * @return {Manager} self or value
  26103. * @api public
  26104. */
  26105. Manager.prototype.timeout = function(v){
  26106. if (!arguments.length) return this._timeout;
  26107. this._timeout = v;
  26108. return this;
  26109. };
  26110. /**
  26111. * Starts trying to reconnect if reconnection is enabled and we have not
  26112. * started reconnecting yet
  26113. *
  26114. * @api private
  26115. */
  26116. Manager.prototype.maybeReconnectOnOpen = function() {
  26117. // Only try to reconnect if it's the first time we're connecting
  26118. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  26119. // keeps reconnection from firing twice for the same reconnection loop
  26120. this.reconnect();
  26121. }
  26122. };
  26123. /**
  26124. * Sets the current transport `socket`.
  26125. *
  26126. * @param {Function} optional, callback
  26127. * @return {Manager} self
  26128. * @api public
  26129. */
  26130. Manager.prototype.open =
  26131. Manager.prototype.connect = function(fn){
  26132. debug('readyState %s', this.readyState);
  26133. if (~this.readyState.indexOf('open')) return this;
  26134. debug('opening %s', this.uri);
  26135. this.engine = eio(this.uri, this.opts);
  26136. var socket = this.engine;
  26137. var self = this;
  26138. this.readyState = 'opening';
  26139. this.skipReconnect = false;
  26140. // emit `open`
  26141. var openSub = on(socket, 'open', function() {
  26142. self.onopen();
  26143. fn && fn();
  26144. });
  26145. // emit `connect_error`
  26146. var errorSub = on(socket, 'error', function(data){
  26147. debug('connect_error');
  26148. self.cleanup();
  26149. self.readyState = 'closed';
  26150. self.emitAll('connect_error', data);
  26151. if (fn) {
  26152. var err = new Error('Connection error');
  26153. err.data = data;
  26154. fn(err);
  26155. } else {
  26156. // Only do this if there is no fn to handle the error
  26157. self.maybeReconnectOnOpen();
  26158. }
  26159. });
  26160. // emit `connect_timeout`
  26161. if (false !== this._timeout) {
  26162. var timeout = this._timeout;
  26163. debug('connect attempt will timeout after %d', timeout);
  26164. // set timer
  26165. var timer = setTimeout(function(){
  26166. debug('connect attempt timed out after %d', timeout);
  26167. openSub.destroy();
  26168. socket.close();
  26169. socket.emit('error', 'timeout');
  26170. self.emitAll('connect_timeout', timeout);
  26171. }, timeout);
  26172. this.subs.push({
  26173. destroy: function(){
  26174. clearTimeout(timer);
  26175. }
  26176. });
  26177. }
  26178. this.subs.push(openSub);
  26179. this.subs.push(errorSub);
  26180. return this;
  26181. };
  26182. /**
  26183. * Called upon transport open.
  26184. *
  26185. * @api private
  26186. */
  26187. Manager.prototype.onopen = function(){
  26188. debug('open');
  26189. // clear old subs
  26190. this.cleanup();
  26191. // mark as open
  26192. this.readyState = 'open';
  26193. this.emit('open');
  26194. // add new subs
  26195. var socket = this.engine;
  26196. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  26197. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  26198. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  26199. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  26200. };
  26201. /**
  26202. * Called with data.
  26203. *
  26204. * @api private
  26205. */
  26206. Manager.prototype.ondata = function(data){
  26207. this.decoder.add(data);
  26208. };
  26209. /**
  26210. * Called when parser fully decodes a packet.
  26211. *
  26212. * @api private
  26213. */
  26214. Manager.prototype.ondecoded = function(packet) {
  26215. this.emit('packet', packet);
  26216. };
  26217. /**
  26218. * Called upon socket error.
  26219. *
  26220. * @api private
  26221. */
  26222. Manager.prototype.onerror = function(err){
  26223. debug('error', err);
  26224. this.emitAll('error', err);
  26225. };
  26226. /**
  26227. * Creates a new socket for the given `nsp`.
  26228. *
  26229. * @return {Socket}
  26230. * @api public
  26231. */
  26232. Manager.prototype.socket = function(nsp){
  26233. var socket = this.nsps[nsp];
  26234. if (!socket) {
  26235. socket = new Socket(this, nsp);
  26236. this.nsps[nsp] = socket;
  26237. var self = this;
  26238. socket.on('connect', function(){
  26239. socket.id = self.engine.id;
  26240. if (!~indexOf(self.connected, socket)) {
  26241. self.connected.push(socket);
  26242. }
  26243. });
  26244. }
  26245. return socket;
  26246. };
  26247. /**
  26248. * Called upon a socket close.
  26249. *
  26250. * @param {Socket} socket
  26251. */
  26252. Manager.prototype.destroy = function(socket){
  26253. var index = indexOf(this.connected, socket);
  26254. if (~index) this.connected.splice(index, 1);
  26255. if (this.connected.length) return;
  26256. this.close();
  26257. };
  26258. /**
  26259. * Writes a packet.
  26260. *
  26261. * @param {Object} packet
  26262. * @api private
  26263. */
  26264. Manager.prototype.packet = function(packet){
  26265. debug('writing packet %j', packet);
  26266. var self = this;
  26267. if (!self.encoding) {
  26268. // encode, then write to engine with result
  26269. self.encoding = true;
  26270. this.encoder.encode(packet, function(encodedPackets) {
  26271. for (var i = 0; i < encodedPackets.length; i++) {
  26272. self.engine.write(encodedPackets[i]);
  26273. }
  26274. self.encoding = false;
  26275. self.processPacketQueue();
  26276. });
  26277. } else { // add packet to the queue
  26278. self.packetBuffer.push(packet);
  26279. }
  26280. };
  26281. /**
  26282. * If packet buffer is non-empty, begins encoding the
  26283. * next packet in line.
  26284. *
  26285. * @api private
  26286. */
  26287. Manager.prototype.processPacketQueue = function() {
  26288. if (this.packetBuffer.length > 0 && !this.encoding) {
  26289. var pack = this.packetBuffer.shift();
  26290. this.packet(pack);
  26291. }
  26292. };
  26293. /**
  26294. * Clean up transport subscriptions and packet buffer.
  26295. *
  26296. * @api private
  26297. */
  26298. Manager.prototype.cleanup = function(){
  26299. var sub;
  26300. while (sub = this.subs.shift()) sub.destroy();
  26301. this.packetBuffer = [];
  26302. this.encoding = false;
  26303. this.decoder.destroy();
  26304. };
  26305. /**
  26306. * Close the current socket.
  26307. *
  26308. * @api private
  26309. */
  26310. Manager.prototype.close =
  26311. Manager.prototype.disconnect = function(){
  26312. this.skipReconnect = true;
  26313. this.backoff.reset();
  26314. this.readyState = 'closed';
  26315. this.engine && this.engine.close();
  26316. };
  26317. /**
  26318. * Called upon engine close.
  26319. *
  26320. * @api private
  26321. */
  26322. Manager.prototype.onclose = function(reason){
  26323. debug('close');
  26324. this.cleanup();
  26325. this.backoff.reset();
  26326. this.readyState = 'closed';
  26327. this.emit('close', reason);
  26328. if (this._reconnection && !this.skipReconnect) {
  26329. this.reconnect();
  26330. }
  26331. };
  26332. /**
  26333. * Attempt a reconnection.
  26334. *
  26335. * @api private
  26336. */
  26337. Manager.prototype.reconnect = function(){
  26338. if (this.reconnecting || this.skipReconnect) return this;
  26339. var self = this;
  26340. if (this.backoff.attempts >= this._reconnectionAttempts) {
  26341. debug('reconnect failed');
  26342. this.backoff.reset();
  26343. this.emitAll('reconnect_failed');
  26344. this.reconnecting = false;
  26345. } else {
  26346. var delay = this.backoff.duration();
  26347. debug('will wait %dms before reconnect attempt', delay);
  26348. this.reconnecting = true;
  26349. var timer = setTimeout(function(){
  26350. if (self.skipReconnect) return;
  26351. debug('attempting reconnect');
  26352. self.emitAll('reconnect_attempt', self.backoff.attempts);
  26353. self.emitAll('reconnecting', self.backoff.attempts);
  26354. // check again for the case socket closed in above events
  26355. if (self.skipReconnect) return;
  26356. self.open(function(err){
  26357. if (err) {
  26358. debug('reconnect attempt error');
  26359. self.reconnecting = false;
  26360. self.reconnect();
  26361. self.emitAll('reconnect_error', err.data);
  26362. } else {
  26363. debug('reconnect success');
  26364. self.onreconnect();
  26365. }
  26366. });
  26367. }, delay);
  26368. this.subs.push({
  26369. destroy: function(){
  26370. clearTimeout(timer);
  26371. }
  26372. });
  26373. }
  26374. };
  26375. /**
  26376. * Called upon successful reconnect.
  26377. *
  26378. * @api private
  26379. */
  26380. Manager.prototype.onreconnect = function(){
  26381. var attempt = this.backoff.attempts;
  26382. this.reconnecting = false;
  26383. this.backoff.reset();
  26384. this.updateSocketIds();
  26385. this.emitAll('reconnect', attempt);
  26386. };
  26387. },{"./on":121,"./socket":122,"./url":123,"backo2":48,"component-bind":52,"component-emitter":53,"debug":55,"engine.io-client":56,"indexof":76,"object-component":83,"socket.io-parser":125}],121:[function(require,module,exports){
  26388. /**
  26389. * Module exports.
  26390. */
  26391. module.exports = on;
  26392. /**
  26393. * Helper for subscriptions.
  26394. *
  26395. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  26396. * @param {String} event name
  26397. * @param {Function} callback
  26398. * @api public
  26399. */
  26400. function on(obj, ev, fn) {
  26401. obj.on(ev, fn);
  26402. return {
  26403. destroy: function(){
  26404. obj.removeListener(ev, fn);
  26405. }
  26406. };
  26407. }
  26408. },{}],122:[function(require,module,exports){
  26409. /**
  26410. * Module dependencies.
  26411. */
  26412. var parser = require('socket.io-parser');
  26413. var Emitter = require('component-emitter');
  26414. var toArray = require('to-array');
  26415. var on = require('./on');
  26416. var bind = require('component-bind');
  26417. var debug = require('debug')('socket.io-client:socket');
  26418. var hasBin = require('has-binary');
  26419. /**
  26420. * Module exports.
  26421. */
  26422. module.exports = exports = Socket;
  26423. /**
  26424. * Internal events (blacklisted).
  26425. * These events can't be emitted by the user.
  26426. *
  26427. * @api private
  26428. */
  26429. var events = {
  26430. connect: 1,
  26431. connect_error: 1,
  26432. connect_timeout: 1,
  26433. disconnect: 1,
  26434. error: 1,
  26435. reconnect: 1,
  26436. reconnect_attempt: 1,
  26437. reconnect_failed: 1,
  26438. reconnect_error: 1,
  26439. reconnecting: 1
  26440. };
  26441. /**
  26442. * Shortcut to `Emitter#emit`.
  26443. */
  26444. var emit = Emitter.prototype.emit;
  26445. /**
  26446. * `Socket` constructor.
  26447. *
  26448. * @api public
  26449. */
  26450. function Socket(io, nsp){
  26451. this.io = io;
  26452. this.nsp = nsp;
  26453. this.json = this; // compat
  26454. this.ids = 0;
  26455. this.acks = {};
  26456. if (this.io.autoConnect) this.open();
  26457. this.receiveBuffer = [];
  26458. this.sendBuffer = [];
  26459. this.connected = false;
  26460. this.disconnected = true;
  26461. }
  26462. /**
  26463. * Mix in `Emitter`.
  26464. */
  26465. Emitter(Socket.prototype);
  26466. /**
  26467. * Subscribe to open, close and packet events
  26468. *
  26469. * @api private
  26470. */
  26471. Socket.prototype.subEvents = function() {
  26472. if (this.subs) return;
  26473. var io = this.io;
  26474. this.subs = [
  26475. on(io, 'open', bind(this, 'onopen')),
  26476. on(io, 'packet', bind(this, 'onpacket')),
  26477. on(io, 'close', bind(this, 'onclose'))
  26478. ];
  26479. };
  26480. /**
  26481. * "Opens" the socket.
  26482. *
  26483. * @api public
  26484. */
  26485. Socket.prototype.open =
  26486. Socket.prototype.connect = function(){
  26487. if (this.connected) return this;
  26488. this.subEvents();
  26489. this.io.open(); // ensure open
  26490. if ('open' == this.io.readyState) this.onopen();
  26491. return this;
  26492. };
  26493. /**
  26494. * Sends a `message` event.
  26495. *
  26496. * @return {Socket} self
  26497. * @api public
  26498. */
  26499. Socket.prototype.send = function(){
  26500. var args = toArray(arguments);
  26501. args.unshift('message');
  26502. this.emit.apply(this, args);
  26503. return this;
  26504. };
  26505. /**
  26506. * Override `emit`.
  26507. * If the event is in `events`, it's emitted normally.
  26508. *
  26509. * @param {String} event name
  26510. * @return {Socket} self
  26511. * @api public
  26512. */
  26513. Socket.prototype.emit = function(ev){
  26514. if (events.hasOwnProperty(ev)) {
  26515. emit.apply(this, arguments);
  26516. return this;
  26517. }
  26518. var args = toArray(arguments);
  26519. var parserType = parser.EVENT; // default
  26520. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  26521. var packet = { type: parserType, data: args };
  26522. // event ack callback
  26523. if ('function' == typeof args[args.length - 1]) {
  26524. debug('emitting packet with ack id %d', this.ids);
  26525. this.acks[this.ids] = args.pop();
  26526. packet.id = this.ids++;
  26527. }
  26528. if (this.connected) {
  26529. this.packet(packet);
  26530. } else {
  26531. this.sendBuffer.push(packet);
  26532. }
  26533. return this;
  26534. };
  26535. /**
  26536. * Sends a packet.
  26537. *
  26538. * @param {Object} packet
  26539. * @api private
  26540. */
  26541. Socket.prototype.packet = function(packet){
  26542. packet.nsp = this.nsp;
  26543. this.io.packet(packet);
  26544. };
  26545. /**
  26546. * Called upon engine `open`.
  26547. *
  26548. * @api private
  26549. */
  26550. Socket.prototype.onopen = function(){
  26551. debug('transport is open - connecting');
  26552. // write connect packet if necessary
  26553. if ('/' != this.nsp) {
  26554. this.packet({ type: parser.CONNECT });
  26555. }
  26556. };
  26557. /**
  26558. * Called upon engine `close`.
  26559. *
  26560. * @param {String} reason
  26561. * @api private
  26562. */
  26563. Socket.prototype.onclose = function(reason){
  26564. debug('close (%s)', reason);
  26565. this.connected = false;
  26566. this.disconnected = true;
  26567. delete this.id;
  26568. this.emit('disconnect', reason);
  26569. };
  26570. /**
  26571. * Called with socket packet.
  26572. *
  26573. * @param {Object} packet
  26574. * @api private
  26575. */
  26576. Socket.prototype.onpacket = function(packet){
  26577. if (packet.nsp != this.nsp) return;
  26578. switch (packet.type) {
  26579. case parser.CONNECT:
  26580. this.onconnect();
  26581. break;
  26582. case parser.EVENT:
  26583. this.onevent(packet);
  26584. break;
  26585. case parser.BINARY_EVENT:
  26586. this.onevent(packet);
  26587. break;
  26588. case parser.ACK:
  26589. this.onack(packet);
  26590. break;
  26591. case parser.BINARY_ACK:
  26592. this.onack(packet);
  26593. break;
  26594. case parser.DISCONNECT:
  26595. this.ondisconnect();
  26596. break;
  26597. case parser.ERROR:
  26598. this.emit('error', packet.data);
  26599. break;
  26600. }
  26601. };
  26602. /**
  26603. * Called upon a server event.
  26604. *
  26605. * @param {Object} packet
  26606. * @api private
  26607. */
  26608. Socket.prototype.onevent = function(packet){
  26609. var args = packet.data || [];
  26610. debug('emitting event %j', args);
  26611. if (null != packet.id) {
  26612. debug('attaching ack callback to event');
  26613. args.push(this.ack(packet.id));
  26614. }
  26615. if (this.connected) {
  26616. emit.apply(this, args);
  26617. } else {
  26618. this.receiveBuffer.push(args);
  26619. }
  26620. };
  26621. /**
  26622. * Produces an ack callback to emit with an event.
  26623. *
  26624. * @api private
  26625. */
  26626. Socket.prototype.ack = function(id){
  26627. var self = this;
  26628. var sent = false;
  26629. return function(){
  26630. // prevent double callbacks
  26631. if (sent) return;
  26632. sent = true;
  26633. var args = toArray(arguments);
  26634. debug('sending ack %j', args);
  26635. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  26636. self.packet({
  26637. type: type,
  26638. id: id,
  26639. data: args
  26640. });
  26641. };
  26642. };
  26643. /**
  26644. * Called upon a server acknowlegement.
  26645. *
  26646. * @param {Object} packet
  26647. * @api private
  26648. */
  26649. Socket.prototype.onack = function(packet){
  26650. debug('calling ack %s with %j', packet.id, packet.data);
  26651. var fn = this.acks[packet.id];
  26652. fn.apply(this, packet.data);
  26653. delete this.acks[packet.id];
  26654. };
  26655. /**
  26656. * Called upon server connect.
  26657. *
  26658. * @api private
  26659. */
  26660. Socket.prototype.onconnect = function(){
  26661. this.connected = true;
  26662. this.disconnected = false;
  26663. this.emit('connect');
  26664. this.emitBuffered();
  26665. };
  26666. /**
  26667. * Emit buffered events (received and emitted).
  26668. *
  26669. * @api private
  26670. */
  26671. Socket.prototype.emitBuffered = function(){
  26672. var i;
  26673. for (i = 0; i < this.receiveBuffer.length; i++) {
  26674. emit.apply(this, this.receiveBuffer[i]);
  26675. }
  26676. this.receiveBuffer = [];
  26677. for (i = 0; i < this.sendBuffer.length; i++) {
  26678. this.packet(this.sendBuffer[i]);
  26679. }
  26680. this.sendBuffer = [];
  26681. };
  26682. /**
  26683. * Called upon server disconnect.
  26684. *
  26685. * @api private
  26686. */
  26687. Socket.prototype.ondisconnect = function(){
  26688. debug('server disconnect (%s)', this.nsp);
  26689. this.destroy();
  26690. this.onclose('io server disconnect');
  26691. };
  26692. /**
  26693. * Called upon forced client/server side disconnections,
  26694. * this method ensures the manager stops tracking us and
  26695. * that reconnections don't get triggered for this.
  26696. *
  26697. * @api private.
  26698. */
  26699. Socket.prototype.destroy = function(){
  26700. if (this.subs) {
  26701. // clean subscriptions to avoid reconnections
  26702. for (var i = 0; i < this.subs.length; i++) {
  26703. this.subs[i].destroy();
  26704. }
  26705. this.subs = null;
  26706. }
  26707. this.io.destroy(this);
  26708. };
  26709. /**
  26710. * Disconnects the socket manually.
  26711. *
  26712. * @return {Socket} self
  26713. * @api public
  26714. */
  26715. Socket.prototype.close =
  26716. Socket.prototype.disconnect = function(){
  26717. if (this.connected) {
  26718. debug('performing disconnect (%s)', this.nsp);
  26719. this.packet({ type: parser.DISCONNECT });
  26720. }
  26721. // remove socket from pool
  26722. this.destroy();
  26723. if (this.connected) {
  26724. // fire events
  26725. this.onclose('io client disconnect');
  26726. }
  26727. return this;
  26728. };
  26729. },{"./on":121,"component-bind":52,"component-emitter":53,"debug":55,"has-binary":74,"socket.io-parser":125,"to-array":127}],123:[function(require,module,exports){
  26730. (function (global){
  26731. /**
  26732. * Module dependencies.
  26733. */
  26734. var parseuri = require('parseuri');
  26735. var debug = require('debug')('socket.io-client:url');
  26736. /**
  26737. * Module exports.
  26738. */
  26739. module.exports = url;
  26740. /**
  26741. * URL parser.
  26742. *
  26743. * @param {String} url
  26744. * @param {Object} An object meant to mimic window.location.
  26745. * Defaults to window.location.
  26746. * @api public
  26747. */
  26748. function url(uri, loc){
  26749. var obj = uri;
  26750. // default to window.location
  26751. var loc = loc || global.location;
  26752. if (null == uri) uri = loc.protocol + '//' + loc.host;
  26753. // relative path support
  26754. if ('string' == typeof uri) {
  26755. if ('/' == uri.charAt(0)) {
  26756. if ('/' == uri.charAt(1)) {
  26757. uri = loc.protocol + uri;
  26758. } else {
  26759. uri = loc.hostname + uri;
  26760. }
  26761. }
  26762. if (!/^(https?|wss?):\/\//.test(uri)) {
  26763. debug('protocol-less url %s', uri);
  26764. if ('undefined' != typeof loc) {
  26765. uri = loc.protocol + '//' + uri;
  26766. } else {
  26767. uri = 'https://' + uri;
  26768. }
  26769. }
  26770. // parse
  26771. debug('parse %s', uri);
  26772. obj = parseuri(uri);
  26773. }
  26774. // make sure we treat `localhost:80` and `localhost` equally
  26775. if (!obj.port) {
  26776. if (/^(http|ws)$/.test(obj.protocol)) {
  26777. obj.port = '80';
  26778. }
  26779. else if (/^(http|ws)s$/.test(obj.protocol)) {
  26780. obj.port = '443';
  26781. }
  26782. }
  26783. obj.path = obj.path || '/';
  26784. // define unique id
  26785. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  26786. // define href
  26787. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  26788. return obj;
  26789. }
  26790. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26791. },{"debug":55,"parseuri":102}],124:[function(require,module,exports){
  26792. (function (global){
  26793. /*global Blob,File*/
  26794. /**
  26795. * Module requirements
  26796. */
  26797. var isArray = require('isarray');
  26798. var isBuf = require('./is-buffer');
  26799. /**
  26800. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26801. * Anything with blobs or files should be fed through removeBlobs before coming
  26802. * here.
  26803. *
  26804. * @param {Object} packet - socket.io event packet
  26805. * @return {Object} with deconstructed packet and list of buffers
  26806. * @api public
  26807. */
  26808. exports.deconstructPacket = function(packet){
  26809. var buffers = [];
  26810. var packetData = packet.data;
  26811. function _deconstructPacket(data) {
  26812. if (!data) return data;
  26813. if (isBuf(data)) {
  26814. var placeholder = { _placeholder: true, num: buffers.length };
  26815. buffers.push(data);
  26816. return placeholder;
  26817. } else if (isArray(data)) {
  26818. var newData = new Array(data.length);
  26819. for (var i = 0; i < data.length; i++) {
  26820. newData[i] = _deconstructPacket(data[i]);
  26821. }
  26822. return newData;
  26823. } else if ('object' == typeof data && !(data instanceof Date)) {
  26824. var newData = {};
  26825. for (var key in data) {
  26826. newData[key] = _deconstructPacket(data[key]);
  26827. }
  26828. return newData;
  26829. }
  26830. return data;
  26831. }
  26832. var pack = packet;
  26833. pack.data = _deconstructPacket(packetData);
  26834. pack.attachments = buffers.length; // number of binary 'attachments'
  26835. return {packet: pack, buffers: buffers};
  26836. };
  26837. /**
  26838. * Reconstructs a binary packet from its placeholder packet and buffers
  26839. *
  26840. * @param {Object} packet - event packet with placeholders
  26841. * @param {Array} buffers - binary buffers to put in placeholder positions
  26842. * @return {Object} reconstructed packet
  26843. * @api public
  26844. */
  26845. exports.reconstructPacket = function(packet, buffers) {
  26846. var curPlaceHolder = 0;
  26847. function _reconstructPacket(data) {
  26848. if (data && data._placeholder) {
  26849. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26850. return buf;
  26851. } else if (isArray(data)) {
  26852. for (var i = 0; i < data.length; i++) {
  26853. data[i] = _reconstructPacket(data[i]);
  26854. }
  26855. return data;
  26856. } else if (data && 'object' == typeof data) {
  26857. for (var key in data) {
  26858. data[key] = _reconstructPacket(data[key]);
  26859. }
  26860. return data;
  26861. }
  26862. return data;
  26863. }
  26864. packet.data = _reconstructPacket(packet.data);
  26865. packet.attachments = undefined; // no longer useful
  26866. return packet;
  26867. };
  26868. /**
  26869. * Asynchronously removes Blobs or Files from data via
  26870. * FileReader's readAsArrayBuffer method. Used before encoding
  26871. * data as msgpack. Calls callback with the blobless data.
  26872. *
  26873. * @param {Object} data
  26874. * @param {Function} callback
  26875. * @api private
  26876. */
  26877. exports.removeBlobs = function(data, callback) {
  26878. function _removeBlobs(obj, curKey, containingObject) {
  26879. if (!obj) return obj;
  26880. // convert any blob
  26881. if ((global.Blob && obj instanceof Blob) ||
  26882. (global.File && obj instanceof File)) {
  26883. pendingBlobs++;
  26884. // async filereader
  26885. var fileReader = new FileReader();
  26886. fileReader.onload = function() { // this.result == arraybuffer
  26887. if (containingObject) {
  26888. containingObject[curKey] = this.result;
  26889. }
  26890. else {
  26891. bloblessData = this.result;
  26892. }
  26893. // if nothing pending its callback time
  26894. if(! --pendingBlobs) {
  26895. callback(bloblessData);
  26896. }
  26897. };
  26898. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26899. } else if (isArray(obj)) { // handle array
  26900. for (var i = 0; i < obj.length; i++) {
  26901. _removeBlobs(obj[i], i, obj);
  26902. }
  26903. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26904. for (var key in obj) {
  26905. _removeBlobs(obj[key], key, obj);
  26906. }
  26907. }
  26908. }
  26909. var pendingBlobs = 0;
  26910. var bloblessData = data;
  26911. _removeBlobs(bloblessData);
  26912. if (!pendingBlobs) {
  26913. callback(bloblessData);
  26914. }
  26915. };
  26916. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26917. },{"./is-buffer":126,"isarray":77}],125:[function(require,module,exports){
  26918. /**
  26919. * Module dependencies.
  26920. */
  26921. var debug = require('debug')('socket.io-parser');
  26922. var json = require('json3');
  26923. var isArray = require('isarray');
  26924. var Emitter = require('component-emitter');
  26925. var binary = require('./binary');
  26926. var isBuf = require('./is-buffer');
  26927. /**
  26928. * Protocol version.
  26929. *
  26930. * @api public
  26931. */
  26932. exports.protocol = 4;
  26933. /**
  26934. * Packet types.
  26935. *
  26936. * @api public
  26937. */
  26938. exports.types = [
  26939. 'CONNECT',
  26940. 'DISCONNECT',
  26941. 'EVENT',
  26942. 'BINARY_EVENT',
  26943. 'ACK',
  26944. 'BINARY_ACK',
  26945. 'ERROR'
  26946. ];
  26947. /**
  26948. * Packet type `connect`.
  26949. *
  26950. * @api public
  26951. */
  26952. exports.CONNECT = 0;
  26953. /**
  26954. * Packet type `disconnect`.
  26955. *
  26956. * @api public
  26957. */
  26958. exports.DISCONNECT = 1;
  26959. /**
  26960. * Packet type `event`.
  26961. *
  26962. * @api public
  26963. */
  26964. exports.EVENT = 2;
  26965. /**
  26966. * Packet type `ack`.
  26967. *
  26968. * @api public
  26969. */
  26970. exports.ACK = 3;
  26971. /**
  26972. * Packet type `error`.
  26973. *
  26974. * @api public
  26975. */
  26976. exports.ERROR = 4;
  26977. /**
  26978. * Packet type 'binary event'
  26979. *
  26980. * @api public
  26981. */
  26982. exports.BINARY_EVENT = 5;
  26983. /**
  26984. * Packet type `binary ack`. For acks with binary arguments.
  26985. *
  26986. * @api public
  26987. */
  26988. exports.BINARY_ACK = 6;
  26989. /**
  26990. * Encoder constructor.
  26991. *
  26992. * @api public
  26993. */
  26994. exports.Encoder = Encoder;
  26995. /**
  26996. * Decoder constructor.
  26997. *
  26998. * @api public
  26999. */
  27000. exports.Decoder = Decoder;
  27001. /**
  27002. * A socket.io Encoder instance
  27003. *
  27004. * @api public
  27005. */
  27006. function Encoder() {}
  27007. /**
  27008. * Encode a packet as a single string if non-binary, or as a
  27009. * buffer sequence, depending on packet type.
  27010. *
  27011. * @param {Object} obj - packet object
  27012. * @param {Function} callback - function to handle encodings (likely engine.write)
  27013. * @return Calls callback with Array of encodings
  27014. * @api public
  27015. */
  27016. Encoder.prototype.encode = function(obj, callback){
  27017. debug('encoding packet %j', obj);
  27018. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  27019. encodeAsBinary(obj, callback);
  27020. }
  27021. else {
  27022. var encoding = encodeAsString(obj);
  27023. callback([encoding]);
  27024. }
  27025. };
  27026. /**
  27027. * Encode packet as string.
  27028. *
  27029. * @param {Object} packet
  27030. * @return {String} encoded
  27031. * @api private
  27032. */
  27033. function encodeAsString(obj) {
  27034. var str = '';
  27035. var nsp = false;
  27036. // first is type
  27037. str += obj.type;
  27038. // attachments if we have them
  27039. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  27040. str += obj.attachments;
  27041. str += '-';
  27042. }
  27043. // if we have a namespace other than `/`
  27044. // we append it followed by a comma `,`
  27045. if (obj.nsp && '/' != obj.nsp) {
  27046. nsp = true;
  27047. str += obj.nsp;
  27048. }
  27049. // immediately followed by the id
  27050. if (null != obj.id) {
  27051. if (nsp) {
  27052. str += ',';
  27053. nsp = false;
  27054. }
  27055. str += obj.id;
  27056. }
  27057. // json data
  27058. if (null != obj.data) {
  27059. if (nsp) str += ',';
  27060. str += json.stringify(obj.data);
  27061. }
  27062. debug('encoded %j as %s', obj, str);
  27063. return str;
  27064. }
  27065. /**
  27066. * Encode packet as 'buffer sequence' by removing blobs, and
  27067. * deconstructing packet into object with placeholders and
  27068. * a list of buffers.
  27069. *
  27070. * @param {Object} packet
  27071. * @return {Buffer} encoded
  27072. * @api private
  27073. */
  27074. function encodeAsBinary(obj, callback) {
  27075. function writeEncoding(bloblessData) {
  27076. var deconstruction = binary.deconstructPacket(bloblessData);
  27077. var pack = encodeAsString(deconstruction.packet);
  27078. var buffers = deconstruction.buffers;
  27079. buffers.unshift(pack); // add packet info to beginning of data list
  27080. callback(buffers); // write all the buffers
  27081. }
  27082. binary.removeBlobs(obj, writeEncoding);
  27083. }
  27084. /**
  27085. * A socket.io Decoder instance
  27086. *
  27087. * @return {Object} decoder
  27088. * @api public
  27089. */
  27090. function Decoder() {
  27091. this.reconstructor = null;
  27092. }
  27093. /**
  27094. * Mix in `Emitter` with Decoder.
  27095. */
  27096. Emitter(Decoder.prototype);
  27097. /**
  27098. * Decodes an ecoded packet string into packet JSON.
  27099. *
  27100. * @param {String} obj - encoded packet
  27101. * @return {Object} packet
  27102. * @api public
  27103. */
  27104. Decoder.prototype.add = function(obj) {
  27105. var packet;
  27106. if ('string' == typeof obj) {
  27107. packet = decodeString(obj);
  27108. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  27109. this.reconstructor = new BinaryReconstructor(packet);
  27110. // no attachments, labeled binary but no binary data to follow
  27111. if (this.reconstructor.reconPack.attachments === 0) {
  27112. this.emit('decoded', packet);
  27113. }
  27114. } else { // non-binary full packet
  27115. this.emit('decoded', packet);
  27116. }
  27117. }
  27118. else if (isBuf(obj) || obj.base64) { // raw binary data
  27119. if (!this.reconstructor) {
  27120. throw new Error('got binary data when not reconstructing a packet');
  27121. } else {
  27122. packet = this.reconstructor.takeBinaryData(obj);
  27123. if (packet) { // received final buffer
  27124. this.reconstructor = null;
  27125. this.emit('decoded', packet);
  27126. }
  27127. }
  27128. }
  27129. else {
  27130. throw new Error('Unknown type: ' + obj);
  27131. }
  27132. };
  27133. /**
  27134. * Decode a packet String (JSON data)
  27135. *
  27136. * @param {String} str
  27137. * @return {Object} packet
  27138. * @api private
  27139. */
  27140. function decodeString(str) {
  27141. var p = {};
  27142. var i = 0;
  27143. // look up type
  27144. p.type = Number(str.charAt(0));
  27145. if (null == exports.types[p.type]) return error();
  27146. // look up attachments if type binary
  27147. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  27148. var buf = '';
  27149. while (str.charAt(++i) != '-') {
  27150. buf += str.charAt(i);
  27151. if (i == str.length) break;
  27152. }
  27153. if (buf != Number(buf) || str.charAt(i) != '-') {
  27154. throw new Error('Illegal attachments');
  27155. }
  27156. p.attachments = Number(buf);
  27157. }
  27158. // look up namespace (if any)
  27159. if ('/' == str.charAt(i + 1)) {
  27160. p.nsp = '';
  27161. while (++i) {
  27162. var c = str.charAt(i);
  27163. if (',' == c) break;
  27164. p.nsp += c;
  27165. if (i == str.length) break;
  27166. }
  27167. } else {
  27168. p.nsp = '/';
  27169. }
  27170. // look up id
  27171. var next = str.charAt(i + 1);
  27172. if ('' !== next && Number(next) == next) {
  27173. p.id = '';
  27174. while (++i) {
  27175. var c = str.charAt(i);
  27176. if (null == c || Number(c) != c) {
  27177. --i;
  27178. break;
  27179. }
  27180. p.id += str.charAt(i);
  27181. if (i == str.length) break;
  27182. }
  27183. p.id = Number(p.id);
  27184. }
  27185. // look up json data
  27186. if (str.charAt(++i)) {
  27187. try {
  27188. p.data = json.parse(str.substr(i));
  27189. } catch(e){
  27190. return error();
  27191. }
  27192. }
  27193. debug('decoded %s as %j', str, p);
  27194. return p;
  27195. }
  27196. /**
  27197. * Deallocates a parser's resources
  27198. *
  27199. * @api public
  27200. */
  27201. Decoder.prototype.destroy = function() {
  27202. if (this.reconstructor) {
  27203. this.reconstructor.finishedReconstruction();
  27204. }
  27205. };
  27206. /**
  27207. * A manager of a binary event's 'buffer sequence'. Should
  27208. * be constructed whenever a packet of type BINARY_EVENT is
  27209. * decoded.
  27210. *
  27211. * @param {Object} packet
  27212. * @return {BinaryReconstructor} initialized reconstructor
  27213. * @api private
  27214. */
  27215. function BinaryReconstructor(packet) {
  27216. this.reconPack = packet;
  27217. this.buffers = [];
  27218. }
  27219. /**
  27220. * Method to be called when binary data received from connection
  27221. * after a BINARY_EVENT packet.
  27222. *
  27223. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  27224. * @return {null | Object} returns null if more binary data is expected or
  27225. * a reconstructed packet object if all buffers have been received.
  27226. * @api private
  27227. */
  27228. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  27229. this.buffers.push(binData);
  27230. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  27231. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  27232. this.finishedReconstruction();
  27233. return packet;
  27234. }
  27235. return null;
  27236. };
  27237. /**
  27238. * Cleans up binary packet reconstruction variables.
  27239. *
  27240. * @api private
  27241. */
  27242. BinaryReconstructor.prototype.finishedReconstruction = function() {
  27243. this.reconPack = null;
  27244. this.buffers = [];
  27245. };
  27246. function error(data){
  27247. return {
  27248. type: exports.ERROR,
  27249. data: 'parser error'
  27250. };
  27251. }
  27252. },{"./binary":124,"./is-buffer":126,"component-emitter":53,"debug":55,"isarray":77,"json3":80}],126:[function(require,module,exports){
  27253. (function (global){
  27254. module.exports = isBuf;
  27255. /**
  27256. * Returns true if obj is a buffer or an arraybuffer.
  27257. *
  27258. * @api private
  27259. */
  27260. function isBuf(obj) {
  27261. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  27262. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  27263. }
  27264. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27265. },{}],127:[function(require,module,exports){
  27266. module.exports = toArray
  27267. function toArray(list, index) {
  27268. var array = []
  27269. index = index || 0
  27270. for (var i = index || 0; i < list.length; i++) {
  27271. array[i - index] = list[i]
  27272. }
  27273. return array
  27274. }
  27275. },{}],128:[function(require,module,exports){
  27276. (function (global){
  27277. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  27278. ;(function(root) {
  27279. // Detect free variables `exports`
  27280. var freeExports = typeof exports == 'object' && exports;
  27281. // Detect free variable `module`
  27282. var freeModule = typeof module == 'object' && module &&
  27283. module.exports == freeExports && module;
  27284. // Detect free variable `global`, from Node.js or Browserified code,
  27285. // and use it as `root`
  27286. var freeGlobal = typeof global == 'object' && global;
  27287. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  27288. root = freeGlobal;
  27289. }
  27290. /*--------------------------------------------------------------------------*/
  27291. var stringFromCharCode = String.fromCharCode;
  27292. // Taken from http://mths.be/punycode
  27293. function ucs2decode(string) {
  27294. var output = [];
  27295. var counter = 0;
  27296. var length = string.length;
  27297. var value;
  27298. var extra;
  27299. while (counter < length) {
  27300. value = string.charCodeAt(counter++);
  27301. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  27302. // high surrogate, and there is a next character
  27303. extra = string.charCodeAt(counter++);
  27304. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  27305. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  27306. } else {
  27307. // unmatched surrogate; only append this code unit, in case the next
  27308. // code unit is the high surrogate of a surrogate pair
  27309. output.push(value);
  27310. counter--;
  27311. }
  27312. } else {
  27313. output.push(value);
  27314. }
  27315. }
  27316. return output;
  27317. }
  27318. // Taken from http://mths.be/punycode
  27319. function ucs2encode(array) {
  27320. var length = array.length;
  27321. var index = -1;
  27322. var value;
  27323. var output = '';
  27324. while (++index < length) {
  27325. value = array[index];
  27326. if (value > 0xFFFF) {
  27327. value -= 0x10000;
  27328. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  27329. value = 0xDC00 | value & 0x3FF;
  27330. }
  27331. output += stringFromCharCode(value);
  27332. }
  27333. return output;
  27334. }
  27335. /*--------------------------------------------------------------------------*/
  27336. function createByte(codePoint, shift) {
  27337. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  27338. }
  27339. function encodeCodePoint(codePoint) {
  27340. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  27341. return stringFromCharCode(codePoint);
  27342. }
  27343. var symbol = '';
  27344. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  27345. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  27346. }
  27347. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  27348. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  27349. symbol += createByte(codePoint, 6);
  27350. }
  27351. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  27352. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  27353. symbol += createByte(codePoint, 12);
  27354. symbol += createByte(codePoint, 6);
  27355. }
  27356. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  27357. return symbol;
  27358. }
  27359. function utf8encode(string) {
  27360. var codePoints = ucs2decode(string);
  27361. // console.log(JSON.stringify(codePoints.map(function(x) {
  27362. // return 'U+' + x.toString(16).toUpperCase();
  27363. // })));
  27364. var length = codePoints.length;
  27365. var index = -1;
  27366. var codePoint;
  27367. var byteString = '';
  27368. while (++index < length) {
  27369. codePoint = codePoints[index];
  27370. byteString += encodeCodePoint(codePoint);
  27371. }
  27372. return byteString;
  27373. }
  27374. /*--------------------------------------------------------------------------*/
  27375. function readContinuationByte() {
  27376. if (byteIndex >= byteCount) {
  27377. throw Error('Invalid byte index');
  27378. }
  27379. var continuationByte = byteArray[byteIndex] & 0xFF;
  27380. byteIndex++;
  27381. if ((continuationByte & 0xC0) == 0x80) {
  27382. return continuationByte & 0x3F;
  27383. }
  27384. // If we end up here, it’s not a continuation byte
  27385. throw Error('Invalid continuation byte');
  27386. }
  27387. function decodeSymbol() {
  27388. var byte1;
  27389. var byte2;
  27390. var byte3;
  27391. var byte4;
  27392. var codePoint;
  27393. if (byteIndex > byteCount) {
  27394. throw Error('Invalid byte index');
  27395. }
  27396. if (byteIndex == byteCount) {
  27397. return false;
  27398. }
  27399. // Read first byte
  27400. byte1 = byteArray[byteIndex] & 0xFF;
  27401. byteIndex++;
  27402. // 1-byte sequence (no continuation bytes)
  27403. if ((byte1 & 0x80) == 0) {
  27404. return byte1;
  27405. }
  27406. // 2-byte sequence
  27407. if ((byte1 & 0xE0) == 0xC0) {
  27408. var byte2 = readContinuationByte();
  27409. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  27410. if (codePoint >= 0x80) {
  27411. return codePoint;
  27412. } else {
  27413. throw Error('Invalid continuation byte');
  27414. }
  27415. }
  27416. // 3-byte sequence (may include unpaired surrogates)
  27417. if ((byte1 & 0xF0) == 0xE0) {
  27418. byte2 = readContinuationByte();
  27419. byte3 = readContinuationByte();
  27420. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  27421. if (codePoint >= 0x0800) {
  27422. return codePoint;
  27423. } else {
  27424. throw Error('Invalid continuation byte');
  27425. }
  27426. }
  27427. // 4-byte sequence
  27428. if ((byte1 & 0xF8) == 0xF0) {
  27429. byte2 = readContinuationByte();
  27430. byte3 = readContinuationByte();
  27431. byte4 = readContinuationByte();
  27432. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  27433. (byte3 << 0x06) | byte4;
  27434. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  27435. return codePoint;
  27436. }
  27437. }
  27438. throw Error('Invalid UTF-8 detected');
  27439. }
  27440. var byteArray;
  27441. var byteCount;
  27442. var byteIndex;
  27443. function utf8decode(byteString) {
  27444. byteArray = ucs2decode(byteString);
  27445. byteCount = byteArray.length;
  27446. byteIndex = 0;
  27447. var codePoints = [];
  27448. var tmp;
  27449. while ((tmp = decodeSymbol()) !== false) {
  27450. codePoints.push(tmp);
  27451. }
  27452. return ucs2encode(codePoints);
  27453. }
  27454. /*--------------------------------------------------------------------------*/
  27455. var utf8 = {
  27456. 'version': '2.0.0',
  27457. 'encode': utf8encode,
  27458. 'decode': utf8decode
  27459. };
  27460. // Some AMD build optimizers, like r.js, check for specific condition patterns
  27461. // like the following:
  27462. if (
  27463. typeof define == 'function' &&
  27464. typeof define.amd == 'object' &&
  27465. define.amd
  27466. ) {
  27467. define(function() {
  27468. return utf8;
  27469. });
  27470. } else if (freeExports && !freeExports.nodeType) {
  27471. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  27472. freeModule.exports = utf8;
  27473. } else { // in Narwhal or RingoJS v0.7.0-
  27474. var object = {};
  27475. var hasOwnProperty = object.hasOwnProperty;
  27476. for (var key in utf8) {
  27477. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  27478. }
  27479. }
  27480. } else { // in Rhino or a web browser
  27481. root.utf8 = utf8;
  27482. }
  27483. }(this));
  27484. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27485. },{}],129:[function(require,module,exports){
  27486. /**
  27487. * Module dependencies.
  27488. */
  27489. var global = (function() { return this; })();
  27490. /**
  27491. * WebSocket constructor.
  27492. */
  27493. var WebSocket = global.WebSocket || global.MozWebSocket;
  27494. /**
  27495. * Module exports.
  27496. */
  27497. module.exports = WebSocket ? ws : null;
  27498. /**
  27499. * WebSocket constructor.
  27500. *
  27501. * The third `opts` options object gets ignored in web browsers, since it's
  27502. * non-standard, and throws a TypeError if passed to the constructor.
  27503. * See: https://github.com/einaros/ws/issues/227
  27504. *
  27505. * @param {String} uri
  27506. * @param {Array} protocols (optional)
  27507. * @param {Object) opts (optional)
  27508. * @api public
  27509. */
  27510. function ws(uri, protocols, opts) {
  27511. var instance;
  27512. if (protocols) {
  27513. instance = new WebSocket(uri, protocols);
  27514. } else {
  27515. instance = new WebSocket(uri);
  27516. }
  27517. return instance;
  27518. }
  27519. if (WebSocket) ws.prototype = WebSocket.prototype;
  27520. },{}],130:[function(require,module,exports){
  27521. var MediaStreamType = {
  27522. VIDEO_TYPE: "Video",
  27523. AUDIO_TYPE: "Audio"
  27524. };
  27525. module.exports = MediaStreamType;
  27526. },{}],131:[function(require,module,exports){
  27527. var RTCEvents = {
  27528. RTC_READY: "rtc.ready",
  27529. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27530. LASTN_CHANGED: "rtc.lastn_changed",
  27531. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27532. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27533. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27534. FAKE_VIDEO_TRACK_CREATED: "rtc.fake_video_track_created"
  27535. };
  27536. module.exports = RTCEvents;
  27537. },{}],132:[function(require,module,exports){
  27538. var Resolutions = {
  27539. "1080": {
  27540. width: 1920,
  27541. height: 1080,
  27542. order: 7
  27543. },
  27544. "fullhd": {
  27545. width: 1920,
  27546. height: 1080,
  27547. order: 7
  27548. },
  27549. "720": {
  27550. width: 1280,
  27551. height: 720,
  27552. order: 6
  27553. },
  27554. "hd": {
  27555. width: 1280,
  27556. height: 720,
  27557. order: 6
  27558. },
  27559. "960": {
  27560. width: 960,
  27561. height: 720,
  27562. order: 5
  27563. },
  27564. "640": {
  27565. width: 640,
  27566. height: 480,
  27567. order: 4
  27568. },
  27569. "vga": {
  27570. width: 640,
  27571. height: 480,
  27572. order: 4
  27573. },
  27574. "360": {
  27575. width: 640,
  27576. height: 360,
  27577. order: 3
  27578. },
  27579. "320": {
  27580. width: 320,
  27581. height: 240,
  27582. order: 2
  27583. },
  27584. "180": {
  27585. width: 320,
  27586. height: 180,
  27587. order: 1
  27588. }
  27589. };
  27590. module.exports = Resolutions;
  27591. },{}],133:[function(require,module,exports){
  27592. var AuthenticationEvents = {
  27593. /**
  27594. * Event callback arguments:
  27595. * function(authenticationEnabled, userIdentity)
  27596. * authenticationEnabled - indicates whether authentication has been enabled
  27597. * in this session
  27598. * userIdentity - if user has been logged in then it contains user name. If
  27599. * contains 'null' or 'undefined' then user is not logged in.
  27600. */
  27601. IDENTITY_UPDATED: "authentication.identity_updated"
  27602. };
  27603. module.exports = AuthenticationEvents;
  27604. },{}],134:[function(require,module,exports){
  27605. var DesktopSharingEventTypes = {
  27606. /**
  27607. * An event which indicates that the jidesha extension for Firefox is
  27608. * needed to proceed with screen sharing, and that it is not installed.
  27609. */
  27610. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27611. };
  27612. module.exports = DesktopSharingEventTypes;
  27613. },{}],135:[function(require,module,exports){
  27614. module.exports = {
  27615. /**
  27616. * An event carrying connection statistics.
  27617. */
  27618. CONNECTION_STATS: "statistics.connectionstats",
  27619. /**
  27620. * FIXME: needs documentation.
  27621. */
  27622. AUDIO_LEVEL: "statistics.audioLevel",
  27623. /**
  27624. * FIXME: needs documentation.
  27625. */
  27626. STOP: "statistics.stop"
  27627. };
  27628. },{}],136:[function(require,module,exports){
  27629. var Constants = {
  27630. LOCAL_JID: 'local'
  27631. };
  27632. module.exports = Constants;
  27633. },{}],137:[function(require,module,exports){
  27634. var XMPPEvents = {
  27635. // Designates an event indicating that the connection to the XMPP server
  27636. // failed.
  27637. CONNECTION_FAILED: "xmpp.connection.failed",
  27638. // Designates an event indicating that the media (ICE) connection was
  27639. // interrupted. This should go to the RTC module.
  27640. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27641. // Designates an event indicating that the media (ICE) connection was
  27642. // restored. This should go to the RTC module.
  27643. CONNECTION_RESTORED: "xmpp.connection.restored",
  27644. // Designates an event indicating that an offer (e.g. Jingle
  27645. // session-initiate) was received.
  27646. CALL_INCOMING: "xmpp.callincoming.jingle",
  27647. // Designates an event indicating that we were kicked from the XMPP MUC.
  27648. KICKED: "xmpp.kicked",
  27649. // Designates an event indicating that the userID for a specific JID has
  27650. // changed.
  27651. // Note: currently this event fires every time we receive presence from
  27652. // someone (regardless of whether or not the "userID" changed).
  27653. USER_ID_CHANGED: "xmpp.user_id_changed",
  27654. // Designates an event indicating that we have joined the XMPP MUC.
  27655. MUC_JOINED: "xmpp.muc_joined",
  27656. // Designates an event indicating that a participant joined the XMPP MUC.
  27657. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27658. // Designates an event indicating that a participant left the XMPP MUC.
  27659. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27660. // Designates an event indicating that the MUC role of a participant has
  27661. // changed.
  27662. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27663. // Designates an event indicating that the XMPP MUC was destroyed.
  27664. MUC_DESTROYED: "xmpp.muc_destroyed",
  27665. // Designates an event indicating that the display name of a participant
  27666. // has changed.
  27667. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27668. // Designates an event indicating that we received statistics from a
  27669. // participant in the MUC.
  27670. REMOTE_STATS: "xmpp.remote_stats",
  27671. // Designates an event indicating that our role in the XMPP MUC has changed.
  27672. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27673. // Designates an event indicating that the subject of the XMPP MUC has
  27674. // changed.
  27675. SUBJECT_CHANGED: "xmpp.subject_changed",
  27676. // Designates an event indicating that an XMPP message in the MUC was
  27677. // received.
  27678. MESSAGE_RECEIVED: "xmpp.message_received",
  27679. // Designates an event indicating that we sent an XMPP message to the MUC.
  27680. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27681. // Designates an event indicating that the video type (e.g. 'camera' or
  27682. // 'screen') for a participant has changed.
  27683. // Note: currently this event fires every time we receive presence from
  27684. // someone (regardless of whether or not the "video type" changed).
  27685. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  27686. // Designates an event indicating that a participant in the XMPP MUC has
  27687. // advertised that they have audio muted (or unmuted).
  27688. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  27689. // Designates an event indicating that a participant in the XMPP MUC has
  27690. // advertised that they have video muted (or unmuted).
  27691. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  27692. // Designates an event indicating that the focus has asked us to mute our
  27693. // audio.
  27694. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27695. // Designates an event indicating that we should join the conference with
  27696. // audio and/or video muted.
  27697. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27698. // Designates an event indicating that a remote participant's available
  27699. // devices (whether he supports a audio and/or video) changed.
  27700. // Note: currently this event fires every time we receive presence from
  27701. // someone (regardless of whether or not the devices changed).
  27702. DEVICE_AVAILABLE: "xmpp.device_available",
  27703. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27704. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27705. PASSWORD_REQUIRED: "xmpp.password_required",
  27706. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27707. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27708. ETHERPAD: "xmpp.etherpad",
  27709. BRIDGE_DOWN: "xmpp.bridge_down",
  27710. PRESENCE_STATUS: "xmpp.presence_status",
  27711. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27712. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27713. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27714. // TODO: only used in a hack, should probably be removed.
  27715. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27716. // TODO: only used in a hack, should probably be removed.
  27717. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27718. // TODO: only used in a hack, should probably be removed.
  27719. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27720. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27721. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27722. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27723. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27724. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27725. // xmpp is connected and obtained user media
  27726. READY_TO_JOIN: 'xmpp.ready_to_join',
  27727. FOCUS_LEFT: "xmpp.focus_left",
  27728. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  27729. /**
  27730. * Indicates that recording state changed.
  27731. */
  27732. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  27733. /**
  27734. * Indicates that phone number changed.
  27735. */
  27736. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  27737. /**
  27738. * Indicates error while create offer call.
  27739. */
  27740. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  27741. /**
  27742. * Indicates error while create answer call.
  27743. */
  27744. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  27745. /**
  27746. * Indicates error while set local description.
  27747. */
  27748. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  27749. /**
  27750. * Indicates error while set remote description.
  27751. */
  27752. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  27753. /**
  27754. * Indicates error while adding ice candidate.
  27755. */
  27756. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  27757. };
  27758. module.exports = XMPPEvents;
  27759. },{}]},{},[7])(7)
  27760. });