Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824
  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.APP = 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. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  13. this.xmpp = require("./modules/xmpp/xmpp");
  14. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  15. this.translation = require("./modules/translation/translation");
  16. this.settings = require("./modules/settings/Settings");
  17. this.DTMF = require("./modules/DTMF/DTMF");
  18. this.members = require("./modules/members/MemberList");
  19. this.configFetch = require("./modules/config/HttpConfigFetch");
  20. }
  21. };
  22. function init() {
  23. APP.desktopsharing.init();
  24. APP.RTC.start();
  25. APP.xmpp.start();
  26. APP.statistics.start();
  27. APP.connectionquality.init();
  28. APP.keyboardshortcut.init();
  29. APP.members.start();
  30. }
  31. /**
  32. * If we have HTTP endpoint for getting confgi.json configured we're going to
  33. * read it and override properties from config.js and interfaceConfig.js.
  34. * If there is no endpoint we'll just continue with initialization.
  35. * Keep in mind that if the endpoint has been configured and we fail to obtain
  36. * the config for any reason then the conference won't start and error message
  37. * will be displayed to the user.
  38. */
  39. function obtainConfigAndInit() {
  40. if (config.configLocation) {
  41. APP.configFetch.obtainConfig(
  42. config.configLocation, APP.UI.getRoomNode(),
  43. // Get config result callback
  44. function(success, error) {
  45. if (success) {
  46. init();
  47. } else {
  48. // Show obtain config error,
  49. // pass the error object for report
  50. APP.UI.messageHandler.openReportDialog(
  51. null, "dialog.connectError", error);
  52. }
  53. });
  54. } else {
  55. init();
  56. }
  57. }
  58. $(document).ready(function () {
  59. var URLProcessor = require("./modules/config/URLProcessor");
  60. URLProcessor.setConfigParametersFromUrl();
  61. APP.init();
  62. APP.translation.init();
  63. if(APP.API.isEnabled())
  64. APP.API.init();
  65. APP.UI.start(obtainConfigAndInit);
  66. });
  67. $(window).bind('beforeunload', function () {
  68. if(APP.API.isEnabled())
  69. APP.API.dispose();
  70. });
  71. module.exports = APP;
  72. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":11,"./modules/config/HttpConfigFetch":42,"./modules/config/URLProcessor":43,"./modules/connectionquality/connectionquality":45,"./modules/desktopsharing/desktopsharing":46,"./modules/keyboardshortcut/keyboardshortcut":47,"./modules/members/MemberList":48,"./modules/settings/Settings":49,"./modules/statistics/statistics":53,"./modules/translation/translation":54,"./modules/xmpp/xmpp":71}],2:[function(require,module,exports){
  73. /* global APP */
  74. /**
  75. * Implements API class that communicates with external api class
  76. * and provides interface to access Jitsi Meet features by external
  77. * applications that embed Jitsi Meet
  78. */
  79. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  80. /**
  81. * List of the available commands.
  82. * @type {{
  83. * displayName: inputDisplayNameHandler,
  84. * toggleAudio: toggleAudio,
  85. * toggleVideo: toggleVideo,
  86. * toggleFilmStrip: toggleFilmStrip,
  87. * toggleChat: toggleChat,
  88. * toggleContactList: toggleContactList
  89. * }}
  90. */
  91. var commands = {};
  92. function initCommands() {
  93. commands = {
  94. displayName: APP.UI.inputDisplayNameHandler,
  95. toggleAudio: APP.UI.toggleAudio,
  96. toggleVideo: APP.UI.toggleVideo,
  97. toggleFilmStrip: APP.UI.toggleFilmStrip,
  98. toggleChat: APP.UI.toggleChat,
  99. toggleContactList: APP.UI.toggleContactList
  100. };
  101. }
  102. /**
  103. * Maps the supported events and their status
  104. * (true it the event is enabled and false if it is disabled)
  105. * @type {{
  106. * incomingMessage: boolean,
  107. * outgoingMessage: boolean,
  108. * displayNameChange: boolean,
  109. * participantJoined: boolean,
  110. * participantLeft: boolean
  111. * }}
  112. */
  113. var events = {
  114. incomingMessage: false,
  115. outgoingMessage:false,
  116. displayNameChange: false,
  117. participantJoined: false,
  118. participantLeft: false
  119. };
  120. var displayName = {};
  121. /**
  122. * Processes commands from external application.
  123. * @param message the object with the command
  124. */
  125. function processCommand(message) {
  126. if (message.action != "execute") {
  127. console.error("Unknown action of the message");
  128. return;
  129. }
  130. for (var key in message) {
  131. if(commands[key])
  132. commands[key].apply(null, message[key]);
  133. }
  134. }
  135. /**
  136. * Processes events objects from external applications
  137. * @param event the event
  138. */
  139. function processEvent(event) {
  140. if (!event.action) {
  141. console.error("Event with no action is received.");
  142. return;
  143. }
  144. var i = 0;
  145. switch(event.action) {
  146. case "add":
  147. for (; i < event.events.length; i++) {
  148. events[event.events[i]] = true;
  149. }
  150. break;
  151. case "remove":
  152. for (; i < event.events.length; i++) {
  153. events[event.events[i]] = false;
  154. }
  155. break;
  156. default:
  157. console.error("Unknown action for event.");
  158. }
  159. }
  160. /**
  161. * Sends message to the external application.
  162. * @param object
  163. */
  164. function sendMessage(object) {
  165. window.parent.postMessage(JSON.stringify(object), "*");
  166. }
  167. /**
  168. * Processes a message event from the external application
  169. * @param event the message event
  170. */
  171. function processMessage(event) {
  172. var message;
  173. try {
  174. message = JSON.parse(event.data);
  175. } catch (e) {}
  176. if(!message.type)
  177. return;
  178. switch (message.type) {
  179. case "command":
  180. processCommand(message);
  181. break;
  182. case "event":
  183. processEvent(message);
  184. break;
  185. default:
  186. console.error("Unknown type of the message");
  187. return;
  188. }
  189. }
  190. function setupListeners() {
  191. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  192. API.triggerEvent("participantJoined", {jid: from});
  193. });
  194. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  195. if (from != myjid)
  196. API.triggerEvent("incomingMessage",
  197. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  198. });
  199. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  200. API.triggerEvent("participantLeft", {jid: jid});
  201. });
  202. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  203. var name = displayName[jid];
  204. if(!name || name != newDisplayName) {
  205. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  206. displayName[jid] = newDisplayName;
  207. }
  208. });
  209. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  210. APP.API.triggerEvent("outgoingMessage", {"message": body});
  211. });
  212. }
  213. var API = {
  214. /**
  215. * Check whether the API should be enabled or not.
  216. * @returns {boolean}
  217. */
  218. isEnabled: function () {
  219. var hash = location.hash;
  220. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  221. return true;
  222. return false;
  223. },
  224. /**
  225. * Initializes the APIConnector. Setups message event listeners that will
  226. * receive information from external applications that embed Jitsi Meet.
  227. * It also sends a message to the external application that APIConnector
  228. * is initialized.
  229. */
  230. init: function () {
  231. initCommands();
  232. if (window.addEventListener) {
  233. window.addEventListener('message',
  234. processMessage, false);
  235. }
  236. else {
  237. window.attachEvent('onmessage', processMessage);
  238. }
  239. sendMessage({type: "system", loaded: true});
  240. setupListeners();
  241. },
  242. /**
  243. * Checks whether the event is enabled ot not.
  244. * @param name the name of the event.
  245. * @returns {*}
  246. */
  247. isEventEnabled: function (name) {
  248. return events[name];
  249. },
  250. /**
  251. * Sends event object to the external application that has been subscribed
  252. * for that event.
  253. * @param name the name event
  254. * @param object data associated with the event
  255. */
  256. triggerEvent: function (name, object) {
  257. if(this.isEnabled() && this.isEventEnabled(name))
  258. sendMessage({
  259. type: "event", action: "result", event: name, result: object});
  260. },
  261. /**
  262. * Removes the listeners.
  263. */
  264. dispose: function () {
  265. if(window.removeEventListener) {
  266. window.removeEventListener("message",
  267. processMessage, false);
  268. }
  269. else {
  270. window.detachEvent('onmessage', processMessage);
  271. }
  272. }
  273. };
  274. module.exports = API;
  275. },{"../../service/xmpp/XMPPEvents":172}],3:[function(require,module,exports){
  276. /* global APP */
  277. /**
  278. * A module for sending DTMF tones.
  279. */
  280. var DTMFSender;
  281. var initDtmfSender = function() {
  282. // TODO: This needs to reset this if the peerconnection changes
  283. // (e.g. the call is re-made)
  284. if (DTMFSender)
  285. return;
  286. var localAudio = APP.RTC.localAudio;
  287. if (localAudio && localAudio.getTracks().length > 0)
  288. {
  289. var peerconnection
  290. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  291. if (peerconnection) {
  292. DTMFSender =
  293. peerconnection.peerconnection
  294. .createDTMFSender(localAudio.getTracks()[0]);
  295. console.log("Initialized DTMFSender");
  296. }
  297. else {
  298. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  299. }
  300. }
  301. else {
  302. console.log("Failed to initialize DTMFSender: no audio track.");
  303. }
  304. };
  305. var DTMF = {
  306. sendTones: function (tones, duration, pause) {
  307. if (!DTMFSender)
  308. initDtmfSender();
  309. if (DTMFSender){
  310. DTMFSender.insertDTMF(tones,
  311. (duration || 200),
  312. (pause || 200));
  313. }
  314. }
  315. };
  316. module.exports = DTMF;
  317. },{}],4:[function(require,module,exports){
  318. /* global config, APP, Strophe */
  319. // cache datachannels to avoid garbage collection
  320. // https://code.google.com/p/chromium/issues/detail?id=405545
  321. var RTCEvents = require("../../service/RTC/RTCEvents");
  322. var _dataChannels = [];
  323. var eventEmitter = null;
  324. var DataChannels = {
  325. /**
  326. * Callback triggered by PeerConnection when new data channel is opened
  327. * on the bridge.
  328. * @param event the event info object.
  329. */
  330. onDataChannel: function (event) {
  331. var dataChannel = event.channel;
  332. dataChannel.onopen = function () {
  333. console.info("Data channel opened by the Videobridge!", dataChannel);
  334. // Code sample for sending string and/or binary data
  335. // Sends String message to the bridge
  336. //dataChannel.send("Hello bridge!");
  337. // Sends 12 bytes binary message to the bridge
  338. //dataChannel.send(new ArrayBuffer(12));
  339. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  340. };
  341. dataChannel.onerror = function (error) {
  342. console.error("Data Channel Error:", error, dataChannel);
  343. };
  344. dataChannel.onmessage = function (event) {
  345. var data = event.data;
  346. // JSON
  347. var obj;
  348. try {
  349. obj = JSON.parse(data);
  350. }
  351. catch (e) {
  352. console.error(
  353. "Failed to parse data channel message as JSON: ",
  354. data,
  355. dataChannel);
  356. }
  357. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  358. var colibriClass = obj.colibriClass;
  359. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  360. // Endpoint ID from the Videobridge.
  361. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  362. console.info(
  363. "Data channel new dominant speaker event: ",
  364. dominantSpeakerEndpoint);
  365. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  366. }
  367. else if ("InLastNChangeEvent" === colibriClass) {
  368. var oldValue = obj.oldValue;
  369. var newValue = obj.newValue;
  370. // Make sure that oldValue and newValue are of type boolean.
  371. var type;
  372. if ((type = typeof oldValue) !== 'boolean') {
  373. if (type === 'string') {
  374. oldValue = (oldValue == "true");
  375. } else {
  376. oldValue = new Boolean(oldValue).valueOf();
  377. }
  378. }
  379. if ((type = typeof newValue) !== 'boolean') {
  380. if (type === 'string') {
  381. newValue = (newValue == "true");
  382. } else {
  383. newValue = new Boolean(newValue).valueOf();
  384. }
  385. }
  386. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  387. }
  388. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  389. // The new/latest list of last-n endpoint IDs.
  390. var lastNEndpoints = obj.lastNEndpoints;
  391. // The list of endpoint IDs which are entering the list of
  392. // last-n at this time i.e. were not in the old list of last-n
  393. // endpoint IDs.
  394. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  395. console.log(
  396. "Data channel new last-n event: ",
  397. lastNEndpoints, endpointsEnteringLastN, obj);
  398. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  399. lastNEndpoints, endpointsEnteringLastN, obj);
  400. }
  401. else {
  402. console.debug("Data channel JSON-formatted message: ", obj);
  403. }
  404. }
  405. };
  406. dataChannel.onclose = function () {
  407. console.info("The Data Channel closed", dataChannel);
  408. var idx = _dataChannels.indexOf(dataChannel);
  409. if (idx > -1)
  410. _dataChannels = _dataChannels.splice(idx, 1);
  411. };
  412. _dataChannels.push(dataChannel);
  413. },
  414. /**
  415. * Binds "ondatachannel" event listener to given PeerConnection instance.
  416. * @param peerConnection WebRTC peer connection instance.
  417. */
  418. init: function (peerConnection, emitter) {
  419. if(!config.openSctp)
  420. return;
  421. peerConnection.ondatachannel = this.onDataChannel;
  422. eventEmitter = emitter;
  423. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  424. // Although it's not a requirement to open separate channels from both bridge
  425. // and peer as single channel can be used for sending and receiving data.
  426. // So either channel opened by the bridge or the one opened here is enough
  427. // for communication with the bridge.
  428. /*var dataChannelOptions =
  429. {
  430. reliable: true
  431. };
  432. var dataChannel
  433. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  434. // Can be used only when is in open state
  435. dataChannel.onopen = function ()
  436. {
  437. dataChannel.send("My channel !!!");
  438. };
  439. dataChannel.onmessage = function (event)
  440. {
  441. var msgData = event.data;
  442. console.info("Got My Data Channel Message:", msgData, dataChannel);
  443. };*/
  444. },
  445. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  446. handlePinnedEndpointEvent: onPinnedEndpointChanged
  447. };
  448. function onSelectedEndpointChanged(userResource) {
  449. console.log('selected endpoint changed: ', userResource);
  450. if (_dataChannels && _dataChannels.length != 0) {
  451. _dataChannels.some(function (dataChannel) {
  452. if (dataChannel.readyState == 'open') {
  453. console.log('sending selected endpoint changed ' +
  454. 'notification to the bridge: ', userResource);
  455. dataChannel.send(JSON.stringify({
  456. 'colibriClass': 'SelectedEndpointChangedEvent',
  457. 'selectedEndpoint':
  458. (!userResource || userResource === null)?
  459. null : userResource
  460. }));
  461. return true;
  462. }
  463. });
  464. }
  465. }
  466. function onPinnedEndpointChanged(userResource) {
  467. console.log('pinned endpoint changed: ', userResource);
  468. if (_dataChannels && _dataChannels.length != 0) {
  469. _dataChannels.some(function (dataChannel) {
  470. if (dataChannel.readyState == 'open') {
  471. dataChannel.send(JSON.stringify({
  472. 'colibriClass': 'PinnedEndpointChangedEvent',
  473. 'pinnedEndpoint':
  474. (!userResource || userResource == null)?
  475. null : userResource
  476. }));
  477. return true;
  478. }
  479. });
  480. }
  481. }
  482. module.exports = DataChannels;
  483. },{"../../service/RTC/RTCEvents":163}],5:[function(require,module,exports){
  484. /* global APP */
  485. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  486. var RTCEvents = require("../../service/RTC/RTCEvents");
  487. var RTCBrowserType = require("./RTCBrowserType");
  488. /**
  489. * This implements 'onended' callback normally fired by WebRTC after the stream
  490. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  491. * @param stream original WebRTC stream object to which 'onended' handling
  492. * will be added.
  493. */
  494. function implementOnEndedHandling(stream) {
  495. var originalStop = stream.stop;
  496. stream.stop = function () {
  497. originalStop.apply(stream);
  498. if (!stream.ended) {
  499. stream.ended = true;
  500. stream.onended();
  501. }
  502. };
  503. }
  504. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  505. this.stream = stream;
  506. this.eventEmitter = eventEmitter;
  507. this.type = type;
  508. this.videoType = videoType;
  509. this.isGUMStream = true;
  510. if(isGUMStream === false)
  511. this.isGUMStream = isGUMStream;
  512. var self = this;
  513. if(type == "audio") {
  514. this.getTracks = function () {
  515. return self.stream.getAudioTracks();
  516. };
  517. } else {
  518. this.getTracks = function () {
  519. return self.stream.getVideoTracks();
  520. };
  521. }
  522. this.stream.onended = function () {
  523. self.streamEnded();
  524. };
  525. if (RTCBrowserType.isFirefox()) {
  526. implementOnEndedHandling(this.stream);
  527. }
  528. }
  529. LocalStream.prototype.streamEnded = function () {
  530. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  531. };
  532. LocalStream.prototype.getOriginalStream = function()
  533. {
  534. return this.stream;
  535. };
  536. LocalStream.prototype.isAudioStream = function () {
  537. return this.type === "audio";
  538. };
  539. LocalStream.prototype.setMute = function (mute)
  540. {
  541. var isAudio = this.isAudioStream();
  542. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  543. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  544. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  545. // FIXME FF does not support 'removeStream' method used to mute
  546. RTCBrowserType.isFirefox()) {
  547. var tracks = this.getTracks();
  548. for (var idx = 0; idx < tracks.length; idx++) {
  549. tracks[idx].enabled = !mute;
  550. }
  551. this.eventEmitter.emit(eventType, mute);
  552. } else {
  553. if (mute) {
  554. APP.xmpp.removeStream(this.stream);
  555. this.stream.stop();
  556. this.eventEmitter.emit(eventType, true);
  557. } else {
  558. var self = this;
  559. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  560. (this.isAudioStream() ? ["audio"] : ["video"]),
  561. function (stream) {
  562. if (isAudio) {
  563. APP.RTC.changeLocalAudio(stream,
  564. function () {
  565. self.eventEmitter.emit(eventType, false);
  566. });
  567. } else {
  568. APP.RTC.changeLocalVideo(stream, false,
  569. function () {
  570. self.eventEmitter.emit(eventType, false);
  571. });
  572. }
  573. });
  574. }
  575. }
  576. };
  577. LocalStream.prototype.isMuted = function () {
  578. var tracks = [];
  579. if (this.isAudioStream()) {
  580. tracks = this.stream.getAudioTracks();
  581. } else {
  582. if (this.stream.ended)
  583. return true;
  584. tracks = this.stream.getVideoTracks();
  585. }
  586. for (var idx = 0; idx < tracks.length; idx++) {
  587. if(tracks[idx].enabled)
  588. return false;
  589. }
  590. return true;
  591. };
  592. LocalStream.prototype.getId = function () {
  593. return this.stream.getTracks()[0].id;
  594. };
  595. module.exports = LocalStream;
  596. },{"../../service/RTC/RTCEvents":163,"../../service/RTC/StreamEventTypes.js":165,"./RTCBrowserType":8}],6:[function(require,module,exports){
  597. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  598. /**
  599. * Creates a MediaStream object for the given data, session id and ssrc.
  600. * It is a wrapper class for the MediaStream.
  601. *
  602. * @param data the data object from which we obtain the stream,
  603. * the peerjid, etc.
  604. * @param sid the session id
  605. * @param ssrc the ssrc corresponding to this MediaStream
  606. * @param mute the whether this MediaStream is muted
  607. *
  608. * @constructor
  609. */
  610. function MediaStream(data, sid, ssrc, browser, eventEmitter, mute) {
  611. // XXX(gp) to minimize headaches in the future, we should build our
  612. // abstractions around tracks and not streams. ORTC is track based API.
  613. // Mozilla expects m-lines to represent media tracks.
  614. //
  615. // Practically, what I'm saying is that we should have a MediaTrack class
  616. // and not a MediaStream class.
  617. //
  618. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  619. // a track might have an associated RTX and FEC sources.
  620. this.sid = sid;
  621. this.stream = data.stream;
  622. this.peerjid = data.peerjid;
  623. this.videoType = data.videoType;
  624. this.ssrc = ssrc;
  625. this.type = (this.stream.getVideoTracks().length > 0)?
  626. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  627. this.muted = mute;
  628. this.eventEmitter = eventEmitter;
  629. }
  630. MediaStream.prototype.getOriginalStream = function() {
  631. return this.stream;
  632. };
  633. MediaStream.prototype.setMute = function (value) {
  634. this.stream.muted = value;
  635. this.muted = value;
  636. };
  637. module.exports = MediaStream;
  638. },{"../../service/RTC/MediaStreamTypes":162}],7:[function(require,module,exports){
  639. /* global APP */
  640. var EventEmitter = require("events");
  641. var RTCBrowserType = require("./RTCBrowserType");
  642. var RTCUtils = require("./RTCUtils.js");
  643. var LocalStream = require("./LocalStream.js");
  644. var DataChannels = require("./DataChannels");
  645. var MediaStream = require("./MediaStream.js");
  646. var DesktopSharingEventTypes
  647. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  648. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  649. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  650. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  651. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  652. var UIEvents = require("../../service/UI/UIEvents");
  653. var eventEmitter = new EventEmitter();
  654. function getMediaStreamUsage()
  655. {
  656. var result = {
  657. audio: true,
  658. video: true
  659. };
  660. /** There are some issues with the desktop sharing
  661. * when this property is enabled.
  662. * WARNING: We must change the implementation to start video/audio if we
  663. * receive from the focus that the peer is not muted.
  664. var isSecureConnection = window.location.protocol == "https:";
  665. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  666. {
  667. result = {
  668. audio: false,
  669. video: false
  670. };
  671. }
  672. **/
  673. return result;
  674. }
  675. var RTC = {
  676. rtcUtils: null,
  677. devices: {
  678. audio: true,
  679. video: true
  680. },
  681. localStreams: [],
  682. remoteStreams: {},
  683. localAudio: null,
  684. localVideo: null,
  685. addStreamListener: function (listener, eventType) {
  686. eventEmitter.on(eventType, listener);
  687. },
  688. addListener: function (type, listener) {
  689. eventEmitter.on(type, listener);
  690. },
  691. removeStreamListener: function (listener, eventType) {
  692. if(!(eventType instanceof StreamEventTypes))
  693. throw "Illegal argument";
  694. eventEmitter.removeListener(eventType, listener);
  695. },
  696. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  697. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  698. //in firefox we have only one stream object
  699. if(this.localStreams.length == 0 ||
  700. this.localStreams[0].getOriginalStream() != stream)
  701. this.localStreams.push(localStream);
  702. if(isMuted === true)
  703. localStream.setMute(true);
  704. if(type == "audio") {
  705. this.localAudio = localStream;
  706. } else {
  707. this.localVideo = localStream;
  708. }
  709. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  710. if(change)
  711. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  712. eventEmitter.emit(eventType, localStream, isMuted);
  713. return localStream;
  714. },
  715. removeLocalStream: function (stream) {
  716. for(var i = 0; i < this.localStreams.length; i++) {
  717. if(this.localStreams[i].getOriginalStream() === stream) {
  718. delete this.localStreams[i];
  719. return;
  720. }
  721. }
  722. },
  723. createRemoteStream: function (data, sid, thessrc) {
  724. var jid = data.peerjid || APP.xmpp.myJid();
  725. // check the video muted state from last stored presence if any
  726. var muted = false;
  727. var pres = APP.xmpp.getLastPresence(jid);
  728. if(pres != null && pres.videoMuted) {
  729. muted = pres.videoMuted;
  730. }
  731. var remoteStream = new MediaStream(data, sid, thessrc,
  732. RTCBrowserType.getBrowserType(), eventEmitter, muted);
  733. if(!this.remoteStreams[jid]) {
  734. this.remoteStreams[jid] = {};
  735. }
  736. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  737. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  738. return remoteStream;
  739. },
  740. getPCConstraints: function () {
  741. return this.rtcUtils.pc_constraints;
  742. },
  743. getUserMediaWithConstraints:function(um, success_callback,
  744. failure_callback, resolution,
  745. bandwidth, fps, desktopStream)
  746. {
  747. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  748. failure_callback, resolution, bandwidth, fps, desktopStream);
  749. },
  750. attachMediaStream: function (elSelector, stream) {
  751. this.rtcUtils.attachMediaStream(elSelector, stream);
  752. },
  753. getStreamID: function (stream) {
  754. return this.rtcUtils.getStreamID(stream);
  755. },
  756. getVideoSrc: function (element) {
  757. return this.rtcUtils.getVideoSrc(element);
  758. },
  759. setVideoSrc: function (element, src) {
  760. this.rtcUtils.setVideoSrc(element, src);
  761. },
  762. getVideoElementName: function () {
  763. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  764. },
  765. dispose: function() {
  766. if (this.rtcUtils) {
  767. this.rtcUtils = null;
  768. }
  769. },
  770. stop: function () {
  771. this.dispose();
  772. },
  773. start: function () {
  774. var self = this;
  775. APP.desktopsharing.addListener(
  776. function (stream, isUsingScreenStream, callback) {
  777. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  778. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  779. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  780. DataChannels.init(event.peerconnection, eventEmitter);
  781. });
  782. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  783. DataChannels.handleSelectedEndpointEvent);
  784. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  785. DataChannels.handlePinnedEndpointEvent);
  786. // In case of IE we continue from 'onReady' callback
  787. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  788. // once it is initialized.
  789. var onReady = function () {
  790. eventEmitter.emit(RTCEvents.RTC_READY, true);
  791. self.rtcUtils.obtainAudioAndVideoPermissions(
  792. null, null, getMediaStreamUsage());
  793. };
  794. this.rtcUtils = new RTCUtils(this, onReady);
  795. // Call onReady() if Temasys plugin is not used
  796. if (!RTCBrowserType.isTemasysPluginUsed()) {
  797. onReady();
  798. }
  799. },
  800. muteRemoteVideoStream: function (jid, value) {
  801. var stream;
  802. if(this.remoteStreams[jid] &&
  803. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  804. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  805. }
  806. if(!stream)
  807. return true;
  808. if (value != stream.muted) {
  809. stream.setMute(value);
  810. return true;
  811. }
  812. return false;
  813. },
  814. switchVideoStreams: function (new_stream) {
  815. this.localVideo.stream = new_stream;
  816. this.localStreams = [];
  817. //in firefox we have only one stream object
  818. if (this.localAudio.getOriginalStream() != new_stream)
  819. this.localStreams.push(this.localAudio);
  820. this.localStreams.push(this.localVideo);
  821. },
  822. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  823. var oldStream = this.localVideo.getOriginalStream();
  824. var type = (isUsingScreenStream ? "screen" : "camera");
  825. var localCallback = callback;
  826. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  827. localCallback = function() {
  828. APP.xmpp.setVideoMute(false, function(mute) {
  829. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  830. });
  831. callback();
  832. };
  833. }
  834. // FIXME: Workaround for FF/IE/Safari
  835. if (stream && stream.videoStream) {
  836. stream = stream.videoStream;
  837. }
  838. var videoStream = this.rtcUtils.createStream(stream, true);
  839. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  840. // Stop the stream to trigger onended event for old stream
  841. oldStream.stop();
  842. this.switchVideoStreams(videoStream, oldStream);
  843. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  844. },
  845. changeLocalAudio: function (stream, callback) {
  846. var oldStream = this.localAudio.getOriginalStream();
  847. var newStream = this.rtcUtils.createStream(stream);
  848. this.localAudio = this.createLocalStream(newStream, "audio", true);
  849. // Stop the stream to trigger onended event for old stream
  850. oldStream.stop();
  851. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  852. },
  853. isVideoMuted: function (jid) {
  854. if (jid === APP.xmpp.myJid()) {
  855. var localVideo = APP.RTC.localVideo;
  856. return (!localVideo || localVideo.isMuted());
  857. } else {
  858. if (!APP.RTC.remoteStreams[jid] ||
  859. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  860. return null;
  861. }
  862. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  863. }
  864. },
  865. setVideoMute: function (mute, callback, options) {
  866. if (!this.localVideo)
  867. return;
  868. if (mute == APP.RTC.localVideo.isMuted())
  869. {
  870. APP.xmpp.sendVideoInfoPresence(mute);
  871. if (callback)
  872. callback(mute);
  873. }
  874. else
  875. {
  876. APP.RTC.localVideo.setMute(mute);
  877. APP.xmpp.setVideoMute(
  878. mute,
  879. callback,
  880. options);
  881. }
  882. },
  883. setDeviceAvailability: function (devices) {
  884. if(!devices)
  885. return;
  886. if(devices.audio === true || devices.audio === false)
  887. this.devices.audio = devices.audio;
  888. if(devices.video === true || devices.video === false)
  889. this.devices.video = devices.video;
  890. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  891. }
  892. };
  893. module.exports = RTC;
  894. },{"../../service/RTC/MediaStreamTypes":162,"../../service/RTC/RTCEvents.js":163,"../../service/RTC/StreamEventTypes.js":165,"../../service/UI/UIEvents":166,"../../service/desktopsharing/DesktopSharingEventTypes":169,"../../service/xmpp/XMPPEvents":172,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCBrowserType":8,"./RTCUtils.js":9,"events":173}],8:[function(require,module,exports){
  895. var currentBrowser;
  896. var browserVersion;
  897. var isAndroid;
  898. var RTCBrowserType = {
  899. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  900. RTC_BROWSER_OPERA: "rtc_browser.opera",
  901. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  902. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  903. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  904. getBrowserType: function () {
  905. return currentBrowser;
  906. },
  907. isChrome: function () {
  908. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  909. },
  910. isOpera: function () {
  911. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  912. },
  913. isFirefox: function () {
  914. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  915. },
  916. isIExplorer: function () {
  917. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  918. },
  919. isSafari: function () {
  920. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  921. },
  922. isTemasysPluginUsed: function () {
  923. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  924. },
  925. getFirefoxVersion: function () {
  926. return RTCBrowserType.isFirefox() ? browserVersion : null;
  927. },
  928. getChromeVersion: function () {
  929. return RTCBrowserType.isChrome() ? browserVersion : null;
  930. },
  931. usesPlanB: function() {
  932. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  933. RTCBrowserType.isTemasysPluginUsed();
  934. },
  935. usesUnifiedPlan: function() {
  936. return RTCBrowserType.isFirefox();
  937. },
  938. /**
  939. * Whether the browser is running on an android device.
  940. */
  941. isAndroid: function() {
  942. return isAndroid;
  943. }
  944. // Add version getters for other browsers when needed
  945. };
  946. // detectOpera() must be called before detectChrome() !!!
  947. // otherwise Opera wil be detected as Chrome
  948. function detectChrome() {
  949. if (navigator.webkitGetUserMedia) {
  950. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  951. var userAgent = navigator.userAgent.toLowerCase();
  952. // We can assume that user agent is chrome, because it's
  953. // enforced when 'ext' streaming method is set
  954. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  955. console.log("This appears to be Chrome, ver: " + ver);
  956. return ver;
  957. }
  958. return null;
  959. }
  960. function detectOpera() {
  961. var userAgent = navigator.userAgent;
  962. if (userAgent.match(/Opera|OPR/)) {
  963. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  964. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  965. console.info("This appears to be Opera, ver: " + version);
  966. return version;
  967. }
  968. return null;
  969. }
  970. function detectFirefox() {
  971. if (navigator.mozGetUserMedia) {
  972. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  973. var version = parseInt(
  974. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  975. console.log('This appears to be Firefox, ver: ' + version);
  976. return version;
  977. }
  978. return null;
  979. }
  980. function detectSafari() {
  981. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  982. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  983. console.info("This appears to be Safari");
  984. // FIXME detect Safari version when needed
  985. return 1;
  986. }
  987. return null;
  988. }
  989. function detectIE() {
  990. var version;
  991. var ua = window.navigator.userAgent;
  992. var msie = ua.indexOf('MSIE ');
  993. if (msie > 0) {
  994. // IE 10 or older => return version number
  995. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  996. }
  997. var trident = ua.indexOf('Trident/');
  998. if (!version && trident > 0) {
  999. // IE 11 => return version number
  1000. var rv = ua.indexOf('rv:');
  1001. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1002. }
  1003. var edge = ua.indexOf('Edge/');
  1004. if (!version && edge > 0) {
  1005. // IE 12 => return version number
  1006. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1007. }
  1008. if (version) {
  1009. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1010. console.info("This appears to be IExplorer, ver: " + version);
  1011. }
  1012. return version;
  1013. }
  1014. function detectBrowser() {
  1015. var version;
  1016. var detectors = [
  1017. detectOpera,
  1018. detectChrome,
  1019. detectFirefox,
  1020. detectIE,
  1021. detectSafari
  1022. ];
  1023. // Try all browser detectors
  1024. for (var i = 0; i < detectors.length; i++) {
  1025. version = detectors[i]();
  1026. if (version)
  1027. return version;
  1028. }
  1029. console.error("Failed to detect browser type");
  1030. return undefined;
  1031. }
  1032. browserVersion = detectBrowser();
  1033. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1034. module.exports = RTCBrowserType;
  1035. },{}],9:[function(require,module,exports){
  1036. /* global APP, config, require, attachMediaStream, getUserMedia */
  1037. var RTCBrowserType = require("./RTCBrowserType");
  1038. var Resolutions = require("../../service/RTC/Resolutions");
  1039. var AdapterJS = require("./adapter.screenshare");
  1040. var currentResolution = null;
  1041. function getPreviousResolution(resolution) {
  1042. if(!Resolutions[resolution])
  1043. return null;
  1044. var order = Resolutions[resolution].order;
  1045. var res = null;
  1046. var resName = null;
  1047. for(var i in Resolutions) {
  1048. var tmp = Resolutions[i];
  1049. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1050. resName = i;
  1051. res = tmp;
  1052. }
  1053. }
  1054. return resName;
  1055. }
  1056. function setResolutionConstraints(constraints, resolution) {
  1057. var isAndroid = RTCBrowserType.isAndroid();
  1058. if (Resolutions[resolution]) {
  1059. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1060. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1061. }
  1062. else if (isAndroid) {
  1063. // FIXME can't remember if the purpose of this was to always request
  1064. // low resolution on Android ? if yes it should be moved up front
  1065. constraints.video.mandatory.minWidth = 320;
  1066. constraints.video.mandatory.minHeight = 240;
  1067. constraints.video.mandatory.maxFrameRate = 15;
  1068. }
  1069. if (constraints.video.mandatory.minWidth)
  1070. constraints.video.mandatory.maxWidth =
  1071. constraints.video.mandatory.minWidth;
  1072. if (constraints.video.mandatory.minHeight)
  1073. constraints.video.mandatory.maxHeight =
  1074. constraints.video.mandatory.minHeight;
  1075. }
  1076. function getConstraints(um, resolution, bandwidth, fps, desktopStream) {
  1077. var constraints = {audio: false, video: false};
  1078. if (um.indexOf('video') >= 0) {
  1079. // same behaviour as true
  1080. constraints.video = { mandatory: {}, optional: [] };
  1081. constraints.video.optional.push({ googLeakyBucket: true });
  1082. setResolutionConstraints(constraints, resolution);
  1083. }
  1084. if (um.indexOf('audio') >= 0) {
  1085. if (!RTCBrowserType.isFirefox()) {
  1086. // same behaviour as true
  1087. constraints.audio = { mandatory: {}, optional: []};
  1088. // if it is good enough for hangouts...
  1089. constraints.audio.optional.push(
  1090. {googEchoCancellation: true},
  1091. {googAutoGainControl: true},
  1092. {googNoiseSupression: true},
  1093. {googHighpassFilter: true},
  1094. {googNoisesuppression2: true},
  1095. {googEchoCancellation2: true},
  1096. {googAutoGainControl2: true}
  1097. );
  1098. } else {
  1099. constraints.audio = true;
  1100. }
  1101. }
  1102. if (um.indexOf('screen') >= 0) {
  1103. if (RTCBrowserType.isChrome()) {
  1104. constraints.video = {
  1105. mandatory: {
  1106. chromeMediaSource: "screen",
  1107. googLeakyBucket: true,
  1108. maxWidth: window.screen.width,
  1109. maxHeight: window.screen.height,
  1110. maxFrameRate: 3
  1111. },
  1112. optional: []
  1113. };
  1114. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1115. constraints.video = {
  1116. optional: [
  1117. {
  1118. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1119. }
  1120. ]
  1121. };
  1122. } else {
  1123. console.error(
  1124. "'screen' WebRTC media source is supported only in Chrome" +
  1125. " and with Temasys plugin");
  1126. }
  1127. }
  1128. if (um.indexOf('desktop') >= 0) {
  1129. constraints.video = {
  1130. mandatory: {
  1131. chromeMediaSource: "desktop",
  1132. chromeMediaSourceId: desktopStream,
  1133. googLeakyBucket: true,
  1134. maxWidth: window.screen.width,
  1135. maxHeight: window.screen.height,
  1136. maxFrameRate: 3
  1137. },
  1138. optional: []
  1139. };
  1140. }
  1141. if (bandwidth) {
  1142. if (!constraints.video) {
  1143. //same behaviour as true
  1144. constraints.video = {mandatory: {}, optional: []};
  1145. }
  1146. constraints.video.optional.push({bandwidth: bandwidth});
  1147. }
  1148. if (fps) {
  1149. // for some cameras it might be necessary to request 30fps
  1150. // so they choose 30fps mjpg over 10fps yuy2
  1151. if (!constraints.video) {
  1152. // same behaviour as true;
  1153. constraints.video = {mandatory: {}, optional: []};
  1154. }
  1155. constraints.video.mandatory.minFrameRate = fps;
  1156. }
  1157. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  1158. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  1159. // this later can be a problem with some of the tests
  1160. if(RTCBrowserType.isFirefox() && config.firefox_fake_device)
  1161. {
  1162. constraints.audio = true;
  1163. constraints.fake = true;
  1164. }
  1165. return constraints;
  1166. }
  1167. function RTCUtils(RTCService, onTemasysPluginReady)
  1168. {
  1169. var self = this;
  1170. this.service = RTCService;
  1171. if (RTCBrowserType.isFirefox()) {
  1172. var FFversion = RTCBrowserType.getFirefoxVersion();
  1173. if (FFversion >= 40) {
  1174. this.peerconnection = mozRTCPeerConnection;
  1175. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1176. this.pc_constraints = {};
  1177. this.attachMediaStream = function (element, stream) {
  1178. // srcObject is being standardized and FF will eventually
  1179. // support that unprefixed. FF also supports the
  1180. // "element.src = URL.createObjectURL(...)" combo, but that
  1181. // will be deprecated in favour of srcObject.
  1182. //
  1183. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1184. // https://github.com/webrtc/samples/issues/302
  1185. if(!element[0])
  1186. return;
  1187. element[0].mozSrcObject = stream;
  1188. element[0].play();
  1189. };
  1190. this.getStreamID = function (stream) {
  1191. var id = stream.id;
  1192. if (!id) {
  1193. var tracks = stream.getVideoTracks();
  1194. if (!tracks || tracks.length === 0) {
  1195. tracks = stream.getAudioTracks();
  1196. }
  1197. id = tracks[0].id;
  1198. }
  1199. return APP.xmpp.filter_special_chars(id);
  1200. };
  1201. this.getVideoSrc = function (element) {
  1202. if(!element)
  1203. return null;
  1204. return element.mozSrcObject;
  1205. };
  1206. this.setVideoSrc = function (element, src) {
  1207. if(element)
  1208. element.mozSrcObject = src;
  1209. };
  1210. RTCSessionDescription = mozRTCSessionDescription;
  1211. RTCIceCandidate = mozRTCIceCandidate;
  1212. } else {
  1213. console.error(
  1214. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1215. window.location.href = 'unsupported_browser.html';
  1216. return;
  1217. }
  1218. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1219. this.peerconnection = webkitRTCPeerConnection;
  1220. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1221. this.attachMediaStream = function (element, stream) {
  1222. element.attr('src', webkitURL.createObjectURL(stream));
  1223. };
  1224. this.getStreamID = function (stream) {
  1225. // streams from FF endpoints have the characters '{' and '}'
  1226. // that make jQuery choke.
  1227. return APP.xmpp.filter_special_chars(stream.id);
  1228. };
  1229. this.getVideoSrc = function (element) {
  1230. if(!element)
  1231. return null;
  1232. return element.getAttribute("src");
  1233. };
  1234. this.setVideoSrc = function (element, src) {
  1235. if(element)
  1236. element.setAttribute("src", src);
  1237. };
  1238. // DTLS should now be enabled by default but..
  1239. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1240. if (RTCBrowserType.isAndroid()) {
  1241. this.pc_constraints = {}; // disable DTLS on Android
  1242. }
  1243. if (!webkitMediaStream.prototype.getVideoTracks) {
  1244. webkitMediaStream.prototype.getVideoTracks = function () {
  1245. return this.videoTracks;
  1246. };
  1247. }
  1248. if (!webkitMediaStream.prototype.getAudioTracks) {
  1249. webkitMediaStream.prototype.getAudioTracks = function () {
  1250. return this.audioTracks;
  1251. };
  1252. }
  1253. }
  1254. // Detect IE/Safari
  1255. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1256. //AdapterJS.WebRTCPlugin.setLogLevel(
  1257. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1258. AdapterJS.webRTCReady(function (isPlugin) {
  1259. self.peerconnection = RTCPeerConnection;
  1260. self.getUserMedia = getUserMedia;
  1261. self.attachMediaStream = function (elSel, stream) {
  1262. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1263. return;
  1264. }
  1265. attachMediaStream(elSel[0], stream);
  1266. };
  1267. self.getStreamID = function (stream) {
  1268. var id = APP.xmpp.filter_special_chars(stream.label);
  1269. return id;
  1270. };
  1271. self.getVideoSrc = function (element) {
  1272. if (!element) {
  1273. console.warn("Attempt to get video SRC of null element");
  1274. return null;
  1275. }
  1276. var children = element.children;
  1277. for (var i = 0; i !== children.length; ++i) {
  1278. if (children[i].name === 'streamId') {
  1279. return children[i].value;
  1280. }
  1281. }
  1282. //console.info(element.id + " SRC: " + src);
  1283. return null;
  1284. };
  1285. self.setVideoSrc = function (element, src) {
  1286. //console.info("Set video src: ", element, src);
  1287. if (!src) {
  1288. console.warn("Not attaching video stream, 'src' is null");
  1289. return;
  1290. }
  1291. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1292. var stream = AdapterJS.WebRTCPlugin.plugin
  1293. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1294. attachMediaStream(element, stream);
  1295. };
  1296. onTemasysPluginReady(isPlugin);
  1297. });
  1298. } else {
  1299. try {
  1300. console.log('Browser does not appear to be WebRTC-capable');
  1301. } catch (e) { }
  1302. window.location.href = 'unsupported_browser.html';
  1303. }
  1304. }
  1305. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1306. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1307. desktopStream) {
  1308. currentResolution = resolution;
  1309. var constraints = getConstraints(
  1310. um, resolution, bandwidth, fps, desktopStream);
  1311. console.info("Get media constraints", constraints);
  1312. var self = this;
  1313. try {
  1314. this.getUserMedia(constraints,
  1315. function (stream) {
  1316. console.log('onUserMediaSuccess');
  1317. self.setAvailableDevices(um, true);
  1318. success_callback(stream);
  1319. },
  1320. function (error) {
  1321. self.setAvailableDevices(um, false);
  1322. console.warn('Failed to get access to local media. Error ',
  1323. error, constraints);
  1324. if (failure_callback) {
  1325. failure_callback(error);
  1326. }
  1327. });
  1328. } catch (e) {
  1329. console.error('GUM failed: ', e);
  1330. if(failure_callback) {
  1331. failure_callback(e);
  1332. }
  1333. }
  1334. };
  1335. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1336. var devices = {};
  1337. if(um.indexOf("video") != -1) {
  1338. devices.video = available;
  1339. }
  1340. if(um.indexOf("audio") != -1) {
  1341. devices.audio = available;
  1342. }
  1343. this.service.setDeviceAvailability(devices);
  1344. };
  1345. /**
  1346. * We ask for audio and video combined stream in order to get permissions and
  1347. * not to ask twice.
  1348. */
  1349. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1350. function(devices, callback, usageOptions)
  1351. {
  1352. var self = this;
  1353. // Get AV
  1354. var successCallback = function (stream) {
  1355. if(callback)
  1356. callback(stream, usageOptions);
  1357. else
  1358. self.successCallback(stream, usageOptions);
  1359. };
  1360. if(!devices)
  1361. devices = ['audio', 'video'];
  1362. var newDevices = [];
  1363. if(usageOptions)
  1364. for(var i = 0; i < devices.length; i++) {
  1365. var device = devices[i];
  1366. if(usageOptions[device] === true)
  1367. newDevices.push(device);
  1368. }
  1369. else
  1370. newDevices = devices;
  1371. if(newDevices.length === 0) {
  1372. successCallback();
  1373. return;
  1374. }
  1375. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1376. // With FF/IE we can't split the stream into audio and video because FF
  1377. // doesn't support media stream constructors. So, we need to get the
  1378. // audio stream separately from the video stream using two distinct GUM
  1379. // calls. Not very user friendly :-( but we don't have many other
  1380. // options neither.
  1381. //
  1382. // Note that we pack those 2 streams in a single object and pass it to
  1383. // the successCallback method.
  1384. var obtainVideo = function (audioStream) {
  1385. self.getUserMediaWithConstraints(
  1386. ['video'],
  1387. function (videoStream) {
  1388. return successCallback({
  1389. audioStream: audioStream,
  1390. videoStream: videoStream
  1391. });
  1392. },
  1393. function (error) {
  1394. console.error(
  1395. 'failed to obtain video stream - stop', error);
  1396. self.errorCallback(error);
  1397. },
  1398. config.resolution || '360');
  1399. };
  1400. var obtainAudio = function () {
  1401. self.getUserMediaWithConstraints(
  1402. ['audio'],
  1403. function (audioStream) {
  1404. if (newDevices.indexOf('video') !== -1)
  1405. obtainVideo(audioStream);
  1406. },
  1407. function (error) {
  1408. console.error(
  1409. 'failed to obtain audio stream - stop', error);
  1410. self.errorCallback(error);
  1411. }
  1412. );
  1413. };
  1414. if (newDevices.indexOf('audio') !== -1) {
  1415. obtainAudio();
  1416. } else {
  1417. obtainVideo(null);
  1418. }
  1419. } else {
  1420. this.getUserMediaWithConstraints(
  1421. newDevices,
  1422. function (stream) {
  1423. successCallback(stream);
  1424. },
  1425. function (error) {
  1426. self.errorCallback(error);
  1427. },
  1428. config.resolution || '360');
  1429. }
  1430. };
  1431. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1432. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1433. // it's an object with two properties: audioStream, videoStream.
  1434. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1435. console.log('got', stream, stream.getAudioTracks().length,
  1436. stream.getVideoTracks().length);
  1437. this.handleLocalStream(stream, usageOptions);
  1438. };
  1439. RTCUtils.prototype.errorCallback = function (error) {
  1440. var self = this;
  1441. console.error('failed to obtain audio/video stream - trying audio only', error);
  1442. var resolution = getPreviousResolution(currentResolution);
  1443. if(typeof error == "object" && error.constraintName && error.name
  1444. && (error.name == "ConstraintNotSatisfiedError" ||
  1445. error.name == "OverconstrainedError") &&
  1446. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1447. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1448. && resolution != null)
  1449. {
  1450. self.getUserMediaWithConstraints(['audio', 'video'],
  1451. function (stream) {
  1452. return self.successCallback(stream);
  1453. }, function (error) {
  1454. return self.errorCallback(error);
  1455. }, resolution);
  1456. }
  1457. else {
  1458. self.getUserMediaWithConstraints(
  1459. ['audio'],
  1460. function (stream) {
  1461. return self.successCallback(stream);
  1462. },
  1463. function (error) {
  1464. console.error('failed to obtain audio/video stream - stop',
  1465. error);
  1466. return self.successCallback(null);
  1467. }
  1468. );
  1469. }
  1470. };
  1471. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1472. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1473. // an object with two properties: audioStream, videoStream.
  1474. var audioStream, videoStream;
  1475. if(window.webkitMediaStream)
  1476. {
  1477. audioStream = new webkitMediaStream();
  1478. videoStream = new webkitMediaStream();
  1479. if(stream) {
  1480. var audioTracks = stream.getAudioTracks();
  1481. for (var i = 0; i < audioTracks.length; i++) {
  1482. audioStream.addTrack(audioTracks[i]);
  1483. }
  1484. var videoTracks = stream.getVideoTracks();
  1485. for (i = 0; i < videoTracks.length; i++) {
  1486. videoStream.addTrack(videoTracks[i]);
  1487. }
  1488. }
  1489. }
  1490. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1491. { // Firefox and Temasys plugin
  1492. if (stream && stream.audioStream)
  1493. audioStream = stream.audioStream;
  1494. else
  1495. audioStream = new DummyMediaStream("dummyAudio");
  1496. if (stream && stream.videoStream)
  1497. videoStream = stream.videoStream;
  1498. else
  1499. videoStream = new DummyMediaStream("dummyVideo");
  1500. }
  1501. var audioMuted = (usageOptions && usageOptions.audio === false),
  1502. videoMuted = (usageOptions && usageOptions.video === false);
  1503. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1504. videoGUM = (!usageOptions || usageOptions.video !== false);
  1505. this.service.createLocalStream(audioStream, "audio", null, null,
  1506. audioMuted, audioGUM);
  1507. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1508. videoMuted, videoGUM);
  1509. };
  1510. function DummyMediaStream(id) {
  1511. this.id = id;
  1512. this.label = id;
  1513. this.stop = function() { };
  1514. this.getAudioTracks = function() { return []; };
  1515. this.getVideoTracks = function() { return []; };
  1516. }
  1517. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1518. var newStream = null;
  1519. if (window.webkitMediaStream) {
  1520. newStream = new webkitMediaStream();
  1521. if (newStream) {
  1522. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1523. for (var i = 0; i < tracks.length; i++) {
  1524. newStream.addTrack(tracks[i]);
  1525. }
  1526. }
  1527. }
  1528. else {
  1529. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1530. if (stream) {
  1531. newStream = stream;
  1532. } else {
  1533. newStream =
  1534. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1535. }
  1536. }
  1537. return newStream;
  1538. };
  1539. module.exports = RTCUtils;
  1540. },{"../../service/RTC/Resolutions":164,"./RTCBrowserType":8,"./adapter.screenshare":10}],10:[function(require,module,exports){
  1541. /*! adapterjs - custom version from - 2015-08-19 */
  1542. // Adapter's interface.
  1543. var AdapterJS = AdapterJS || {};
  1544. // Browserify compatibility
  1545. if(typeof exports !== 'undefined') {
  1546. module.exports = AdapterJS;
  1547. }
  1548. AdapterJS.options = AdapterJS.options || {};
  1549. // uncomment to get virtual webcams
  1550. // AdapterJS.options.getAllCams = true;
  1551. // uncomment to prevent the install prompt when the plugin in not yet installed
  1552. // AdapterJS.options.hidePluginInstallPrompt = true;
  1553. // AdapterJS version
  1554. AdapterJS.VERSION = '0.12.0';
  1555. // This function will be called when the WebRTC API is ready to be used
  1556. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1557. // the plugin
  1558. // You may Override this function to synchronise the start of your application
  1559. // with the WebRTC API being ready.
  1560. // If you decide not to override use this synchronisation, it may result in
  1561. // an extensive CPU usage on the plugin start (once per tab loaded)
  1562. // Params:
  1563. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1564. //
  1565. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1566. // The WebRTC API is ready.
  1567. // Override me and do whatever you want here
  1568. };
  1569. // Sets a callback function to be called when the WebRTC interface is ready.
  1570. // The first argument is the function to callback.\
  1571. // Throws an error if the first argument is not a function
  1572. AdapterJS.webRTCReady = function (callback) {
  1573. if (typeof callback !== 'function') {
  1574. throw new Error('Callback provided is not a function');
  1575. }
  1576. if (true === AdapterJS.onwebrtcreadyDone) {
  1577. // All WebRTC interfaces are ready, just call the callback
  1578. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1579. } else {
  1580. // will be triggered automatically when your browser/plugin is ready.
  1581. AdapterJS.onwebrtcready = callback;
  1582. }
  1583. };
  1584. // Plugin namespace
  1585. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1586. // The object to store plugin information
  1587. AdapterJS.WebRTCPlugin.pluginInfo = {
  1588. prefix : 'Tem',
  1589. plugName : 'TemWebRTCPlugin',
  1590. pluginId : 'plugin0',
  1591. type : 'application/x-temwebrtcplugin',
  1592. onload : '__TemWebRTCReady0',
  1593. portalLink : 'http://skylink.io/plugin/',
  1594. downloadLink : null, //set below
  1595. companyName: 'Temasys'
  1596. };
  1597. if(!!navigator.platform.match(/^Mac/i)) {
  1598. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1599. }
  1600. else if(!!navigator.platform.match(/^Win/i)) {
  1601. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1602. }
  1603. AdapterJS.WebRTCPlugin.TAGS = {
  1604. NONE : 'none',
  1605. AUDIO : 'audio',
  1606. VIDEO : 'video'
  1607. };
  1608. // Unique identifier of each opened page
  1609. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1610. // Use this whenever you want to call the plugin.
  1611. AdapterJS.WebRTCPlugin.plugin = null;
  1612. // Set log level for the plugin once it is ready.
  1613. // The different values are
  1614. // This is an asynchronous function that will run when the plugin is ready
  1615. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1616. // Defines webrtc's JS interface according to the plugin's implementation.
  1617. // Define plugin Browsers as WebRTC Interface.
  1618. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1619. // This function detects whether or not a plugin is installed.
  1620. // Checks if Not IE (firefox, for example), else if it's IE,
  1621. // we're running IE and do something. If not it is not supported.
  1622. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1623. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1624. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1625. // Inject the HTML DOM object element into the page.
  1626. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1627. // States of readiness that the plugin goes through when
  1628. // being injected and stated
  1629. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1630. NONE : 0, // no plugin use
  1631. INITIALIZING : 1, // Detected need for plugin
  1632. INJECTING : 2, // Injecting plugin
  1633. INJECTED: 3, // Plugin element injected but not usable yet
  1634. READY: 4 // Plugin ready to be used
  1635. };
  1636. // Current state of the plugin. You cannot use the plugin before this is
  1637. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1638. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1639. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1640. // Used to make sure AdapterJS.onwebrtcready is only called once
  1641. AdapterJS.onwebrtcreadyDone = false;
  1642. // Log levels for the plugin.
  1643. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1644. /*
  1645. Log outputs are prefixed in some cases.
  1646. INFO: Information reported by the plugin.
  1647. ERROR: Errors originating from within the plugin.
  1648. WEBRTC: Error originating from within the libWebRTC library
  1649. */
  1650. // From the least verbose to the most verbose
  1651. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1652. NONE : 'NONE',
  1653. ERROR : 'ERROR',
  1654. WARNING : 'WARNING',
  1655. INFO: 'INFO',
  1656. VERBOSE: 'VERBOSE',
  1657. SENSITIVE: 'SENSITIVE'
  1658. };
  1659. // Does a waiting check before proceeding to load the plugin.
  1660. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1661. // This methid will use an interval to wait for the plugin to be ready.
  1662. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1663. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1664. // This function will be called when plugin is ready. It sends necessary
  1665. // details to the plugin.
  1666. // The function will wait for the document to be ready and the set the
  1667. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1668. // indicating that it can start being requested.
  1669. // This function is not in the IE/Safari condition brackets so that
  1670. // TemPluginLoaded function might be called on Chrome/Firefox.
  1671. // This function is the only private function that is not encapsulated to
  1672. // allow the plugin method to be called.
  1673. __TemWebRTCReady0 = function () {
  1674. if (document.readyState === 'complete') {
  1675. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1676. AdapterJS.maybeThroughWebRTCReady();
  1677. } else {
  1678. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1679. if (document.readyState === 'complete') {
  1680. // TODO: update comments, we wait for the document to be ready
  1681. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1682. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1683. AdapterJS.maybeThroughWebRTCReady();
  1684. }
  1685. }, 100);
  1686. }
  1687. };
  1688. AdapterJS.maybeThroughWebRTCReady = function() {
  1689. if (!AdapterJS.onwebrtcreadyDone) {
  1690. AdapterJS.onwebrtcreadyDone = true;
  1691. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1692. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1693. }
  1694. }
  1695. };
  1696. // Text namespace
  1697. AdapterJS.TEXT = {
  1698. PLUGIN: {
  1699. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1700. 'to work on this browser.',
  1701. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1702. BUTTON: 'Install Now'
  1703. },
  1704. REFRESH: {
  1705. REQUIRE_REFRESH: 'Please refresh page',
  1706. BUTTON: 'Refresh Page'
  1707. }
  1708. };
  1709. // The result of ice connection states.
  1710. // - starting: Ice connection is starting.
  1711. // - checking: Ice connection is checking.
  1712. // - connected Ice connection is connected.
  1713. // - completed Ice connection is connected.
  1714. // - done Ice connection has been completed.
  1715. // - disconnected Ice connection has been disconnected.
  1716. // - failed Ice connection has failed.
  1717. // - closed Ice connection is closed.
  1718. AdapterJS._iceConnectionStates = {
  1719. starting : 'starting',
  1720. checking : 'checking',
  1721. connected : 'connected',
  1722. completed : 'connected',
  1723. done : 'completed',
  1724. disconnected : 'disconnected',
  1725. failed : 'failed',
  1726. closed : 'closed'
  1727. };
  1728. //The IceConnection states that has been fired for each peer.
  1729. AdapterJS._iceConnectionFiredStates = [];
  1730. // Check if WebRTC Interface is defined.
  1731. AdapterJS.isDefined = null;
  1732. // This function helps to retrieve the webrtc detected browser information.
  1733. // This sets:
  1734. // - webrtcDetectedBrowser: The browser agent name.
  1735. // - webrtcDetectedVersion: The browser version.
  1736. // - webrtcDetectedType: The types of webRTC support.
  1737. // - 'moz': Mozilla implementation of webRTC.
  1738. // - 'webkit': WebKit implementation of webRTC.
  1739. // - 'plugin': Using the plugin implementation.
  1740. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1741. var hasMatch, checkMatch = navigator.userAgent.match(
  1742. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1743. if (/trident/i.test(checkMatch[1])) {
  1744. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1745. webrtcDetectedBrowser = 'IE';
  1746. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1747. } else if (checkMatch[1] === 'Chrome') {
  1748. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1749. if (hasMatch !== null) {
  1750. webrtcDetectedBrowser = 'opera';
  1751. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  1752. }
  1753. }
  1754. if (navigator.userAgent.indexOf('Safari')) {
  1755. if (typeof InstallTrigger !== 'undefined') {
  1756. webrtcDetectedBrowser = 'firefox';
  1757. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  1758. webrtcDetectedBrowser = 'IE';
  1759. } else if (
  1760. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  1761. webrtcDetectedBrowser = 'safari';
  1762. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  1763. webrtcDetectedBrowser = 'opera';
  1764. } else if (!!window.chrome) {
  1765. webrtcDetectedBrowser = 'chrome';
  1766. }
  1767. }
  1768. if (!webrtcDetectedBrowser) {
  1769. webrtcDetectedVersion = checkMatch[1];
  1770. }
  1771. if (!webrtcDetectedVersion) {
  1772. try {
  1773. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  1774. [navigator.appName, navigator.appVersion, '-?'];
  1775. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  1776. checkMatch.splice(1, 1, hasMatch[1]);
  1777. }
  1778. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  1779. } catch (error) { }
  1780. }
  1781. };
  1782. // To fix configuration as some browsers does not support
  1783. // the 'urls' attribute.
  1784. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  1785. if (pcConfig === null) {
  1786. return;
  1787. }
  1788. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1789. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  1790. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  1791. delete pcConfig.iceServers[i].urls;
  1792. }
  1793. }
  1794. };
  1795. AdapterJS.addEvent = function(elem, evnt, func) {
  1796. if (elem.addEventListener) { // W3C DOM
  1797. elem.addEventListener(evnt, func, false);
  1798. } else if (elem.attachEvent) {// OLD IE DOM
  1799. elem.attachEvent('on'+evnt, func);
  1800. } else { // No much to do
  1801. elem[evnt] = func;
  1802. }
  1803. };
  1804. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  1805. // only inject once the page is ready
  1806. if (document.readyState !== 'complete') {
  1807. return;
  1808. }
  1809. var w = window;
  1810. var i = document.createElement('iframe');
  1811. i.style.position = 'fixed';
  1812. i.style.top = '-41px';
  1813. i.style.left = 0;
  1814. i.style.right = 0;
  1815. i.style.width = '100%';
  1816. i.style.height = '40px';
  1817. i.style.backgroundColor = '#ffffe1';
  1818. i.style.border = 'none';
  1819. i.style.borderBottom = '1px solid #888888';
  1820. i.style.zIndex = '9999999';
  1821. if(typeof i.style.webkitTransition === 'string') {
  1822. i.style.webkitTransition = 'all .5s ease-out';
  1823. } else if(typeof i.style.transition === 'string') {
  1824. i.style.transition = 'all .5s ease-out';
  1825. }
  1826. document.body.appendChild(i);
  1827. c = (i.contentWindow) ? i.contentWindow :
  1828. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  1829. c.document.open();
  1830. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  1831. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  1832. 'middle; cursor: default;">' + text + '</span>');
  1833. if(buttonText && buttonLink) {
  1834. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  1835. c.document.close();
  1836. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  1837. if (!!displayRefreshBar) {
  1838. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  1839. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  1840. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  1841. }
  1842. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  1843. e.preventDefault();
  1844. try {
  1845. event.cancelBubble = true;
  1846. } catch(error) { }
  1847. var pluginInstallInterval = setInterval(function(){
  1848. if(! isIE) {
  1849. navigator.plugins.refresh(false);
  1850. }
  1851. AdapterJS.WebRTCPlugin.isPluginInstalled(
  1852. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  1853. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  1854. function() { // plugin now installed
  1855. clearInterval(pluginInstallInterval);
  1856. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  1857. },
  1858. function() {
  1859. // still no plugin detected, nothing to do
  1860. });
  1861. } , 500);
  1862. });
  1863. } else {
  1864. c.document.close();
  1865. }
  1866. AdapterJS.addEvent(c.document, 'click', function() {
  1867. w.document.body.removeChild(i);
  1868. });
  1869. setTimeout(function() {
  1870. if(typeof i.style.webkitTransform === 'string') {
  1871. i.style.webkitTransform = 'translateY(40px)';
  1872. } else if(typeof i.style.transform === 'string') {
  1873. i.style.transform = 'translateY(40px)';
  1874. } else {
  1875. i.style.top = '0px';
  1876. }
  1877. }, 300);
  1878. };
  1879. // -----------------------------------------------------------
  1880. // Detected webrtc implementation. Types are:
  1881. // - 'moz': Mozilla implementation of webRTC.
  1882. // - 'webkit': WebKit implementation of webRTC.
  1883. // - 'plugin': Using the plugin implementation.
  1884. webrtcDetectedType = null;
  1885. // Detected webrtc datachannel support. Types are:
  1886. // - 'SCTP': SCTP datachannel support.
  1887. // - 'RTP': RTP datachannel support.
  1888. webrtcDetectedDCSupport = null;
  1889. // Set the settings for creating DataChannels, MediaStream for
  1890. // Cross-browser compability.
  1891. // - This is only for SCTP based support browsers.
  1892. // the 'urls' attribute.
  1893. checkMediaDataChannelSettings =
  1894. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  1895. if (typeof callback !== 'function') {
  1896. return;
  1897. }
  1898. var beOfferer = true;
  1899. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  1900. // Nightly version does not require MozDontOfferDataChannel for interop
  1901. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  1902. var isPeerFirefox = peerBrowserAgent === 'firefox';
  1903. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  1904. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  1905. // Resends an updated version of constraints for MozDataChannel to work
  1906. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  1907. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  1908. try {
  1909. delete constraints.mandatory.MozDontOfferDataChannel;
  1910. } catch (error) {
  1911. console.error('Failed deleting MozDontOfferDataChannel');
  1912. console.error(error);
  1913. }
  1914. } else if ((isLocalFirefox && !isPeerFirefox)) {
  1915. constraints.mandatory.MozDontOfferDataChannel = true;
  1916. }
  1917. if (!isLocalFirefox) {
  1918. // temporary measure to remove Moz* constraints in non Firefox browsers
  1919. for (var prop in constraints.mandatory) {
  1920. if (constraints.mandatory.hasOwnProperty(prop)) {
  1921. if (prop.indexOf('Moz') !== -1) {
  1922. delete constraints.mandatory[prop];
  1923. }
  1924. }
  1925. }
  1926. }
  1927. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  1928. // interopability of the media stream
  1929. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  1930. beOfferer = false;
  1931. }
  1932. callback(beOfferer, constraints);
  1933. };
  1934. // Handles the differences for all browsers ice connection state output.
  1935. // - Tested outcomes are:
  1936. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  1937. // - Chrome (answerer) : 'checking' > 'connected'
  1938. // - Firefox (offerer) : 'checking' > 'connected'
  1939. // - Firefox (answerer): 'checking' > 'connected'
  1940. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  1941. if (typeof callback !== 'function') {
  1942. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  1943. return;
  1944. }
  1945. peerId = (peerId) ? peerId : 'peer';
  1946. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  1947. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  1948. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  1949. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  1950. AdapterJS._iceConnectionFiredStates[peerId] = [];
  1951. }
  1952. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  1953. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  1954. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  1955. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  1956. setTimeout(function () {
  1957. AdapterJS._iceConnectionFiredStates[peerId]
  1958. .push(AdapterJS._iceConnectionStates.done);
  1959. callback(AdapterJS._iceConnectionStates.done);
  1960. }, 1000);
  1961. }
  1962. callback(iceConnectionState);
  1963. }
  1964. return;
  1965. };
  1966. // Firefox:
  1967. // - Creates iceServer from the url for Firefox.
  1968. // - Create iceServer with stun url.
  1969. // - Create iceServer with turn url.
  1970. // - Ignore the transport parameter from TURN url for FF version <=27.
  1971. // - Return null for createIceServer if transport=tcp.
  1972. // - FF 27 and above supports transport parameters in TURN url,
  1973. // - So passing in the full url to create iceServer.
  1974. // Chrome:
  1975. // - Creates iceServer from the url for Chrome M33 and earlier.
  1976. // - Create iceServer with stun url.
  1977. // - Chrome M28 & above uses below TURN format.
  1978. // Plugin:
  1979. // - Creates Ice Server for Plugin Browsers
  1980. // - If Stun - Create iceServer with stun url.
  1981. // - Else - Create iceServer with turn url
  1982. // - This is a WebRTC Function
  1983. createIceServer = null;
  1984. // Firefox:
  1985. // - Creates IceServers for Firefox
  1986. // - Use .url for FireFox.
  1987. // - Multiple Urls support
  1988. // Chrome:
  1989. // - Creates iceServers from the urls for Chrome M34 and above.
  1990. // - .urls is supported since Chrome M34.
  1991. // - Multiple Urls support
  1992. // Plugin:
  1993. // - Creates Ice Servers for Plugin Browsers
  1994. // - Multiple Urls support
  1995. // - This is a WebRTC Function
  1996. createIceServers = null;
  1997. //------------------------------------------------------------
  1998. //The RTCPeerConnection object.
  1999. RTCPeerConnection = null;
  2000. // Creates RTCSessionDescription object for Plugin Browsers
  2001. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2002. RTCSessionDescription : null;
  2003. // Creates RTCIceCandidate object for Plugin Browsers
  2004. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2005. RTCIceCandidate : null;
  2006. // Get UserMedia (only difference is the prefix).
  2007. // Code from Adam Barth.
  2008. getUserMedia = null;
  2009. // Attach a media stream to an element.
  2010. attachMediaStream = null;
  2011. // Re-attach a media stream to an element.
  2012. reattachMediaStream = null;
  2013. // Detected browser agent name. Types are:
  2014. // - 'firefox': Firefox browser.
  2015. // - 'chrome': Chrome browser.
  2016. // - 'opera': Opera browser.
  2017. // - 'safari': Safari browser.
  2018. // - 'IE' - Internet Explorer browser.
  2019. webrtcDetectedBrowser = null;
  2020. // Detected browser version.
  2021. webrtcDetectedVersion = null;
  2022. // Check for browser types and react accordingly
  2023. if (navigator.mozGetUserMedia) {
  2024. webrtcDetectedBrowser = 'firefox';
  2025. webrtcDetectedVersion = parseInt(navigator
  2026. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2027. webrtcDetectedType = 'moz';
  2028. webrtcDetectedDCSupport = 'SCTP';
  2029. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2030. AdapterJS.maybeFixConfiguration(pcConfig);
  2031. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2032. };
  2033. // The RTCSessionDescription object.
  2034. RTCSessionDescription = mozRTCSessionDescription;
  2035. window.RTCSessionDescription = RTCSessionDescription;
  2036. // The RTCIceCandidate object.
  2037. RTCIceCandidate = mozRTCIceCandidate;
  2038. window.RTCIceCandidate = RTCIceCandidate;
  2039. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2040. navigator.getUserMedia = window.getUserMedia;
  2041. // Shim for MediaStreamTrack.getSources.
  2042. MediaStreamTrack.getSources = function(successCb) {
  2043. setTimeout(function() {
  2044. var infos = [
  2045. { kind: 'audio', id: 'default', label:'', facing:'' },
  2046. { kind: 'video', id: 'default', label:'', facing:'' }
  2047. ];
  2048. successCb(infos);
  2049. }, 0);
  2050. };
  2051. createIceServer = function (url, username, password) {
  2052. var iceServer = null;
  2053. var url_parts = url.split(':');
  2054. if (url_parts[0].indexOf('stun') === 0) {
  2055. iceServer = { url : url };
  2056. } else if (url_parts[0].indexOf('turn') === 0) {
  2057. if (webrtcDetectedVersion < 27) {
  2058. var turn_url_parts = url.split('?');
  2059. if (turn_url_parts.length === 1 ||
  2060. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2061. iceServer = {
  2062. url : turn_url_parts[0],
  2063. credential : password,
  2064. username : username
  2065. };
  2066. }
  2067. } else {
  2068. iceServer = {
  2069. url : url,
  2070. credential : password,
  2071. username : username
  2072. };
  2073. }
  2074. }
  2075. return iceServer;
  2076. };
  2077. createIceServers = function (urls, username, password) {
  2078. var iceServers = [];
  2079. for (i = 0; i < urls.length; i++) {
  2080. var iceServer = createIceServer(urls[i], username, password);
  2081. if (iceServer !== null) {
  2082. iceServers.push(iceServer);
  2083. }
  2084. }
  2085. return iceServers;
  2086. };
  2087. attachMediaStream = function (element, stream) {
  2088. element.mozSrcObject = stream;
  2089. if (stream !== null)
  2090. element.play();
  2091. return element;
  2092. };
  2093. reattachMediaStream = function (to, from) {
  2094. to.mozSrcObject = from.mozSrcObject;
  2095. to.play();
  2096. return to;
  2097. };
  2098. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2099. if (!callback) {
  2100. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2101. ': 1 argument required, but only 0 present.');
  2102. }
  2103. return callback([]);
  2104. };
  2105. // Fake get{Video,Audio}Tracks
  2106. if (!MediaStream.prototype.getVideoTracks) {
  2107. MediaStream.prototype.getVideoTracks = function () {
  2108. return [];
  2109. };
  2110. }
  2111. if (!MediaStream.prototype.getAudioTracks) {
  2112. MediaStream.prototype.getAudioTracks = function () {
  2113. return [];
  2114. };
  2115. }
  2116. AdapterJS.maybeThroughWebRTCReady();
  2117. } else if (navigator.webkitGetUserMedia) {
  2118. webrtcDetectedBrowser = 'chrome';
  2119. webrtcDetectedType = 'webkit';
  2120. webrtcDetectedVersion = parseInt(navigator
  2121. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2122. // check if browser is opera 20+
  2123. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2124. if (checkIfOpera !== null) {
  2125. webrtcDetectedBrowser = 'opera';
  2126. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2127. }
  2128. // check browser datachannel support
  2129. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2130. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2131. webrtcDetectedDCSupport = 'SCTP';
  2132. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2133. webrtcDetectedVersion > 24) {
  2134. webrtcDetectedDCSupport = 'RTP';
  2135. } else {
  2136. webrtcDetectedDCSupport = '';
  2137. }
  2138. createIceServer = function (url, username, password) {
  2139. var iceServer = null;
  2140. var url_parts = url.split(':');
  2141. if (url_parts[0].indexOf('stun') === 0) {
  2142. iceServer = { 'url' : url };
  2143. } else if (url_parts[0].indexOf('turn') === 0) {
  2144. iceServer = {
  2145. 'url' : url,
  2146. 'credential' : password,
  2147. 'username' : username
  2148. };
  2149. }
  2150. return iceServer;
  2151. };
  2152. createIceServers = function (urls, username, password) {
  2153. var iceServers = [];
  2154. if (webrtcDetectedVersion >= 34) {
  2155. iceServers = {
  2156. 'urls' : urls,
  2157. 'credential' : password,
  2158. 'username' : username
  2159. };
  2160. } else {
  2161. for (i = 0; i < urls.length; i++) {
  2162. var iceServer = createIceServer(urls[i], username, password);
  2163. if (iceServer !== null) {
  2164. iceServers.push(iceServer);
  2165. }
  2166. }
  2167. }
  2168. return iceServers;
  2169. };
  2170. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2171. if (webrtcDetectedVersion < 34) {
  2172. AdapterJS.maybeFixConfiguration(pcConfig);
  2173. }
  2174. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2175. };
  2176. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2177. navigator.getUserMedia = window.getUserMedia;
  2178. attachMediaStream = function (element, stream) {
  2179. if (typeof element.srcObject !== 'undefined') {
  2180. element.srcObject = stream;
  2181. } else if (typeof element.mozSrcObject !== 'undefined') {
  2182. element.mozSrcObject = stream;
  2183. } else if (typeof element.src !== 'undefined') {
  2184. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2185. } else {
  2186. console.log('Error attaching stream to element.');
  2187. }
  2188. return element;
  2189. };
  2190. reattachMediaStream = function (to, from) {
  2191. to.src = from.src;
  2192. return to;
  2193. };
  2194. AdapterJS.maybeThroughWebRTCReady();
  2195. } else if (navigator.mediaDevices && navigator.userAgent.match(
  2196. /Edge\/(\d+).(\d+)$/)) {
  2197. webrtcDetectedBrowser = 'edge';
  2198. webrtcDetectedVersion =
  2199. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  2200. // the minimum version still supported by adapter.
  2201. webrtcMinimumVersion = 12;
  2202. getUserMedia = navigator.getUserMedia;
  2203. attachMediaStream = function(element, stream) {
  2204. element.srcObject = stream;
  2205. return element;
  2206. };
  2207. reattachMediaStream = function(to, from) {
  2208. to.srcObject = from.srcObject;
  2209. return to;
  2210. };
  2211. AdapterJS.maybeThroughWebRTCReady();
  2212. } else { // TRY TO USE PLUGIN
  2213. // IE 9 is not offering an implementation of console.log until you open a console
  2214. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2215. /* jshint -W020 */
  2216. console = {} || console;
  2217. // Implemented based on console specs from MDN
  2218. // You may override these functions
  2219. console.log = function (arg) {};
  2220. console.info = function (arg) {};
  2221. console.error = function (arg) {};
  2222. console.dir = function (arg) {};
  2223. console.exception = function (arg) {};
  2224. console.trace = function (arg) {};
  2225. console.warn = function (arg) {};
  2226. console.count = function (arg) {};
  2227. console.debug = function (arg) {};
  2228. console.count = function (arg) {};
  2229. console.time = function (arg) {};
  2230. console.timeEnd = function (arg) {};
  2231. console.group = function (arg) {};
  2232. console.groupCollapsed = function (arg) {};
  2233. console.groupEnd = function (arg) {};
  2234. /* jshint +W020 */
  2235. }
  2236. webrtcDetectedType = 'plugin';
  2237. webrtcDetectedDCSupport = 'plugin';
  2238. AdapterJS.parseWebrtcDetectedBrowser();
  2239. isIE = webrtcDetectedBrowser === 'IE';
  2240. /* jshint -W035 */
  2241. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2242. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2243. /* empty because it needs to prevent the function from running. */
  2244. }
  2245. };
  2246. /* jshint +W035 */
  2247. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2248. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2249. // Call immediately if possible
  2250. // Once the plugin is set, the code will always take this path
  2251. callback();
  2252. } else {
  2253. // otherwise start a 100ms interval
  2254. var checkPluginReadyState = setInterval(function () {
  2255. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2256. clearInterval(checkPluginReadyState);
  2257. callback();
  2258. }
  2259. }, 100);
  2260. }
  2261. };
  2262. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2263. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2264. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2265. });
  2266. };
  2267. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2268. // only inject once the page is ready
  2269. if (document.readyState !== 'complete') {
  2270. return;
  2271. }
  2272. // Prevent multiple injections
  2273. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2274. return;
  2275. }
  2276. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2277. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2278. var frag = document.createDocumentFragment();
  2279. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2280. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2281. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2282. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2283. '<param name="pluginId" value="' +
  2284. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2285. '<param name="windowless" value="false" /> ' +
  2286. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2287. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  2288. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  2289. // uncomment to be able to use virtual cams
  2290. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2291. '</object>';
  2292. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2293. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2294. }
  2295. document.body.appendChild(frag);
  2296. // Need to re-fetch the plugin
  2297. AdapterJS.WebRTCPlugin.plugin =
  2298. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2299. } else {
  2300. // Load Plugin
  2301. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2302. AdapterJS.WebRTCPlugin.plugin.id =
  2303. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2304. // IE will only start the plugin if it's ACTUALLY visible
  2305. if (isIE) {
  2306. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2307. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2308. } else { // The size of the plugin on Safari should be 0x0px
  2309. // so that the autorisation prompt is at the top
  2310. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2311. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2312. }
  2313. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2314. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2315. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2316. '<param name="pluginId" value="' +
  2317. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2318. '<param name="windowless" value="false" /> ' +
  2319. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2320. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  2321. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  2322. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2323. }
  2324. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2325. };
  2326. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2327. function (comName, plugName, installedCb, notInstalledCb) {
  2328. if (!isIE) {
  2329. var pluginArray = navigator.plugins;
  2330. for (var i = 0; i < pluginArray.length; i++) {
  2331. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2332. installedCb();
  2333. return;
  2334. }
  2335. }
  2336. notInstalledCb();
  2337. } else {
  2338. try {
  2339. var axo = new ActiveXObject(comName + '.' + plugName);
  2340. } catch (e) {
  2341. notInstalledCb();
  2342. return;
  2343. }
  2344. installedCb();
  2345. }
  2346. };
  2347. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2348. if (AdapterJS.WebRTCPlugin.pluginState ===
  2349. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2350. console.error("AdapterJS - WebRTC interface has already been defined");
  2351. return;
  2352. }
  2353. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2354. AdapterJS.isDefined = function (variable) {
  2355. return variable !== null && variable !== undefined;
  2356. };
  2357. createIceServer = function (url, username, password) {
  2358. var iceServer = null;
  2359. var url_parts = url.split(':');
  2360. if (url_parts[0].indexOf('stun') === 0) {
  2361. iceServer = {
  2362. 'url' : url,
  2363. 'hasCredentials' : false
  2364. };
  2365. } else if (url_parts[0].indexOf('turn') === 0) {
  2366. iceServer = {
  2367. 'url' : url,
  2368. 'hasCredentials' : true,
  2369. 'credential' : password,
  2370. 'username' : username
  2371. };
  2372. }
  2373. return iceServer;
  2374. };
  2375. createIceServers = function (urls, username, password) {
  2376. var iceServers = [];
  2377. for (var i = 0; i < urls.length; ++i) {
  2378. iceServers.push(createIceServer(urls[i], username, password));
  2379. }
  2380. return iceServers;
  2381. };
  2382. RTCSessionDescription = function (info) {
  2383. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2384. return AdapterJS.WebRTCPlugin.plugin.
  2385. ConstructSessionDescription(info.type, info.sdp);
  2386. };
  2387. RTCPeerConnection = function (servers, constraints) {
  2388. var iceServers = null;
  2389. if (servers) {
  2390. iceServers = servers.iceServers;
  2391. for (var i = 0; i < iceServers.length; i++) {
  2392. if (iceServers[i].urls && !iceServers[i].url) {
  2393. iceServers[i].url = iceServers[i].urls;
  2394. }
  2395. iceServers[i].hasCredentials = AdapterJS.
  2396. isDefined(iceServers[i].username) &&
  2397. AdapterJS.isDefined(iceServers[i].credential);
  2398. }
  2399. }
  2400. var mandatory = (constraints && constraints.mandatory) ?
  2401. constraints.mandatory : null;
  2402. var optional = (constraints && constraints.optional) ?
  2403. constraints.optional : null;
  2404. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2405. return AdapterJS.WebRTCPlugin.plugin.
  2406. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2407. iceServers, mandatory, optional);
  2408. };
  2409. MediaStreamTrack = {};
  2410. MediaStreamTrack.getSources = function (callback) {
  2411. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2412. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2413. });
  2414. };
  2415. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2416. constraints.audio = constraints.audio || false;
  2417. constraints.video = constraints.video || false;
  2418. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2419. AdapterJS.WebRTCPlugin.plugin.
  2420. getUserMedia(constraints, successCallback, failureCallback);
  2421. });
  2422. };
  2423. window.navigator.getUserMedia = window.getUserMedia;
  2424. attachMediaStream = function (element, stream) {
  2425. if (!element || !element.parentNode) {
  2426. return;
  2427. }
  2428. var streamId
  2429. if (stream === null) {
  2430. streamId = '';
  2431. }
  2432. else {
  2433. stream.enableSoundTracks(true); // TODO: remove on 0.12.0
  2434. streamId = stream.id;
  2435. }
  2436. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2437. var nodeName = element.nodeName.toLowerCase();
  2438. if (nodeName !== 'object') { // not a plugin <object> tag yet
  2439. var tag;
  2440. switch(nodeName) {
  2441. case 'audio':
  2442. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  2443. break;
  2444. case 'video':
  2445. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  2446. break;
  2447. default:
  2448. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  2449. }
  2450. var frag = document.createDocumentFragment();
  2451. var temp = document.createElement('div');
  2452. var classHTML = '';
  2453. if (element.className) {
  2454. classHTML = 'class="' + element.className + '" ';
  2455. } else if (element.attributes && element.attributes['class']) {
  2456. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2457. }
  2458. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2459. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2460. '<param name="pluginId" value="' + elementId + '" /> ' +
  2461. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2462. '<param name="windowless" value="true" /> ' +
  2463. '<param name="streamId" value="' + streamId + '" /> ' +
  2464. '<param name="tag" value="' + tag + '" /> ' +
  2465. '</object>';
  2466. while (temp.firstChild) {
  2467. frag.appendChild(temp.firstChild);
  2468. }
  2469. var height = '';
  2470. var width = '';
  2471. if (element.getBoundingClientRect) {
  2472. var rectObject = element.getBoundingClientRect();
  2473. width = rectObject.width + 'px';
  2474. height = rectObject.height + 'px';
  2475. }
  2476. else if (element.width) {
  2477. width = element.width;
  2478. height = element.height;
  2479. } else {
  2480. // TODO: What scenario could bring us here?
  2481. }
  2482. element.parentNode.insertBefore(frag, element);
  2483. frag = document.getElementById(elementId);
  2484. frag.width = width;
  2485. frag.height = height;
  2486. element.parentNode.removeChild(element);
  2487. } else { // already an <object> tag, just change the stream id
  2488. var children = element.children;
  2489. for (var i = 0; i !== children.length; ++i) {
  2490. if (children[i].name === 'streamId') {
  2491. children[i].value = streamId;
  2492. break;
  2493. }
  2494. }
  2495. element.setStreamId(streamId);
  2496. }
  2497. var newElement = document.getElementById(elementId);
  2498. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2499. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2500. if (isIE) { // on IE the event needs to be plugged manually
  2501. newElement.attachEvent('onplaying', newElement.onplaying);
  2502. newElement._TemOnClick = function (id) {
  2503. var arg = {
  2504. srcElement : document.getElementById(id)
  2505. };
  2506. newElement.onclick(arg);
  2507. };
  2508. }
  2509. return newElement;
  2510. };
  2511. reattachMediaStream = function (to, from) {
  2512. var stream = null;
  2513. var children = from.children;
  2514. for (var i = 0; i !== children.length; ++i) {
  2515. if (children[i].name === 'streamId') {
  2516. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2517. stream = AdapterJS.WebRTCPlugin.plugin
  2518. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2519. break;
  2520. }
  2521. }
  2522. if (stream !== null) {
  2523. return attachMediaStream(to, stream);
  2524. } else {
  2525. console.log('Could not find the stream associated with this element');
  2526. }
  2527. };
  2528. RTCIceCandidate = function (candidate) {
  2529. if (!candidate.sdpMid) {
  2530. candidate.sdpMid = '';
  2531. }
  2532. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2533. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2534. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2535. );
  2536. };
  2537. // inject plugin
  2538. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2539. AdapterJS.WebRTCPlugin.injectPlugin();
  2540. };
  2541. // This function will be called if the plugin is needed (browser different
  2542. // from Chrome or Firefox), but the plugin is not installed.
  2543. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2544. function() {
  2545. AdapterJS.addEvent(document,
  2546. 'readystatechange',
  2547. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2548. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2549. };
  2550. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2551. if (AdapterJS.options.hidePluginInstallPrompt) {
  2552. return;
  2553. }
  2554. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2555. if(downloadLink) { // if download link
  2556. var popupString;
  2557. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2558. popupString = 'This website requires you to install the ' +
  2559. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2560. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2561. ' WebRTC Plugin</a>' +
  2562. ' to work on this browser.';
  2563. } else { // no portal link, just print a generic explanation
  2564. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2565. }
  2566. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2567. } else { // no download link, just print a generic explanation
  2568. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2569. }
  2570. };
  2571. // Try to detect the plugin and act accordingly
  2572. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2573. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2574. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2575. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2576. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2577. }
  2578. },{}],11:[function(require,module,exports){
  2579. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2580. var UI = {};
  2581. var VideoLayout = require("./videolayout/VideoLayout.js");
  2582. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2583. var Prezi = require("./prezi/Prezi.js");
  2584. var Etherpad = require("./etherpad/Etherpad.js");
  2585. var Chat = require("./side_pannels/chat/Chat.js");
  2586. var Toolbar = require("./toolbars/Toolbar");
  2587. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2588. var BottomToolbar = require("./toolbars/BottomToolbar");
  2589. var ContactList = require("./side_pannels/contactlist/ContactList");
  2590. var Avatar = require("./avatar/Avatar");
  2591. var EventEmitter = require("events");
  2592. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2593. var Settings = require("./../settings/Settings");
  2594. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2595. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2596. UI.messageHandler = require("./util/MessageHandler");
  2597. var messageHandler = UI.messageHandler;
  2598. var Authentication = require("./authentication/Authentication");
  2599. var UIUtil = require("./util/UIUtil");
  2600. var NicknameHandler = require("./util/NicknameHandler");
  2601. var JitsiPopover = require("./util/JitsiPopover");
  2602. var CQEvents = require("../../service/connectionquality/CQEvents");
  2603. var DesktopSharingEventTypes
  2604. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2605. var RTCEvents = require("../../service/RTC/RTCEvents");
  2606. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2607. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2608. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2609. var UIEvents = require("../../service/UI/UIEvents");
  2610. var MemberEvents = require("../../service/members/Events");
  2611. var eventEmitter = new EventEmitter();
  2612. var roomNode = null;
  2613. var roomName = null;
  2614. function promptDisplayName() {
  2615. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2616. message += APP.translation.translateString(
  2617. "dialog.displayNameRequired");
  2618. message += '</h2>' +
  2619. '<input name="displayName" type="text" data-i18n=' +
  2620. '"[placeholder]defaultNickname" placeholder="' +
  2621. APP.translation.translateString(
  2622. "defaultNickname", {name: "Jane Pink"}) +
  2623. '" autofocus>';
  2624. var buttonTxt
  2625. = APP.translation.generateTranslationHTML("dialog.Ok");
  2626. var buttons = [];
  2627. buttons.push({title: buttonTxt, value: "ok"});
  2628. messageHandler.openDialog(null, message,
  2629. true,
  2630. buttons,
  2631. function (e, v, m, f) {
  2632. if (v == "ok") {
  2633. var displayName = f.displayName;
  2634. if (displayName) {
  2635. VideoLayout.inputDisplayNameHandler(displayName);
  2636. return true;
  2637. }
  2638. }
  2639. e.preventDefault();
  2640. },
  2641. function () {
  2642. var form = $.prompt.getPrompt();
  2643. var input = form.find("input[name='displayName']");
  2644. input.focus();
  2645. var button = form.find("button");
  2646. button.attr("disabled", "disabled");
  2647. input.keyup(function () {
  2648. if(!input.val())
  2649. button.attr("disabled", "disabled");
  2650. else
  2651. button.removeAttr("disabled");
  2652. });
  2653. }
  2654. );
  2655. }
  2656. function notifyForInitialMute() {
  2657. messageHandler.notify(null, "notify.mutedTitle", "connected",
  2658. "notify.muted", null, {timeOut: 120000});
  2659. }
  2660. function setupPrezi() {
  2661. $("#reloadPresentationLink").click(function() {
  2662. Prezi.reloadPresentation();
  2663. });
  2664. }
  2665. function setupChat() {
  2666. Chat.init();
  2667. $("#toggle_smileys").click(function() {
  2668. Chat.toggleSmileys();
  2669. });
  2670. }
  2671. function setupToolbars() {
  2672. Toolbar.init(UI);
  2673. Toolbar.setupButtonsFromConfig();
  2674. BottomToolbar.init();
  2675. }
  2676. function streamHandler(stream, isMuted) {
  2677. switch (stream.type) {
  2678. case "audio":
  2679. VideoLayout.changeLocalAudio(stream, isMuted);
  2680. break;
  2681. case "video":
  2682. VideoLayout.changeLocalVideo(stream, isMuted);
  2683. break;
  2684. case "stream":
  2685. VideoLayout.changeLocalStream(stream, isMuted);
  2686. break;
  2687. }
  2688. }
  2689. function onXmppConnectionFailed(stropheErrorMsg) {
  2690. var title = APP.translation.generateTranslationHTML(
  2691. "dialog.error");
  2692. var message;
  2693. if (stropheErrorMsg) {
  2694. message = APP.translation.generateTranslationHTML(
  2695. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  2696. } else {
  2697. message = APP.translation.generateTranslationHTML(
  2698. "dialog.connectError");
  2699. }
  2700. messageHandler.openDialog(
  2701. title, message, true, {}, function (e, v, m, f) { return false; });
  2702. }
  2703. function onDisposeConference(unload) {
  2704. Toolbar.showAuthenticateButton(false);
  2705. }
  2706. function onDisplayNameChanged(jid, displayName) {
  2707. ContactList.onDisplayNameChange(jid, displayName);
  2708. SettingsMenu.onDisplayNameChange(jid, displayName);
  2709. VideoLayout.onDisplayNameChanged(jid, displayName);
  2710. }
  2711. function registerListeners() {
  2712. APP.RTC.addStreamListener(streamHandler,
  2713. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  2714. APP.RTC.addStreamListener(streamHandler,
  2715. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  2716. APP.RTC.addStreamListener(function (stream) {
  2717. VideoLayout.onRemoteStreamAdded(stream);
  2718. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  2719. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  2720. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  2721. function (resourceJid) {
  2722. VideoLayout.onDominantSpeakerChanged(resourceJid);
  2723. });
  2724. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  2725. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  2726. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  2727. endpointsEnteringLastN, stream);
  2728. });
  2729. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  2730. function (devices) {
  2731. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  2732. });
  2733. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  2734. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  2735. // when the data channel becomes available, tell the bridge about video
  2736. // selections so that it can do adaptive simulcast,
  2737. // we want the notification to trigger even if userJid is undefined,
  2738. // or null.
  2739. var userResource = APP.UI.getLargeVideoResource();
  2740. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  2741. });
  2742. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  2743. var resourceJid;
  2744. if(jid === APP.statistics.LOCAL_JID) {
  2745. resourceJid = AudioLevels.LOCAL_LEVEL;
  2746. if(APP.RTC.localAudio.isMuted()) {
  2747. audioLevel = 0;
  2748. }
  2749. } else {
  2750. resourceJid = Strophe.getResourceFromJid(jid);
  2751. }
  2752. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  2753. UI.getLargeVideoResource());
  2754. });
  2755. APP.desktopsharing.addListener(function () {
  2756. ToolbarToggler.showDesktopSharingButton();
  2757. }, DesktopSharingEventTypes.INIT);
  2758. APP.desktopsharing.addListener(
  2759. Toolbar.changeDesktopSharingButtonState,
  2760. DesktopSharingEventTypes.SWITCHING_DONE);
  2761. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  2762. VideoLayout.updateLocalConnectionStats);
  2763. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  2764. VideoLayout.updateConnectionStats);
  2765. APP.connectionquality.addListener(CQEvents.STOP,
  2766. VideoLayout.onStatsStop);
  2767. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  2768. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  2769. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  2770. messageHandler.openMessageDialog(
  2771. 'dialog.serviceUnavailable',
  2772. 'dialog.gracefulShutdown'
  2773. );
  2774. });
  2775. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  2776. var title = APP.translation.generateTranslationHTML(
  2777. "dialog.reservationError");
  2778. var message = APP.translation.generateTranslationHTML(
  2779. "dialog.reservationErrorMsg", {code: code, msg: msg});
  2780. messageHandler.openDialog(
  2781. title,
  2782. message,
  2783. true, {},
  2784. function (event, value, message, formVals) {
  2785. return false;
  2786. }
  2787. );
  2788. });
  2789. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  2790. messageHandler.openMessageDialog("dialog.sessTerminated",
  2791. "dialog.kickMessage");
  2792. });
  2793. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  2794. //FIXME: use Session Terminated from translation, but
  2795. // 'reason' text comes from XMPP packet and is not translated
  2796. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  2797. messageHandler.openDialog(
  2798. title, reason, true, {},
  2799. function (event, value, message, formVals) {
  2800. return false;
  2801. }
  2802. );
  2803. });
  2804. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  2805. messageHandler.showError("dialog.error",
  2806. "dialog.bridgeUnavailable");
  2807. });
  2808. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  2809. Avatar.setUserAvatar(from, id);
  2810. });
  2811. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  2812. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  2813. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  2814. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  2815. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  2816. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  2817. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  2818. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  2819. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  2820. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  2821. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  2822. onAuthenticationRequired);
  2823. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  2824. onPeerVideoTypeChanged);
  2825. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  2826. function (resource, devices) {
  2827. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  2828. });
  2829. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  2830. VideoLayout.onAudioMute);
  2831. APP.xmpp.addListener(XMPPEvents.PARTICIPANT_VIDEO_MUTED,
  2832. VideoLayout.onVideoMute);
  2833. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  2834. UI.setAudioMuted(doMuteAudio);
  2835. });
  2836. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  2837. onDtmfSupportChanged);
  2838. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  2839. SettingsMenu.setStartMuted(audio, video);
  2840. });
  2841. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  2842. UI.setInitialMuteFromFocus(audio, video);
  2843. });
  2844. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  2845. UI.messageHandler.showError("dialog.sorry",
  2846. "dialog.internalError");
  2847. });
  2848. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  2849. messageHandler.showError("dialog.error",
  2850. "dialog.SLDFailure");
  2851. });
  2852. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  2853. messageHandler.showError("dialog.error",
  2854. "dialog.SRDFailure");
  2855. });
  2856. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  2857. messageHandler.showError();
  2858. });
  2859. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  2860. // FIXME: re-use LoginDialog which supports retries
  2861. UI.showLoginPopup(connect);
  2862. });
  2863. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  2864. UI.messageHandler.notify(
  2865. null, "notify.focus",
  2866. 'disconnected', "notify.focusFail",
  2867. {component: focusComponent, ms: retrySec});
  2868. });
  2869. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  2870. UI.messageHandler.openReportDialog(null,
  2871. "dialog.connectError", pres);
  2872. });
  2873. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  2874. UI.messageHandler.openReportDialog(null,
  2875. "dialog.connectError", pres);
  2876. });
  2877. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  2878. var roomName = UI.generateRoomName();
  2879. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  2880. });
  2881. //NicknameHandler emits this event
  2882. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  2883. APP.xmpp.addToPresence("displayName", nickname);
  2884. });
  2885. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  2886. AudioLevels.init();
  2887. });
  2888. if (!interfaceConfig.filmStripOnly) {
  2889. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  2890. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  2891. // Listens for video interruption events.
  2892. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  2893. // Listens for video restores events.
  2894. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  2895. }
  2896. }
  2897. /**
  2898. * Mutes/unmutes the local video.
  2899. *
  2900. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  2901. * @param options an object which specifies optional arguments such as the
  2902. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  2903. * specifies whether the method was initiated in response to a user command (in
  2904. * contrast to an automatic decision taken by the application logic)
  2905. */
  2906. function setVideoMute(mute, options) {
  2907. APP.RTC.setVideoMute(mute,
  2908. UI.setVideoMuteButtonsState,
  2909. options);
  2910. }
  2911. function onResize() {
  2912. Chat.resizeChat();
  2913. VideoLayout.resizeLargeVideoContainer();
  2914. }
  2915. function bindEvents() {
  2916. /**
  2917. * Resizes and repositions videos in full screen mode.
  2918. */
  2919. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  2920. onResize);
  2921. $(window).resize(onResize);
  2922. }
  2923. UI.start = function (init) {
  2924. document.title = interfaceConfig.APP_NAME;
  2925. var setupWelcomePage = null;
  2926. if(config.enableWelcomePage && window.location.pathname == "/" &&
  2927. (!window.localStorage.welcomePageDisabled ||
  2928. window.localStorage.welcomePageDisabled == "false")) {
  2929. $("#videoconference_page").hide();
  2930. if (!setupWelcomePage)
  2931. setupWelcomePage = require("./welcome_page/WelcomePage");
  2932. setupWelcomePage();
  2933. return;
  2934. }
  2935. $("#welcome_page").hide();
  2936. // Set the defaults for prompt dialogs.
  2937. $.prompt.setDefaults({persistent: false});
  2938. registerListeners();
  2939. VideoLayout.init(eventEmitter);
  2940. NicknameHandler.init(eventEmitter);
  2941. bindEvents();
  2942. setupPrezi();
  2943. if (!interfaceConfig.filmStripOnly) {
  2944. $("#videospace").mousemove(function () {
  2945. return ToolbarToggler.showToolbar();
  2946. });
  2947. setupToolbars();
  2948. setupChat();
  2949. // Display notice message at the top of the toolbar
  2950. if (config.noticeMessage) {
  2951. $('#noticeText').text(config.noticeMessage);
  2952. $('#notice').css({display: 'block'});
  2953. }
  2954. $("#downloadlog").click(function (event) {
  2955. dump(event.target);
  2956. });
  2957. }
  2958. else
  2959. {
  2960. $("#header").css("display", "none");
  2961. $("#bottomToolbar").css("display", "none");
  2962. $("#downloadlog").css("display", "none");
  2963. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  2964. $("#remoteVideos").css("right", "0px");
  2965. messageHandler.disableNotifications();
  2966. $('body').popover("disable");
  2967. // $("[data-toggle=popover]").popover("disable");
  2968. JitsiPopover.enabled = false;
  2969. }
  2970. document.title = interfaceConfig.APP_NAME;
  2971. if(config.requireDisplayName) {
  2972. var currentSettings = Settings.getSettings();
  2973. if (!currentSettings.displayName) {
  2974. promptDisplayName();
  2975. }
  2976. }
  2977. init();
  2978. if (!interfaceConfig.filmStripOnly) {
  2979. toastr.options = {
  2980. "closeButton": true,
  2981. "debug": false,
  2982. "positionClass": "notification-bottom-right",
  2983. "onclick": null,
  2984. "showDuration": "300",
  2985. "hideDuration": "1000",
  2986. "timeOut": "2000",
  2987. "extendedTimeOut": "1000",
  2988. "showEasing": "swing",
  2989. "hideEasing": "linear",
  2990. "showMethod": "fadeIn",
  2991. "hideMethod": "fadeOut",
  2992. "reposition": function () {
  2993. if (PanelToggler.isVisible()) {
  2994. $("#toast-container").addClass("notification-bottom-right-center");
  2995. } else {
  2996. $("#toast-container").removeClass("notification-bottom-right-center");
  2997. }
  2998. },
  2999. "newestOnTop": false
  3000. };
  3001. SettingsMenu.init();
  3002. }
  3003. };
  3004. function chatAddError(errorMessage, originalText) {
  3005. return Chat.chatAddError(errorMessage, originalText);
  3006. }
  3007. function chatSetSubject(text) {
  3008. return Chat.chatSetSubject(text);
  3009. }
  3010. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3011. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3012. }
  3013. function onMucJoined(jid, info) {
  3014. Toolbar.updateRoomUrl(window.location.href);
  3015. var meHTML = APP.translation.generateTranslationHTML("me");
  3016. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3017. var settings = Settings.getSettings();
  3018. // Make sure we configure our avatar id, before creating avatar for us
  3019. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3020. // Add myself to the contact list.
  3021. ContactList.addContact(jid);
  3022. // Once we've joined the muc show the toolbar
  3023. ToolbarToggler.showToolbar();
  3024. var displayName =
  3025. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3026. if (displayName)
  3027. onDisplayNameChanged('localVideoContainer', displayName);
  3028. VideoLayout.mucJoined();
  3029. }
  3030. function initEtherpad(name) {
  3031. Etherpad.init(name);
  3032. }
  3033. function onMucMemberLeft(jid) {
  3034. console.log('left.muc', jid);
  3035. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3036. '>.displayname').html();
  3037. messageHandler.notify(displayName,'notify.somebody',
  3038. 'disconnected',
  3039. 'notify.disconnected');
  3040. if (!config.startAudioMuted ||
  3041. config.startAudioMuted > APP.members.size()) {
  3042. UIUtil.playSoundNotification('userLeft');
  3043. }
  3044. ContactList.removeContact(jid);
  3045. VideoLayout.participantLeft(jid);
  3046. }
  3047. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3048. console.info("My role changed, new role: " + info.role);
  3049. onModeratorStatusChanged(isModerator);
  3050. VideoLayout.showModeratorIndicator();
  3051. SettingsMenu.onRoleChanged();
  3052. if (isModerator) {
  3053. Authentication.closeAuthenticationWindow();
  3054. messageHandler.notify(null, "notify.me",
  3055. 'connected', "notify.moderator");
  3056. Toolbar.checkAutoRecord();
  3057. }
  3058. }
  3059. function onModeratorStatusChanged(isModerator) {
  3060. Toolbar.showSipCallButton(isModerator);
  3061. Toolbar.showRecordingButton(
  3062. isModerator); //&&
  3063. // FIXME:
  3064. // Recording visible if
  3065. // there are at least 2(+ 1 focus) participants
  3066. //Object.keys(connection.emuc.members).length >= 3);
  3067. }
  3068. function onPasswordRequired(callback) {
  3069. // password is required
  3070. Toolbar.lockLockButton();
  3071. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3072. message += APP.translation.translateString(
  3073. "dialog.passwordRequired");
  3074. message += '</h2>' +
  3075. '<input name="lockKey" type="text" data-i18n=' +
  3076. '"[placeholder]dialog.password" placeholder="' +
  3077. APP.translation.translateString("dialog.password") +
  3078. '" autofocus>';
  3079. messageHandler.openTwoButtonDialog(null, null, null, message,
  3080. true,
  3081. "dialog.Ok",
  3082. function (e, v, m, f) {},
  3083. null,
  3084. function (e, v, m, f) {
  3085. if (v) {
  3086. var lockKey = f.lockKey;
  3087. if (lockKey) {
  3088. Toolbar.setSharedKey(lockKey);
  3089. callback(lockKey);
  3090. }
  3091. }
  3092. },
  3093. ':input:first'
  3094. );
  3095. }
  3096. /**
  3097. * The dialpad button is shown iff there is at least one member that supports
  3098. * DTMF (e.g. jigasi).
  3099. */
  3100. function onDtmfSupportChanged(dtmfSupport) {
  3101. //TODO: enable when the UI is ready
  3102. //Toolbar.showDialPadButton(dtmfSupport);
  3103. }
  3104. function onMucMemberJoined(jid, id, displayName) {
  3105. messageHandler.notify(displayName,'notify.somebody',
  3106. 'connected',
  3107. 'notify.connected');
  3108. if (!config.startAudioMuted ||
  3109. config.startAudioMuted > APP.members.size())
  3110. UIUtil.playSoundNotification('userJoined');
  3111. // Configure avatar
  3112. Avatar.setUserAvatar(jid, id);
  3113. // Add Peer's container
  3114. VideoLayout.ensurePeerContainerExists(jid);
  3115. }
  3116. function onMucPresenceStatus(jid, info) {
  3117. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3118. }
  3119. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3120. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3121. }
  3122. function onMucRoleChanged(role, displayName) {
  3123. VideoLayout.showModeratorIndicator();
  3124. if (role === 'moderator') {
  3125. var messageKey, messageOptions = {};
  3126. if (!displayName) {
  3127. messageKey = "notify.grantedToUnknown";
  3128. }
  3129. else {
  3130. messageKey = "notify.grantedTo";
  3131. messageOptions = {to: displayName};
  3132. }
  3133. messageHandler.notify(
  3134. displayName,'notify.somebody',
  3135. 'connected', messageKey,
  3136. messageOptions);
  3137. }
  3138. }
  3139. function onAuthenticationRequired(intervalCallback) {
  3140. Authentication.openAuthenticationDialog(
  3141. roomName, intervalCallback, function () {
  3142. Toolbar.authenticateClicked();
  3143. });
  3144. }
  3145. function onLastNChanged(oldValue, newValue) {
  3146. if (config.muteLocalVideoIfNotInLastN) {
  3147. setVideoMute(!newValue, { 'byUser': false });
  3148. }
  3149. }
  3150. UI.toggleSmileys = function () {
  3151. Chat.toggleSmileys();
  3152. };
  3153. UI.getSettings = function () {
  3154. return Settings.getSettings();
  3155. };
  3156. UI.toggleFilmStrip = function () {
  3157. return BottomToolbar.toggleFilmStrip();
  3158. };
  3159. UI.toggleChat = function () {
  3160. return BottomToolbar.toggleChat();
  3161. };
  3162. UI.toggleContactList = function () {
  3163. return BottomToolbar.toggleContactList();
  3164. };
  3165. UI.inputDisplayNameHandler = function (value) {
  3166. VideoLayout.inputDisplayNameHandler(value);
  3167. };
  3168. UI.getLargeVideoResource = function () {
  3169. return VideoLayout.getLargeVideoResource();
  3170. };
  3171. UI.getRoomNode = function () {
  3172. if (roomNode)
  3173. return roomNode;
  3174. var path = window.location.pathname;
  3175. // determinde the room node from the url
  3176. // TODO: just the roomnode or the whole bare jid?
  3177. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3178. // custom function might be responsible for doing the pushstate
  3179. roomNode = config.getroomnode(path);
  3180. } else {
  3181. /* fall back to default strategy
  3182. * this is making assumptions about how the URL->room mapping happens.
  3183. * It currently assumes deployment at root, with a rewrite like the
  3184. * following one (for nginx):
  3185. location ~ ^/([a-zA-Z0-9]+)$ {
  3186. rewrite ^/(.*)$ / break;
  3187. }
  3188. */
  3189. if (path.length > 1) {
  3190. roomNode = path.substr(1).toLowerCase();
  3191. } else {
  3192. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3193. roomNode = word.toLowerCase();
  3194. window.history.pushState('VideoChat',
  3195. 'Room: ' + word, window.location.pathname + word);
  3196. }
  3197. }
  3198. return roomNode;
  3199. };
  3200. UI.generateRoomName = function () {
  3201. if (roomName)
  3202. return roomName;
  3203. var roomNode = UI.getRoomNode();
  3204. roomName = roomNode + '@' + config.hosts.muc;
  3205. return roomName;
  3206. };
  3207. UI.connectionIndicatorShowMore = function(jid) {
  3208. return VideoLayout.showMore(jid);
  3209. };
  3210. UI.showLoginPopup = function(callback) {
  3211. console.log('password is required');
  3212. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3213. message += APP.translation.translateString(
  3214. "dialog.passwordRequired");
  3215. message += '</h2>' +
  3216. '<input name="username" type="text" ' +
  3217. 'placeholder="user@domain.net" autofocus>' +
  3218. '<input name="password" ' +
  3219. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3220. ' placeholder="user password">';
  3221. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3222. true,
  3223. "dialog.Ok",
  3224. function (e, v, m, f) {
  3225. if (v) {
  3226. if (f.username !== null && f.password != null) {
  3227. callback(f.username, f.password);
  3228. }
  3229. }
  3230. },
  3231. null, null, ':input:first'
  3232. );
  3233. };
  3234. UI.checkForNicknameAndJoin = function () {
  3235. Authentication.closeAuthenticationDialog();
  3236. Authentication.stopInterval();
  3237. var nick = null;
  3238. if (config.useNicks) {
  3239. nick = window.prompt('Your nickname (optional)');
  3240. }
  3241. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3242. };
  3243. function dump(elem, filename) {
  3244. elem = elem.parentNode;
  3245. elem.download = filename || 'meetlog.json';
  3246. elem.href = 'data:application/json;charset=utf-8,\n';
  3247. var data = APP.xmpp.getJingleLog();
  3248. var metadata = {};
  3249. metadata.time = new Date();
  3250. metadata.url = window.location.href;
  3251. metadata.ua = navigator.userAgent;
  3252. var log = APP.xmpp.getXmppLog();
  3253. if (log) {
  3254. metadata.xmpp = log;
  3255. }
  3256. data.metadata = metadata;
  3257. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3258. return false;
  3259. }
  3260. UI.getRoomName = function () {
  3261. return roomName;
  3262. };
  3263. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3264. if (muteAudio || muteVideo)
  3265. notifyForInitialMute();
  3266. if (muteAudio)
  3267. UI.setAudioMuted(true);
  3268. if (muteVideo)
  3269. UI.setVideoMute(true);
  3270. };
  3271. /**
  3272. * Mutes/unmutes the local video.
  3273. */
  3274. UI.toggleVideo = function () {
  3275. setVideoMute(!APP.RTC.localVideo.isMuted());
  3276. };
  3277. /**
  3278. * Mutes / unmutes audio for the local participant.
  3279. */
  3280. UI.toggleAudio = function() {
  3281. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3282. };
  3283. /**
  3284. * Sets muted audio state for the local participant.
  3285. */
  3286. UI.setAudioMuted = function (mute, earlyMute) {
  3287. var audioMute = null;
  3288. if (earlyMute)
  3289. audioMute = function (mute, cb) {
  3290. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3291. };
  3292. else
  3293. audioMute = function (mute, cb) {
  3294. return APP.xmpp.setAudioMute(mute, cb);
  3295. };
  3296. if (!audioMute(mute, function () {
  3297. VideoLayout.showLocalAudioIndicator(mute);
  3298. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3299. })) {
  3300. // We still click the button.
  3301. UIUtil.buttonClick("#toolbar_button_mute", "icon-microphone icon-mic-disabled");
  3302. return;
  3303. }
  3304. };
  3305. UI.addListener = function (type, listener) {
  3306. eventEmitter.on(type, listener);
  3307. };
  3308. UI.clickOnVideo = function (videoNumber) {
  3309. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3310. if (remoteVideos.length > videoNumber) {
  3311. remoteVideos[videoNumber].click();
  3312. }
  3313. };
  3314. //Used by torture
  3315. UI.showToolbar = function () {
  3316. return ToolbarToggler.showToolbar();
  3317. };
  3318. //Used by torture
  3319. UI.dockToolbar = function (isDock) {
  3320. return ToolbarToggler.dockToolbar(isDock);
  3321. };
  3322. UI.setVideoMuteButtonsState = function (mute) {
  3323. var video = $('#toolbar_button_camera');
  3324. var communicativeClass = "icon-camera";
  3325. var muteClass = "icon-camera icon-camera-disabled";
  3326. if (mute) {
  3327. video.removeClass(communicativeClass);
  3328. video.addClass(muteClass);
  3329. } else {
  3330. video.removeClass(muteClass);
  3331. video.addClass(communicativeClass);
  3332. }
  3333. };
  3334. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3335. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3336. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3337. if(resourceJid === APP.xmpp.myResource())
  3338. SettingsMenu.changeAvatar(thumbUrl);
  3339. };
  3340. UI.setVideoMute = setVideoMute;
  3341. module.exports = UI;
  3342. },{"../../service/RTC/RTCEvents":163,"../../service/RTC/StreamEventTypes":165,"../../service/UI/UIEvents":166,"../../service/connectionquality/CQEvents":168,"../../service/desktopsharing/DesktopSharingEventTypes":169,"../../service/members/Events":170,"../../service/xmpp/XMPPEvents":172,"../RTC/RTCBrowserType":8,"./../settings/Settings":49,"./audio_levels/AudioLevels.js":12,"./authentication/Authentication":14,"./avatar/Avatar":16,"./etherpad/Etherpad.js":17,"./prezi/Prezi.js":18,"./side_pannels/SidePanelToggler":20,"./side_pannels/chat/Chat.js":21,"./side_pannels/contactlist/ContactList":25,"./side_pannels/settings/SettingsMenu":26,"./toolbars/BottomToolbar":27,"./toolbars/Toolbar":28,"./toolbars/ToolbarToggler":29,"./util/JitsiPopover":30,"./util/MessageHandler":31,"./util/NicknameHandler":32,"./util/UIUtil":33,"./videolayout/VideoLayout.js":39,"./welcome_page/RoomnameGenerator":40,"./welcome_page/WelcomePage":41,"events":173}],12:[function(require,module,exports){
  3343. /* global APP, interfaceConfig, $, Strophe */
  3344. var CanvasUtil = require("./CanvasUtils");
  3345. var ASDrawContext = null;
  3346. function initActiveSpeakerAudioLevels() {
  3347. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3348. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3349. // Draw a circle.
  3350. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3351. // Add a shadow around the circle
  3352. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3353. ASDrawContext.shadowOffsetX = 0;
  3354. ASDrawContext.shadowOffsetY = 0;
  3355. }
  3356. /**
  3357. * The audio Levels plugin.
  3358. */
  3359. var AudioLevels = (function(my) {
  3360. var audioLevelCanvasCache = {};
  3361. my.LOCAL_LEVEL = 'local';
  3362. my.init = function () {
  3363. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3364. initActiveSpeakerAudioLevels();
  3365. };
  3366. /**
  3367. * Updates the audio level canvas for the given peerJid. If the canvas
  3368. * didn't exist we create it.
  3369. */
  3370. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3371. var resourceJid = null;
  3372. var videoSpanId = null;
  3373. if (!peerJid)
  3374. videoSpanId = 'localVideoContainer';
  3375. else {
  3376. resourceJid = Strophe.getResourceFromJid(peerJid);
  3377. videoSpanId = 'participant_' + resourceJid;
  3378. }
  3379. var videoSpan = document.getElementById(videoSpanId);
  3380. if (!videoSpan) {
  3381. if (resourceJid)
  3382. console.error("No video element for jid", resourceJid);
  3383. else
  3384. console.error("No video element for local video.");
  3385. return;
  3386. }
  3387. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3388. var videoSpaceWidth = $('#remoteVideos').width();
  3389. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3390. var thumbnailWidth = thumbnailSize[0];
  3391. var thumbnailHeight = thumbnailSize[1];
  3392. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3393. audioLevelCanvas = document.createElement('canvas');
  3394. audioLevelCanvas.className = "audiolevel";
  3395. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3396. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3397. resizeAudioLevelCanvas( audioLevelCanvas,
  3398. thumbnailWidth,
  3399. thumbnailHeight);
  3400. videoSpan.appendChild(audioLevelCanvas);
  3401. } else {
  3402. audioLevelCanvas = audioLevelCanvas.get(0);
  3403. resizeAudioLevelCanvas( audioLevelCanvas,
  3404. thumbnailWidth,
  3405. thumbnailHeight);
  3406. }
  3407. };
  3408. /**
  3409. * Updates the audio level UI for the given resourceJid.
  3410. *
  3411. * @param resourceJid the resource jid indicating the video element for
  3412. * which we draw the audio level
  3413. * @param audioLevel the newAudio level to render
  3414. */
  3415. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3416. drawAudioLevelCanvas(resourceJid, audioLevel);
  3417. var videoSpanId = getVideoSpanId(resourceJid);
  3418. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3419. if (!audioLevelCanvas)
  3420. return;
  3421. var drawContext = audioLevelCanvas.getContext('2d');
  3422. var canvasCache = audioLevelCanvasCache[resourceJid];
  3423. drawContext.clearRect (0, 0,
  3424. audioLevelCanvas.width, audioLevelCanvas.height);
  3425. drawContext.drawImage(canvasCache, 0, 0);
  3426. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3427. if(!APP.xmpp.myJid()) {
  3428. return;
  3429. }
  3430. resourceJid = APP.xmpp.myResource();
  3431. }
  3432. if(resourceJid === largeVideoResourceJid) {
  3433. window.requestAnimationFrame(function () {
  3434. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3435. });
  3436. }
  3437. };
  3438. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3439. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3440. return;
  3441. ASDrawContext.clearRect(0, 0, 300, 300);
  3442. if(audioLevel == 0)
  3443. return;
  3444. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3445. // Fill the shape.
  3446. ASDrawContext.fill();
  3447. };
  3448. /**
  3449. * Resizes the given audio level canvas to match the given thumbnail size.
  3450. */
  3451. function resizeAudioLevelCanvas(audioLevelCanvas,
  3452. thumbnailWidth,
  3453. thumbnailHeight) {
  3454. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3455. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3456. }
  3457. /**
  3458. * Draws the audio level canvas into the cached canvas object.
  3459. *
  3460. * @param resourceJid the resource jid indicating the video element for
  3461. * which we draw the audio level
  3462. * @param audioLevel the newAudio level to render
  3463. */
  3464. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3465. if (!audioLevelCanvasCache[resourceJid]) {
  3466. var videoSpanId = getVideoSpanId(resourceJid);
  3467. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3468. /*
  3469. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3470. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3471. * error. Since audio levels are frequently updated, the errors have
  3472. * been observed to pile into the console, strain the CPU.
  3473. */
  3474. if (audioLevelCanvasOrig) {
  3475. audioLevelCanvasCache[resourceJid] =
  3476. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3477. }
  3478. }
  3479. var canvas = audioLevelCanvasCache[resourceJid];
  3480. if (!canvas)
  3481. return;
  3482. var drawContext = canvas.getContext('2d');
  3483. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3484. var shadowLevel = getShadowLevel(audioLevel);
  3485. if (shadowLevel > 0) {
  3486. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3487. CanvasUtil.drawRoundRectGlow(drawContext,
  3488. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3489. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3490. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3491. interfaceConfig.CANVAS_RADIUS,
  3492. interfaceConfig.SHADOW_COLOR,
  3493. shadowLevel);
  3494. }
  3495. }
  3496. /**
  3497. * Returns the shadow/glow level for the given audio level.
  3498. *
  3499. * @param audioLevel the audio level from which we determine the shadow
  3500. * level
  3501. */
  3502. function getShadowLevel (audioLevel) {
  3503. var shadowLevel = 0;
  3504. if (audioLevel <= 0.3) {
  3505. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3506. }
  3507. else if (audioLevel <= 0.6) {
  3508. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3509. }
  3510. else {
  3511. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3512. }
  3513. return shadowLevel;
  3514. }
  3515. /**
  3516. * Returns the video span id corresponding to the given resourceJid or local
  3517. * user.
  3518. */
  3519. function getVideoSpanId(resourceJid) {
  3520. var videoSpanId = null;
  3521. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3522. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3523. videoSpanId = 'localVideoContainer';
  3524. else
  3525. videoSpanId = 'participant_' + resourceJid;
  3526. return videoSpanId;
  3527. }
  3528. /**
  3529. * Indicates that the remote video has been resized.
  3530. */
  3531. $(document).bind('remotevideo.resized', function (event, width, height) {
  3532. var resized = false;
  3533. $('#remoteVideos>span>canvas').each(function() {
  3534. var canvas = $(this).get(0);
  3535. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3536. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3537. resized = true;
  3538. }
  3539. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3540. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3541. resized = true;
  3542. }
  3543. });
  3544. if (resized)
  3545. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3546. audioLevelCanvasCache[resourceJid].width =
  3547. width + interfaceConfig.CANVAS_EXTRA;
  3548. audioLevelCanvasCache[resourceJid].height =
  3549. height + interfaceConfig.CANVAS_EXTRA;
  3550. });
  3551. });
  3552. return my;
  3553. })(AudioLevels || {});
  3554. module.exports = AudioLevels;
  3555. },{"./CanvasUtils":13}],13:[function(require,module,exports){
  3556. /**
  3557. * Utility class for drawing canvas shapes.
  3558. */
  3559. var CanvasUtil = (function(my) {
  3560. /**
  3561. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3562. * of the glow.
  3563. *
  3564. * @param drawContext the context of the canvas to draw to
  3565. * @param x the x coordinate of the round rectangle
  3566. * @param y the y coordinate of the round rectangle
  3567. * @param w the width of the round rectangle
  3568. * @param h the height of the round rectangle
  3569. * @param glowColor the color of the glow
  3570. * @param glowWidth the width of the glow
  3571. */
  3572. my.drawRoundRectGlow
  3573. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3574. // Save the previous state of the context.
  3575. drawContext.save();
  3576. if (w < 2 * r) r = w / 2;
  3577. if (h < 2 * r) r = h / 2;
  3578. // Draw a round rectangle.
  3579. drawContext.beginPath();
  3580. drawContext.moveTo(x+r, y);
  3581. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3582. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3583. drawContext.arcTo(x, y+h, x, y, r);
  3584. drawContext.arcTo(x, y, x+w, y, r);
  3585. drawContext.closePath();
  3586. // Add a shadow around the rectangle
  3587. drawContext.shadowColor = glowColor;
  3588. drawContext.shadowBlur = glowWidth;
  3589. drawContext.shadowOffsetX = 0;
  3590. drawContext.shadowOffsetY = 0;
  3591. // Fill the shape.
  3592. drawContext.fill();
  3593. drawContext.save();
  3594. drawContext.restore();
  3595. // 1) Uncomment this line to use Composite Operation, which is doing the
  3596. // same as the clip function below and is also antialiasing the round
  3597. // border, but is said to be less fast performance wise.
  3598. // drawContext.globalCompositeOperation='destination-out';
  3599. drawContext.beginPath();
  3600. drawContext.moveTo(x+r, y);
  3601. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3602. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3603. drawContext.arcTo(x, y+h, x, y, r);
  3604. drawContext.arcTo(x, y, x+w, y, r);
  3605. drawContext.closePath();
  3606. // 2) Uncomment this line to use Composite Operation, which is doing the
  3607. // same as the clip function below and is also antialiasing the round
  3608. // border, but is said to be less fast performance wise.
  3609. // drawContext.fill();
  3610. // Comment these two lines if choosing to do the same with composite
  3611. // operation above 1 and 2.
  3612. drawContext.clip();
  3613. drawContext.clearRect(0, 0, 277, 200);
  3614. // Restore the previous context state.
  3615. drawContext.restore();
  3616. };
  3617. /**
  3618. * Clones the given canvas.
  3619. *
  3620. * @return the new cloned canvas.
  3621. */
  3622. my.cloneCanvas = function (oldCanvas) {
  3623. /*
  3624. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3625. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3626. * levels are frequently updated, the errors have been observed to pile
  3627. * into the console, strain the CPU.
  3628. */
  3629. if (!oldCanvas)
  3630. return oldCanvas;
  3631. //create a new canvas
  3632. var newCanvas = document.createElement('canvas');
  3633. var context = newCanvas.getContext('2d');
  3634. //set dimensions
  3635. newCanvas.width = oldCanvas.width;
  3636. newCanvas.height = oldCanvas.height;
  3637. //apply the old canvas to the new one
  3638. context.drawImage(oldCanvas, 0, 0);
  3639. //return the new canvas
  3640. return newCanvas;
  3641. };
  3642. return my;
  3643. })(CanvasUtil || {});
  3644. module.exports = CanvasUtil;
  3645. },{}],14:[function(require,module,exports){
  3646. /* global $, APP*/
  3647. var LoginDialog = require('./LoginDialog');
  3648. var Moderator = require('../../xmpp/moderator');
  3649. /* Initial "authentication required" dialog */
  3650. var authDialog = null;
  3651. /* Loop retry ID that wits for other user to create the room */
  3652. var authRetryId = null;
  3653. var authenticationWindow = null;
  3654. var Authentication = {
  3655. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  3656. // This is the loop that will wait for the room to be created by
  3657. // someone else. 'auth_required.moderator' will bring us back here.
  3658. authRetryId = window.setTimeout(intervalCallback, 5000);
  3659. // Show prompt only if it's not open
  3660. if (authDialog !== null) {
  3661. return;
  3662. }
  3663. // extract room name from 'room@muc.server.net'
  3664. var room = roomName.substr(0, roomName.indexOf('@'));
  3665. var title
  3666. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  3667. var msg
  3668. = APP.translation.generateTranslationHTML(
  3669. "dialog.WaitForHostMsg", {room: room});
  3670. var buttonTxt
  3671. = APP.translation.generateTranslationHTML("dialog.IamHost");
  3672. var buttons = [];
  3673. buttons.push({title: buttonTxt, value: "authNow"});
  3674. authDialog = APP.UI.messageHandler.openDialog(
  3675. title,
  3676. msg,
  3677. true,
  3678. buttons,
  3679. function (onSubmitEvent, submitValue) {
  3680. // Do not close the dialog yet
  3681. onSubmitEvent.preventDefault();
  3682. // Open login popup
  3683. if (submitValue === 'authNow') {
  3684. callback();
  3685. }
  3686. }
  3687. );
  3688. },
  3689. closeAuthenticationWindow: function () {
  3690. if (authenticationWindow) {
  3691. authenticationWindow.close();
  3692. authenticationWindow = null;
  3693. }
  3694. },
  3695. xmppAuthenticate: function () {
  3696. var loginDialog = LoginDialog.show(
  3697. function (connection, state) {
  3698. if (!state) {
  3699. // User cancelled
  3700. loginDialog.close();
  3701. return;
  3702. } else if (state == APP.xmpp.Status.CONNECTED) {
  3703. loginDialog.close();
  3704. Authentication.stopInterval();
  3705. Authentication.closeAuthenticationDialog();
  3706. // Close the connection as anonymous one will be used
  3707. // to create the conference. Session-id will authorize
  3708. // the request.
  3709. connection.disconnect();
  3710. var roomName = APP.UI.generateRoomName();
  3711. Moderator.allocateConferenceFocus(roomName, function () {
  3712. // If it's not "on the fly" authentication now join
  3713. // the conference room
  3714. if (!APP.xmpp.isMUCJoined()) {
  3715. APP.UI.checkForNicknameAndJoin();
  3716. }
  3717. });
  3718. }
  3719. }, true);
  3720. },
  3721. focusAuthenticationWindow: function () {
  3722. // If auth window exists just bring it to the front
  3723. if (authenticationWindow) {
  3724. authenticationWindow.focus();
  3725. return;
  3726. }
  3727. },
  3728. closeAuthenticationDialog: function () {
  3729. // Close authentication dialog if opened
  3730. if (authDialog) {
  3731. authDialog.close();
  3732. authDialog = null;
  3733. }
  3734. },
  3735. createAuthenticationWindow: function (callback, url) {
  3736. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  3737. url, 910, 660,
  3738. // On closed
  3739. function () {
  3740. // Close authentication dialog if opened
  3741. Authentication.closeAuthenticationDialog();
  3742. callback();
  3743. authenticationWindow = null;
  3744. });
  3745. return authenticationWindow;
  3746. },
  3747. stopInterval: function () {
  3748. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  3749. if (authRetryId) {
  3750. window.clearTimeout(authRetryId);
  3751. authRetryId = null;
  3752. }
  3753. }
  3754. };
  3755. module.exports = Authentication;
  3756. },{"../../xmpp/moderator":62,"./LoginDialog":15}],15:[function(require,module,exports){
  3757. /* global $, APP, config*/
  3758. var XMPP = require('../../xmpp/xmpp');
  3759. var Moderator = require('../../xmpp/moderator');
  3760. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  3761. // anonymous domain is not enabled
  3762. /**
  3763. * Creates new <tt>Dialog</tt> instance.
  3764. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  3765. * when we either fail to connect or succeed(check Strophe.Status).
  3766. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  3767. * in order to create session-id after the connection is established.
  3768. * @constructor
  3769. */
  3770. function Dialog(callback, obtainSession) {
  3771. var self = this;
  3772. var stop = false;
  3773. var connection = APP.xmpp.createConnection();
  3774. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3775. message += APP.translation.translateString("dialog.passwordRequired");
  3776. message += '</h2>' +
  3777. '<input name="username" type="text" ' +
  3778. 'placeholder="user@domain.net" autofocus>' +
  3779. '<input name="password" ' +
  3780. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3781. ' placeholder="user password">';
  3782. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  3783. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  3784. var states = {
  3785. login: {
  3786. html: message,
  3787. buttons: [
  3788. { title: okButton, value: true},
  3789. { title: cancelButton, value: false}
  3790. ],
  3791. focus: ':input:first',
  3792. submit: function (e, v, m, f) {
  3793. e.preventDefault();
  3794. if (v) {
  3795. var jid = f.username;
  3796. var password = f.password;
  3797. if (jid && password) {
  3798. stop = false;
  3799. connection.reset();
  3800. connDialog.goToState('connecting');
  3801. connection.connect(jid, password, stateHandler);
  3802. }
  3803. } else {
  3804. // User cancelled
  3805. stop = true;
  3806. callback();
  3807. }
  3808. }
  3809. },
  3810. connecting: {
  3811. title: APP.translation.translateString('dialog.connecting'),
  3812. html: '<div id="connectionStatus"></div>',
  3813. buttons: [],
  3814. defaultButton: 0
  3815. },
  3816. finished: {
  3817. title: APP.translation.translateString('dialog.error'),
  3818. html: '<div id="errorMessage"></div>',
  3819. buttons: [
  3820. {
  3821. title: APP.translation.translateString('dialog.retry'),
  3822. value: 'retry'
  3823. },
  3824. {
  3825. title: APP.translation.translateString('dialog.Cancel'),
  3826. value: 'cancel'
  3827. },
  3828. ],
  3829. defaultButton: 0,
  3830. submit: function (e, v, m, f) {
  3831. e.preventDefault();
  3832. if (v === 'retry')
  3833. connDialog.goToState('login');
  3834. else
  3835. callback();
  3836. }
  3837. }
  3838. };
  3839. var connDialog
  3840. = APP.UI.messageHandler.openDialogWithStates(states,
  3841. { persistent: true, closeText: '' }, null);
  3842. var stateHandler = function (status, message) {
  3843. if (stop) {
  3844. return;
  3845. }
  3846. var translateKey = "connection." + XMPP.getStatusString(status);
  3847. var statusStr = APP.translation.translateString(translateKey);
  3848. // Display current state
  3849. var connectionStatus =
  3850. connDialog.getState('connecting').find('#connectionStatus');
  3851. connectionStatus.text(statusStr);
  3852. switch (status) {
  3853. case XMPP.Status.CONNECTED:
  3854. stop = true;
  3855. if (!obtainSession) {
  3856. callback(connection, status);
  3857. return;
  3858. }
  3859. // Obtaining session-id status
  3860. connectionStatus.text(
  3861. APP.translation.translateString(
  3862. 'connection.FETCH_SESSION_ID'));
  3863. // Authenticate with Jicofo and obtain session-id
  3864. var roomName = APP.UI.generateRoomName();
  3865. // Jicofo will return new session-id when connected
  3866. // from authenticated domain
  3867. connection.sendIQ(
  3868. Moderator.createConferenceIq(roomName),
  3869. function (result) {
  3870. connectionStatus.text(
  3871. APP.translation.translateString(
  3872. 'connection.GOT_SESSION_ID'));
  3873. stop = true;
  3874. // Parse session-id
  3875. Moderator.parseSessionId(result);
  3876. callback(connection, status);
  3877. },
  3878. function (error) {
  3879. console.error("Auth on the fly failed", error);
  3880. stop = true;
  3881. var errorMsg =
  3882. APP.translation.translateString(
  3883. 'connection.GET_SESSION_ID_ERROR') +
  3884. $(error).find('>error').attr('code');
  3885. self.displayError(errorMsg);
  3886. connection.disconnect();
  3887. });
  3888. break;
  3889. case XMPP.Status.AUTHFAIL:
  3890. case XMPP.Status.CONNFAIL:
  3891. case XMPP.Status.DISCONNECTED:
  3892. stop = true;
  3893. callback(connection, status);
  3894. var errorMessage = statusStr;
  3895. if (message)
  3896. {
  3897. errorMessage += ': ' + message;
  3898. }
  3899. self.displayError(errorMessage);
  3900. break;
  3901. default:
  3902. break;
  3903. }
  3904. };
  3905. /**
  3906. * Displays error message in 'finished' state which allows either to cancel
  3907. * or retry.
  3908. * @param message the final message to be displayed.
  3909. */
  3910. this.displayError = function (message) {
  3911. var finishedState = connDialog.getState('finished');
  3912. var errorMessageElem = finishedState.find('#errorMessage');
  3913. errorMessageElem.text(message);
  3914. connDialog.goToState('finished');
  3915. };
  3916. /**
  3917. * Closes LoginDialog.
  3918. */
  3919. this.close = function () {
  3920. stop = true;
  3921. connDialog.close();
  3922. };
  3923. }
  3924. var LoginDialog = {
  3925. /**
  3926. * Displays login prompt used to establish new XMPP connection. Given
  3927. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  3928. * called when we connect successfully(status === CONNECTED) or when we fail
  3929. * to do so. On connection failure program can call Dialog.close() method in
  3930. * order to cancel or do nothing to let the user retry.
  3931. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  3932. * called when we either fail to connect or succeed(check
  3933. * Strophe.Status).
  3934. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  3935. * Jicofo in order to create session-id after the connection is
  3936. * established.
  3937. * @returns {Dialog}
  3938. */
  3939. show: function (callback, obtainSession) {
  3940. return new Dialog(callback, obtainSession);
  3941. }
  3942. };
  3943. module.exports = LoginDialog;
  3944. },{"../../xmpp/moderator":62,"../../xmpp/xmpp":71}],16:[function(require,module,exports){
  3945. var Settings = require("../../settings/Settings");
  3946. var users = {};
  3947. var Avatar = {
  3948. /**
  3949. * Sets the user's avatar in the settings menu(if local user), contact list
  3950. * and thumbnail
  3951. * @param jid jid of the user
  3952. * @param id email or userID to be used as a hash
  3953. */
  3954. setUserAvatar: function (jid, id) {
  3955. if (id) {
  3956. if (users[jid] === id) {
  3957. return;
  3958. }
  3959. users[jid] = id;
  3960. }
  3961. var thumbUrl = this.getThumbUrl(jid);
  3962. var contactListUrl = this.getContactListUrl(jid);
  3963. var resourceJid = Strophe.getResourceFromJid(jid);
  3964. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  3965. },
  3966. /**
  3967. * Returns image URL for the avatar to be displayed on large video area
  3968. * where current active speaker is presented.
  3969. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  3970. */
  3971. getActiveSpeakerUrl: function (jid) {
  3972. return this.getGravatarUrl(jid, 100);
  3973. },
  3974. /**
  3975. * Returns image URL for the avatar to be displayed on small video thumbnail
  3976. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  3977. */
  3978. getThumbUrl: function (jid) {
  3979. return this.getGravatarUrl(jid, 100);
  3980. },
  3981. /**
  3982. * Returns the URL for the avatar to be displayed as contactlist item
  3983. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  3984. */
  3985. getContactListUrl: function (jid) {
  3986. return this.getGravatarUrl(jid, 30);
  3987. },
  3988. getGravatarUrl: function (jid, size) {
  3989. if (!jid) {
  3990. console.error("Get gravatar - jid is undefined");
  3991. return null;
  3992. }
  3993. var id = users[jid];
  3994. if (!id) {
  3995. console.warn(
  3996. "No avatar stored yet for " + jid + " - using JID as ID");
  3997. id = jid;
  3998. }
  3999. return 'https://www.gravatar.com/avatar/' +
  4000. MD5.hexdigest(id.trim().toLowerCase()) +
  4001. "?d=wavatar&size=" + (size || "30");
  4002. }
  4003. };
  4004. module.exports = Avatar;
  4005. },{"../../settings/Settings":49}],17:[function(require,module,exports){
  4006. /* global $, config,
  4007. setLargeVideoVisible, Util */
  4008. var VideoLayout = require("../videolayout/VideoLayout");
  4009. var Prezi = require("../prezi/Prezi");
  4010. var UIUtil = require("../util/UIUtil");
  4011. var etherpadName = null;
  4012. var etherpadIFrame = null;
  4013. var domain = null;
  4014. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4015. /**
  4016. * Resizes the etherpad.
  4017. */
  4018. function resize() {
  4019. if ($('#etherpad>iframe').length) {
  4020. var remoteVideos = $('#remoteVideos');
  4021. var availableHeight
  4022. = window.innerHeight - remoteVideos.outerHeight();
  4023. var availableWidth = UIUtil.getAvailableVideoWidth();
  4024. $('#etherpad>iframe').width(availableWidth);
  4025. $('#etherpad>iframe').height(availableHeight);
  4026. }
  4027. }
  4028. /**
  4029. * Creates the Etherpad button and adds it to the toolbar.
  4030. */
  4031. function enableEtherpadButton() {
  4032. if (!$('#toolbar_button_etherpad').is(":visible"))
  4033. $('#toolbar_button_etherpad').css({display: 'inline-block'});
  4034. }
  4035. /**
  4036. * Creates the IFrame for the etherpad.
  4037. */
  4038. function createIFrame() {
  4039. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4040. domain + etherpadName + options, function() {
  4041. document.domain = document.domain;
  4042. bubbleIframeMouseMove(etherpadIFrame);
  4043. setTimeout(function() {
  4044. // the iframes inside of the etherpad are
  4045. // not yet loaded when the etherpad iframe is loaded
  4046. var outer = etherpadIFrame.
  4047. contentDocument.getElementsByName("ace_outer")[0];
  4048. bubbleIframeMouseMove(outer);
  4049. var inner = outer.
  4050. contentDocument.getElementsByName("ace_inner")[0];
  4051. bubbleIframeMouseMove(inner);
  4052. }, 2000);
  4053. });
  4054. }
  4055. function bubbleIframeMouseMove(iframe){
  4056. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4057. iframe.contentWindow.onmousemove = function(e){
  4058. if(existingOnMouseMove) existingOnMouseMove(e);
  4059. var evt = document.createEvent("MouseEvents");
  4060. var boundingClientRect = iframe.getBoundingClientRect();
  4061. evt.initMouseEvent(
  4062. "mousemove",
  4063. true, // bubbles
  4064. false, // not cancelable
  4065. window,
  4066. e.detail,
  4067. e.screenX,
  4068. e.screenY,
  4069. e.clientX + boundingClientRect.left,
  4070. e.clientY + boundingClientRect.top,
  4071. e.ctrlKey,
  4072. e.altKey,
  4073. e.shiftKey,
  4074. e.metaKey,
  4075. e.button,
  4076. null // no related element
  4077. );
  4078. iframe.dispatchEvent(evt);
  4079. };
  4080. }
  4081. var Etherpad = {
  4082. /**
  4083. * Initializes the etherpad.
  4084. */
  4085. init: function (name) {
  4086. if (config.etherpad_base && !etherpadName && name) {
  4087. domain = config.etherpad_base;
  4088. etherpadName = name;
  4089. enableEtherpadButton();
  4090. /**
  4091. * Resizes the etherpad, when the window is resized.
  4092. */
  4093. $(window).resize(function () {
  4094. resize();
  4095. });
  4096. }
  4097. },
  4098. /**
  4099. * Opens/hides the Etherpad.
  4100. */
  4101. toggleEtherpad: function (isPresentation) {
  4102. if (!etherpadIFrame)
  4103. createIFrame();
  4104. if(VideoLayout.getLargeVideoState() === "etherpad")
  4105. {
  4106. VideoLayout.setLargeVideoState("video");
  4107. }
  4108. else
  4109. {
  4110. VideoLayout.setLargeVideoState("etherpad");
  4111. }
  4112. resize();
  4113. }
  4114. };
  4115. module.exports = Etherpad;
  4116. },{"../prezi/Prezi":18,"../util/UIUtil":33,"../videolayout/VideoLayout":39}],18:[function(require,module,exports){
  4117. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4118. var UIUtil = require("../util/UIUtil");
  4119. var VideoLayout = require("../videolayout/VideoLayout");
  4120. var messageHandler = require("../util/MessageHandler");
  4121. var PreziPlayer = require("./PreziPlayer");
  4122. var preziPlayer = null;
  4123. /**
  4124. * Shows/hides a presentation.
  4125. */
  4126. function setPresentationVisible(visible) {
  4127. if (visible) {
  4128. VideoLayout.setLargeVideoState("prezi");
  4129. }
  4130. else {
  4131. VideoLayout.setLargeVideoState("video");
  4132. }
  4133. }
  4134. var Prezi = {
  4135. /**
  4136. * Reloads the current presentation.
  4137. */
  4138. reloadPresentation: function() {
  4139. var iframe = document.getElementById(preziPlayer.options.preziId);
  4140. iframe.src = iframe.src;
  4141. },
  4142. /**
  4143. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4144. * otherwise.
  4145. */
  4146. isPresentationVisible: function () {
  4147. return ($('#presentation>iframe') != null
  4148. && $('#presentation>iframe').css('opacity') == 1);
  4149. },
  4150. /**
  4151. * Opens the Prezi dialog, from which the user could choose a presentation
  4152. * to load.
  4153. */
  4154. openPreziDialog: function() {
  4155. var myprezi = APP.xmpp.getPrezi();
  4156. if (myprezi) {
  4157. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4158. null,
  4159. "dialog.removePreziMsg",
  4160. null,
  4161. false,
  4162. "dialog.Remove",
  4163. function(e,v,m,f) {
  4164. if(v) {
  4165. APP.xmpp.removePreziFromPresence();
  4166. }
  4167. }
  4168. );
  4169. }
  4170. else if (preziPlayer != null) {
  4171. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4172. null, "dialog.sharePreziMsg",
  4173. null,
  4174. false,
  4175. "dialog.Ok",
  4176. function(e,v,m,f) {
  4177. $.prompt.close();
  4178. }
  4179. );
  4180. }
  4181. else {
  4182. var html = APP.translation.generateTranslationHTML(
  4183. "dialog.sharePreziTitle");
  4184. var cancelButton = APP.translation.generateTranslationHTML(
  4185. "dialog.Cancel");
  4186. var shareButton = APP.translation.generateTranslationHTML(
  4187. "dialog.Share");
  4188. var backButton = APP.translation.generateTranslationHTML(
  4189. "dialog.Back");
  4190. var buttons = [];
  4191. var buttons1 = [];
  4192. // Cancel button to both states
  4193. buttons.push({title: cancelButton, value: false});
  4194. buttons1.push({title: cancelButton, value: false});
  4195. // Share button
  4196. buttons.push({title: shareButton, value: true});
  4197. // Back button
  4198. buttons1.push({title: backButton, value: true});
  4199. var linkError = APP.translation.generateTranslationHTML(
  4200. "dialog.preziLinkError");
  4201. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4202. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4203. var openPreziState = {
  4204. state0: {
  4205. html: '<h2>' + html + '</h2>' +
  4206. '<input name="preziUrl" type="text" ' +
  4207. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4208. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4209. '\' placeholder="' + defaultUrl + '" autofocus>',
  4210. persistent: false,
  4211. buttons: buttons,
  4212. focus: ':input:first',
  4213. defaultButton: 0,
  4214. submit: function (e, v, m, f) {
  4215. e.preventDefault();
  4216. if(v)
  4217. {
  4218. var preziUrl = f.preziUrl;
  4219. if (preziUrl)
  4220. {
  4221. var urlValue
  4222. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4223. if (urlValue.indexOf('http://prezi.com/') != 0
  4224. && urlValue.indexOf('https://prezi.com/') != 0)
  4225. {
  4226. $.prompt.goToState('state1');
  4227. return false;
  4228. }
  4229. else {
  4230. var presIdTmp = urlValue.substring(
  4231. urlValue.indexOf("prezi.com/") + 10);
  4232. if (!isAlphanumeric(presIdTmp)
  4233. || presIdTmp.indexOf('/') < 2) {
  4234. $.prompt.goToState('state1');
  4235. return false;
  4236. }
  4237. else {
  4238. APP.xmpp.addToPresence("prezi", urlValue);
  4239. $.prompt.close();
  4240. }
  4241. }
  4242. }
  4243. }
  4244. else
  4245. $.prompt.close();
  4246. }
  4247. },
  4248. state1: {
  4249. html: '<h2>' + html + '</h2>' +
  4250. linkError,
  4251. persistent: false,
  4252. buttons: buttons1,
  4253. focus: ':input:first',
  4254. defaultButton: 1,
  4255. submit: function (e, v, m, f) {
  4256. e.preventDefault();
  4257. if (v === 0)
  4258. $.prompt.close();
  4259. else
  4260. $.prompt.goToState('state0');
  4261. }
  4262. }
  4263. };
  4264. messageHandler.openDialogWithStates(openPreziState);
  4265. }
  4266. }
  4267. };
  4268. /**
  4269. * A new presentation has been added.
  4270. *
  4271. * @param event the event indicating the add of a presentation
  4272. * @param jid the jid from which the presentation was added
  4273. * @param presUrl url of the presentation
  4274. * @param currentSlide the current slide to which we should move
  4275. */
  4276. function presentationAdded(event, jid, presUrl, currentSlide) {
  4277. console.log("presentation added", presUrl);
  4278. var presId = getPresentationId(presUrl);
  4279. var elementId = 'participant_'
  4280. + Strophe.getResourceFromJid(jid)
  4281. + '_' + presId;
  4282. VideoLayout.addPreziContainer(elementId);
  4283. var controlsEnabled = false;
  4284. if (jid === APP.xmpp.myJid())
  4285. controlsEnabled = true;
  4286. setPresentationVisible(true);
  4287. VideoLayout.setLargeVideoHover(
  4288. function (event) {
  4289. if (Prezi.isPresentationVisible()) {
  4290. var reloadButtonRight = window.innerWidth
  4291. - $('#presentation>iframe').offset().left
  4292. - $('#presentation>iframe').width();
  4293. $('#reloadPresentation').css({ right: reloadButtonRight,
  4294. display:'inline-block'});
  4295. }
  4296. },
  4297. function (event) {
  4298. if (!Prezi.isPresentationVisible())
  4299. $('#reloadPresentation').css({display:'none'});
  4300. else {
  4301. var e = event.toElement || event.relatedTarget;
  4302. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4303. $('#reloadPresentation').css({display:'none'});
  4304. }
  4305. });
  4306. preziPlayer = new PreziPlayer(
  4307. 'presentation',
  4308. {preziId: presId,
  4309. width: getPresentationWidth(),
  4310. height: getPresentationHeihgt(),
  4311. controls: controlsEnabled,
  4312. debug: true
  4313. });
  4314. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4315. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4316. console.log("prezi status", event.value);
  4317. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4318. if (jid != APP.xmpp.myJid())
  4319. preziPlayer.flyToStep(currentSlide);
  4320. }
  4321. });
  4322. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4323. console.log("event value", event.value);
  4324. APP.xmpp.addToPresence("preziSlide", event.value);
  4325. });
  4326. $("#" + elementId).css( 'background-image',
  4327. 'url(../images/avatarprezi.png)');
  4328. $("#" + elementId).click(
  4329. function () {
  4330. setPresentationVisible(true);
  4331. }
  4332. );
  4333. };
  4334. /**
  4335. * A presentation has been removed.
  4336. *
  4337. * @param event the event indicating the remove of a presentation
  4338. * @param jid the jid for which the presentation was removed
  4339. * @param the url of the presentation
  4340. */
  4341. function presentationRemoved(event, jid, presUrl) {
  4342. console.log('presentation removed', presUrl);
  4343. var presId = getPresentationId(presUrl);
  4344. setPresentationVisible(false);
  4345. $('#participant_'
  4346. + Strophe.getResourceFromJid(jid)
  4347. + '_' + presId).remove();
  4348. $('#presentation>iframe').remove();
  4349. if (preziPlayer != null) {
  4350. preziPlayer.destroy();
  4351. preziPlayer = null;
  4352. }
  4353. };
  4354. /**
  4355. * Indicates if the given string is an alphanumeric string.
  4356. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4357. * purpose of checking URIs.
  4358. */
  4359. function isAlphanumeric(unsafeText) {
  4360. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4361. return regex.test(unsafeText);
  4362. }
  4363. /**
  4364. * Returns the presentation id from the given url.
  4365. */
  4366. function getPresentationId (presUrl) {
  4367. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4368. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4369. }
  4370. /**
  4371. * Returns the presentation width.
  4372. */
  4373. function getPresentationWidth() {
  4374. var availableWidth = UIUtil.getAvailableVideoWidth();
  4375. var availableHeight = getPresentationHeihgt();
  4376. var aspectRatio = 16.0 / 9.0;
  4377. if (availableHeight < availableWidth / aspectRatio) {
  4378. availableWidth = Math.floor(availableHeight * aspectRatio);
  4379. }
  4380. return availableWidth;
  4381. }
  4382. /**
  4383. * Returns the presentation height.
  4384. */
  4385. function getPresentationHeihgt() {
  4386. var remoteVideos = $('#remoteVideos');
  4387. return window.innerHeight - remoteVideos.outerHeight();
  4388. }
  4389. /**
  4390. * Resizes the presentation iframe.
  4391. */
  4392. function resize() {
  4393. if ($('#presentation>iframe')) {
  4394. $('#presentation>iframe').width(getPresentationWidth());
  4395. $('#presentation>iframe').height(getPresentationHeihgt());
  4396. }
  4397. }
  4398. /**
  4399. * Presentation has been removed.
  4400. */
  4401. $(document).bind('presentationremoved.muc', presentationRemoved);
  4402. /**
  4403. * Presentation has been added.
  4404. */
  4405. $(document).bind('presentationadded.muc', presentationAdded);
  4406. /*
  4407. * Indicates presentation slide change.
  4408. */
  4409. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4410. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4411. preziPlayer.flyToStep(current);
  4412. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4413. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4414. preziPlayer.flyToStep(current, i);
  4415. }
  4416. }
  4417. });
  4418. $(window).resize(function () {
  4419. resize();
  4420. });
  4421. module.exports = Prezi;
  4422. },{"../toolbars/ToolbarToggler":29,"../util/MessageHandler":31,"../util/UIUtil":33,"../videolayout/VideoLayout":39,"./PreziPlayer":19}],19:[function(require,module,exports){
  4423. (function() {
  4424. "use strict";
  4425. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4426. window.PreziPlayer = (function() {
  4427. PreziPlayer.API_VERSION = 1;
  4428. PreziPlayer.CURRENT_STEP = 'currentStep';
  4429. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4430. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4431. PreziPlayer.STATUS_LOADING = 'loading';
  4432. PreziPlayer.STATUS_READY = 'ready';
  4433. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4434. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4435. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4436. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4437. PreziPlayer.EVENT_STATUS = "statusChange";
  4438. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4439. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4440. PreziPlayer.domain = "https://prezi.com";
  4441. PreziPlayer.path = "/player/";
  4442. PreziPlayer.players = {};
  4443. PreziPlayer.binded_methods = ['changesHandler'];
  4444. PreziPlayer.createMultiplePlayers = function(optionArray){
  4445. for(var i=0; i<optionArray.length; i++) {
  4446. var optionSet = optionArray[i];
  4447. new PreziPlayer(optionSet.id, optionSet);
  4448. };
  4449. };
  4450. PreziPlayer.messageReceived = function(event){
  4451. var message, item, player;
  4452. try {
  4453. message = JSON.parse(event.data);
  4454. if (message.id && (player = PreziPlayer.players[message.id])) {
  4455. if (player.options.debug === true) {
  4456. if (console && console.log)
  4457. console.log('received', message);
  4458. }
  4459. if (message.type === "changes") {
  4460. player.changesHandler(message);
  4461. }
  4462. for (var i = 0; i < player.callbacks.length; i++) {
  4463. item = player.callbacks[i];
  4464. if (item && message.type === item.event) {
  4465. item.callback(message);
  4466. }
  4467. }
  4468. }
  4469. } catch (e) { }
  4470. };
  4471. function PreziPlayer(id, options) {
  4472. var params, paramString = "", _this = this;
  4473. if (PreziPlayer.players[id]){
  4474. PreziPlayer.players[id].destroy();
  4475. }
  4476. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4477. var method_name = PreziPlayer.binded_methods[i];
  4478. _this[method_name] = __bind(_this[method_name], _this);
  4479. };
  4480. options = options || {};
  4481. this.options = options;
  4482. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4483. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4484. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4485. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4486. this.callbacks = [];
  4487. this.id = id;
  4488. this.embedTo = document.getElementById(id);
  4489. if (!this.embedTo) {
  4490. throw "The element id is not available.";
  4491. }
  4492. this.iframe = document.createElement('iframe');
  4493. params = [
  4494. { name: 'oid', value: options.preziId },
  4495. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4496. { name: 'controls', value: options.controls ? 1 : 0 }
  4497. ];
  4498. for(var i=0; i<params.length; i++) {
  4499. var param = params[i];
  4500. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4501. };
  4502. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4503. this.iframe.frameBorder = 0;
  4504. this.iframe.scrolling = "no";
  4505. this.iframe.width = options.width || 640;
  4506. this.iframe.height = options.height || 480;
  4507. this.embedTo.innerHTML = '';
  4508. // JITSI: IN CASE SOMETHING GOES WRONG.
  4509. try {
  4510. this.embedTo.appendChild(this.iframe);
  4511. }
  4512. catch (err) {
  4513. console.log("CATCH ERROR");
  4514. }
  4515. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4516. // crashes for us.
  4517. this.initPollInterval = setInterval(function(){
  4518. _this.sendMessage({'action': 'init'});
  4519. }, 500);
  4520. PreziPlayer.players[id] = this;
  4521. }
  4522. PreziPlayer.prototype.changesHandler = function(message) {
  4523. var key, value, j, item;
  4524. if (this.initPollInterval) {
  4525. clearInterval(this.initPollInterval);
  4526. this.initPollInterval = false;
  4527. }
  4528. for (key in message.data) {
  4529. if (message.data.hasOwnProperty(key)){
  4530. value = message.data[key];
  4531. this.values[key] = value;
  4532. for (j=0; j<this.callbacks.length; j++) {
  4533. item = this.callbacks[j];
  4534. if (item && item.event === key + "Change"){
  4535. item.callback({type: item.event, value: value});
  4536. }
  4537. }
  4538. }
  4539. }
  4540. };
  4541. PreziPlayer.prototype.destroy = function() {
  4542. if (this.initPollInterval) {
  4543. clearInterval(this.initPollInterval);
  4544. this.initPollInterval = false;
  4545. }
  4546. this.embedTo.innerHTML = '';
  4547. };
  4548. PreziPlayer.prototype.sendMessage = function(message) {
  4549. if (this.options.debug === true) {
  4550. if (console && console.log) console.log('sent', message);
  4551. }
  4552. message.version = PreziPlayer.API_VERSION;
  4553. message.id = this.id;
  4554. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4555. };
  4556. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4557. PreziPlayer.prototype.flyToNextStep = function() {
  4558. return this.sendMessage({
  4559. 'action': 'present',
  4560. 'data': ['moveToNextStep']
  4561. });
  4562. };
  4563. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4564. PreziPlayer.prototype.flyToPreviousStep = function() {
  4565. return this.sendMessage({
  4566. 'action': 'present',
  4567. 'data': ['moveToPrevStep']
  4568. });
  4569. };
  4570. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4571. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4572. var obj = this;
  4573. // check animation_step
  4574. if (animation_step > 0 &&
  4575. obj.values.animationCountOnSteps &&
  4576. obj.values.animationCountOnSteps[step] <= animation_step) {
  4577. animation_step = obj.values.animationCountOnSteps[step];
  4578. }
  4579. // jump to animation steps by calling flyToNextStep()
  4580. function doAnimationSteps() {
  4581. if (obj.values.isMoving == true) {
  4582. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4583. return;
  4584. }
  4585. while (animation_step-- > 0) {
  4586. obj.flyToNextStep(); // do the animation steps
  4587. }
  4588. }
  4589. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4590. // jump to the step
  4591. return this.sendMessage({
  4592. 'action': 'present',
  4593. 'data': ['moveToStep', step]
  4594. });
  4595. };
  4596. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4597. PreziPlayer.prototype.flyToObject = function(objectId) {
  4598. return this.sendMessage({
  4599. 'action': 'present',
  4600. 'data': ['moveToObject', objectId]
  4601. });
  4602. };
  4603. PreziPlayer.prototype.play = function(defaultDelay) {
  4604. return this.sendMessage({
  4605. 'action': 'present',
  4606. 'data': ['startAutoPlay', defaultDelay]
  4607. });
  4608. };
  4609. PreziPlayer.prototype.stop = function() {
  4610. return this.sendMessage({
  4611. 'action': 'present',
  4612. 'data': ['stopAutoPlay']
  4613. });
  4614. };
  4615. PreziPlayer.prototype.pause = function(defaultDelay) {
  4616. return this.sendMessage({
  4617. 'action': 'present',
  4618. 'data': ['pauseAutoPlay', defaultDelay]
  4619. });
  4620. };
  4621. PreziPlayer.prototype.getCurrentStep = function() {
  4622. return this.values.currentStep;
  4623. };
  4624. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4625. return this.values.currentAnimationStep;
  4626. };
  4627. PreziPlayer.prototype.getCurrentObject = function() {
  4628. return this.values.currentObject;
  4629. };
  4630. PreziPlayer.prototype.getStatus = function() {
  4631. return this.values.status;
  4632. };
  4633. PreziPlayer.prototype.isPlaying = function() {
  4634. return this.values.isAutoPlaying;
  4635. };
  4636. PreziPlayer.prototype.getStepCount = function() {
  4637. return this.values.stepCount;
  4638. };
  4639. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4640. return this.values.animationCountOnSteps;
  4641. };
  4642. PreziPlayer.prototype.getTitle = function() {
  4643. return this.values.title;
  4644. };
  4645. PreziPlayer.prototype.setDimensions = function(dims) {
  4646. for (var parameter in dims) {
  4647. this.iframe[parameter] = dims[parameter];
  4648. }
  4649. }
  4650. PreziPlayer.prototype.getDimensions = function() {
  4651. return {
  4652. width: parseInt(this.iframe.width, 10),
  4653. height: parseInt(this.iframe.height, 10)
  4654. }
  4655. }
  4656. PreziPlayer.prototype.on = function(event, callback) {
  4657. this.callbacks.push({
  4658. event: event,
  4659. callback: callback
  4660. });
  4661. };
  4662. PreziPlayer.prototype.off = function(event, callback) {
  4663. var j, item;
  4664. if (event === undefined) {
  4665. this.callbacks = [];
  4666. }
  4667. j = this.callbacks.length;
  4668. while (j--) {
  4669. item = this.callbacks[j];
  4670. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  4671. this.callbacks.splice(j, 1);
  4672. }
  4673. }
  4674. };
  4675. if (window.addEventListener) {
  4676. window.addEventListener('message', PreziPlayer.messageReceived, false);
  4677. } else {
  4678. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  4679. }
  4680. return PreziPlayer;
  4681. })();
  4682. })();
  4683. module.exports = PreziPlayer;
  4684. },{}],20:[function(require,module,exports){
  4685. /* global require, $ */
  4686. var Chat = require("./chat/Chat");
  4687. var ContactList = require("./contactlist/ContactList");
  4688. var Settings = require("./../../settings/Settings");
  4689. var SettingsMenu = require("./settings/SettingsMenu");
  4690. var VideoLayout = require("../videolayout/VideoLayout");
  4691. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4692. var UIUtil = require("../util/UIUtil");
  4693. var LargeVideo = require("../videolayout/LargeVideo");
  4694. /**
  4695. * Toggler for the chat, contact list, settings menu, etc..
  4696. */
  4697. var PanelToggler = (function(my) {
  4698. var currentlyOpen = null;
  4699. var buttons = {
  4700. '#chatspace': '#chatBottomButton',
  4701. '#contactlist': '#contactListButton',
  4702. '#settingsmenu': '#toolbar_button_settings'
  4703. };
  4704. /**
  4705. * Toggles the windows in the side panel
  4706. * @param object the window that should be shown
  4707. * @param selector the selector for the element containing the panel
  4708. * @param onOpenComplete function to be called when the panel is opened
  4709. * @param onOpen function to be called if the window is going to be opened
  4710. * @param onClose function to be called if the window is going to be closed
  4711. */
  4712. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  4713. UIUtil.buttonClick(buttons[selector], "active");
  4714. if (object.isVisible()) {
  4715. $("#toast-container").animate({
  4716. right: '5px'
  4717. },
  4718. {
  4719. queue: false,
  4720. duration: 500
  4721. });
  4722. $(selector).hide("slide", {
  4723. direction: "right",
  4724. queue: false,
  4725. duration: 500
  4726. });
  4727. if(typeof onClose === "function") {
  4728. onClose();
  4729. }
  4730. currentlyOpen = null;
  4731. }
  4732. else {
  4733. // Undock the toolbar when the chat is shown and if we're in a
  4734. // video mode.
  4735. if (LargeVideo.isLargeVideoVisible()) {
  4736. ToolbarToggler.dockToolbar(false);
  4737. }
  4738. if(currentlyOpen) {
  4739. var current = $(currentlyOpen);
  4740. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  4741. current.css('z-index', 4);
  4742. setTimeout(function () {
  4743. current.css('display', 'none');
  4744. current.css('z-index', 5);
  4745. }, 500);
  4746. }
  4747. $("#toast-container").animate({
  4748. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  4749. },
  4750. {
  4751. queue: false,
  4752. duration: 500
  4753. });
  4754. $(selector).show("slide", {
  4755. direction: "right",
  4756. queue: false,
  4757. duration: 500,
  4758. complete: onOpenComplete
  4759. });
  4760. if(typeof onOpen === "function") {
  4761. onOpen();
  4762. }
  4763. currentlyOpen = selector;
  4764. }
  4765. };
  4766. /**
  4767. * Opens / closes the chat area.
  4768. */
  4769. my.toggleChat = function() {
  4770. var chatCompleteFunction = Chat.isVisible() ?
  4771. function() {} : function () {
  4772. Chat.scrollChatToBottom();
  4773. $('#chatspace').trigger('shown');
  4774. };
  4775. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  4776. toggle(Chat,
  4777. '#chatspace',
  4778. function () {
  4779. // Request the focus in the nickname field or the chat input field.
  4780. if ($('#nickname').css('visibility') === 'visible') {
  4781. $('#nickinput').focus();
  4782. } else {
  4783. $('#usermsg').focus();
  4784. }
  4785. },
  4786. null,
  4787. Chat.resizeChat,
  4788. null);
  4789. };
  4790. /**
  4791. * Opens / closes the contact list area.
  4792. */
  4793. my.toggleContactList = function () {
  4794. var completeFunction = ContactList.isVisible() ?
  4795. function() {} : function () { $('#contactlist').trigger('shown');};
  4796. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  4797. toggle(ContactList,
  4798. '#contactlist',
  4799. null,
  4800. function() {
  4801. ContactList.setVisualNotification(false);
  4802. },
  4803. null);
  4804. };
  4805. /**
  4806. * Opens / closes the settings menu
  4807. */
  4808. my.toggleSettingsMenu = function() {
  4809. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  4810. toggle(SettingsMenu,
  4811. '#settingsmenu',
  4812. null,
  4813. function() {
  4814. var settings = Settings.getSettings();
  4815. $('#setDisplayName').get(0).value = settings.displayName;
  4816. $('#setEmail').get(0).value = settings.email;
  4817. },
  4818. null);
  4819. };
  4820. /**
  4821. * Returns the size of the side panel.
  4822. */
  4823. my.getPanelSize = function () {
  4824. var availableHeight = window.innerHeight;
  4825. var availableWidth = window.innerWidth;
  4826. var panelWidth = 200;
  4827. if (availableWidth * 0.2 < 200) {
  4828. panelWidth = availableWidth * 0.2;
  4829. }
  4830. return [panelWidth, availableHeight];
  4831. };
  4832. my.isVisible = function() {
  4833. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  4834. };
  4835. return my;
  4836. }(PanelToggler || {}));
  4837. module.exports = PanelToggler;
  4838. },{"../toolbars/ToolbarToggler":29,"../util/UIUtil":33,"../videolayout/LargeVideo":35,"../videolayout/VideoLayout":39,"./../../settings/Settings":49,"./chat/Chat":21,"./contactlist/ContactList":25,"./settings/SettingsMenu":26}],21:[function(require,module,exports){
  4839. /* global APP, $, Util, nickname:true */
  4840. var Replacement = require("./Replacement");
  4841. var CommandsProcessor = require("./Commands");
  4842. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  4843. var smileys = require("./smileys.json").smileys;
  4844. var NicknameHandler = require("../../util/NicknameHandler");
  4845. var UIUtil = require("../../util/UIUtil");
  4846. var UIEvents = require("../../../../service/UI/UIEvents");
  4847. var notificationInterval = false;
  4848. var unreadMessages = 0;
  4849. /**
  4850. * Shows/hides a visual notification, indicating that a message has arrived.
  4851. */
  4852. function setVisualNotification(show) {
  4853. var unreadMsgElement = document.getElementById('unreadMessages');
  4854. var unreadMsgBottomElement
  4855. = document.getElementById('bottomUnreadMessages');
  4856. var glower = $('#toolbar_button_chat');
  4857. var bottomGlower = $('#chatBottomButton');
  4858. if (unreadMessages) {
  4859. unreadMsgElement.innerHTML = unreadMessages.toString();
  4860. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  4861. ToolbarToggler.dockToolbar(true);
  4862. var chatButtonElement
  4863. = document.getElementById('toolbar_button_chat');
  4864. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  4865. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  4866. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  4867. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  4868. unreadMsgElement.setAttribute(
  4869. 'style',
  4870. 'top:' + topIndent +
  4871. '; left:' + leftIndent + ';');
  4872. var chatBottomButtonElement
  4873. = document.getElementById('chatBottomButton').parentNode;
  4874. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  4875. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  4876. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  4877. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  4878. unreadMsgBottomElement.setAttribute(
  4879. 'style',
  4880. 'top:' + bottomTopIndent +
  4881. '; left:' + bottomLeftIndent + ';');
  4882. if (!glower.hasClass('icon-chat-simple')) {
  4883. glower.removeClass('icon-chat');
  4884. glower.addClass('icon-chat-simple');
  4885. }
  4886. }
  4887. else {
  4888. unreadMsgElement.innerHTML = '';
  4889. unreadMsgBottomElement.innerHTML = '';
  4890. glower.removeClass('icon-chat-simple');
  4891. glower.addClass('icon-chat');
  4892. }
  4893. if (show && !notificationInterval) {
  4894. notificationInterval = window.setInterval(function () {
  4895. glower.toggleClass('active');
  4896. bottomGlower.toggleClass('active glowing');
  4897. }, 800);
  4898. }
  4899. else if (!show && notificationInterval) {
  4900. window.clearInterval(notificationInterval);
  4901. notificationInterval = false;
  4902. glower.removeClass('active');
  4903. bottomGlower.removeClass('glowing');
  4904. bottomGlower.addClass('active');
  4905. }
  4906. }
  4907. /**
  4908. * Returns the current time in the format it is shown to the user
  4909. * @returns {string}
  4910. */
  4911. function getCurrentTime(stamp) {
  4912. var now = (stamp? new Date(stamp): new Date());
  4913. var hour = now.getHours();
  4914. var minute = now.getMinutes();
  4915. var second = now.getSeconds();
  4916. if(hour.toString().length === 1) {
  4917. hour = '0'+hour;
  4918. }
  4919. if(minute.toString().length === 1) {
  4920. minute = '0'+minute;
  4921. }
  4922. if(second.toString().length === 1) {
  4923. second = '0'+second;
  4924. }
  4925. return hour+':'+minute+':'+second;
  4926. }
  4927. function toggleSmileys() {
  4928. var smileys = $('#smileysContainer');
  4929. if(!smileys.is(':visible')) {
  4930. smileys.show("slide", { direction: "down", duration: 300});
  4931. } else {
  4932. smileys.hide("slide", { direction: "down", duration: 300});
  4933. }
  4934. $('#usermsg').focus();
  4935. }
  4936. function addClickFunction(smiley, number) {
  4937. smiley.onclick = function addSmileyToMessage() {
  4938. var usermsg = $('#usermsg');
  4939. var message = usermsg.val();
  4940. message += smileys['smiley' + number];
  4941. usermsg.val(message);
  4942. usermsg.get(0).setSelectionRange(message.length, message.length);
  4943. toggleSmileys();
  4944. usermsg.focus();
  4945. };
  4946. }
  4947. /**
  4948. * Adds the smileys container to the chat
  4949. */
  4950. function addSmileys() {
  4951. var smileysContainer = document.createElement('div');
  4952. smileysContainer.id = 'smileysContainer';
  4953. for(var i = 1; i <= 21; i++) {
  4954. var smileyContainer = document.createElement('div');
  4955. smileyContainer.id = 'smiley' + i;
  4956. smileyContainer.className = 'smileyContainer';
  4957. var smiley = document.createElement('img');
  4958. smiley.src = 'images/smileys/smiley' + i + '.svg';
  4959. smiley.className = 'smiley';
  4960. addClickFunction(smiley, i);
  4961. smileyContainer.appendChild(smiley);
  4962. smileysContainer.appendChild(smileyContainer);
  4963. }
  4964. $("#chatspace").append(smileysContainer);
  4965. }
  4966. /**
  4967. * Resizes the chat conversation.
  4968. */
  4969. function resizeChatConversation() {
  4970. var msgareaHeight = $('#usermsg').outerHeight();
  4971. var chatspace = $('#chatspace');
  4972. var width = chatspace.width();
  4973. var chat = $('#chatconversation');
  4974. var smileys = $('#smileysarea');
  4975. smileys.height(msgareaHeight);
  4976. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  4977. $('#smileysContainer').css('bottom', msgareaHeight);
  4978. chat.width(width - 10);
  4979. chat.height(window.innerHeight - 15 - msgareaHeight);
  4980. }
  4981. /**
  4982. * Chat related user interface.
  4983. */
  4984. var Chat = (function (my) {
  4985. /**
  4986. * Initializes chat related interface.
  4987. */
  4988. my.init = function () {
  4989. if(NicknameHandler.getNickname())
  4990. Chat.setChatConversationMode(true);
  4991. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  4992. function (nickname) {
  4993. Chat.setChatConversationMode(true);
  4994. });
  4995. $('#nickinput').keydown(function (event) {
  4996. if (event.keyCode === 13) {
  4997. event.preventDefault();
  4998. var val = UIUtil.escapeHtml(this.value);
  4999. this.value = '';
  5000. if (!NicknameHandler.getNickname()) {
  5001. NicknameHandler.setNickname(val);
  5002. return;
  5003. }
  5004. }
  5005. });
  5006. var usermsg = $('#usermsg');
  5007. usermsg.keydown(function (event) {
  5008. if (event.keyCode === 13) {
  5009. event.preventDefault();
  5010. var value = this.value;
  5011. usermsg.val('').trigger('autosize.resize');
  5012. this.focus();
  5013. var command = new CommandsProcessor(value);
  5014. if(command.isCommand()) {
  5015. command.processCommand();
  5016. }
  5017. else {
  5018. var message = UIUtil.escapeHtml(value);
  5019. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5020. }
  5021. }
  5022. });
  5023. var onTextAreaResize = function () {
  5024. resizeChatConversation();
  5025. Chat.scrollChatToBottom();
  5026. };
  5027. usermsg.autosize({callback: onTextAreaResize});
  5028. $("#chatspace").bind("shown",
  5029. function () {
  5030. unreadMessages = 0;
  5031. setVisualNotification(false);
  5032. });
  5033. addSmileys();
  5034. };
  5035. /**
  5036. * Appends the given message to the chat conversation.
  5037. */
  5038. my.updateChatConversation =
  5039. function (from, displayName, message, myjid, stamp) {
  5040. var divClassName = '';
  5041. if (APP.xmpp.myJid() === from) {
  5042. divClassName = "localuser";
  5043. }
  5044. else {
  5045. divClassName = "remoteuser";
  5046. if (!Chat.isVisible()) {
  5047. unreadMessages++;
  5048. UIUtil.playSoundNotification('chatNotification');
  5049. setVisualNotification(true);
  5050. }
  5051. }
  5052. // replace links and smileys
  5053. // Strophe already escapes special symbols on sending,
  5054. // so we escape here only tags to avoid double &amp;
  5055. var escMessage = message.replace(/</g, '&lt;').
  5056. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5057. var escDisplayName = UIUtil.escapeHtml(displayName);
  5058. message = Replacement.processReplacements(escMessage);
  5059. var messageContainer =
  5060. '<div class="chatmessage">'+
  5061. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5062. '<div class="username ' + divClassName +'">' + escDisplayName +
  5063. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5064. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5065. '</div>';
  5066. $('#chatconversation').append(messageContainer);
  5067. $('#chatconversation').animate(
  5068. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5069. };
  5070. /**
  5071. * Appends error message to the conversation
  5072. * @param errorMessage the received error message.
  5073. * @param originalText the original message.
  5074. */
  5075. my.chatAddError = function(errorMessage, originalText) {
  5076. errorMessage = UIUtil.escapeHtml(errorMessage);
  5077. originalText = UIUtil.escapeHtml(originalText);
  5078. $('#chatconversation').append(
  5079. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5080. (originalText? (' \"'+ originalText + '\"') : "") +
  5081. ' was not sent.' +
  5082. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5083. $('#chatconversation').animate(
  5084. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5085. };
  5086. /**
  5087. * Sets the subject to the UI
  5088. * @param subject the subject
  5089. */
  5090. my.chatSetSubject = function(subject) {
  5091. if (subject)
  5092. subject = subject.trim();
  5093. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5094. if(subject === "") {
  5095. $("#subject").css({display: "none"});
  5096. }
  5097. else {
  5098. $("#subject").css({display: "block"});
  5099. }
  5100. };
  5101. /**
  5102. * Sets the chat conversation mode.
  5103. */
  5104. my.setChatConversationMode = function (isConversationMode) {
  5105. if (isConversationMode) {
  5106. $('#nickname').css({visibility: 'hidden'});
  5107. $('#chatconversation').css({visibility: 'visible'});
  5108. $('#usermsg').css({visibility: 'visible'});
  5109. $('#smileysarea').css({visibility: 'visible'});
  5110. $('#usermsg').focus();
  5111. }
  5112. };
  5113. /**
  5114. * Resizes the chat area.
  5115. */
  5116. my.resizeChat = function () {
  5117. var chatSize = require("../SidePanelToggler").getPanelSize();
  5118. $('#chatspace').width(chatSize[0]);
  5119. $('#chatspace').height(chatSize[1]);
  5120. resizeChatConversation();
  5121. };
  5122. /**
  5123. * Indicates if the chat is currently visible.
  5124. */
  5125. my.isVisible = function () {
  5126. return $('#chatspace').is(":visible");
  5127. };
  5128. /**
  5129. * Shows and hides the window with the smileys
  5130. */
  5131. my.toggleSmileys = toggleSmileys;
  5132. /**
  5133. * Scrolls chat to the bottom.
  5134. */
  5135. my.scrollChatToBottom = function() {
  5136. setTimeout(function () {
  5137. $('#chatconversation').scrollTop(
  5138. $('#chatconversation')[0].scrollHeight);
  5139. }, 5);
  5140. };
  5141. return my;
  5142. }(Chat || {}));
  5143. module.exports = Chat;
  5144. },{"../../../../service/UI/UIEvents":166,"../../toolbars/ToolbarToggler":29,"../../util/NicknameHandler":32,"../../util/UIUtil":33,"../SidePanelToggler":20,"./Commands":22,"./Replacement":23,"./smileys.json":24}],22:[function(require,module,exports){
  5145. /* global APP, require */
  5146. var UIUtil = require("../../util/UIUtil");
  5147. /**
  5148. * List with supported commands. The keys are the names of the commands and
  5149. * the value is the function that processes the message.
  5150. * @type {{String: function}}
  5151. */
  5152. var commands = {
  5153. "topic" : processTopic
  5154. };
  5155. /**
  5156. * Extracts the command from the message.
  5157. * @param message the received message
  5158. * @returns {string} the command
  5159. */
  5160. function getCommand(message) {
  5161. if(message) {
  5162. for(var command in commands) {
  5163. if(message.indexOf("/" + command) == 0)
  5164. return command;
  5165. }
  5166. }
  5167. return "";
  5168. }
  5169. /**
  5170. * Processes the data for topic command.
  5171. * @param commandArguments the arguments of the topic command.
  5172. */
  5173. function processTopic(commandArguments) {
  5174. var topic = UIUtil.escapeHtml(commandArguments);
  5175. APP.xmpp.setSubject(topic);
  5176. }
  5177. /**
  5178. * Constructs a new CommandProccessor instance from a message that
  5179. * handles commands received via chat messages.
  5180. * @param message the message
  5181. * @constructor
  5182. */
  5183. function CommandsProcessor(message) {
  5184. var command = getCommand(message);
  5185. /**
  5186. * Returns the name of the command.
  5187. * @returns {String} the command
  5188. */
  5189. this.getCommand = function() {
  5190. return command;
  5191. };
  5192. var messageArgument = message.substr(command.length + 2);
  5193. /**
  5194. * Returns the arguments of the command.
  5195. * @returns {string}
  5196. */
  5197. this.getArgument = function() {
  5198. return messageArgument;
  5199. };
  5200. }
  5201. /**
  5202. * Checks whether this instance is valid command or not.
  5203. * @returns {boolean}
  5204. */
  5205. CommandsProcessor.prototype.isCommand = function() {
  5206. if (this.getCommand())
  5207. return true;
  5208. return false;
  5209. };
  5210. /**
  5211. * Processes the command.
  5212. */
  5213. CommandsProcessor.prototype.processCommand = function() {
  5214. if(!this.isCommand())
  5215. return;
  5216. commands[this.getCommand()](this.getArgument());
  5217. };
  5218. module.exports = CommandsProcessor;
  5219. },{"../../util/UIUtil":33}],23:[function(require,module,exports){
  5220. var Smileys = require("./smileys.json");
  5221. /**
  5222. * Processes links and smileys in "body"
  5223. */
  5224. function processReplacements(body)
  5225. {
  5226. //make links clickable
  5227. body = linkify(body);
  5228. //add smileys
  5229. body = smilify(body);
  5230. return body;
  5231. }
  5232. /**
  5233. * Finds and replaces all links in the links in "body"
  5234. * with their <a href=""></a>
  5235. */
  5236. function linkify(inputText)
  5237. {
  5238. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5239. //URLs starting with http://, https://, or ftp://
  5240. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5241. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5242. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5243. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5244. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5245. //Change email addresses to mailto:: links.
  5246. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5247. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5248. return replacedText;
  5249. }
  5250. /**
  5251. * Replaces common smiley strings with images
  5252. */
  5253. function smilify(body)
  5254. {
  5255. if(!body) {
  5256. return body;
  5257. }
  5258. var regexs = Smileys["regexs"];
  5259. for(var smiley in regexs) {
  5260. if(regexs.hasOwnProperty(smiley)) {
  5261. body = body.replace(regexs[smiley],
  5262. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5263. }
  5264. }
  5265. return body;
  5266. }
  5267. module.exports = {
  5268. processReplacements: processReplacements,
  5269. linkify: linkify
  5270. };
  5271. },{"./smileys.json":24}],24:[function(require,module,exports){
  5272. module.exports={
  5273. "smileys": {
  5274. "smiley1": ":)",
  5275. "smiley2": ":(",
  5276. "smiley3": ":D",
  5277. "smiley4": "(y)",
  5278. "smiley5": " :P",
  5279. "smiley6": "(wave)",
  5280. "smiley7": "(blush)",
  5281. "smiley8": "(chuckle)",
  5282. "smiley9": "(shocked)",
  5283. "smiley10": ":*",
  5284. "smiley11": "(n)",
  5285. "smiley12": "(search)",
  5286. "smiley13": " <3",
  5287. "smiley14": "(oops)",
  5288. "smiley15": "(angry)",
  5289. "smiley16": "(angel)",
  5290. "smiley17": "(sick)",
  5291. "smiley18": ";(",
  5292. "smiley19": "(bomb)",
  5293. "smiley20": "(clap)",
  5294. "smiley21": " ;)"
  5295. },
  5296. "regexs": {
  5297. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5298. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5299. "smiley1": /(:-\)|:\))/gi,
  5300. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5301. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5302. "smiley6": /(\(wave\))/gi,
  5303. "smiley7": /(\(blush\))/gi,
  5304. "smiley8": /(\(chuckle\))/gi,
  5305. "smiley9": /(:-0|\(shocked\))/gi,
  5306. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5307. "smiley11": /(\(n\))/gi,
  5308. "smiley12": /(\(search\))/g,
  5309. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5310. "smiley14": /(\(oops\))/gi,
  5311. "smiley15": /(\(angry\))/gi,
  5312. "smiley16": /(\(angel\))/gi,
  5313. "smiley17": /(\(sick\))/gi,
  5314. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5315. "smiley19": /(\(bomb\))/gi,
  5316. "smiley20": /(\(clap\))/gi,
  5317. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5318. }
  5319. }
  5320. },{}],25:[function(require,module,exports){
  5321. /* global $, APP, Strophe */
  5322. var Avatar = require('../../avatar/Avatar');
  5323. var numberOfContacts = 0;
  5324. var notificationInterval;
  5325. /**
  5326. * Updates the number of participants in the contact list button and sets
  5327. * the glow
  5328. * @param delta indicates whether a new user has joined (1) or someone has
  5329. * left(-1)
  5330. */
  5331. function updateNumberOfParticipants(delta) {
  5332. numberOfContacts += delta;
  5333. if (numberOfContacts === 1) {
  5334. // when the user is alone we don't show the number of participants
  5335. $("#numberOfParticipants").text('');
  5336. ContactList.setVisualNotification(false);
  5337. } else if (numberOfContacts > 1) {
  5338. ContactList.setVisualNotification(!ContactList.isVisible());
  5339. $("#numberOfParticipants").text(numberOfContacts);
  5340. } else {
  5341. console.error("Invalid number of participants: " + numberOfContacts);
  5342. }
  5343. }
  5344. /**
  5345. * Creates the avatar element.
  5346. *
  5347. * @return {object} the newly created avatar element
  5348. */
  5349. function createAvatar(jid) {
  5350. var avatar = document.createElement('img');
  5351. avatar.className = "icon-avatar avatar";
  5352. avatar.src = Avatar.getContactListUrl(jid);
  5353. return avatar;
  5354. }
  5355. /**
  5356. * Creates the display name paragraph.
  5357. *
  5358. * @param displayName the display name to set
  5359. */
  5360. function createDisplayNameParagraph(key, displayName) {
  5361. var p = document.createElement('p');
  5362. if(displayName)
  5363. p.innerText = displayName;
  5364. else if(key) {
  5365. p.setAttribute("data-i18n",key);
  5366. p.innerText = APP.translation.translateString(key);
  5367. }
  5368. return p;
  5369. }
  5370. function stopGlowing(glower) {
  5371. window.clearInterval(notificationInterval);
  5372. notificationInterval = false;
  5373. glower.removeClass('glowing');
  5374. if (!ContactList.isVisible()) {
  5375. glower.removeClass('active');
  5376. }
  5377. }
  5378. /**
  5379. * Contact list.
  5380. */
  5381. var ContactList = {
  5382. /**
  5383. * Indicates if the chat is currently visible.
  5384. *
  5385. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5386. * otherwise
  5387. */
  5388. isVisible: function () {
  5389. return $('#contactlist').is(":visible");
  5390. },
  5391. /**
  5392. * Adds a contact for the given peerJid if such doesn't yet exist.
  5393. *
  5394. * @param peerJid the peerJid corresponding to the contact
  5395. */
  5396. ensureAddContact: function (peerJid) {
  5397. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5398. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5399. if (!contact || contact.length <= 0)
  5400. ContactList.addContact(peerJid);
  5401. },
  5402. /**
  5403. * Adds a contact for the given peer jid.
  5404. *
  5405. * @param peerJid the jid of the contact to add
  5406. */
  5407. addContact: function (peerJid) {
  5408. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5409. var contactlist = $('#contacts');
  5410. var newContact = document.createElement('li');
  5411. newContact.id = resourceJid;
  5412. newContact.className = "clickable";
  5413. newContact.onclick = function (event) {
  5414. if (event.currentTarget.className === "clickable") {
  5415. $(ContactList).trigger('contactclicked', [peerJid]);
  5416. }
  5417. };
  5418. newContact.appendChild(createAvatar(peerJid));
  5419. newContact.appendChild(createDisplayNameParagraph("participant"));
  5420. if (resourceJid === APP.xmpp.myResource()) {
  5421. contactlist.prepend(newContact);
  5422. }
  5423. else {
  5424. contactlist.append(newContact);
  5425. }
  5426. updateNumberOfParticipants(1);
  5427. },
  5428. /**
  5429. * Removes a contact for the given peer jid.
  5430. *
  5431. * @param peerJid the peerJid corresponding to the contact to remove
  5432. */
  5433. removeContact: function (peerJid) {
  5434. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5435. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5436. if (contact && contact.length > 0) {
  5437. var contactlist = $('#contactlist>ul');
  5438. contactlist.get(0).removeChild(contact.get(0));
  5439. updateNumberOfParticipants(-1);
  5440. }
  5441. },
  5442. setVisualNotification: function (show, stopGlowingIn) {
  5443. var glower = $('#contactListButton');
  5444. if (show && !notificationInterval) {
  5445. notificationInterval = window.setInterval(function () {
  5446. glower.toggleClass('active glowing');
  5447. }, 800);
  5448. }
  5449. else if (!show && notificationInterval) {
  5450. stopGlowing(glower);
  5451. }
  5452. if (stopGlowingIn) {
  5453. setTimeout(function () {
  5454. stopGlowing(glower);
  5455. }, stopGlowingIn);
  5456. }
  5457. },
  5458. setClickable: function (resourceJid, isClickable) {
  5459. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5460. if (isClickable) {
  5461. contact.addClass('clickable');
  5462. } else {
  5463. contact.removeClass('clickable');
  5464. }
  5465. },
  5466. onDisplayNameChange: function (peerJid, displayName) {
  5467. if (peerJid === 'localVideoContainer')
  5468. peerJid = APP.xmpp.myJid();
  5469. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5470. var contactName = $('#contacts #' + resourceJid + '>p');
  5471. if (contactName && displayName && displayName.length > 0)
  5472. contactName.html(displayName);
  5473. },
  5474. userAvatarChanged: function (resourceJid, contactListUrl) {
  5475. // set the avatar in the contact list
  5476. var contact = $('#' + resourceJid + '>img');
  5477. if (contact && contact.length > 0) {
  5478. contact.get(0).src = contactListUrl;
  5479. }
  5480. }
  5481. };
  5482. module.exports = ContactList;
  5483. },{"../../avatar/Avatar":16}],26:[function(require,module,exports){
  5484. /* global APP, $ */
  5485. var Avatar = require("../../avatar/Avatar");
  5486. var Settings = require("./../../../settings/Settings");
  5487. var UIUtil = require("../../util/UIUtil");
  5488. var languages = require("../../../../service/translation/languages");
  5489. function generateLanguagesSelectBox() {
  5490. var currentLang = APP.translation.getCurrentLanguage();
  5491. var html = "<select id=\"languages_selectbox\">";
  5492. var langArray = languages.getLanguages();
  5493. for(var i = 0; i < langArray.length; i++) {
  5494. var lang = langArray[i];
  5495. html += "<option ";
  5496. if(lang === currentLang)
  5497. html += "selected ";
  5498. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5499. html += "</option>";
  5500. }
  5501. return html + "</select>";
  5502. }
  5503. var SettingsMenu = {
  5504. init: function () {
  5505. var startMutedSelector = $("#startMutedOptions");
  5506. startMutedSelector.before(generateLanguagesSelectBox());
  5507. APP.translation.translateElement($("#languages_selectbox"));
  5508. $('#settingsmenu>input').keyup(function(event){
  5509. if(event.keyCode === 13) {//enter
  5510. SettingsMenu.update();
  5511. }
  5512. });
  5513. if (APP.xmpp.isModerator()) {
  5514. startMutedSelector.css("display", "block");
  5515. }
  5516. else {
  5517. startMutedSelector.css("display", "none");
  5518. }
  5519. $("#updateSettings").click(function () {
  5520. SettingsMenu.update();
  5521. });
  5522. },
  5523. onRoleChanged: function () {
  5524. if(APP.xmpp.isModerator()) {
  5525. $("#startMutedOptions").css("display", "block");
  5526. }
  5527. else {
  5528. $("#startMutedOptions").css("display", "none");
  5529. }
  5530. },
  5531. setStartMuted: function (audio, video) {
  5532. $("#startAudioMuted").attr("checked", audio);
  5533. $("#startVideoMuted").attr("checked", video);
  5534. },
  5535. update: function() {
  5536. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5537. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5538. if(newDisplayName) {
  5539. var displayName = Settings.setDisplayName(newDisplayName);
  5540. APP.xmpp.addToPresence("displayName", displayName, true);
  5541. }
  5542. var language = $("#languages_selectbox").val();
  5543. APP.translation.setLanguage(language);
  5544. Settings.setLanguage(language);
  5545. APP.xmpp.addToPresence("email", newEmail);
  5546. var email = Settings.setEmail(newEmail);
  5547. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5548. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5549. APP.xmpp.addToPresence("startMuted",
  5550. [startAudioMuted, startVideoMuted]);
  5551. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5552. },
  5553. isVisible: function() {
  5554. return $('#settingsmenu').is(':visible');
  5555. },
  5556. setDisplayName: function(newDisplayName) {
  5557. var displayName = Settings.setDisplayName(newDisplayName);
  5558. $('#setDisplayName').get(0).value = displayName;
  5559. },
  5560. onDisplayNameChange: function(peerJid, newDisplayName) {
  5561. if(peerJid === 'localVideoContainer' ||
  5562. peerJid === APP.xmpp.myJid()) {
  5563. this.setDisplayName(newDisplayName);
  5564. }
  5565. },
  5566. changeAvatar: function (thumbUrl) {
  5567. $('#avatar').get(0).src = thumbUrl;
  5568. }
  5569. };
  5570. module.exports = SettingsMenu;
  5571. },{"../../../../service/translation/languages":171,"../../avatar/Avatar":16,"../../util/UIUtil":33,"./../../../settings/Settings":49}],27:[function(require,module,exports){
  5572. /* global $ */
  5573. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5574. var buttonHandlers = {
  5575. "bottom_toolbar_contact_list": function () {
  5576. BottomToolbar.toggleContactList();
  5577. },
  5578. "bottom_toolbar_film_strip": function () {
  5579. BottomToolbar.toggleFilmStrip();
  5580. },
  5581. "bottom_toolbar_chat": function () {
  5582. BottomToolbar.toggleChat();
  5583. }
  5584. };
  5585. var BottomToolbar = (function (my) {
  5586. my.init = function () {
  5587. for(var k in buttonHandlers)
  5588. $("#" + k).click(buttonHandlers[k]);
  5589. };
  5590. my.toggleChat = function() {
  5591. PanelToggler.toggleChat();
  5592. };
  5593. my.toggleContactList = function() {
  5594. PanelToggler.toggleContactList();
  5595. };
  5596. my.toggleFilmStrip = function() {
  5597. var filmstrip = $("#remoteVideos");
  5598. filmstrip.toggleClass("hidden");
  5599. };
  5600. $(document).bind("remotevideo.resized", function (event, width, height) {
  5601. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5602. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5603. });
  5604. return my;
  5605. }(BottomToolbar || {}));
  5606. module.exports = BottomToolbar;
  5607. },{"../side_pannels/SidePanelToggler":20}],28:[function(require,module,exports){
  5608. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5609. Util */
  5610. var messageHandler = require("../util/MessageHandler");
  5611. var BottomToolbar = require("./BottomToolbar");
  5612. var Prezi = require("../prezi/Prezi");
  5613. var Etherpad = require("../etherpad/Etherpad");
  5614. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5615. var Authentication = require("../authentication/Authentication");
  5616. var UIUtil = require("../util/UIUtil");
  5617. var AuthenticationEvents
  5618. = require("../../../service/authentication/AuthenticationEvents");
  5619. var roomUrl = null;
  5620. var sharedKey = '';
  5621. var UI = null;
  5622. var recordingToaster = null;
  5623. var buttonHandlers = {
  5624. "toolbar_button_mute": function () {
  5625. return APP.UI.toggleAudio();
  5626. },
  5627. "toolbar_button_camera": function () {
  5628. return APP.UI.toggleVideo();
  5629. },
  5630. /*"toolbar_button_authentication": function () {
  5631. return Toolbar.authenticateClicked();
  5632. },*/
  5633. "toolbar_button_record": function () {
  5634. return toggleRecording();
  5635. },
  5636. "toolbar_button_security": function () {
  5637. return Toolbar.openLockDialog();
  5638. },
  5639. "toolbar_button_link": function () {
  5640. return Toolbar.openLinkDialog();
  5641. },
  5642. "toolbar_button_chat": function () {
  5643. return BottomToolbar.toggleChat();
  5644. },
  5645. "toolbar_button_prezi": function () {
  5646. return Prezi.openPreziDialog();
  5647. },
  5648. "toolbar_button_etherpad": function () {
  5649. return Etherpad.toggleEtherpad(0);
  5650. },
  5651. "toolbar_button_desktopsharing": function () {
  5652. return APP.desktopsharing.toggleScreenSharing();
  5653. },
  5654. "toolbar_button_fullScreen": function() {
  5655. UIUtil.buttonClick("#toolbar_button_fullScreen", "icon-full-screen icon-exit-full-screen");
  5656. return Toolbar.toggleFullScreen();
  5657. },
  5658. "toolbar_button_sip": function () {
  5659. return callSipButtonClicked();
  5660. },
  5661. "toolbar_button_dialpad": function () {
  5662. return dialpadButtonClicked();
  5663. },
  5664. "toolbar_button_settings": function () {
  5665. PanelToggler.toggleSettingsMenu();
  5666. },
  5667. "toolbar_button_hangup": function () {
  5668. return hangup();
  5669. },
  5670. "toolbar_button_login": function () {
  5671. Toolbar.authenticateClicked();
  5672. },
  5673. "toolbar_button_logout": function () {
  5674. // Ask for confirmation
  5675. messageHandler.openTwoButtonDialog(
  5676. "dialog.logoutTitle",
  5677. null,
  5678. "dialog.logoutQuestion",
  5679. null,
  5680. false,
  5681. "dialog.Yes",
  5682. function (evt, yes) {
  5683. if (yes) {
  5684. APP.xmpp.logout(function (url) {
  5685. if (url) {
  5686. window.location.href = url;
  5687. } else {
  5688. hangup();
  5689. }
  5690. });
  5691. }
  5692. });
  5693. }
  5694. };
  5695. function hangup() {
  5696. APP.xmpp.disposeConference();
  5697. if(config.enableWelcomePage) {
  5698. setTimeout(function() {
  5699. window.localStorage.welcomePageDisabled = false;
  5700. window.location.pathname = "/";
  5701. }, 10000);
  5702. }
  5703. var title = APP.translation.generateTranslationHTML(
  5704. "dialog.sessTerminated");
  5705. var msg = APP.translation.generateTranslationHTML(
  5706. "dialog.hungUp");
  5707. var button = APP.translation.generateTranslationHTML(
  5708. "dialog.joinAgain");
  5709. var buttons = [];
  5710. buttons.push({title: button, value: true});
  5711. UI.messageHandler.openDialog(
  5712. title,
  5713. msg,
  5714. true,
  5715. buttons,
  5716. function(event, value, message, formVals) {
  5717. window.location.reload();
  5718. return false;
  5719. }
  5720. );
  5721. }
  5722. /**
  5723. * Starts or stops the recording for the conference.
  5724. */
  5725. function toggleRecording(predefinedToken) {
  5726. APP.xmpp.toggleRecording(function (callback) {
  5727. if (predefinedToken) {
  5728. callback(UIUtil.escapeHtml(predefinedToken));
  5729. return;
  5730. }
  5731. var msg = APP.translation.generateTranslationHTML(
  5732. "dialog.recordingToken");
  5733. var token = APP.translation.translateString("dialog.token");
  5734. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  5735. '<h2>' + msg + '</h2>' +
  5736. '<input name="recordingToken" type="text" ' +
  5737. ' data-i18n="[placeholder]dialog.token" ' +
  5738. 'placeholder="' + token + '" autofocus>',
  5739. false,
  5740. "dialog.Save",
  5741. function (e, v, m, f) {
  5742. if (v) {
  5743. var token = f.recordingToken;
  5744. if (token) {
  5745. callback(UIUtil.escapeHtml(token));
  5746. }
  5747. }
  5748. },
  5749. null,
  5750. function () { },
  5751. ':input:first'
  5752. );
  5753. }, Toolbar.setRecordingButtonState);
  5754. }
  5755. /**
  5756. * Locks / unlocks the room.
  5757. */
  5758. function lockRoom(lock) {
  5759. var currentSharedKey = '';
  5760. if (lock)
  5761. currentSharedKey = sharedKey;
  5762. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  5763. // password is required
  5764. if (sharedKey) {
  5765. console.log('set room password');
  5766. Toolbar.lockLockButton();
  5767. }
  5768. else {
  5769. console.log('removed room password');
  5770. Toolbar.unlockLockButton();
  5771. }
  5772. }, function (err) {
  5773. console.warn('setting password failed', err);
  5774. messageHandler.showError("dialog.lockTitle",
  5775. "dialog.lockMessage");
  5776. Toolbar.setSharedKey('');
  5777. }, function () {
  5778. console.warn('room passwords not supported');
  5779. messageHandler.showError("dialog.warning",
  5780. "dialog.passwordNotSupported");
  5781. Toolbar.setSharedKey('');
  5782. });
  5783. }
  5784. /**
  5785. * Invite participants to conference.
  5786. */
  5787. function inviteParticipants() {
  5788. if (roomUrl === null)
  5789. return;
  5790. var sharedKeyText = "";
  5791. if (sharedKey && sharedKey.length > 0) {
  5792. sharedKeyText =
  5793. APP.translation.translateString("email.sharedKey",
  5794. {sharedKey: sharedKey});
  5795. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  5796. }
  5797. var supportedBrowsers = "Chromium, Google Chrome " +
  5798. APP.translation.translateString("email.and") + " Opera";
  5799. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  5800. var subject = APP.translation.translateString("email.subject",
  5801. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  5802. var body = APP.translation.translateString("email.body",
  5803. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  5804. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  5805. body = body.replace(/\n/g, "%0D%0A");
  5806. if (window.localStorage.displayname) {
  5807. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  5808. }
  5809. if (interfaceConfig.INVITATION_POWERED_BY) {
  5810. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  5811. }
  5812. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  5813. }
  5814. function dialpadButtonClicked() {
  5815. //TODO show the dialpad box
  5816. }
  5817. function callSipButtonClicked() {
  5818. var defaultNumber
  5819. = config.defaultSipNumber ? config.defaultSipNumber : '';
  5820. var sipMsg = APP.translation.generateTranslationHTML(
  5821. "dialog.sipMsg");
  5822. messageHandler.openTwoButtonDialog(null, null, null,
  5823. '<h2>' + sipMsg + '</h2>' +
  5824. '<input name="sipNumber" type="text"' +
  5825. ' value="' + defaultNumber + '" autofocus>',
  5826. false,
  5827. "dialog.Dial",
  5828. function (e, v, m, f) {
  5829. if (v) {
  5830. var numberInput = f.sipNumber;
  5831. if (numberInput) {
  5832. APP.xmpp.dial(
  5833. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  5834. }
  5835. }
  5836. },
  5837. null, null, ':input:first'
  5838. );
  5839. }
  5840. var Toolbar = (function (my) {
  5841. my.init = function (ui) {
  5842. for(var k in buttonHandlers)
  5843. $("#" + k).click(buttonHandlers[k]);
  5844. UI = ui;
  5845. // Update login info
  5846. APP.xmpp.addListener(
  5847. AuthenticationEvents.IDENTITY_UPDATED,
  5848. function (authenticationEnabled, userIdentity) {
  5849. var loggedIn = false;
  5850. if (userIdentity) {
  5851. loggedIn = true;
  5852. }
  5853. Toolbar.showAuthenticateButton(authenticationEnabled);
  5854. if (authenticationEnabled) {
  5855. Toolbar.setAuthenticatedIdentity(userIdentity);
  5856. Toolbar.showLoginButton(!loggedIn);
  5857. Toolbar.showLogoutButton(loggedIn);
  5858. }
  5859. }
  5860. );
  5861. };
  5862. /**
  5863. * Sets shared key
  5864. * @param sKey the shared key
  5865. */
  5866. my.setSharedKey = function (sKey) {
  5867. sharedKey = sKey;
  5868. };
  5869. my.authenticateClicked = function () {
  5870. Authentication.focusAuthenticationWindow();
  5871. if (!APP.xmpp.isExternalAuthEnabled()) {
  5872. Authentication.xmppAuthenticate();
  5873. return;
  5874. }
  5875. // Get authentication URL
  5876. if (!APP.xmpp.isMUCJoined()) {
  5877. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  5878. // If conference has not been started yet - redirect to login page
  5879. window.location.href = url;
  5880. });
  5881. } else {
  5882. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  5883. // Otherwise - open popup with authentication URL
  5884. var authenticationWindow = Authentication.createAuthenticationWindow(
  5885. function () {
  5886. // On popup closed - retry room allocation
  5887. APP.xmpp.allocateConferenceFocus(
  5888. APP.UI.getRoomName(),
  5889. function () { console.info("AUTH DONE"); }
  5890. );
  5891. }, url);
  5892. if (!authenticationWindow) {
  5893. messageHandler.openMessageDialog(
  5894. null, "dialog.popupError");
  5895. }
  5896. });
  5897. }
  5898. };
  5899. /**
  5900. * Updates the room invite url.
  5901. */
  5902. my.updateRoomUrl = function (newRoomUrl) {
  5903. roomUrl = newRoomUrl;
  5904. // If the invite dialog has been already opened we update the information.
  5905. var inviteLink = document.getElementById('inviteLinkRef');
  5906. if (inviteLink) {
  5907. inviteLink.value = roomUrl;
  5908. inviteLink.select();
  5909. $('#inviteLinkRef').parent()
  5910. .find('button[value=true]').prop('disabled', false);
  5911. }
  5912. };
  5913. /**
  5914. * Disables and enables some of the buttons.
  5915. */
  5916. my.setupButtonsFromConfig = function () {
  5917. if (config.disablePrezi) {
  5918. $("#toolbar_button_prezi").css({display: "none"});
  5919. }
  5920. };
  5921. /**
  5922. * Opens the lock room dialog.
  5923. */
  5924. my.openLockDialog = function () {
  5925. // Only the focus is able to set a shared key.
  5926. if (!APP.xmpp.isModerator()) {
  5927. if (sharedKey) {
  5928. messageHandler.openMessageDialog(null,
  5929. "dialog.passwordError");
  5930. } else {
  5931. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  5932. }
  5933. } else {
  5934. if (sharedKey) {
  5935. messageHandler.openTwoButtonDialog(null, null,
  5936. "dialog.passwordCheck",
  5937. null,
  5938. false,
  5939. "dialog.Remove",
  5940. function (e, v) {
  5941. if (v) {
  5942. Toolbar.setSharedKey('');
  5943. lockRoom(false);
  5944. }
  5945. });
  5946. } else {
  5947. var msg = APP.translation.generateTranslationHTML(
  5948. "dialog.passwordMsg");
  5949. var yourPassword = APP.translation.translateString(
  5950. "dialog.yourPassword");
  5951. messageHandler.openTwoButtonDialog(null, null, null,
  5952. '<h2>' + msg + '</h2>' +
  5953. '<input name="lockKey" type="text"' +
  5954. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  5955. 'placeholder="' + yourPassword + '" autofocus>',
  5956. false,
  5957. "dialog.Save",
  5958. function (e, v, m, f) {
  5959. if (v) {
  5960. var lockKey = f.lockKey;
  5961. if (lockKey) {
  5962. Toolbar.setSharedKey(
  5963. UIUtil.escapeHtml(lockKey));
  5964. lockRoom(true);
  5965. }
  5966. }
  5967. },
  5968. null, null, 'input:first'
  5969. );
  5970. }
  5971. }
  5972. };
  5973. /**
  5974. * Opens the invite link dialog.
  5975. */
  5976. my.openLinkDialog = function () {
  5977. var inviteAttreibutes;
  5978. if (roomUrl === null) {
  5979. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  5980. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  5981. } else {
  5982. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  5983. }
  5984. messageHandler.openTwoButtonDialog("dialog.shareLink",
  5985. null, null,
  5986. '<input id="inviteLinkRef" type="text" ' +
  5987. inviteAttreibutes + ' onclick="this.select();" readonly>',
  5988. false,
  5989. "dialog.Invite",
  5990. function (e, v) {
  5991. if (v) {
  5992. if (roomUrl) {
  5993. inviteParticipants();
  5994. }
  5995. }
  5996. },
  5997. function (event) {
  5998. if (roomUrl) {
  5999. document.getElementById('inviteLinkRef').select();
  6000. } else {
  6001. if (event && event.target)
  6002. $(event.target)
  6003. .find('button[value=true]').prop('disabled', true);
  6004. }
  6005. }
  6006. );
  6007. };
  6008. /**
  6009. * Opens the settings dialog.
  6010. * FIXME: not used ?
  6011. */
  6012. my.openSettingsDialog = function () {
  6013. var settings1 = APP.translation.generateTranslationHTML(
  6014. "dialog.settings1");
  6015. var settings2 = APP.translation.generateTranslationHTML(
  6016. "dialog.settings2");
  6017. var settings3 = APP.translation.generateTranslationHTML(
  6018. "dialog.settings3");
  6019. var yourPassword = APP.translation.translateString(
  6020. "dialog.yourPassword");
  6021. messageHandler.openTwoButtonDialog(null,
  6022. '<h2>' + settings1 + '</h2>' +
  6023. '<input type="checkbox" id="initMuted">' +
  6024. settings2 + '<br/>' +
  6025. '<input type="checkbox" id="requireNicknames">' +
  6026. settings3 +
  6027. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6028. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6029. null,
  6030. null,
  6031. false,
  6032. "dialog.Save",
  6033. function () {
  6034. document.getElementById('lockKey').focus();
  6035. },
  6036. function (e, v) {
  6037. if (v) {
  6038. if ($('#initMuted').is(":checked")) {
  6039. // it is checked
  6040. }
  6041. if ($('#requireNicknames').is(":checked")) {
  6042. // it is checked
  6043. }
  6044. /*
  6045. var lockKey = document.getElementById('lockKey');
  6046. if (lockKey.value) {
  6047. setSharedKey(lockKey.value);
  6048. lockRoom(true);
  6049. }
  6050. */
  6051. }
  6052. }
  6053. );
  6054. };
  6055. /**
  6056. * Toggles the application in and out of full screen mode
  6057. * (a.k.a. presentation mode in Chrome).
  6058. */
  6059. my.toggleFullScreen = function () {
  6060. var fsElement = document.documentElement;
  6061. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6062. //Enter Full Screen
  6063. if (fsElement.mozRequestFullScreen) {
  6064. fsElement.mozRequestFullScreen();
  6065. }
  6066. else {
  6067. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6068. }
  6069. } else {
  6070. //Exit Full Screen
  6071. if (document.mozCancelFullScreen) {
  6072. document.mozCancelFullScreen();
  6073. } else {
  6074. document.webkitCancelFullScreen();
  6075. }
  6076. }
  6077. };
  6078. /**
  6079. * Unlocks the lock button state.
  6080. */
  6081. my.unlockLockButton = function () {
  6082. if ($("#toolbar_button_security").hasClass("icon-security-locked"))
  6083. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6084. };
  6085. /**
  6086. * Updates the lock button state to locked.
  6087. */
  6088. my.lockLockButton = function () {
  6089. if ($("#toolbar_button_security").hasClass("icon-security"))
  6090. UIUtil.buttonClick("#toolbar_button_security", "icon-security icon-security-locked");
  6091. };
  6092. /**
  6093. * Shows or hides authentication button
  6094. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6095. */
  6096. my.showAuthenticateButton = function (show) {
  6097. if (show) {
  6098. $('#authentication').css({display: "inline"});
  6099. }
  6100. else {
  6101. $('#authentication').css({display: "none"});
  6102. }
  6103. };
  6104. // Shows or hides the 'recording' button.
  6105. my.showRecordingButton = function (show) {
  6106. if (!config.enableRecording) {
  6107. return;
  6108. }
  6109. if (show) {
  6110. $('#toolbar_button_record').css({display: "inline-block"});
  6111. }
  6112. else {
  6113. $('#toolbar_button_record').css({display: "none"});
  6114. }
  6115. };
  6116. // Sets the state of the recording button
  6117. my.setRecordingButtonState = function (recordingState) {
  6118. var selector = $('#toolbar_button_record');
  6119. if (recordingState === 'on') {
  6120. selector.removeClass("icon-recEnable");
  6121. selector.addClass("icon-recEnable active");
  6122. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6123. var recordOnKey = "recording.on";
  6124. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6125. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6126. setTimeout(function(){
  6127. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6128. $('#videoConnectionMessage').css({display: "none"});
  6129. }, 1500);
  6130. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6131. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6132. } else if (recordingState === 'off') {
  6133. selector.removeClass("icon-recEnable active");
  6134. selector.addClass("icon-recEnable");
  6135. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6136. $('#videoConnectionMessage').css({display: "none"});
  6137. if (recordingToaster)
  6138. messageHandler.remove(recordingToaster);
  6139. } else if (recordingState === 'pending') {
  6140. selector.removeClass("icon-recEnable active");
  6141. selector.addClass("icon-recEnable");
  6142. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6143. var recordPendingKey = "recording.pending";
  6144. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6145. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6146. $('#videoConnectionMessage').css({display: "block"});
  6147. }
  6148. };
  6149. // checks whether recording is enabled and whether we have params to start automatically recording
  6150. my.checkAutoRecord = function () {
  6151. if (config.enableRecording && config.autoRecord) {
  6152. toggleRecording(config.autoRecordToken);
  6153. }
  6154. }
  6155. // Shows or hides SIP calls button
  6156. my.showSipCallButton = function (show) {
  6157. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6158. $('#toolbar_button_sip').css({display: "inline-block"});
  6159. } else {
  6160. $('#toolbar_button_sip').css({display: "none"});
  6161. }
  6162. };
  6163. // Shows or hides the dialpad button
  6164. my.showDialPadButton = function (show) {
  6165. if (show) {
  6166. $('#toolbar_button_dialpad').css({display: "inline-block"});
  6167. } else {
  6168. $('#toolbar_button_dialpad').css({display: "none"});
  6169. }
  6170. };
  6171. /**
  6172. * Displays user authenticated identity name(login).
  6173. * @param authIdentity identity name to be displayed.
  6174. */
  6175. my.setAuthenticatedIdentity = function (authIdentity) {
  6176. if (authIdentity) {
  6177. var selector = $('#toolbar_auth_identity');
  6178. selector.css({display: "list-item"});
  6179. selector.text(authIdentity);
  6180. } else {
  6181. $('#toolbar_auth_identity').css({display: "none"});
  6182. }
  6183. };
  6184. /**
  6185. * Shows/hides login button.
  6186. * @param show <tt>true</tt> to show
  6187. */
  6188. my.showLoginButton = function (show) {
  6189. if (show) {
  6190. $('#toolbar_button_login').css({display: "list-item"});
  6191. } else {
  6192. $('#toolbar_button_login').css({display: "none"});
  6193. }
  6194. };
  6195. /**
  6196. * Shows/hides logout button.
  6197. * @param show <tt>true</tt> to show
  6198. */
  6199. my.showLogoutButton = function (show) {
  6200. if (show) {
  6201. $('#toolbar_button_logout').css({display: "list-item"});
  6202. } else {
  6203. $('#toolbar_button_logout').css({display: "none"});
  6204. }
  6205. };
  6206. /**
  6207. * Sets the state of the button. The button has blue glow if desktop
  6208. * streaming is active.
  6209. * @param active the state of the desktop streaming.
  6210. */
  6211. my.changeDesktopSharingButtonState = function (active) {
  6212. var button = $("#toolbar_button_desktopsharing");
  6213. if (active) {
  6214. button.addClass("glow");
  6215. } else {
  6216. button.removeClass("glow");
  6217. }
  6218. };
  6219. return my;
  6220. }(Toolbar || {}));
  6221. module.exports = Toolbar;
  6222. },{"../../../service/authentication/AuthenticationEvents":167,"../authentication/Authentication":14,"../etherpad/Etherpad":17,"../prezi/Prezi":18,"../side_pannels/SidePanelToggler":20,"../util/MessageHandler":31,"../util/UIUtil":33,"./BottomToolbar":27}],29:[function(require,module,exports){
  6223. /* global APP, config, $, interfaceConfig, Moderator,
  6224. DesktopStreaming.showDesktopSharingButton */
  6225. var toolbarTimeoutObject,
  6226. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6227. function showDesktopSharingButton() {
  6228. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6229. $('#toolbar_button_desktopsharing').css({display: "inline-block"});
  6230. } else {
  6231. $('#toolbar_button_desktopsharing').css({display: "none"});
  6232. }
  6233. }
  6234. /**
  6235. * Hides the toolbar.
  6236. */
  6237. function hideToolbar() {
  6238. if(config.alwaysVisibleToolbar)
  6239. return;
  6240. var header = $("#header"),
  6241. bottomToolbar = $("#bottomToolbar");
  6242. var isToolbarHover = false;
  6243. header.find('*').each(function () {
  6244. var id = $(this).attr('id');
  6245. if ($("#" + id + ":hover").length > 0) {
  6246. isToolbarHover = true;
  6247. }
  6248. });
  6249. if ($("#bottomToolbar:hover").length > 0) {
  6250. isToolbarHover = true;
  6251. }
  6252. clearTimeout(toolbarTimeoutObject);
  6253. toolbarTimeoutObject = null;
  6254. if (!isToolbarHover) {
  6255. header.hide("slide", { direction: "up", duration: 300});
  6256. $('#subject').animate({top: "-=40"}, 300);
  6257. if ($("#remoteVideos").hasClass("hidden")) {
  6258. bottomToolbar.hide(
  6259. "slide", {direction: "right", duration: 300});
  6260. }
  6261. }
  6262. else {
  6263. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6264. }
  6265. }
  6266. var ToolbarToggler = {
  6267. /**
  6268. * Shows the main toolbar.
  6269. */
  6270. showToolbar: function () {
  6271. if (interfaceConfig.filmStripOnly)
  6272. return;
  6273. var header = $("#header"),
  6274. bottomToolbar = $("#bottomToolbar");
  6275. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6276. header.show("slide", { direction: "up", duration: 300});
  6277. $('#subject').animate({top: "+=40"}, 300);
  6278. if (!bottomToolbar.is(":visible")) {
  6279. bottomToolbar.show(
  6280. "slide", {direction: "right", duration: 300});
  6281. }
  6282. if (toolbarTimeoutObject) {
  6283. clearTimeout(toolbarTimeoutObject);
  6284. toolbarTimeoutObject = null;
  6285. }
  6286. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6287. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6288. }
  6289. if (APP.xmpp.isModerator())
  6290. {
  6291. // TODO: Enable settings functionality.
  6292. // Need to uncomment the settings button in index.html.
  6293. // $('#settingsButton').css({visibility:"visible"});
  6294. }
  6295. // Show/hide desktop sharing button
  6296. showDesktopSharingButton();
  6297. },
  6298. /**
  6299. * Docks/undocks the toolbar.
  6300. *
  6301. * @param isDock indicates what operation to perform
  6302. */
  6303. dockToolbar: function (isDock) {
  6304. if (interfaceConfig.filmStripOnly)
  6305. return;
  6306. if (isDock) {
  6307. // First make sure the toolbar is shown.
  6308. if (!$('#header').is(':visible')) {
  6309. this.showToolbar();
  6310. }
  6311. // Then clear the time out, to dock the toolbar.
  6312. if (toolbarTimeoutObject) {
  6313. clearTimeout(toolbarTimeoutObject);
  6314. toolbarTimeoutObject = null;
  6315. }
  6316. }
  6317. else {
  6318. if (!$('#header').is(':visible')) {
  6319. this.showToolbar();
  6320. }
  6321. else {
  6322. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6323. }
  6324. }
  6325. },
  6326. showDesktopSharingButton: showDesktopSharingButton
  6327. };
  6328. module.exports = ToolbarToggler;
  6329. },{}],30:[function(require,module,exports){
  6330. /* global $ */
  6331. var JitsiPopover = (function () {
  6332. /**
  6333. * Constructs new JitsiPopover and attaches it to the element
  6334. * @param element jquery selector
  6335. * @param options the options for the popover.
  6336. * @constructor
  6337. */
  6338. function JitsiPopover(element, options)
  6339. {
  6340. this.options = {
  6341. skin: "white",
  6342. content: ""
  6343. };
  6344. if(options)
  6345. {
  6346. if(options.skin)
  6347. this.options.skin = options.skin;
  6348. if(options.content)
  6349. this.options.content = options.content;
  6350. }
  6351. this.elementIsHovered = false;
  6352. this.popoverIsHovered = false;
  6353. this.popoverShown = false;
  6354. element.data("jitsi_popover", this);
  6355. this.element = element;
  6356. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6357. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6358. '<div class="jitsiPopupmenuPadding"></div></div>';
  6359. var self = this;
  6360. this.element.on("mouseenter", function () {
  6361. self.elementIsHovered = true;
  6362. self.show();
  6363. }).on("mouseleave", function () {
  6364. self.elementIsHovered = false;
  6365. setTimeout(function () {
  6366. self.hide();
  6367. }, 10);
  6368. });
  6369. }
  6370. /**
  6371. * Shows the popover
  6372. */
  6373. JitsiPopover.prototype.show = function () {
  6374. if(!JitsiPopover.enabled)
  6375. return;
  6376. this.createPopover();
  6377. this.popoverShown = true;
  6378. };
  6379. /**
  6380. * Hides the popover
  6381. */
  6382. JitsiPopover.prototype.hide = function () {
  6383. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6384. this.popoverShown) {
  6385. this.forceHide();
  6386. }
  6387. };
  6388. /**
  6389. * Hides the popover.
  6390. */
  6391. JitsiPopover.prototype.forceHide = function () {
  6392. $(".jitsipopover").remove();
  6393. this.popoverShown = false;
  6394. };
  6395. /**
  6396. * Creates the popover html.
  6397. */
  6398. JitsiPopover.prototype.createPopover = function () {
  6399. $("body").append(this.template);
  6400. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6401. var self = this;
  6402. $(".jitsipopover").on("mouseenter", function () {
  6403. self.popoverIsHovered = true;
  6404. }).on("mouseleave", function () {
  6405. self.popoverIsHovered = false;
  6406. self.hide();
  6407. });
  6408. this.refreshPosition();
  6409. };
  6410. /**
  6411. * Refreshes the position of the popover.
  6412. */
  6413. JitsiPopover.prototype.refreshPosition = function () {
  6414. $(".jitsipopover").position({
  6415. my: "bottom",
  6416. at: "top",
  6417. collision: "fit",
  6418. of: this.element,
  6419. using: function (position, elements) {
  6420. var calcLeft = elements.target.left - elements.element.left +
  6421. elements.target.width/2;
  6422. $(".jitsipopover").css(
  6423. {top: position.top, left: position.left, display: "table"});
  6424. $(".jitsipopover > .arrow").css({left: calcLeft});
  6425. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6426. {left: calcLeft - 50});
  6427. }
  6428. });
  6429. };
  6430. /**
  6431. * Updates the content of popover.
  6432. * @param content new content
  6433. */
  6434. JitsiPopover.prototype.updateContent = function (content) {
  6435. this.options.content = content;
  6436. if(!this.popoverShown)
  6437. return;
  6438. $(".jitsipopover").remove();
  6439. this.createPopover();
  6440. };
  6441. JitsiPopover.enabled = true;
  6442. return JitsiPopover;
  6443. })();
  6444. module.exports = JitsiPopover;
  6445. },{}],31:[function(require,module,exports){
  6446. /* global $, APP, jQuery, toastr */
  6447. /**
  6448. * Flag for enable/disable of the notifications.
  6449. * @type {boolean}
  6450. */
  6451. var notificationsEnabled = true;
  6452. var messageHandler = (function(my) {
  6453. /**
  6454. * Shows a message to the user.
  6455. *
  6456. * @param titleKey the title of the message
  6457. * @param messageKey the text of the message
  6458. */
  6459. my.openMessageDialog = function(titleKey, messageKey) {
  6460. var title = null;
  6461. if(titleKey) {
  6462. title = APP.translation.generateTranslationHTML(titleKey);
  6463. }
  6464. var message = APP.translation.generateTranslationHTML(messageKey);
  6465. $.prompt(message,
  6466. {title: title, persistent: false}
  6467. );
  6468. };
  6469. /**
  6470. * Shows a message to the user with two buttons: first is given as a
  6471. * parameter and the second is Cancel.
  6472. *
  6473. * @param titleString the title of the message
  6474. * @param msgString the text of the message
  6475. * @param persistent boolean value which determines whether the message is
  6476. * persistent or not
  6477. * @param leftButton the fist button's text
  6478. * @param submitFunction function to be called on submit
  6479. * @param loadedFunction function to be called after the prompt is fully
  6480. * loaded
  6481. * @param closeFunction function to be called after the prompt is closed
  6482. * @param focus optional focus selector or button index to be focused after
  6483. * the dialog is opened
  6484. * @param defaultButton index of default button which will be activated when
  6485. * the user press 'enter'. Indexed from 0.
  6486. */
  6487. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6488. persistent, leftButtonKey, submitFunction, loadedFunction,
  6489. closeFunction, focus, defaultButton) {
  6490. var buttons = [];
  6491. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6492. buttons.push({ title: leftButton, value: true});
  6493. var cancelButton
  6494. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6495. buttons.push({title: cancelButton, value: false});
  6496. var message = msgString, title = titleString;
  6497. if (titleKey) {
  6498. title = APP.translation.generateTranslationHTML(titleKey);
  6499. }
  6500. if (msgKey) {
  6501. message = APP.translation.generateTranslationHTML(msgKey);
  6502. }
  6503. $.prompt(message, {
  6504. title: title,
  6505. persistent: false,
  6506. buttons: buttons,
  6507. defaultButton: defaultButton,
  6508. focus: focus,
  6509. loaded: loadedFunction,
  6510. submit: submitFunction,
  6511. close: closeFunction
  6512. });
  6513. };
  6514. /**
  6515. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6516. *
  6517. * @param titleString the title of the message
  6518. * @param msgString the text of the message
  6519. * @param persistent boolean value which determines whether the message is
  6520. * persistent or not
  6521. * @param buttons object with the buttons. The keys must be the name of the
  6522. * button and value is the value that will be passed to
  6523. * submitFunction
  6524. * @param submitFunction function to be called on submit
  6525. * @param loadedFunction function to be called after the prompt is fully
  6526. * loaded
  6527. */
  6528. my.openDialog = function (titleString, msgString, persistent, buttons,
  6529. submitFunction, loadedFunction) {
  6530. var args = {
  6531. title: titleString,
  6532. persistent: persistent,
  6533. buttons: buttons,
  6534. defaultButton: 1,
  6535. loaded: loadedFunction,
  6536. submit: submitFunction
  6537. };
  6538. if (persistent) {
  6539. args.closeText = '';
  6540. }
  6541. return new Impromptu(msgString, args);
  6542. };
  6543. /**
  6544. * Closes currently opened dialog.
  6545. */
  6546. my.closeDialog = function () {
  6547. $.prompt.close();
  6548. };
  6549. /**
  6550. * Shows a dialog with different states to the user.
  6551. *
  6552. * @param statesObject object containing all the states of the dialog.
  6553. */
  6554. my.openDialogWithStates = function (statesObject, options) {
  6555. return new Impromptu(statesObject, options);
  6556. };
  6557. /**
  6558. * Opens new popup window for given <tt>url</tt> centered over current
  6559. * window.
  6560. *
  6561. * @param url the URL to be displayed in the popup window
  6562. * @param w the width of the popup window
  6563. * @param h the height of the popup window
  6564. * @param onPopupClosed optional callback function called when popup window
  6565. * has been closed.
  6566. *
  6567. * @returns {object} popup window object if opened successfully or undefined
  6568. * in case we failed to open it(popup blocked)
  6569. */
  6570. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6571. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6572. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6573. var popup = window.open(
  6574. url, '_blank',
  6575. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6576. if (popup && onPopupClosed) {
  6577. var pollTimer = window.setInterval(function () {
  6578. if (popup.closed !== false) {
  6579. window.clearInterval(pollTimer);
  6580. onPopupClosed();
  6581. }
  6582. }, 200);
  6583. }
  6584. return popup;
  6585. };
  6586. /**
  6587. * Shows a dialog prompting the user to send an error report.
  6588. *
  6589. * @param titleKey the title of the message
  6590. * @param msgKey the text of the message
  6591. * @param error the error that is being reported
  6592. */
  6593. my.openReportDialog = function(titleKey, msgKey, error) {
  6594. my.openMessageDialog(titleKey, msgKey);
  6595. console.log(error);
  6596. //FIXME send the error to the server
  6597. };
  6598. /**
  6599. * Shows an error dialog to the user.
  6600. * @param titleKey the title of the message.
  6601. * @param msgKey the text of the message.
  6602. */
  6603. my.showError = function(titleKey, msgKey) {
  6604. if (!titleKey) {
  6605. titleKey = "dialog.oops";
  6606. }
  6607. if (!msgKey) {
  6608. msgKey = "dialog.defaultError";
  6609. }
  6610. messageHandler.openMessageDialog(titleKey, msgKey);
  6611. };
  6612. /**
  6613. * Displayes notification.
  6614. * @param displayName display name of the participant that is associated with the notification.
  6615. * @param displayNameKey the key from the language file for the display name.
  6616. * @param cls css class for the notification
  6617. * @param messageKey the key from the language file for the text of the message.
  6618. * @param messageArguments object with the arguments for the message.
  6619. * @param options object with language options.
  6620. */
  6621. my.notify = function(displayName, displayNameKey,
  6622. cls, messageKey, messageArguments, options) {
  6623. if(!notificationsEnabled)
  6624. return;
  6625. var displayNameSpan = '<span class="nickname" ';
  6626. if (displayName) {
  6627. displayNameSpan += ">" + displayName;
  6628. } else {
  6629. displayNameSpan += "data-i18n='" + displayNameKey +
  6630. "'>" + APP.translation.translateString(displayNameKey);
  6631. }
  6632. displayNameSpan += "</span>";
  6633. return toastr.info(
  6634. displayNameSpan + '<br>' +
  6635. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6636. (messageArguments?
  6637. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6638. : "") + ">" +
  6639. APP.translation.translateString(messageKey,
  6640. messageArguments) +
  6641. '</span>', null, options);
  6642. };
  6643. /**
  6644. * Removes the toaster.
  6645. * @param toasterElement
  6646. */
  6647. my.remove = function(toasterElement) {
  6648. toasterElement.remove();
  6649. };
  6650. /**
  6651. * Disables notifications.
  6652. */
  6653. my.disableNotifications = function () {
  6654. notificationsEnabled = false;
  6655. };
  6656. /**
  6657. * Enables notifications.
  6658. */
  6659. my.enableNotifications = function () {
  6660. notificationsEnabled = true;
  6661. };
  6662. return my;
  6663. }(messageHandler || {}));
  6664. module.exports = messageHandler;
  6665. },{}],32:[function(require,module,exports){
  6666. var UIEvents = require("../../../service/UI/UIEvents");
  6667. var nickname = null;
  6668. var eventEmitter = null;
  6669. var NicknameHandler = {
  6670. init: function (emitter) {
  6671. eventEmitter = emitter;
  6672. var storedDisplayName = window.localStorage.displayname;
  6673. if (storedDisplayName) {
  6674. nickname = storedDisplayName;
  6675. }
  6676. },
  6677. setNickname: function (newNickname) {
  6678. if (!newNickname || nickname === newNickname)
  6679. return;
  6680. nickname = newNickname;
  6681. window.localStorage.displayname = nickname;
  6682. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  6683. },
  6684. getNickname: function () {
  6685. return nickname;
  6686. },
  6687. addListener: function (type, listener) {
  6688. eventEmitter.on(type, listener);
  6689. }
  6690. };
  6691. module.exports = NicknameHandler;
  6692. },{"../../../service/UI/UIEvents":166}],33:[function(require,module,exports){
  6693. /* global $ */
  6694. /**
  6695. * Created by hristo on 12/22/14.
  6696. */
  6697. module.exports = {
  6698. /**
  6699. * Returns the available video width.
  6700. */
  6701. getAvailableVideoWidth: function (isVisible) {
  6702. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6703. if(typeof isVisible === "undefined" || isVisible === null)
  6704. isVisible = PanelToggler.isVisible();
  6705. var rightPanelWidth
  6706. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  6707. return window.innerWidth - rightPanelWidth;
  6708. },
  6709. /**
  6710. * Changes the style class of the element given by id.
  6711. */
  6712. buttonClick: function(id, classname) {
  6713. $(id).toggleClass(classname); // add the class to the clicked element
  6714. },
  6715. /**
  6716. * Returns the text width for the given element.
  6717. *
  6718. * @param el the element
  6719. */
  6720. getTextWidth: function (el) {
  6721. return (el.clientWidth + 1);
  6722. },
  6723. /**
  6724. * Returns the text height for the given element.
  6725. *
  6726. * @param el the element
  6727. */
  6728. getTextHeight: function (el) {
  6729. return (el.clientHeight + 1);
  6730. },
  6731. /**
  6732. * Plays the sound given by id.
  6733. *
  6734. * @param id the identifier of the audio element.
  6735. */
  6736. playSoundNotification: function (id) {
  6737. document.getElementById(id).play();
  6738. },
  6739. /**
  6740. * Escapes the given text.
  6741. */
  6742. escapeHtml: function (unsafeText) {
  6743. return $('<div/>').text(unsafeText).html();
  6744. },
  6745. imageToGrayScale: function (canvas) {
  6746. var context = canvas.getContext('2d');
  6747. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  6748. var pixels = imgData.data;
  6749. for (var i = 0, n = pixels.length; i < n; i += 4) {
  6750. var grayscale
  6751. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  6752. pixels[i ] = grayscale; // red
  6753. pixels[i+1] = grayscale; // green
  6754. pixels[i+2] = grayscale; // blue
  6755. // pixels[i+3] is alpha
  6756. }
  6757. // redraw the image in black & white
  6758. context.putImageData(imgData, 0, 0);
  6759. },
  6760. setTooltip: function (element, key, position) {
  6761. element.setAttribute("data-i18n", "[data-content]" + key);
  6762. element.setAttribute("data-toggle", "popover");
  6763. element.setAttribute("data-placement", position);
  6764. element.setAttribute("data-html", true);
  6765. element.setAttribute("data-container", "body");
  6766. },
  6767. /**
  6768. * Inserts given child element as the first one into the container.
  6769. * @param container the container to which new child element will be added
  6770. * @param newChild the new element that will be inserted into the container
  6771. */
  6772. prependChild: function (container, newChild) {
  6773. var firstChild = container.childNodes[0];
  6774. if (firstChild) {
  6775. container.insertBefore(newChild, firstChild);
  6776. } else {
  6777. container.appendChild(newChild);
  6778. }
  6779. }
  6780. };
  6781. },{"../side_pannels/SidePanelToggler":20}],34:[function(require,module,exports){
  6782. /* global APP, $ */
  6783. var JitsiPopover = require("../util/JitsiPopover");
  6784. /**
  6785. * Constructs new connection indicator.
  6786. * @param videoContainer the video container associated with the indicator.
  6787. * @constructor
  6788. */
  6789. function ConnectionIndicator(videoContainer, jid) {
  6790. this.videoContainer = videoContainer;
  6791. this.bandwidth = null;
  6792. this.packetLoss = null;
  6793. this.bitrate = null;
  6794. this.showMoreValue = false;
  6795. this.resolution = null;
  6796. this.transport = [];
  6797. this.popover = null;
  6798. this.jid = jid;
  6799. this.create();
  6800. }
  6801. /**
  6802. * Values for the connection quality
  6803. * @type {{98: string,
  6804. * 81: string,
  6805. * 64: string,
  6806. * 47: string,
  6807. * 30: string,
  6808. * 0: string}}
  6809. */
  6810. ConnectionIndicator.connectionQualityValues = {
  6811. 98: "18px", //full
  6812. 81: "15px",//4 bars
  6813. 64: "11px",//3 bars
  6814. 47: "7px",//2 bars
  6815. 30: "3px",//1 bar
  6816. 0: "0px"//empty
  6817. };
  6818. ConnectionIndicator.getIP = function(value) {
  6819. return value.substring(0, value.lastIndexOf(":"));
  6820. };
  6821. ConnectionIndicator.getPort = function(value) {
  6822. return value.substring(value.lastIndexOf(":") + 1, value.length);
  6823. };
  6824. ConnectionIndicator.getStringFromArray = function (array) {
  6825. var res = "";
  6826. for(var i = 0; i < array.length; i++) {
  6827. res += (i === 0? "" : ", ") + array[i];
  6828. }
  6829. return res;
  6830. };
  6831. /**
  6832. * Generates the html content.
  6833. * @returns {string} the html content.
  6834. */
  6835. ConnectionIndicator.prototype.generateText = function () {
  6836. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  6837. var translate = APP.translation.translateString;
  6838. if(this.bitrate === null) {
  6839. downloadBitrate = "N/A";
  6840. uploadBitrate = "N/A";
  6841. }
  6842. else {
  6843. downloadBitrate =
  6844. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  6845. uploadBitrate =
  6846. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  6847. }
  6848. if(this.packetLoss === null) {
  6849. packetLoss = "N/A";
  6850. } else {
  6851. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  6852. (this.packetLoss.download !== null ?
  6853. this.packetLoss.download : "N/A") +
  6854. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  6855. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  6856. "%";
  6857. }
  6858. var resolutionValue = null;
  6859. if(this.resolution && this.jid != null) {
  6860. var keys = Object.keys(this.resolution);
  6861. for(var ssrc in this.resolution) {
  6862. resolutionValue = this.resolution[ssrc];
  6863. }
  6864. }
  6865. if(this.jid === null) {
  6866. resolution = "";
  6867. if(this.resolution === null || !Object.keys(this.resolution) ||
  6868. Object.keys(this.resolution).length === 0) {
  6869. resolution = "N/A";
  6870. } else {
  6871. for (i in this.resolution) {
  6872. resolutionValue = this.resolution[i];
  6873. if (resolutionValue) {
  6874. if (resolutionValue.height &&
  6875. resolutionValue.width) {
  6876. resolution += (resolution === "" ? "" : ", ") +
  6877. resolutionValue.width + "x" +
  6878. resolutionValue.height;
  6879. }
  6880. }
  6881. }
  6882. }
  6883. } else if(!resolutionValue ||
  6884. !resolutionValue.height ||
  6885. !resolutionValue.width) {
  6886. resolution = "N/A";
  6887. } else {
  6888. resolution = resolutionValue.width + "x" + resolutionValue.height;
  6889. }
  6890. var result = "<table style='width:100%'>" +
  6891. "<tr>" +
  6892. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  6893. translate("connectionindicator.bitrate") + "</span></td>" +
  6894. "<td><span class='jitsipopover_green'>&darr;</span>" +
  6895. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  6896. uploadBitrate + "</td>" +
  6897. "</tr><tr>" +
  6898. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  6899. translate("connectionindicator.packetloss") + "</span></td>" +
  6900. "<td>" + packetLoss + "</td>" +
  6901. "</tr><tr>" +
  6902. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  6903. translate("connectionindicator.resolution") + "</span></td>" +
  6904. "<td>" + resolution + "</td></tr></table>";
  6905. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  6906. result += "<div class=\"jitsipopover_showmore\" " +
  6907. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  6908. // FIXME: we do not know local jid when this text is generated
  6909. //this.jid + "')\" data-i18n='connectionindicator." +
  6910. "local')\" data-i18n='connectionindicator." +
  6911. (this.showMoreValue ? "less" : "more") + "'>" +
  6912. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  6913. "</div><br />";
  6914. }
  6915. if (this.showMoreValue) {
  6916. var downloadBandwidth, uploadBandwidth, transport;
  6917. if (this.bandwidth === null) {
  6918. downloadBandwidth = "N/A";
  6919. uploadBandwidth = "N/A";
  6920. } else {
  6921. downloadBandwidth = this.bandwidth.download?
  6922. this.bandwidth.download + " Kbps" :
  6923. "N/A";
  6924. uploadBandwidth = this.bandwidth.upload?
  6925. this.bandwidth.upload + " Kbps" :
  6926. "N/A";
  6927. }
  6928. if (!this.transport || this.transport.length === 0) {
  6929. transport = "<tr>" +
  6930. "<td><span class='jitsipopover_blue' " +
  6931. "data-i18n='connectionindicator.address'>" +
  6932. translate("connectionindicator.address") + "</span></td>" +
  6933. "<td> N/A</td></tr>";
  6934. } else {
  6935. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  6936. for(i = 0; i < this.transport.length; i++) {
  6937. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  6938. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  6939. var localIP =
  6940. ConnectionIndicator.getIP(this.transport[i].localip);
  6941. var localPort =
  6942. ConnectionIndicator.getPort(this.transport[i].localip);
  6943. if(data.remoteIP.indexOf(ip) == -1) {
  6944. data.remoteIP.push(ip);
  6945. }
  6946. if(data.remotePort.indexOf(port) == -1) {
  6947. data.remotePort.push(port);
  6948. }
  6949. if(data.localIP.indexOf(localIP) == -1) {
  6950. data.localIP.push(localIP);
  6951. }
  6952. if(data.localPort.indexOf(localPort) == -1) {
  6953. data.localPort.push(localPort);
  6954. }
  6955. }
  6956. var local_address_key = "connectionindicator.localaddress";
  6957. var remote_address_key = "connectionindicator.remoteaddress";
  6958. var localTransport =
  6959. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6960. local_address_key +"' data-i18n-options='" +
  6961. JSON.stringify({count: data.localIP.length}) + "'>" +
  6962. translate(local_address_key, {count: data.localIP.length}) +
  6963. "</span></td><td> " +
  6964. ConnectionIndicator.getStringFromArray(data.localIP) +
  6965. "</td></tr>";
  6966. transport =
  6967. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  6968. remote_address_key + "' data-i18n-options='" +
  6969. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  6970. translate(remote_address_key,
  6971. {count: data.remoteIP.length}) +
  6972. "</span></td><td> " +
  6973. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  6974. "</td></tr>";
  6975. var key_remote = "connectionindicator.remoteport",
  6976. key_local = "connectionindicator.localport";
  6977. transport += "<tr>" +
  6978. "<td>" +
  6979. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  6980. "' data-i18n-options='" +
  6981. JSON.stringify({count: this.transport.length}) + "'>" +
  6982. translate(key_remote, {count: this.transport.length}) +
  6983. "</span></td><td>";
  6984. localTransport += "<tr>" +
  6985. "<td>" +
  6986. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  6987. "' data-i18n-options='" +
  6988. JSON.stringify({count: this.transport.length}) + "'>" +
  6989. translate(key_local, {count: this.transport.length}) +
  6990. "</span></td><td>";
  6991. transport +=
  6992. ConnectionIndicator.getStringFromArray(data.remotePort);
  6993. localTransport +=
  6994. ConnectionIndicator.getStringFromArray(data.localPort);
  6995. transport += "</td></tr>";
  6996. transport += localTransport + "</td></tr>";
  6997. transport +="<tr>" +
  6998. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  6999. translate("connectionindicator.transport") + "</span></td>" +
  7000. "<td>" + this.transport[0].type + "</td></tr>";
  7001. }
  7002. result += "<table style='width:100%'>" +
  7003. "<tr>" +
  7004. "<td>" +
  7005. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7006. translate("connectionindicator.bandwidth") + "</span>" +
  7007. "</td><td>" +
  7008. "<span class='jitsipopover_green'>&darr;</span>" +
  7009. downloadBandwidth +
  7010. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7011. uploadBandwidth + "</td></tr>";
  7012. result += transport + "</table>";
  7013. }
  7014. return result;
  7015. };
  7016. /**
  7017. * Shows or hide the additional information.
  7018. */
  7019. ConnectionIndicator.prototype.showMore = function () {
  7020. this.showMoreValue = !this.showMoreValue;
  7021. this.updatePopoverData();
  7022. };
  7023. function createIcon(classes) {
  7024. var icon = document.createElement("span");
  7025. for(var i in classes) {
  7026. icon.classList.add(classes[i]);
  7027. }
  7028. icon.appendChild(
  7029. document.createElement("i")).classList.add("icon-connection");
  7030. return icon;
  7031. }
  7032. /**
  7033. * Creates the indicator
  7034. */
  7035. ConnectionIndicator.prototype.create = function () {
  7036. this.connectionIndicatorContainer = document.createElement("div");
  7037. this.connectionIndicatorContainer.className = "connectionindicator";
  7038. this.connectionIndicatorContainer.style.display = "none";
  7039. this.videoContainer.container.appendChild(
  7040. this.connectionIndicatorContainer);
  7041. this.popover = new JitsiPopover(
  7042. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7043. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7044. APP.translation.translateString("connectionindicator.na") + "</div>",
  7045. skin: "black"});
  7046. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7047. createIcon(["connection", "connection_empty"]));
  7048. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7049. createIcon(["connection", "connection_full"]));
  7050. };
  7051. /**
  7052. * Removes the indicator
  7053. */
  7054. ConnectionIndicator.prototype.remove = function() {
  7055. if (this.connectionIndicatorContainer.parentNode) {
  7056. this.connectionIndicatorContainer.parentNode.removeChild(
  7057. this.connectionIndicatorContainer);
  7058. }
  7059. this.popover.forceHide();
  7060. };
  7061. /**
  7062. * Updates the data of the indicator
  7063. * @param percent the percent of connection quality
  7064. * @param object the statistics data.
  7065. */
  7066. ConnectionIndicator.prototype.updateConnectionQuality =
  7067. function (percent, object) {
  7068. if (percent === null) {
  7069. this.connectionIndicatorContainer.style.display = "none";
  7070. this.popover.forceHide();
  7071. return;
  7072. } else {
  7073. if(this.connectionIndicatorContainer.style.display == "none") {
  7074. this.connectionIndicatorContainer.style.display = "block";
  7075. this.videoContainer.updateIconPositions();
  7076. }
  7077. }
  7078. this.bandwidth = object.bandwidth;
  7079. this.bitrate = object.bitrate;
  7080. this.packetLoss = object.packetLoss;
  7081. this.transport = object.transport;
  7082. if (object.resolution) {
  7083. this.resolution = object.resolution;
  7084. }
  7085. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7086. if (percent >= quality) {
  7087. this.fullIcon.style.width =
  7088. ConnectionIndicator.connectionQualityValues[quality];
  7089. }
  7090. }
  7091. this.updatePopoverData();
  7092. };
  7093. /**
  7094. * Updates the resolution
  7095. * @param resolution the new resolution
  7096. */
  7097. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7098. this.resolution = resolution;
  7099. this.updatePopoverData();
  7100. };
  7101. /**
  7102. * Updates the content of the popover
  7103. */
  7104. ConnectionIndicator.prototype.updatePopoverData = function () {
  7105. this.popover.updateContent(
  7106. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7107. APP.translation.translateElement($(".connection_info"));
  7108. };
  7109. /**
  7110. * Hides the popover
  7111. */
  7112. ConnectionIndicator.prototype.hide = function () {
  7113. this.popover.forceHide();
  7114. };
  7115. /**
  7116. * Hides the indicator
  7117. */
  7118. ConnectionIndicator.prototype.hideIndicator = function () {
  7119. this.connectionIndicatorContainer.style.display = "none";
  7120. if(this.popover)
  7121. this.popover.forceHide();
  7122. };
  7123. module.exports = ConnectionIndicator;
  7124. },{"../util/JitsiPopover":30}],35:[function(require,module,exports){
  7125. /* global $, APP, Strophe, interfaceConfig */
  7126. var Avatar = require("../avatar/Avatar");
  7127. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7128. var UIUtil = require("../util/UIUtil");
  7129. var UIEvents = require("../../../service/UI/UIEvents");
  7130. var xmpp = require("../../xmpp/xmpp");
  7131. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7132. // FIXME: With Temasys we have to re-select everytime
  7133. //var video = $('#largeVideo');
  7134. var currentVideoWidth = null;
  7135. var currentVideoHeight = null;
  7136. // By default we use camera
  7137. var getVideoSize = getCameraVideoSize;
  7138. var getVideoPosition = getCameraVideoPosition;
  7139. /**
  7140. * The small video instance that is displayed in the large video
  7141. * @type {SmallVideo}
  7142. */
  7143. var currentSmallVideo = null;
  7144. /**
  7145. * Indicates whether the large video is enabled.
  7146. * @type {boolean}
  7147. */
  7148. var isEnabled = true;
  7149. /**
  7150. * Current large video state.
  7151. * Possible values - video, prezi or etherpad.
  7152. * @type {string}
  7153. */
  7154. var state = "video";
  7155. /**
  7156. * Returns the html element associated with the passed state of large video
  7157. * @param state the state.
  7158. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7159. */
  7160. function getContainerByState(state)
  7161. {
  7162. var selector = null;
  7163. switch (state)
  7164. {
  7165. case "video":
  7166. selector = "#largeVideoWrapper";
  7167. break;
  7168. case "etherpad":
  7169. selector = "#etherpad>iframe";
  7170. break;
  7171. case "prezi":
  7172. selector = "#presentation>iframe";
  7173. break;
  7174. }
  7175. return (selector !== null)? $(selector) : null;
  7176. }
  7177. /**
  7178. * Sets the size and position of the given video element.
  7179. *
  7180. * @param video the video element to position
  7181. * @param width the desired video width
  7182. * @param height the desired video height
  7183. * @param horizontalIndent the left and right indent
  7184. * @param verticalIndent the top and bottom indent
  7185. */
  7186. function positionVideo(video,
  7187. width,
  7188. height,
  7189. horizontalIndent,
  7190. verticalIndent,
  7191. animate) {
  7192. if (animate) {
  7193. video.animate({
  7194. width: width,
  7195. height: height,
  7196. top: verticalIndent,
  7197. bottom: verticalIndent,
  7198. left: horizontalIndent,
  7199. right: horizontalIndent
  7200. },
  7201. {
  7202. queue: false,
  7203. duration: 500
  7204. });
  7205. } else {
  7206. video.width(width);
  7207. video.height(height);
  7208. video.css({ top: verticalIndent + 'px',
  7209. bottom: verticalIndent + 'px',
  7210. left: horizontalIndent + 'px',
  7211. right: horizontalIndent + 'px'});
  7212. }
  7213. }
  7214. /**
  7215. * Returns an array of the video dimensions, so that it keeps it's aspect
  7216. * ratio and fits available area with it's larger dimension. This method
  7217. * ensures that whole video will be visible and can leave empty areas.
  7218. *
  7219. * @return an array with 2 elements, the video width and the video height
  7220. */
  7221. function getDesktopVideoSize(videoWidth,
  7222. videoHeight,
  7223. videoSpaceWidth,
  7224. videoSpaceHeight) {
  7225. if (!videoWidth)
  7226. videoWidth = currentVideoWidth;
  7227. if (!videoHeight)
  7228. videoHeight = currentVideoHeight;
  7229. var aspectRatio = videoWidth / videoHeight;
  7230. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7231. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7232. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7233. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7234. {
  7235. availableHeight = videoSpaceHeight;
  7236. availableWidth = availableHeight * aspectRatio;
  7237. }
  7238. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7239. {
  7240. availableWidth = videoSpaceWidth;
  7241. availableHeight = availableWidth / aspectRatio;
  7242. }
  7243. return [availableWidth, availableHeight];
  7244. }
  7245. /**
  7246. * Returns an array of the video horizontal and vertical indents,
  7247. * so that if fits its parent.
  7248. *
  7249. * @return an array with 2 elements, the horizontal indent and the vertical
  7250. * indent
  7251. */
  7252. function getCameraVideoPosition(videoWidth,
  7253. videoHeight,
  7254. videoSpaceWidth,
  7255. videoSpaceHeight) {
  7256. // Parent height isn't completely calculated when we position the video in
  7257. // full screen mode and this is why we use the screen height in this case.
  7258. // Need to think it further at some point and implement it properly.
  7259. var isFullScreen = document.fullScreen ||
  7260. document.mozFullScreen ||
  7261. document.webkitIsFullScreen;
  7262. if (isFullScreen)
  7263. videoSpaceHeight = window.innerHeight;
  7264. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7265. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7266. return [horizontalIndent, verticalIndent];
  7267. }
  7268. /**
  7269. * Returns an array of the video horizontal and vertical indents.
  7270. * Centers horizontally and top aligns vertically.
  7271. *
  7272. * @return an array with 2 elements, the horizontal indent and the vertical
  7273. * indent
  7274. */
  7275. function getDesktopVideoPosition(videoWidth,
  7276. videoHeight,
  7277. videoSpaceWidth,
  7278. videoSpaceHeight) {
  7279. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7280. var verticalIndent = 0;// Top aligned
  7281. return [horizontalIndent, verticalIndent];
  7282. }
  7283. /**
  7284. * Returns an array of the video dimensions, so that it covers the screen.
  7285. * It leaves no empty areas, but some parts of the video might not be visible.
  7286. *
  7287. * @return an array with 2 elements, the video width and the video height
  7288. */
  7289. function getCameraVideoSize(videoWidth,
  7290. videoHeight,
  7291. videoSpaceWidth,
  7292. videoSpaceHeight) {
  7293. if (!videoWidth)
  7294. videoWidth = currentVideoWidth;
  7295. if (!videoHeight)
  7296. videoHeight = currentVideoHeight;
  7297. var aspectRatio = videoWidth / videoHeight;
  7298. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7299. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7300. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7301. availableHeight = videoSpaceHeight;
  7302. availableWidth = availableHeight * aspectRatio;
  7303. }
  7304. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7305. availableWidth = videoSpaceWidth;
  7306. availableHeight = availableWidth / aspectRatio;
  7307. }
  7308. return [availableWidth, availableHeight];
  7309. }
  7310. /**
  7311. * Updates the src of the active speaker avatar
  7312. * @param jid of the current active speaker
  7313. */
  7314. function updateActiveSpeakerAvatarSrc() {
  7315. var avatar = $("#activeSpeakerAvatar")[0];
  7316. var jid = currentSmallVideo.peerJid;
  7317. var url = Avatar.getActiveSpeakerUrl(jid);
  7318. if (avatar.src === url)
  7319. return;
  7320. if (jid) {
  7321. avatar.src = url;
  7322. currentSmallVideo.showAvatar();
  7323. }
  7324. }
  7325. /**
  7326. * Change the video source of the large video.
  7327. * @param isVisible
  7328. */
  7329. function changeVideo(isVisible) {
  7330. if (!currentSmallVideo) {
  7331. console.error("Unable to change large video - no 'currentSmallVideo'");
  7332. return;
  7333. }
  7334. updateActiveSpeakerAvatarSrc();
  7335. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7336. var videoTransform = document.getElementById('largeVideo')
  7337. .style.webkitTransform;
  7338. var flipX = currentSmallVideo.flipX;
  7339. if (flipX && videoTransform !== 'scaleX(-1)') {
  7340. document.getElementById('largeVideo').style.webkitTransform =
  7341. "scaleX(-1)";
  7342. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7343. document.getElementById('largeVideo').style.webkitTransform =
  7344. "none";
  7345. }
  7346. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7347. // Change the way we'll be measuring and positioning large video
  7348. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7349. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7350. getCameraVideoPosition;
  7351. // Only if the large video is currently visible.
  7352. if (isVisible) {
  7353. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7354. $('#largeVideoWrapper').fadeTo(300, 1);
  7355. }
  7356. }
  7357. /**
  7358. * Creates the html elements for the large video.
  7359. */
  7360. function createLargeVideoHTML()
  7361. {
  7362. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7363. html += '<div id="presentation"></div>' +
  7364. '<div id="etherpad"></div>' +
  7365. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7366. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7367. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7368. '<span data-i18n="poweredby"></span> jitsi.org' +
  7369. '</a>'+
  7370. '<div id="activeSpeaker">' +
  7371. '<img id="activeSpeakerAvatar" src=""/>' +
  7372. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7373. '</div>' +
  7374. '<div id="largeVideoWrapper">' +
  7375. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7376. '</div id="largeVideoWrapper">' +
  7377. '<span id="videoConnectionMessage"></span>';
  7378. html += '</div>';
  7379. $(html).prependTo("#videospace");
  7380. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7381. var leftWatermarkDiv
  7382. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7383. leftWatermarkDiv.css({display: 'block'});
  7384. leftWatermarkDiv.parent().get(0).href
  7385. = interfaceConfig.JITSI_WATERMARK_LINK;
  7386. }
  7387. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7388. var rightWatermarkDiv
  7389. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7390. rightWatermarkDiv.css({display: 'block'});
  7391. rightWatermarkDiv.parent().get(0).href
  7392. = interfaceConfig.BRAND_WATERMARK_LINK;
  7393. rightWatermarkDiv.get(0).style.backgroundImage
  7394. = "url(images/rightwatermark.png)";
  7395. }
  7396. if (interfaceConfig.SHOW_POWERED_BY) {
  7397. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7398. }
  7399. if (!RTCBrowserType.isIExplorer()) {
  7400. $('#largeVideo').volume = 0;
  7401. }
  7402. }
  7403. var LargeVideo = {
  7404. init: function (VideoLayout, emitter) {
  7405. if(!isEnabled)
  7406. return;
  7407. createLargeVideoHTML();
  7408. this.VideoLayout = VideoLayout;
  7409. this.eventEmitter = emitter;
  7410. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7411. var self = this;
  7412. // Listen for large video size updates
  7413. var largeVideo = $('#largeVideo')[0];
  7414. var onplaying = function (arg1, arg2, arg3) {
  7415. // re-select
  7416. if (RTCBrowserType.isTemasysPluginUsed())
  7417. largeVideo = $('#largeVideo')[0];
  7418. currentVideoWidth = largeVideo.videoWidth;
  7419. currentVideoHeight = largeVideo.videoHeight;
  7420. self.position(currentVideoWidth, currentVideoHeight);
  7421. };
  7422. largeVideo.onplaying = onplaying;
  7423. },
  7424. /**
  7425. * Indicates if the large video is currently visible.
  7426. *
  7427. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7428. */
  7429. isLargeVideoVisible: function() {
  7430. return $('#largeVideoWrapper').is(':visible');
  7431. },
  7432. /**
  7433. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7434. */
  7435. isCurrentlyOnLarge: function (resourceJid) {
  7436. return currentSmallVideo && resourceJid &&
  7437. currentSmallVideo.getResourceJid() === resourceJid;
  7438. },
  7439. /**
  7440. * Updates the large video with the given new video source.
  7441. */
  7442. updateLargeVideo: function (resourceJid, forceUpdate) {
  7443. if(!isEnabled)
  7444. return;
  7445. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7446. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7447. if (!newSmallVideo) {
  7448. console.error("Small video not found for: " + resourceJid);
  7449. return;
  7450. }
  7451. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7452. $('#activeSpeaker').css('visibility', 'hidden');
  7453. var oldSmallVideo = null;
  7454. if (currentSmallVideo) {
  7455. oldSmallVideo = currentSmallVideo;
  7456. }
  7457. currentSmallVideo = newSmallVideo;
  7458. var oldJid = null;
  7459. if (oldSmallVideo)
  7460. oldJid = oldSmallVideo.peerJid;
  7461. if (oldJid !== resourceJid) {
  7462. // we want the notification to trigger even if userJid is undefined,
  7463. // or null.
  7464. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7465. }
  7466. // We are doing fadeOut/fadeIn animations on parent div which wraps
  7467. // largeVideo, because when Temasys plugin is in use it replaces
  7468. // <video> elements with plugin <object> tag. In Safari jQuery is
  7469. // unable to store values on this plugin object which breaks all
  7470. // animation effects performed on it directly.
  7471. //
  7472. // If for any reason large video was hidden before calling fadeOut
  7473. // changeVideo will never be called, so we call show() in chain just
  7474. // to be sure
  7475. $('#largeVideoWrapper').show().fadeTo(300, 0,
  7476. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7477. } else {
  7478. if (currentSmallVideo) {
  7479. currentSmallVideo.showAvatar();
  7480. }
  7481. }
  7482. },
  7483. /**
  7484. * Shows/hides the large video.
  7485. */
  7486. setLargeVideoVisible: function(isVisible) {
  7487. if(!isEnabled)
  7488. return;
  7489. if (isVisible) {
  7490. $('#largeVideoWrapper').css({visibility: 'visible'});
  7491. $('.watermark').css({visibility: 'visible'});
  7492. if(currentSmallVideo)
  7493. currentSmallVideo.enableDominantSpeaker(true);
  7494. }
  7495. else {
  7496. $('#largeVideoWrapper').css({visibility: 'hidden'});
  7497. $('#activeSpeaker').css('visibility', 'hidden');
  7498. $('.watermark').css({visibility: 'hidden'});
  7499. if(currentSmallVideo)
  7500. currentSmallVideo.enableDominantSpeaker(false);
  7501. }
  7502. },
  7503. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7504. if (!isEnabled)
  7505. return;
  7506. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7507. {
  7508. var isDesktop = newVideoType === 'screen';
  7509. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7510. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7511. : getCameraVideoPosition;
  7512. this.position(null, null, null, null, true);
  7513. }
  7514. },
  7515. /**
  7516. * Positions the large video.
  7517. *
  7518. * @param videoWidth the stream video width
  7519. * @param videoHeight the stream video height
  7520. */
  7521. position: function (videoWidth, videoHeight,
  7522. videoSpaceWidth, videoSpaceHeight, animate) {
  7523. if(!isEnabled)
  7524. return;
  7525. if(!videoSpaceWidth)
  7526. videoSpaceWidth = $('#videospace').width();
  7527. if(!videoSpaceHeight)
  7528. videoSpaceHeight = window.innerHeight;
  7529. var videoSize = getVideoSize(videoWidth,
  7530. videoHeight,
  7531. videoSpaceWidth,
  7532. videoSpaceHeight);
  7533. var largeVideoWidth = videoSize[0];
  7534. var largeVideoHeight = videoSize[1];
  7535. var videoPosition = getVideoPosition(largeVideoWidth,
  7536. largeVideoHeight,
  7537. videoSpaceWidth,
  7538. videoSpaceHeight);
  7539. var horizontalIndent = videoPosition[0];
  7540. var verticalIndent = videoPosition[1];
  7541. positionVideo($('#largeVideoWrapper'),
  7542. largeVideoWidth,
  7543. largeVideoHeight,
  7544. horizontalIndent, verticalIndent, animate);
  7545. },
  7546. /**
  7547. * Resizes the large html elements.
  7548. * @param animate boolean property that indicates whether the resize should be animated or not.
  7549. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7550. * If that parameter is null the method will check the chat pannel visibility.
  7551. * @param completeFunction a function to be called when the video space is resized
  7552. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7553. */
  7554. resize: function (animate, isVisible, completeFunction) {
  7555. if(!isEnabled)
  7556. return;
  7557. var availableHeight = window.innerHeight;
  7558. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7559. if (availableWidth < 0 || availableHeight < 0) return;
  7560. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7561. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7562. $('#activeSpeaker').css('top', top);
  7563. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7564. if(animate) {
  7565. $('#largeVideoContainer').animate({
  7566. width: availableWidth,
  7567. height: availableHeight
  7568. },
  7569. {
  7570. queue: false,
  7571. duration: 500
  7572. });
  7573. } else {
  7574. $('#largeVideoContainer').width(availableWidth);
  7575. $('#largeVideoContainer').height(availableHeight);
  7576. }
  7577. return [availableWidth, availableHeight];
  7578. },
  7579. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7580. if(!isEnabled)
  7581. return;
  7582. var size = this.resize(true, isVisible, completeFunction);
  7583. this.position(null, null, size[0], size[1], true);
  7584. },
  7585. getResourceJid: function () {
  7586. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7587. },
  7588. updateAvatar: function (resourceJid) {
  7589. if(!isEnabled)
  7590. return;
  7591. if (resourceJid === this.getResourceJid()) {
  7592. updateActiveSpeakerAvatarSrc();
  7593. }
  7594. },
  7595. showAvatar: function (resourceJid, show) {
  7596. if (!isEnabled)
  7597. return;
  7598. if (this.getResourceJid() === resourceJid && state === "video") {
  7599. $("#largeVideoWrapper")
  7600. .css("visibility", show ? "hidden" : "visible");
  7601. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7602. return true;
  7603. }
  7604. return false;
  7605. },
  7606. /**
  7607. * Disables the large video
  7608. */
  7609. disable: function () {
  7610. isEnabled = false;
  7611. },
  7612. /**
  7613. * Enables the large video
  7614. */
  7615. enable: function () {
  7616. isEnabled = true;
  7617. },
  7618. /**
  7619. * Returns true if the video is enabled.
  7620. */
  7621. isEnabled: function () {
  7622. return isEnabled;
  7623. },
  7624. /**
  7625. * Creates the iframe used by the etherpad
  7626. * @param src the value for src attribute
  7627. * @param onloadHandler handler executed when the iframe loads it content
  7628. * @returns {HTMLElement} the iframe
  7629. */
  7630. createEtherpadIframe: function (src, onloadHandler) {
  7631. if(!isEnabled)
  7632. return;
  7633. var etherpadIFrame = document.createElement('iframe');
  7634. etherpadIFrame.src = src;
  7635. etherpadIFrame.frameBorder = 0;
  7636. etherpadIFrame.scrolling = "no";
  7637. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7638. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7639. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7640. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7641. etherpadIFrame.onload = onloadHandler;
  7642. return etherpadIFrame;
  7643. },
  7644. /**
  7645. * Changes the state of the large video.
  7646. * Possible values - video, prezi, etherpad.
  7647. * @param newState - the new state
  7648. */
  7649. setState: function (newState) {
  7650. if(state === newState)
  7651. return;
  7652. var currentContainer = getContainerByState(state);
  7653. if(!currentContainer)
  7654. return;
  7655. var self = this;
  7656. var oldState = state;
  7657. switch (newState)
  7658. {
  7659. case "etherpad":
  7660. $('#activeSpeaker').css('visibility', 'hidden');
  7661. currentContainer.fadeOut(300, function () {
  7662. if (oldState === "prezi") {
  7663. currentContainer.css({opacity: '0'});
  7664. $('#reloadPresentation').css({display: 'none'});
  7665. }
  7666. else {
  7667. self.setLargeVideoVisible(false);
  7668. }
  7669. });
  7670. $('#etherpad>iframe').fadeIn(300, function () {
  7671. document.body.style.background = '#eeeeee';
  7672. $('#etherpad>iframe').css({visibility: 'visible'});
  7673. $('#etherpad').css({zIndex: 2});
  7674. });
  7675. break;
  7676. case "prezi":
  7677. var prezi = $('#presentation>iframe');
  7678. currentContainer.fadeOut(300, function() {
  7679. document.body.style.background = 'black';
  7680. });
  7681. prezi.fadeIn(300, function() {
  7682. prezi.css({opacity:'1'});
  7683. ToolbarToggler.dockToolbar(true);//fix that
  7684. self.setLargeVideoVisible(false);
  7685. $('#etherpad>iframe').css({visibility: 'hidden'});
  7686. $('#etherpad').css({zIndex: 0});
  7687. });
  7688. $('#activeSpeaker').css('visibility', 'hidden');
  7689. break;
  7690. case "video":
  7691. currentContainer.fadeOut(300, function () {
  7692. $('#presentation>iframe').css({opacity:'0'});
  7693. $('#reloadPresentation').css({display:'none'});
  7694. $('#etherpad>iframe').css({visibility: 'hidden'});
  7695. $('#etherpad').css({zIndex: 0});
  7696. document.body.style.background = 'black';
  7697. ToolbarToggler.dockToolbar(false);//fix that
  7698. });
  7699. $('#largeVideoWrapper').fadeIn(300, function () {
  7700. self.setLargeVideoVisible(true);
  7701. });
  7702. break;
  7703. }
  7704. state = newState;
  7705. },
  7706. /**
  7707. * Returns the current state of the large video.
  7708. * @returns {string} the current state - video, prezi or etherpad.
  7709. */
  7710. getState: function () {
  7711. return state;
  7712. },
  7713. /**
  7714. * Sets hover handlers for the large video container div.
  7715. *
  7716. * @param inHandler
  7717. * @param outHandler
  7718. */
  7719. setHover: function(inHandler, outHandler)
  7720. {
  7721. $('#largeVideoContainer').hover(inHandler, outHandler);
  7722. },
  7723. /**
  7724. * Enables/disables the filter indicating a video problem to the user.
  7725. *
  7726. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  7727. */
  7728. enableVideoProblemFilter: function (enable) {
  7729. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  7730. }
  7731. };
  7732. module.exports = LargeVideo;
  7733. },{"../../../service/UI/UIEvents":166,"../../RTC/RTCBrowserType":8,"../../xmpp/xmpp":71,"../avatar/Avatar":16,"../toolbars/ToolbarToggler":29,"../util/UIUtil":33}],36:[function(require,module,exports){
  7734. /* global $, interfaceConfig, APP */
  7735. var SmallVideo = require("./SmallVideo");
  7736. var ConnectionIndicator = require("./ConnectionIndicator");
  7737. var NicknameHandler = require("../util/NicknameHandler");
  7738. var UIUtil = require("../util/UIUtil");
  7739. var LargeVideo = require("./LargeVideo");
  7740. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7741. function LocalVideo(VideoLayout) {
  7742. this.videoSpanId = "localVideoContainer";
  7743. this.container = $("#localVideoContainer").get(0);
  7744. this.bindHoverHandler();
  7745. this.VideoLayout = VideoLayout;
  7746. this.flipX = true;
  7747. this.isLocal = true;
  7748. this.peerJid = null;
  7749. }
  7750. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7751. LocalVideo.prototype.constructor = LocalVideo;
  7752. /**
  7753. * Creates the edit display name button.
  7754. *
  7755. * @returns {object} the edit button
  7756. */
  7757. function createEditDisplayNameButton() {
  7758. var editButton = document.createElement('a');
  7759. editButton.className = 'displayname';
  7760. UIUtil.setTooltip(editButton,
  7761. "videothumbnail.editnickname",
  7762. "top");
  7763. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7764. return editButton;
  7765. }
  7766. /**
  7767. * Sets the display name for the given video span id.
  7768. */
  7769. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7770. if (!this.container) {
  7771. console.warn(
  7772. "Unable to set displayName - " + this.videoSpanId +
  7773. " does not exist");
  7774. return;
  7775. }
  7776. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  7777. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  7778. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7779. var meHTML;
  7780. // If we already have a display name for this video.
  7781. if (nameSpan.length > 0) {
  7782. if (nameSpan.text() !== displayName) {
  7783. if (displayName && displayName.length > 0) {
  7784. meHTML = APP.translation.generateTranslationHTML("me");
  7785. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  7786. } else {
  7787. $('#localDisplayName').html(defaultLocalDisplayName);
  7788. }
  7789. }
  7790. } else {
  7791. var editButton = createEditDisplayNameButton();
  7792. nameSpan = document.createElement('span');
  7793. nameSpan.className = 'displayname';
  7794. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  7795. if (displayName && displayName.length > 0) {
  7796. meHTML = APP.translation.generateTranslationHTML("me");
  7797. nameSpan.innerHTML = displayName + meHTML;
  7798. }
  7799. else {
  7800. nameSpan.innerHTML = defaultLocalDisplayName;
  7801. }
  7802. nameSpan.id = 'localDisplayName';
  7803. this.container.appendChild(editButton);
  7804. //translates popover of edit button
  7805. APP.translation.translateElement($("a.displayname"));
  7806. var editableText = document.createElement('input');
  7807. editableText.className = 'displayname';
  7808. editableText.type = 'text';
  7809. editableText.id = 'editDisplayName';
  7810. if (displayName && displayName.length) {
  7811. editableText.value = displayName;
  7812. }
  7813. var defaultNickname = APP.translation.translateString(
  7814. "defaultNickname", {name: "Jane Pink"});
  7815. editableText.setAttribute('style', 'display:none;');
  7816. editableText.setAttribute('data-18n',
  7817. '[placeholder]defaultNickname');
  7818. editableText.setAttribute("data-i18n-options",
  7819. JSON.stringify({name: "Jane Pink"}));
  7820. editableText.setAttribute("placeholder", defaultNickname);
  7821. this.container.appendChild(editableText);
  7822. var self = this;
  7823. $('#localVideoContainer .displayname')
  7824. .bind("click", function (e) {
  7825. var editDisplayName = $('#editDisplayName');
  7826. e.preventDefault();
  7827. e.stopPropagation();
  7828. $('#localDisplayName').hide();
  7829. editDisplayName.show();
  7830. editDisplayName.focus();
  7831. editDisplayName.select();
  7832. editDisplayName.one("focusout", function (e) {
  7833. self.VideoLayout.inputDisplayNameHandler(this.value);
  7834. });
  7835. editDisplayName.on('keydown', function (e) {
  7836. if (e.keyCode === 13) {
  7837. e.preventDefault();
  7838. self.VideoLayout.inputDisplayNameHandler(this.value);
  7839. }
  7840. });
  7841. });
  7842. }
  7843. };
  7844. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  7845. NicknameHandler.setNickname(name);
  7846. var localDisplayName = $('#localDisplayName');
  7847. if (!localDisplayName.is(":visible")) {
  7848. if (NicknameHandler.getNickname()) {
  7849. var meHTML = APP.translation.generateTranslationHTML("me");
  7850. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  7851. meHTML + ")");
  7852. } else {
  7853. var defaultHTML = APP.translation.generateTranslationHTML(
  7854. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7855. localDisplayName .html(defaultHTML);
  7856. }
  7857. localDisplayName.show();
  7858. }
  7859. $('#editDisplayName').hide();
  7860. };
  7861. LocalVideo.prototype.createConnectionIndicator = function() {
  7862. if(this.connectionIndicator)
  7863. return;
  7864. this.connectionIndicator = new ConnectionIndicator(this, null);
  7865. };
  7866. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  7867. var self = this;
  7868. function localVideoClick(event) {
  7869. // FIXME: with Temasys plugin event arg is not an event, but
  7870. // the clicked object itself, so we have to skip this call
  7871. if (event.stopPropagation) {
  7872. event.stopPropagation();
  7873. }
  7874. self.VideoLayout.handleVideoThumbClicked(
  7875. true,
  7876. APP.xmpp.myResource());
  7877. }
  7878. var localVideoContainerSelector = $('#localVideoContainer');
  7879. localVideoContainerSelector.off('click');
  7880. localVideoContainerSelector.on('click', localVideoClick);
  7881. if(isMuted) {
  7882. APP.UI.setVideoMute(true);
  7883. return;
  7884. }
  7885. this.flipX = stream.videoType != "screen";
  7886. var localVideo = document.createElement('video');
  7887. localVideo.id = 'localVideo_' +
  7888. APP.RTC.getStreamID(stream.getOriginalStream());
  7889. if (!RTCBrowserType.isIExplorer()) {
  7890. localVideo.autoplay = true;
  7891. localVideo.volume = 0; // is it required if audio is separated ?
  7892. }
  7893. localVideo.oncontextmenu = function () { return false; };
  7894. var localVideoContainer = document.getElementById('localVideoWrapper');
  7895. // Put the new video always in front
  7896. UIUtil.prependChild(localVideoContainer, localVideo);
  7897. var localVideoSelector = $('#' + localVideo.id);
  7898. // Add click handler to both video and video wrapper elements in case
  7899. // there's no video.
  7900. // onclick has to be used with Temasys plugin
  7901. localVideo.onclick = localVideoClick;
  7902. if (this.flipX) {
  7903. localVideoSelector.addClass("flipVideoX");
  7904. }
  7905. // Attach WebRTC stream
  7906. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  7907. // Add stream ended handler
  7908. stream.getOriginalStream().onended = function () {
  7909. // We have to re-select after attach when Temasys plugin is used,
  7910. // because <video> element is replaced with <object>
  7911. localVideo = $('#' + localVideo.id)[0];
  7912. localVideoContainer.removeChild(localVideo);
  7913. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  7914. };
  7915. };
  7916. LocalVideo.prototype.joined = function (jid) {
  7917. this.peerJid = jid;
  7918. };
  7919. LocalVideo.prototype.getResourceJid = function () {
  7920. var myResource = APP.xmpp.myResource();
  7921. if (!myResource) {
  7922. console.error("Requested local resource before we're in the MUC");
  7923. }
  7924. return myResource;
  7925. };
  7926. module.exports = LocalVideo;
  7927. },{"../../RTC/RTCBrowserType":8,"../util/NicknameHandler":32,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],37:[function(require,module,exports){
  7928. /* global $, APP, require, Strophe, interfaceConfig */
  7929. var ConnectionIndicator = require("./ConnectionIndicator");
  7930. var SmallVideo = require("./SmallVideo");
  7931. var AudioLevels = require("../audio_levels/AudioLevels");
  7932. var LargeVideo = require("./LargeVideo");
  7933. var Avatar = require("../avatar/Avatar");
  7934. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7935. var UIUtils = require("../util/UIUtil");
  7936. function RemoteVideo(peerJid, VideoLayout) {
  7937. this.peerJid = peerJid;
  7938. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  7939. this.videoSpanId = 'participant_' + this.resourceJid;
  7940. this.VideoLayout = VideoLayout;
  7941. this.addRemoteVideoContainer();
  7942. this.connectionIndicator = new ConnectionIndicator(
  7943. this, this.peerJid);
  7944. this.setDisplayName();
  7945. var nickfield = document.createElement('span');
  7946. nickfield.className = "nick";
  7947. nickfield.appendChild(document.createTextNode(this.resourceJid));
  7948. this.container.appendChild(nickfield);
  7949. this.bindHoverHandler();
  7950. this.flipX = false;
  7951. this.isLocal = false;
  7952. }
  7953. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  7954. RemoteVideo.prototype.constructor = RemoteVideo;
  7955. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  7956. this.container = RemoteVideo.createContainer(this.videoSpanId);
  7957. if (APP.xmpp.isModerator())
  7958. this.addRemoteVideoMenu();
  7959. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  7960. return this.container;
  7961. };
  7962. /**
  7963. * Adds the remote video menu element for the given <tt>jid</tt> in the
  7964. * given <tt>parentElement</tt>.
  7965. *
  7966. * @param jid the jid indicating the video for which we're adding a menu.
  7967. * @param parentElement the parent element where this menu will be added
  7968. */
  7969. if (!interfaceConfig.filmStripOnly) {
  7970. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  7971. var spanElement = document.createElement('span');
  7972. spanElement.className = 'remotevideomenu';
  7973. this.container.appendChild(spanElement);
  7974. var menuElement = document.createElement('i');
  7975. menuElement.className = 'fa fa-angle-down';
  7976. menuElement.title = 'Remote user controls';
  7977. spanElement.appendChild(menuElement);
  7978. var popupmenuElement = document.createElement('ul');
  7979. popupmenuElement.className = 'popupmenu';
  7980. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  7981. spanElement.appendChild(popupmenuElement);
  7982. var muteMenuItem = document.createElement('li');
  7983. var muteLinkItem = document.createElement('a');
  7984. var mutedIndicator = "<i style='float:left;' " +
  7985. "class='icon-mic-disabled'></i>";
  7986. if (!this.isMuted) {
  7987. muteLinkItem.innerHTML = mutedIndicator +
  7988. " <div style='width: 90px;margin-left: 20px;' " +
  7989. "data-i18n='videothumbnail.domute'></div>";
  7990. muteLinkItem.className = 'mutelink';
  7991. }
  7992. else {
  7993. muteLinkItem.innerHTML = mutedIndicator +
  7994. " <div style='width: 90px;margin-left: 20px;' " +
  7995. "data-i18n='videothumbnail.muted'></div>";
  7996. muteLinkItem.className = 'mutelink disabled';
  7997. }
  7998. var self = this;
  7999. muteLinkItem.onclick = function(){
  8000. if ($(this).attr('disabled') != undefined) {
  8001. event.preventDefault();
  8002. }
  8003. var isMute = self.isMuted == true;
  8004. APP.xmpp.setMute(self.peerJid, !isMute);
  8005. popupmenuElement.setAttribute('style', 'display:none;');
  8006. if (isMute) {
  8007. this.innerHTML = mutedIndicator +
  8008. " <div style='width: 90px;margin-left: 20px;' " +
  8009. "data-i18n='videothumbnail.muted'></div>";
  8010. this.className = 'mutelink disabled';
  8011. }
  8012. else {
  8013. this.innerHTML = mutedIndicator +
  8014. " <div style='width: 90px;margin-left: 20px;' " +
  8015. "data-i18n='videothumbnail.domute'></div>";
  8016. this.className = 'mutelink';
  8017. }
  8018. };
  8019. muteMenuItem.appendChild(muteLinkItem);
  8020. popupmenuElement.appendChild(muteMenuItem);
  8021. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8022. var ejectMenuItem = document.createElement('li');
  8023. var ejectLinkItem = document.createElement('a');
  8024. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8025. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8026. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8027. ejectLinkItem.onclick = function(){
  8028. APP.xmpp.eject(self.peerJid);
  8029. popupmenuElement.setAttribute('style', 'display:none;');
  8030. };
  8031. ejectMenuItem.appendChild(ejectLinkItem);
  8032. popupmenuElement.appendChild(ejectMenuItem);
  8033. var paddingSpan = document.createElement('span');
  8034. paddingSpan.className = 'popupmenuPadding';
  8035. popupmenuElement.appendChild(paddingSpan);
  8036. APP.translation.translateElement(
  8037. $("#" + popupmenuElement.id + " > li > a > div"));
  8038. };
  8039. } else {
  8040. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8041. }
  8042. /**
  8043. * Removes the remote stream element corresponding to the given stream and
  8044. * parent container.
  8045. *
  8046. * @param stream the stream
  8047. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8048. */
  8049. RemoteVideo.prototype.removeRemoteStreamElement =
  8050. function (stream, isVideo, id) {
  8051. if (!this.container)
  8052. return false;
  8053. var select = null;
  8054. if (isVideo) {
  8055. select = $('#' + id);
  8056. }
  8057. else
  8058. select = $('#' + this.videoSpanId + '>audio');
  8059. select.remove();
  8060. console.info((isVideo ? "Video" : "Audio") +
  8061. " removed " + this.getResourceJid(), select);
  8062. if (isVideo)
  8063. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8064. };
  8065. /**
  8066. * Removes RemoteVideo from the page.
  8067. */
  8068. RemoteVideo.prototype.remove = function () {
  8069. console.log("Remove thumbnail", this.peerJid);
  8070. this.removeConnectionIndicator();
  8071. // Remove whole container
  8072. if (this.container.parentNode)
  8073. this.container.parentNode.removeChild(this.container);
  8074. };
  8075. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8076. var isVideo = stream.getVideoTracks().length > 0;
  8077. if (!isVideo || stream.id === 'mixedmslabel') {
  8078. return;
  8079. }
  8080. var self = this;
  8081. var resourceJid = this.getResourceJid();
  8082. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8083. // when video playback starts
  8084. var onPlayingHandler = function () {
  8085. // FIXME: why do i have to do this for FF?
  8086. if (RTCBrowserType.isFirefox()) {
  8087. APP.RTC.attachMediaStream(sel, stream);
  8088. }
  8089. if (RTCBrowserType.isTemasysPluginUsed()) {
  8090. sel = self.selectVideoElement();
  8091. }
  8092. self.VideoLayout.videoactive(sel, resourceJid);
  8093. sel[0].onplaying = null;
  8094. if (RTCBrowserType.isTemasysPluginUsed()) {
  8095. // 'currentTime' is used to check if the video has started
  8096. // and the value is not set by the plugin, so we do it
  8097. sel[0].currentTime = 1;
  8098. }
  8099. };
  8100. sel[0].onplaying = onPlayingHandler;
  8101. };
  8102. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8103. if (!this.container)
  8104. return;
  8105. var self = this;
  8106. var isVideo = stream.getVideoTracks().length > 0;
  8107. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8108. var newElementId = streamElement.id;
  8109. // Put new stream element always in front
  8110. UIUtils.prependChild(this.container, streamElement);
  8111. var sel = $('#' + newElementId);
  8112. sel.hide();
  8113. // If the container is currently visible we attach the stream.
  8114. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8115. this.waitForPlayback(sel, stream);
  8116. APP.RTC.attachMediaStream(sel, stream);
  8117. }
  8118. stream.onended = function () {
  8119. console.log('stream ended', this);
  8120. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8121. };
  8122. // Add click handler.
  8123. var onClickHandler = function (event) {
  8124. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8125. // On IE we need to populate this handler on video <object>
  8126. // and it does not give event instance as an argument,
  8127. // so we check here for methods.
  8128. if (event.stopPropagation && event.preventDefault) {
  8129. event.stopPropagation();
  8130. event.preventDefault();
  8131. }
  8132. return false;
  8133. };
  8134. this.container.onclick = onClickHandler;
  8135. // reselect
  8136. if (RTCBrowserType.isTemasysPluginUsed())
  8137. sel = $('#' + newElementId);
  8138. sel[0].onclick = onClickHandler;
  8139. },
  8140. /**
  8141. * Show/hide peer container for the given resourceJid.
  8142. */
  8143. RemoteVideo.prototype.showPeerContainer = function (state) {
  8144. if (!this.container)
  8145. return;
  8146. var isHide = state === 'hide';
  8147. var resizeThumbnails = false;
  8148. if (!isHide) {
  8149. if (!$(this.container).is(':visible')) {
  8150. resizeThumbnails = true;
  8151. $(this.container).show();
  8152. }
  8153. this.showAvatar(state !== 'show');
  8154. }
  8155. else if ($(this.container).is(':visible') && isHide)
  8156. {
  8157. resizeThumbnails = true;
  8158. $(this.container).hide();
  8159. if(this.connectionIndicator)
  8160. this.connectionIndicator.hide();
  8161. }
  8162. if (resizeThumbnails) {
  8163. this.VideoLayout.resizeThumbnails();
  8164. }
  8165. // We want to be able to pin a participant from the contact list, even
  8166. // if he's not in the lastN set!
  8167. // ContactList.setClickable(resourceJid, !isHide);
  8168. };
  8169. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8170. if (this.connectionIndicator)
  8171. this.connectionIndicator.remove();
  8172. };
  8173. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8174. if (this.connectionIndicator)
  8175. this.connectionIndicator.hide();
  8176. };
  8177. /**
  8178. * Updates the remote video menu.
  8179. *
  8180. * @param jid the jid indicating the video for which we're adding a menu.
  8181. * @param isMuted indicates the current mute state
  8182. */
  8183. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8184. var muteMenuItem
  8185. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8186. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8187. if (muteMenuItem.length) {
  8188. var muteLink = muteMenuItem.get(0);
  8189. if (isMuted === 'true') {
  8190. muteLink.innerHTML = mutedIndicator + ' Muted';
  8191. muteLink.className = 'mutelink disabled';
  8192. }
  8193. else {
  8194. muteLink.innerHTML = mutedIndicator + ' Mute';
  8195. muteLink.className = 'mutelink';
  8196. }
  8197. }
  8198. };
  8199. /**
  8200. * Sets the display name for the given video span id.
  8201. */
  8202. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8203. if (!this.container) {
  8204. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8205. " does not exist");
  8206. return;
  8207. }
  8208. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8209. // If we already have a display name for this video.
  8210. if (nameSpan.length > 0) {
  8211. if (displayName && displayName.length > 0) {
  8212. $('#' + this.videoSpanId + '_name').html(displayName);
  8213. }
  8214. else if (key && key.length > 0) {
  8215. var nameHtml = APP.translation.generateTranslationHTML(key);
  8216. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8217. }
  8218. else
  8219. $('#' + this.videoSpanId + '_name').text(
  8220. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8221. } else {
  8222. nameSpan = document.createElement('span');
  8223. nameSpan.className = 'displayname';
  8224. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8225. if (displayName && displayName.length > 0) {
  8226. nameSpan.innerText = displayName;
  8227. }
  8228. else
  8229. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8230. nameSpan.id = this.videoSpanId + '_name';
  8231. }
  8232. };
  8233. /**
  8234. * Removes remote video menu element from video element identified by
  8235. * given <tt>videoElementId</tt>.
  8236. *
  8237. * @param videoElementId the id of local or remote video element.
  8238. */
  8239. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8240. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8241. if (menuSpan.length) {
  8242. menuSpan.remove();
  8243. }
  8244. };
  8245. RemoteVideo.prototype.getResourceJid = function () {
  8246. if (!this.resourceJid) {
  8247. console.error("Undefined resource jid");
  8248. }
  8249. return this.resourceJid;
  8250. };
  8251. RemoteVideo.createContainer = function (spanId) {
  8252. var container = document.createElement('span');
  8253. container.id = spanId;
  8254. container.className = 'videocontainer';
  8255. var remotes = document.getElementById('remoteVideos');
  8256. return remotes.appendChild(container);
  8257. };
  8258. module.exports = RemoteVideo;
  8259. },{"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../avatar/Avatar":16,"../util/UIUtil":33,"./ConnectionIndicator":34,"./LargeVideo":35,"./SmallVideo":38}],38:[function(require,module,exports){
  8260. /* global $, APP, require */
  8261. var Avatar = require("../avatar/Avatar");
  8262. var UIUtil = require("../util/UIUtil");
  8263. var LargeVideo = require("./LargeVideo");
  8264. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8265. function SmallVideo() {
  8266. this.isMuted = false;
  8267. this.hasAvatar = false;
  8268. }
  8269. function setVisibility(selector, show) {
  8270. if (selector && selector.length > 0) {
  8271. selector.css("visibility", show ? "visible" : "hidden");
  8272. }
  8273. }
  8274. SmallVideo.prototype.showDisplayName = function(isShow) {
  8275. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8276. if (isShow) {
  8277. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8278. nameSpan.setAttribute("style", "display:inline-block;");
  8279. }
  8280. else {
  8281. if (nameSpan)
  8282. nameSpan.setAttribute("style", "display:none;");
  8283. }
  8284. };
  8285. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8286. if(!this.container)
  8287. return;
  8288. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8289. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8290. noMic.remove();
  8291. noVideo.remove();
  8292. if (!devices.audio) {
  8293. this.container.appendChild(
  8294. document.createElement("div")).setAttribute("class", "noMic");
  8295. }
  8296. if (!devices.video) {
  8297. this.container.appendChild(
  8298. document.createElement("div")).setAttribute("class", "noVideo");
  8299. }
  8300. if (!devices.audio && !devices.video) {
  8301. noMic.css("background-position", "75%");
  8302. noVideo.css("background-position", "25%");
  8303. noVideo.css("background-color", "transparent");
  8304. }
  8305. };
  8306. /**
  8307. * Sets the type of the video displayed by this instance.
  8308. * @param videoType 'camera' or 'screen'
  8309. */
  8310. SmallVideo.prototype.setVideoType = function (videoType) {
  8311. this.videoType = videoType;
  8312. };
  8313. /**
  8314. * Returns the type of the video displayed by this instance.
  8315. * @returns {String} 'camera', 'screen' or undefined.
  8316. */
  8317. SmallVideo.prototype.getVideoType = function () {
  8318. return this.videoType;
  8319. };
  8320. /**
  8321. * Shows the presence status message for the given video.
  8322. */
  8323. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8324. if (!this.container) {
  8325. // No container
  8326. return;
  8327. }
  8328. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8329. if (!statusSpan.length) {
  8330. //Add status span
  8331. statusSpan = document.createElement('span');
  8332. statusSpan.className = 'status';
  8333. statusSpan.id = this.videoSpanId + '_status';
  8334. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8335. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8336. }
  8337. // Display status
  8338. if (statusMsg && statusMsg.length) {
  8339. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8340. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8341. }
  8342. else {
  8343. // Hide
  8344. statusSpan.get(0).setAttribute("style", "display:none;");
  8345. }
  8346. };
  8347. /**
  8348. * Creates an audio or video stream element.
  8349. */
  8350. SmallVideo.createStreamElement = function (sid, stream) {
  8351. var isVideo = stream.getVideoTracks().length > 0;
  8352. var element = isVideo ? document.createElement('video')
  8353. : document.createElement('audio');
  8354. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8355. APP.RTC.getStreamID(stream);
  8356. element.id = id;
  8357. if (!RTCBrowserType.isIExplorer()) {
  8358. element.autoplay = true;
  8359. }
  8360. element.oncontextmenu = function () { return false; };
  8361. return element;
  8362. };
  8363. /**
  8364. * Configures hoverIn/hoverOut handlers.
  8365. */
  8366. SmallVideo.prototype.bindHoverHandler = function () {
  8367. // Add hover handler
  8368. var self = this;
  8369. $(this.container).hover(
  8370. function () {
  8371. self.showDisplayName(true);
  8372. },
  8373. function () {
  8374. // If the video has been "pinned" by the user we want to
  8375. // keep the display name on place.
  8376. if (!LargeVideo.isLargeVideoVisible() ||
  8377. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8378. self.showDisplayName(false);
  8379. }
  8380. );
  8381. };
  8382. /**
  8383. * Updates the data for the indicator
  8384. * @param id the id of the indicator
  8385. * @param percent the percent for connection quality
  8386. * @param object the data
  8387. */
  8388. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8389. if(this.connectionIndicator)
  8390. this.connectionIndicator.updateConnectionQuality(percent, object);
  8391. };
  8392. SmallVideo.prototype.hideIndicator = function () {
  8393. if(this.connectionIndicator)
  8394. this.connectionIndicator.hideIndicator();
  8395. };
  8396. /**
  8397. * Shows audio muted indicator over small videos.
  8398. * @param {string} isMuted
  8399. */
  8400. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8401. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8402. if (!isMuted) {
  8403. if (audioMutedSpan.length > 0) {
  8404. audioMutedSpan.popover('hide');
  8405. audioMutedSpan.remove();
  8406. }
  8407. }
  8408. else {
  8409. if(audioMutedSpan.length == 0 ) {
  8410. audioMutedSpan = document.createElement('span');
  8411. audioMutedSpan.className = 'audioMuted';
  8412. UIUtil.setTooltip(audioMutedSpan,
  8413. "videothumbnail.mute",
  8414. "top");
  8415. this.container.appendChild(audioMutedSpan);
  8416. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8417. var mutedIndicator = document.createElement('i');
  8418. mutedIndicator.className = 'icon-mic-disabled';
  8419. audioMutedSpan.appendChild(mutedIndicator);
  8420. }
  8421. this.updateIconPositions();
  8422. }
  8423. this.isMuted = isMuted;
  8424. };
  8425. /**
  8426. * Shows video muted indicator over small videos.
  8427. */
  8428. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8429. this.showAvatar(isMuted);
  8430. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8431. if (isMuted === false) {
  8432. if (videoMutedSpan.length > 0) {
  8433. videoMutedSpan.remove();
  8434. }
  8435. }
  8436. else {
  8437. if(videoMutedSpan.length == 0) {
  8438. videoMutedSpan = document.createElement('span');
  8439. videoMutedSpan.className = 'videoMuted';
  8440. this.container.appendChild(videoMutedSpan);
  8441. var mutedIndicator = document.createElement('i');
  8442. mutedIndicator.className = 'icon-camera-disabled';
  8443. UIUtil.setTooltip(mutedIndicator,
  8444. "videothumbnail.videomute",
  8445. "top");
  8446. videoMutedSpan.appendChild(mutedIndicator);
  8447. //translate texts for muted indicator
  8448. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8449. }
  8450. this.updateIconPositions();
  8451. }
  8452. };
  8453. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8454. var resourceJid = this.getResourceJid();
  8455. var displayName = resourceJid;
  8456. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8457. if (nameSpan.length > 0)
  8458. displayName = nameSpan.html();
  8459. console.log("UI enable dominant speaker",
  8460. displayName,
  8461. resourceJid,
  8462. isEnable);
  8463. if (!this.container) {
  8464. return;
  8465. }
  8466. if (isEnable) {
  8467. this.showDisplayName(LargeVideo.getState() === "video");
  8468. if (!this.container.classList.contains("dominantspeaker"))
  8469. this.container.classList.add("dominantspeaker");
  8470. }
  8471. else {
  8472. this.showDisplayName(false);
  8473. if (this.container.classList.contains("dominantspeaker"))
  8474. this.container.classList.remove("dominantspeaker");
  8475. }
  8476. this.showAvatar();
  8477. };
  8478. SmallVideo.prototype.updateIconPositions = function () {
  8479. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8480. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8481. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8482. if(connectionIndicator.length > 0 &&
  8483. connectionIndicator[0].style.display != "none") {
  8484. audioMutedSpan.css({right: "23px"});
  8485. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8486. } else {
  8487. audioMutedSpan.css({right: "0px"});
  8488. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8489. }
  8490. };
  8491. /**
  8492. * Creates the element indicating the moderator(owner) of the conference.
  8493. *
  8494. * @param parentElement the parent element where the owner indicator will
  8495. * be added
  8496. */
  8497. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8498. // Show moderator indicator
  8499. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8500. if (!indicatorSpan || indicatorSpan.length === 0) {
  8501. indicatorSpan = document.createElement('span');
  8502. indicatorSpan.className = 'focusindicator';
  8503. this.container.appendChild(indicatorSpan);
  8504. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8505. }
  8506. if (indicatorSpan.children().length !== 0)
  8507. return;
  8508. var moderatorIndicator = document.createElement('i');
  8509. moderatorIndicator.className = 'fa fa-star';
  8510. indicatorSpan[0].appendChild(moderatorIndicator);
  8511. UIUtil.setTooltip(indicatorSpan[0],
  8512. "videothumbnail.moderator",
  8513. "top");
  8514. //translates text in focus indicators
  8515. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8516. };
  8517. SmallVideo.prototype.selectVideoElement = function () {
  8518. var videoElem = APP.RTC.getVideoElementName();
  8519. if (!RTCBrowserType.isTemasysPluginUsed()) {
  8520. return $('#' + this.videoSpanId).find(videoElem);
  8521. } else {
  8522. return $('#' + this.videoSpanId +
  8523. (this.isLocal ? '>>' : '>') +
  8524. videoElem + '>param[value="video"]').parent();
  8525. }
  8526. };
  8527. SmallVideo.prototype.getSrc = function () {
  8528. var videoElement = this.selectVideoElement().get(0);
  8529. return APP.RTC.getVideoSrc(videoElement);
  8530. };
  8531. SmallVideo.prototype.focus = function(isFocused) {
  8532. if(!isFocused) {
  8533. this.container.classList.remove("videoContainerFocused");
  8534. } else {
  8535. this.container.classList.add("videoContainerFocused");
  8536. }
  8537. };
  8538. SmallVideo.prototype.hasVideo = function () {
  8539. return this.selectVideoElement().length !== 0;
  8540. };
  8541. /**
  8542. * Hides or shows the user's avatar
  8543. * @param show whether we should show the avatar or not
  8544. * video because there is no dominant speaker and no focused speaker
  8545. */
  8546. SmallVideo.prototype.showAvatar = function (show) {
  8547. if (!this.hasAvatar) {
  8548. if (this.peerJid) {
  8549. // Init avatar
  8550. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8551. } else {
  8552. console.error("Unable to init avatar - no peerjid", this);
  8553. return;
  8554. }
  8555. }
  8556. var resourceJid = this.getResourceJid();
  8557. var video = this.selectVideoElement();
  8558. var avatar = $('#avatar_' + resourceJid);
  8559. if (show === undefined || show === null) {
  8560. if (!this.isLocal &&
  8561. !this.VideoLayout.isInLastN(resourceJid)) {
  8562. show = true;
  8563. } else {
  8564. // We want to show the avatar when the video is muted or not exists
  8565. // that is when 'true' or 'null' is returned
  8566. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8567. }
  8568. }
  8569. if (LargeVideo.showAvatar(resourceJid, show)) {
  8570. setVisibility(avatar, false);
  8571. setVisibility(video, false);
  8572. } else {
  8573. if (video && video.length > 0) {
  8574. setVisibility(video, !show);
  8575. }
  8576. setVisibility(avatar, show);
  8577. }
  8578. };
  8579. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8580. var thumbnail = $('#' + this.videoSpanId);
  8581. var resourceJid = this.getResourceJid();
  8582. var avatar = $('#avatar_' + resourceJid);
  8583. this.hasAvatar = true;
  8584. // set the avatar in the thumbnail
  8585. if (avatar && avatar.length > 0) {
  8586. avatar[0].src = thumbUrl;
  8587. } else {
  8588. if (thumbnail && thumbnail.length > 0) {
  8589. avatar = document.createElement('img');
  8590. avatar.id = 'avatar_' + resourceJid;
  8591. avatar.className = 'userAvatar';
  8592. avatar.src = thumbUrl;
  8593. thumbnail.append(avatar);
  8594. }
  8595. }
  8596. };
  8597. module.exports = SmallVideo;
  8598. },{"../../RTC/RTCBrowserType":8,"../avatar/Avatar":16,"../util/UIUtil":33,"./LargeVideo":35}],39:[function(require,module,exports){
  8599. /* global config, APP, $, Strophe, require, interfaceConfig */
  8600. var AudioLevels = require("../audio_levels/AudioLevels");
  8601. var ContactList = require("../side_pannels/contactlist/ContactList");
  8602. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8603. var UIEvents = require("../../../service/UI/UIEvents");
  8604. var UIUtil = require("../util/UIUtil");
  8605. var RTC = require("../../RTC/RTC");
  8606. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8607. var RemoteVideo = require("./RemoteVideo");
  8608. var LargeVideo = require("./LargeVideo");
  8609. var LocalVideo = require("./LocalVideo");
  8610. var remoteVideos = {};
  8611. var remoteVideoTypes = {};
  8612. var localVideoThumbnail = null;
  8613. var currentDominantSpeaker = null;
  8614. var lastNCount = config.channelLastN;
  8615. var localLastNCount = config.channelLastN;
  8616. var localLastNSet = [];
  8617. var lastNEndpointsCache = [];
  8618. var lastNPickupJid = null;
  8619. var eventEmitter = null;
  8620. /**
  8621. * Currently focused video jid
  8622. * @type {String}
  8623. */
  8624. var focusedVideoResourceJid = null;
  8625. var VideoLayout = (function (my) {
  8626. my.init = function (emitter) {
  8627. eventEmitter = emitter;
  8628. localVideoThumbnail = new LocalVideo(VideoLayout);
  8629. if (interfaceConfig.filmStripOnly) {
  8630. LargeVideo.disable();
  8631. } else {
  8632. LargeVideo.init(VideoLayout, emitter);
  8633. }
  8634. VideoLayout.resizeLargeVideoContainer();
  8635. };
  8636. my.isInLastN = function(resource) {
  8637. return lastNCount < 0 || // lastN is disabled
  8638. // lastNEndpoints cache not built yet
  8639. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8640. (lastNEndpointsCache &&
  8641. lastNEndpointsCache.indexOf(resource) !== -1);
  8642. };
  8643. my.changeLocalStream = function (stream, isMuted) {
  8644. VideoLayout.changeLocalVideo(stream, isMuted);
  8645. };
  8646. my.changeLocalAudio = function(stream, isMuted) {
  8647. if (isMuted)
  8648. APP.UI.setAudioMuted(true, true);
  8649. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8650. var localAudio = document.getElementById('localAudio');
  8651. // Writing volume not allowed in IE
  8652. if (!RTCBrowserType.isIExplorer()) {
  8653. localAudio.autoplay = true;
  8654. localAudio.volume = 0;
  8655. }
  8656. // Now when Temasys plugin is converting also <audio> elements to
  8657. // plugin's <object>s, in current layout it will capture click events
  8658. // before it reaches the local video object. We hide it here in order
  8659. // to prevent that.
  8660. if (RTCBrowserType.isIExplorer()) {
  8661. // The issue is not present on Safari. Also if we hide it in Safari
  8662. // then the local audio track will have 'enabled' flag set to false
  8663. // which will result in audio mute issues
  8664. $('#localAudio').hide();
  8665. }
  8666. };
  8667. my.changeLocalVideo = function(stream, isMuted) {
  8668. // Set default display name.
  8669. localVideoThumbnail.setDisplayName();
  8670. localVideoThumbnail.createConnectionIndicator();
  8671. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8672. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8673. localVideoThumbnail.changeVideo(stream, isMuted);
  8674. /* force update if we're currently being displayed */
  8675. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8676. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8677. }
  8678. };
  8679. my.mucJoined = function () {
  8680. var myResourceJid = APP.xmpp.myResource();
  8681. localVideoThumbnail.joined(APP.xmpp.myJid());
  8682. if (!LargeVideo.getResourceJid())
  8683. LargeVideo.updateLargeVideo(myResourceJid, true);
  8684. };
  8685. /**
  8686. * Adds or removes icons for not available camera and microphone.
  8687. * @param resourceJid the jid of user
  8688. * @param devices available devices
  8689. */
  8690. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8691. if(!devices)
  8692. return;
  8693. if(!resourceJid) {
  8694. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8695. } else {
  8696. if(remoteVideos[resourceJid])
  8697. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8698. }
  8699. };
  8700. /**
  8701. * Checks if removed video is currently displayed and tries to display
  8702. * another one instead.
  8703. * @param removedVideoSrc src stream identifier of the video.
  8704. */
  8705. my.updateRemovedVideo = function(resourceJid) {
  8706. if (resourceJid === LargeVideo.getResourceJid()) {
  8707. var newResourceJid;
  8708. // We'll show user's avatar if he is the dominant speaker or if
  8709. // his video thumbnail is pinned
  8710. if (remoteVideos[resourceJid] &&
  8711. resourceJid === focusedVideoResourceJid ||
  8712. resourceJid === currentDominantSpeaker) {
  8713. newResourceJid = resourceJid;
  8714. } else {
  8715. // Otherwise select last visible video
  8716. newResourceJid = this.electLastVisibleVideo();
  8717. }
  8718. LargeVideo.updateLargeVideo(newResourceJid);
  8719. }
  8720. };
  8721. my.electLastVisibleVideo = function () {
  8722. // pick the last visible video in the row
  8723. // if nobody else is left, this picks the local video
  8724. var jid;
  8725. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last');
  8726. if (pick.length) {
  8727. jid = VideoLayout.getPeerContainerResourceJid(pick[0]);
  8728. } else {
  8729. console.info("Last visible video no longer exists");
  8730. pick = $('#remoteVideos>span[id!="mixedstream"]');
  8731. if (pick.length) {
  8732. jid = VideoLayout.getPeerContainerResourceJid(pick[0]);
  8733. }
  8734. if (!jid) {
  8735. // Go with local video
  8736. console.info("Fallback to local video...");
  8737. jid = APP.xmpp.myResource();
  8738. }
  8739. }
  8740. console.info("electLastVisibleVideo: " + jid);
  8741. return jid;
  8742. };
  8743. my.onRemoteStreamAdded = function (stream) {
  8744. if (stream.peerjid) {
  8745. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8746. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8747. remoteVideos[resourceJid].addRemoteStreamElement(
  8748. stream.sid,
  8749. stream.getOriginalStream(),
  8750. stream.ssrc);
  8751. }
  8752. };
  8753. my.getLargeVideoResource = function () {
  8754. return LargeVideo.getResourceJid();
  8755. };
  8756. /**
  8757. * Called when large video update is finished
  8758. * @param currentSmallVideo small video currently displayed on large video
  8759. */
  8760. my.largeVideoUpdated = function (currentSmallVideo) {
  8761. // Makes sure that dominant speaker UI
  8762. // is enabled only on current small video
  8763. localVideoThumbnail.enableDominantSpeaker(
  8764. localVideoThumbnail === currentSmallVideo);
  8765. Object.keys(remoteVideos).forEach(
  8766. function (resourceJid) {
  8767. var remoteVideo = remoteVideos[resourceJid];
  8768. if (remoteVideo) {
  8769. remoteVideo.enableDominantSpeaker(
  8770. remoteVideo === currentSmallVideo);
  8771. }
  8772. }
  8773. );
  8774. };
  8775. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8776. resourceJid) {
  8777. if(focusedVideoResourceJid) {
  8778. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8779. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  8780. oldSmallVideo.focus(false);
  8781. }
  8782. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8783. // Unlock current focused.
  8784. if (focusedVideoResourceJid === resourceJid)
  8785. {
  8786. focusedVideoResourceJid = null;
  8787. // Enable the currently set dominant speaker.
  8788. if (currentDominantSpeaker) {
  8789. if(smallVideo && smallVideo.hasVideo()) {
  8790. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8791. }
  8792. }
  8793. if (!noPinnedEndpointChangedEvent) {
  8794. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8795. }
  8796. return;
  8797. }
  8798. // Lock new video
  8799. focusedVideoResourceJid = resourceJid;
  8800. // Update focused/pinned interface.
  8801. if (resourceJid) {
  8802. if (smallVideo && !interfaceConfig.filmStripOnly)
  8803. smallVideo.focus(true);
  8804. if (!noPinnedEndpointChangedEvent) {
  8805. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8806. }
  8807. }
  8808. LargeVideo.setState("video");
  8809. LargeVideo.updateLargeVideo(resourceJid);
  8810. // Writing volume not allowed in IE
  8811. if (!RTCBrowserType.isIExplorer()) {
  8812. $('audio').each(function (idx, el) {
  8813. el.volume = 0;
  8814. el.volume = 1;
  8815. });
  8816. }
  8817. };
  8818. /**
  8819. * Checks if container for participant identified by given peerJid exists
  8820. * in the document and creates it eventually.
  8821. *
  8822. * @param peerJid peer Jid to check.
  8823. *
  8824. * @return Returns <tt>true</tt> if the peer container exists,
  8825. * <tt>false</tt> - otherwise
  8826. */
  8827. my.ensurePeerContainerExists = function(peerJid) {
  8828. ContactList.ensureAddContact(peerJid);
  8829. var resourceJid = Strophe.getResourceFromJid(peerJid);
  8830. if (!remoteVideos[resourceJid]) {
  8831. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  8832. remoteVideos[resourceJid] = remoteVideo;
  8833. var videoType = remoteVideoTypes[resourceJid];
  8834. if (videoType) {
  8835. remoteVideo.setVideoType(videoType);
  8836. }
  8837. // In case this is not currently in the last n we don't show it.
  8838. if (localLastNCount &&
  8839. localLastNCount > 0 &&
  8840. $('#remoteVideos>span').length >= localLastNCount + 2) {
  8841. remoteVideo.showPeerContainer('hide');
  8842. }
  8843. else
  8844. VideoLayout.resizeThumbnails();
  8845. }
  8846. };
  8847. my.inputDisplayNameHandler = function (name) {
  8848. localVideoThumbnail.inputDisplayNameHandler(name);
  8849. };
  8850. my.videoactive = function (videoelem, resourceJid) {
  8851. console.info(resourceJid + " video is now active");
  8852. videoelem.show();
  8853. VideoLayout.resizeThumbnails();
  8854. // Update the large video to the last added video only if there's no
  8855. // current dominant, focused speaker or prezi playing or update it to
  8856. // the current dominant speaker.
  8857. if ((!focusedVideoResourceJid &&
  8858. !currentDominantSpeaker &&
  8859. !require("../prezi/Prezi").isPresentationVisible()) ||
  8860. focusedVideoResourceJid === resourceJid ||
  8861. (resourceJid &&
  8862. currentDominantSpeaker === resourceJid)) {
  8863. LargeVideo.updateLargeVideo(resourceJid, true);
  8864. }
  8865. };
  8866. /**
  8867. * Shows the presence status message for the given video.
  8868. */
  8869. my.setPresenceStatus = function (resourceJid, statusMsg) {
  8870. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  8871. };
  8872. /**
  8873. * Shows a visual indicator for the moderator of the conference.
  8874. */
  8875. my.showModeratorIndicator = function () {
  8876. var isModerator = APP.xmpp.isModerator();
  8877. if (isModerator) {
  8878. localVideoThumbnail.createModeratorIndicatorElement();
  8879. }
  8880. var members = APP.xmpp.getMembers();
  8881. Object.keys(members).forEach(function (jid) {
  8882. if (Strophe.getResourceFromJid(jid) === 'focus') {
  8883. // Skip server side focus
  8884. return;
  8885. }
  8886. var resourceJid = Strophe.getResourceFromJid(jid);
  8887. var member = members[jid];
  8888. if (member.role === 'moderator') {
  8889. remoteVideos[resourceJid].removeRemoteVideoMenu();
  8890. remoteVideos[resourceJid].createModeratorIndicatorElement();
  8891. } else if (isModerator) {
  8892. // We are moderator, but user is not - add menu
  8893. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  8894. remoteVideos[resourceJid].addRemoteVideoMenu();
  8895. }
  8896. }
  8897. });
  8898. };
  8899. /*
  8900. * Shows or hides the audio muted indicator over the local thumbnail video.
  8901. * @param {boolean} isMuted
  8902. */
  8903. my.showLocalAudioIndicator = function(isMuted) {
  8904. localVideoThumbnail.showAudioIndicator(isMuted);
  8905. };
  8906. /**
  8907. * Resizes the large video container.
  8908. */
  8909. my.resizeLargeVideoContainer = function () {
  8910. if(LargeVideo.isEnabled()) {
  8911. LargeVideo.resize();
  8912. } else {
  8913. VideoLayout.resizeVideoSpace();
  8914. }
  8915. VideoLayout.resizeThumbnails();
  8916. LargeVideo.position();
  8917. };
  8918. /**
  8919. * Resizes thumbnails.
  8920. */
  8921. my.resizeThumbnails = function(animate) {
  8922. var videoSpaceWidth = $('#remoteVideos').width();
  8923. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  8924. var width = thumbnailSize[0];
  8925. var height = thumbnailSize[1];
  8926. $('.userAvatar').css('left', (width - height) / 2);
  8927. if(animate) {
  8928. $('#remoteVideos').animate({
  8929. height: height + 2 // adds 2 px because of small video 1px border
  8930. },
  8931. {
  8932. queue: false,
  8933. duration: 500
  8934. });
  8935. $('#remoteVideos>span').animate({
  8936. height: height,
  8937. width: width
  8938. },
  8939. {
  8940. queue: false,
  8941. duration: 500,
  8942. complete: function () {
  8943. $(document).trigger(
  8944. "remotevideo.resized",
  8945. [width,
  8946. height]);
  8947. }
  8948. });
  8949. } else {
  8950. // size videos so that while keeping AR and max height, we have a
  8951. // nice fit
  8952. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  8953. $('#remoteVideos>span').width(width);
  8954. $('#remoteVideos>span').height(height);
  8955. $(document).trigger("remotevideo.resized", [width, height]);
  8956. }
  8957. };
  8958. /**
  8959. * Calculates the thumbnail size.
  8960. *
  8961. * @param videoSpaceWidth the width of the video space
  8962. */
  8963. my.calculateThumbnailSize = function (videoSpaceWidth) {
  8964. // Calculate the available height, which is the inner window height minus
  8965. // 39px for the header minus 2px for the delimiter lines on the top and
  8966. // bottom of the large video, minus the 36px space inside the remoteVideos
  8967. // container used for highlighting shadow.
  8968. var availableHeight = 100;
  8969. var numvids = $('#remoteVideos>span:visible').length;
  8970. if (localLastNCount && localLastNCount > 0) {
  8971. numvids = Math.min(localLastNCount + 1, numvids);
  8972. }
  8973. // Remove the 3px borders arround videos and border around the remote
  8974. // videos area and the 4 pixels between the local video and the others
  8975. //TODO: Find out where the 4 pixels come from and remove them
  8976. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  8977. var availableWidth = availableWinWidth / numvids;
  8978. var aspectRatio = 16.0 / 9.0;
  8979. var maxHeight = Math.min(160, availableHeight);
  8980. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  8981. if (availableHeight < availableWidth / aspectRatio) {
  8982. availableWidth = Math.floor(availableHeight * aspectRatio);
  8983. }
  8984. return [availableWidth, availableHeight];
  8985. };
  8986. /**
  8987. * Returns the corresponding resource jid to the given peer container
  8988. * DOM element.
  8989. *
  8990. * @return the corresponding resource jid to the given peer container
  8991. * DOM element
  8992. */
  8993. my.getPeerContainerResourceJid = function (containerElement) {
  8994. if (localVideoThumbnail.container === containerElement) {
  8995. return localVideoThumbnail.getResourceJid();
  8996. }
  8997. var i = containerElement.id.indexOf('participant_');
  8998. if (i >= 0)
  8999. return containerElement.id.substring(i + 12);
  9000. };
  9001. /**
  9002. * On contact list item clicked.
  9003. */
  9004. $(ContactList).bind('contactclicked', function(event, jid) {
  9005. if (!jid) {
  9006. return;
  9007. }
  9008. if (jid === APP.xmpp.myJid()) {
  9009. $("#localVideoContainer").click();
  9010. return;
  9011. }
  9012. var resource = Strophe.getResourceFromJid(jid);
  9013. var remoteVideo = remoteVideos[resource];
  9014. if (remoteVideo && remoteVideo.selectVideoElement().length) {
  9015. var videoThumb = remoteVideo.selectVideoElement()[0];
  9016. // It is not always the case that a videoThumb exists (if there is
  9017. // no actual video).
  9018. if (RTC.getVideoSrc(videoThumb)) {
  9019. // We have a video src, great! Let's update the large video
  9020. // now.
  9021. VideoLayout.handleVideoThumbClicked(
  9022. false,
  9023. Strophe.getResourceFromJid(jid));
  9024. } else {
  9025. // If we don't have a video src for jid, there's absolutely
  9026. // no point in calling handleVideoThumbClicked; Quite
  9027. // simply, it won't work because it needs an src to attach
  9028. // to the large video.
  9029. //
  9030. // Instead, we trigger the pinned endpoint changed event to
  9031. // let the bridge adjust its lastN set for myjid and store
  9032. // the pinned user in the lastNPickupJid variable to be
  9033. // picked up later by the lastN changed event handler.
  9034. lastNPickupJid = jid;
  9035. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9036. Strophe.getResourceFromJid(jid));
  9037. }
  9038. }
  9039. });
  9040. /**
  9041. * On audio muted event.
  9042. */
  9043. my.onAudioMute = function (jid, isMuted) {
  9044. var resourceJid = Strophe.getResourceFromJid(jid);
  9045. if (resourceJid === APP.xmpp.myResource()) {
  9046. localVideoThumbnail.showAudioIndicator(isMuted);
  9047. } else {
  9048. VideoLayout.ensurePeerContainerExists(jid);
  9049. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9050. if (APP.xmpp.isModerator()) {
  9051. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9052. }
  9053. }
  9054. };
  9055. /**
  9056. * On video muted event.
  9057. */
  9058. my.onVideoMute = function (jid, value) {
  9059. if (jid !== APP.xmpp.myJid() &&
  9060. !APP.RTC.muteRemoteVideoStream(jid, value))
  9061. return;
  9062. if (jid === APP.xmpp.myJid()) {
  9063. localVideoThumbnail.showVideoIndicator(value);
  9064. } else {
  9065. var resource = Strophe.getResourceFromJid(jid);
  9066. VideoLayout.ensurePeerContainerExists(jid);
  9067. var remoteVideo = remoteVideos[resource];
  9068. remoteVideo.showVideoIndicator(value);
  9069. var el = remoteVideo.selectVideoElement();
  9070. if (!value)
  9071. el.show();
  9072. else
  9073. el.hide();
  9074. }
  9075. };
  9076. /**
  9077. * Display name changed.
  9078. */
  9079. my.onDisplayNameChanged =
  9080. function (jid, displayName, status) {
  9081. if (jid === 'localVideoContainer' ||
  9082. jid === APP.xmpp.myJid()) {
  9083. localVideoThumbnail.setDisplayName(displayName);
  9084. } else {
  9085. VideoLayout.ensurePeerContainerExists(jid);
  9086. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9087. displayName,
  9088. status);
  9089. }
  9090. };
  9091. /**
  9092. * On dominant speaker changed event.
  9093. */
  9094. my.onDominantSpeakerChanged = function (resourceJid) {
  9095. // We ignore local user events.
  9096. if (resourceJid === APP.xmpp.myResource())
  9097. return;
  9098. var remoteVideo = remoteVideos[resourceJid];
  9099. var members = APP.xmpp.getMembers();
  9100. // Update the current dominant speaker.
  9101. if (resourceJid !== currentDominantSpeaker) {
  9102. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9103. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9104. if (currentDominantSpeaker && (!members || !members[currentJID] ||
  9105. !members[currentJID].displayName) && remoteVideo) {
  9106. remoteVideo.setDisplayName(null);
  9107. }
  9108. if (resourceJid && (!members || !members[newJID] ||
  9109. !members[newJID].displayName) && remoteVideo) {
  9110. remoteVideo.setDisplayName(null,
  9111. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9112. }
  9113. currentDominantSpeaker = resourceJid;
  9114. } else {
  9115. return;
  9116. }
  9117. if (!remoteVideo)
  9118. return;
  9119. // Obtain container for new dominant speaker.
  9120. var videoSel = remoteVideo.selectVideoElement();
  9121. // Local video will not have container found, but that's ok
  9122. // since we don't want to switch to local video.
  9123. if (!focusedVideoResourceJid && videoSel.length) {
  9124. // Update the large video if the video source is already available,
  9125. // otherwise wait for the "videoactive.jingle" event.
  9126. if (videoSel[0].currentTime > 0) {
  9127. LargeVideo.updateLargeVideo(resourceJid);
  9128. }
  9129. }
  9130. };
  9131. /**
  9132. * On last N change event.
  9133. *
  9134. * @param lastNEndpoints the list of last N endpoints
  9135. * @param endpointsEnteringLastN the list currently entering last N
  9136. * endpoints
  9137. */
  9138. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9139. endpointsEnteringLastN,
  9140. stream) {
  9141. if (lastNCount !== lastNEndpoints.length)
  9142. lastNCount = lastNEndpoints.length;
  9143. lastNEndpointsCache = lastNEndpoints;
  9144. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9145. //
  9146. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9147. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9148. // so E sees them. C is only in E's local LastN set.
  9149. //
  9150. // If F starts talking and LastN = 3, then E should see thumbnails for
  9151. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9152. // enters E's local LastN ejecting C.
  9153. // Increase the local LastN set size, if necessary.
  9154. if (lastNCount > localLastNCount) {
  9155. localLastNCount = lastNCount;
  9156. }
  9157. // Update the local LastN set preserving the order in which the
  9158. // endpoints appeared in the LastN/local LastN set.
  9159. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9160. for (var i = 0; i < localLastNSet.length; i++) {
  9161. if (nextLocalLastNSet.length >= localLastNCount) {
  9162. break;
  9163. }
  9164. var resourceJid = localLastNSet[i];
  9165. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9166. nextLocalLastNSet.push(resourceJid);
  9167. }
  9168. }
  9169. localLastNSet = nextLocalLastNSet;
  9170. var updateLargeVideo = false;
  9171. // Handle LastN/local LastN changes.
  9172. $('#remoteVideos>span').each(function( index, element ) {
  9173. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9174. var isReceived = true;
  9175. if (resourceJid &&
  9176. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9177. localLastNSet.indexOf(resourceJid) < 0) {
  9178. console.log("Remove from last N", resourceJid);
  9179. if (remoteVideos[resourceJid])
  9180. remoteVideos[resourceJid].showPeerContainer('hide');
  9181. else if (APP.xmpp.myResource() !== resourceJid)
  9182. console.error("No remote video for: " + resourceJid);
  9183. isReceived = false;
  9184. } else if (resourceJid &&
  9185. $('#participant_' + resourceJid).is(':visible') &&
  9186. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9187. localLastNSet.indexOf(resourceJid) >= 0) {
  9188. if (remoteVideos[resourceJid])
  9189. remoteVideos[resourceJid].showPeerContainer('avatar');
  9190. else if (APP.xmpp.myResource() !== resourceJid)
  9191. console.error("No remote video for: " + resourceJid);
  9192. isReceived = false;
  9193. }
  9194. if (!isReceived) {
  9195. // resourceJid has dropped out of the server side lastN set, so
  9196. // it is no longer being received. If resourceJid was being
  9197. // displayed in the large video we have to switch to another
  9198. // user.
  9199. if (!updateLargeVideo &&
  9200. resourceJid === LargeVideo.getResourceJid()) {
  9201. updateLargeVideo = true;
  9202. }
  9203. }
  9204. });
  9205. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9206. endpointsEnteringLastN = lastNEndpoints;
  9207. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9208. endpointsEnteringLastN.forEach(function (resourceJid) {
  9209. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9210. var remoteVideo = remoteVideos[resourceJid];
  9211. remoteVideo.showPeerContainer('show');
  9212. if (!isVisible) {
  9213. console.log("Add to last N", resourceJid);
  9214. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9215. var mediaStream =
  9216. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9217. var sel = remoteVideo.selectVideoElement();
  9218. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9219. if (lastNPickupJid == mediaStream.peerjid) {
  9220. // Clean up the lastN pickup jid.
  9221. lastNPickupJid = null;
  9222. // Don't fire the events again, they've already
  9223. // been fired in the contact list click handler.
  9224. VideoLayout.handleVideoThumbClicked(
  9225. false,
  9226. Strophe.getResourceFromJid(mediaStream.peerjid));
  9227. updateLargeVideo = false;
  9228. }
  9229. remoteVideos[resourceJid].
  9230. waitForPlayback(sel, mediaStream.stream);
  9231. }
  9232. });
  9233. }
  9234. // The endpoint that was being shown in the large video has dropped out
  9235. // of the lastN set and there was no lastN pickup jid. We need to update
  9236. // the large video now.
  9237. if (updateLargeVideo) {
  9238. var resource;
  9239. var myResource
  9240. = APP.xmpp.myResource();
  9241. // Find out which endpoint to show in the large video.
  9242. for (i = 0; i < lastNEndpoints.length; i++) {
  9243. resource = lastNEndpoints[i];
  9244. if (!resource || resource === myResource)
  9245. continue;
  9246. // videoSrcToSsrc needs to be update for this call to succeed.
  9247. LargeVideo.updateLargeVideo(resource);
  9248. break;
  9249. }
  9250. }
  9251. };
  9252. /**
  9253. * Updates local stats
  9254. * @param percent
  9255. * @param object
  9256. */
  9257. my.updateLocalConnectionStats = function (percent, object) {
  9258. var resolution = null;
  9259. if (object.resolution !== null) {
  9260. resolution = object.resolution;
  9261. object.resolution = resolution[APP.xmpp.myJid()];
  9262. delete resolution[APP.xmpp.myJid()];
  9263. }
  9264. localVideoThumbnail.updateStatsIndicator(percent, object);
  9265. for (var jid in resolution) {
  9266. if (resolution[jid] === null)
  9267. continue;
  9268. var resourceJid = Strophe.getResourceFromJid(jid);
  9269. if (remoteVideos[resourceJid] &&
  9270. remoteVideos[resourceJid].connectionIndicator) {
  9271. remoteVideos[resourceJid].connectionIndicator.
  9272. updateResolution(resolution[jid]);
  9273. }
  9274. }
  9275. };
  9276. /**
  9277. * Updates remote stats.
  9278. * @param jid the jid associated with the stats
  9279. * @param percent the connection quality percent
  9280. * @param object the stats data
  9281. */
  9282. my.updateConnectionStats = function (jid, percent, object) {
  9283. var resourceJid = Strophe.getResourceFromJid(jid);
  9284. if (remoteVideos[resourceJid])
  9285. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9286. };
  9287. /**
  9288. * Hides the connection indicator
  9289. * @param jid
  9290. */
  9291. my.hideConnectionIndicator = function (jid) {
  9292. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9293. };
  9294. /**
  9295. * Hides all the indicators
  9296. */
  9297. my.onStatsStop = function () {
  9298. for(var video in remoteVideos) {
  9299. remoteVideos[video].hideIndicator();
  9300. }
  9301. localVideoThumbnail.hideIndicator();
  9302. };
  9303. my.participantLeft = function (jid) {
  9304. // Unlock large video
  9305. var resourceJid = Strophe.getResourceFromJid(jid);
  9306. if (focusedVideoResourceJid === resourceJid) {
  9307. console.info("Focused video owner has left the conference");
  9308. focusedVideoResourceJid = null;
  9309. }
  9310. if (currentDominantSpeaker === resourceJid)
  9311. {
  9312. console.info("Dominant speaker has left the conference");
  9313. currentDominantSpeaker = null;
  9314. }
  9315. var remoteVideo = remoteVideos[resourceJid];
  9316. if (remoteVideo) {
  9317. // Remove remote video
  9318. console.info("Removing remote video: " + resourceJid);
  9319. remoteVideo.remove();
  9320. delete remoteVideos[resourceJid];
  9321. } else {
  9322. console.warn("No remote video for " + resourceJid);
  9323. }
  9324. VideoLayout.resizeThumbnails();
  9325. };
  9326. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9327. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9328. return;
  9329. }
  9330. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9331. remoteVideoTypes[resourceJid] = newVideoType;
  9332. var smallVideo;
  9333. if (resourceJid === APP.xmpp.myResource()) {
  9334. if (!localVideoThumbnail) {
  9335. console.warn("Local video not ready yet");
  9336. return;
  9337. }
  9338. smallVideo = localVideoThumbnail;
  9339. } else if (remoteVideos[resourceJid]) {
  9340. smallVideo = remoteVideos[resourceJid];
  9341. } else {
  9342. return;
  9343. }
  9344. smallVideo.setVideoType(newVideoType);
  9345. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9346. };
  9347. my.showMore = function (jid) {
  9348. if (jid === 'local') {
  9349. localVideoThumbnail.connectionIndicator.showMore();
  9350. } else {
  9351. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9352. if (remoteVideo) {
  9353. remoteVideo.connectionIndicator.showMore();
  9354. } else {
  9355. console.info("Error - no remote video for jid: " + jid);
  9356. }
  9357. }
  9358. };
  9359. my.addPreziContainer = function (id) {
  9360. var container = RemoteVideo.createContainer(id);
  9361. VideoLayout.resizeThumbnails();
  9362. return container;
  9363. };
  9364. my.setLargeVideoVisible = function (isVisible) {
  9365. LargeVideo.setLargeVideoVisible(isVisible);
  9366. if(!isVisible && focusedVideoResourceJid) {
  9367. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9368. if(smallVideo) {
  9369. smallVideo.focus(false);
  9370. smallVideo.showAvatar();
  9371. }
  9372. focusedVideoResourceJid = null;
  9373. }
  9374. };
  9375. /**
  9376. * Resizes the video area
  9377. * @param callback a function to be called when the video space is
  9378. * resized.
  9379. */
  9380. my.resizeVideoArea = function(isVisible, callback) {
  9381. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9382. VideoLayout.resizeThumbnails(true);
  9383. };
  9384. /**
  9385. * Resizes the #videospace html element
  9386. * @param animate boolean property that indicates whether the resize should be animated or not.
  9387. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9388. * If that parameter is null the method will check the chat pannel visibility.
  9389. * @param completeFunction a function to be called when the video space is resized
  9390. */
  9391. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9392. var availableHeight = window.innerHeight;
  9393. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9394. if (availableWidth < 0 || availableHeight < 0) return;
  9395. if(animate) {
  9396. $('#videospace').animate({
  9397. right: window.innerWidth - availableWidth,
  9398. width: availableWidth,
  9399. height: availableHeight
  9400. },
  9401. {
  9402. queue: false,
  9403. duration: 500,
  9404. complete: completeFunction
  9405. });
  9406. } else {
  9407. $('#videospace').width(availableWidth);
  9408. $('#videospace').height(availableHeight);
  9409. }
  9410. };
  9411. my.getSmallVideo = function (resourceJid) {
  9412. if(resourceJid == APP.xmpp.myResource()) {
  9413. return localVideoThumbnail;
  9414. } else {
  9415. if(!remoteVideos[resourceJid])
  9416. return null;
  9417. return remoteVideos[resourceJid];
  9418. }
  9419. };
  9420. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9421. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9422. if(smallVideo)
  9423. smallVideo.avatarChanged(thumbUrl);
  9424. else
  9425. console.warn(
  9426. "Missed avatar update - no small video yet for " + resourceJid);
  9427. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9428. };
  9429. my.createEtherpadIframe = function(src, onloadHandler)
  9430. {
  9431. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9432. };
  9433. my.setLargeVideoState = function (state) {
  9434. LargeVideo.setState(state);
  9435. };
  9436. my.getLargeVideoState = function () {
  9437. return LargeVideo.getState();
  9438. };
  9439. my.setLargeVideoHover = function (inHandler, outHandler) {
  9440. LargeVideo.setHover(inHandler, outHandler);
  9441. };
  9442. /**
  9443. * Indicates that the video has been interrupted.
  9444. */
  9445. my.onVideoInterrupted = function () {
  9446. LargeVideo.enableVideoProblemFilter(true);
  9447. var reconnectingKey = "connection.RECONNECTING";
  9448. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9449. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9450. $('#videoConnectionMessage').css({display: "block"});
  9451. };
  9452. /**
  9453. * Indicates that the video has been restored.
  9454. */
  9455. my.onVideoRestored = function () {
  9456. LargeVideo.enableVideoProblemFilter(false);
  9457. $('#videoConnectionMessage').css({display: "none"});
  9458. };
  9459. return my;
  9460. }(VideoLayout || {}));
  9461. module.exports = VideoLayout;
  9462. },{"../../../service/RTC/MediaStreamTypes":162,"../../../service/UI/UIEvents":166,"../../RTC/RTC":7,"../../RTC/RTCBrowserType":8,"../audio_levels/AudioLevels":12,"../prezi/Prezi":18,"../side_pannels/contactlist/ContactList":25,"../util/UIUtil":33,"./LargeVideo":35,"./LocalVideo":36,"./RemoteVideo":37}],40:[function(require,module,exports){
  9463. //var nouns = [
  9464. //];
  9465. var pluralNouns = [
  9466. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9467. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9468. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9469. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9470. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9471. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9472. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9473. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9474. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9475. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9476. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9477. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9478. ];
  9479. //var places = [
  9480. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9481. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9482. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9483. // "Bridge"
  9484. //];
  9485. var verbs = [
  9486. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9487. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9488. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9489. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9490. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9491. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9492. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9493. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9494. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9495. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9496. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9497. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9498. ];
  9499. var adverbs = [
  9500. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9501. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9502. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9503. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9504. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9505. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9506. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9507. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9508. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9509. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9510. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9511. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9512. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9513. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9514. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9515. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9516. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9517. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9518. ];
  9519. var adjectives = [
  9520. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9521. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9522. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9523. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9524. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9525. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9526. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9527. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9528. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9529. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9530. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9531. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9532. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9533. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9534. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9535. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9536. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9537. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9538. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9539. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9540. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9541. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9542. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9543. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9544. "Zealous"
  9545. ];
  9546. //var pronouns = [
  9547. //];
  9548. //var conjunctions = [
  9549. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9550. //];
  9551. /*
  9552. * Maps a string (category name) to the array of words from that category.
  9553. */
  9554. var CATEGORIES =
  9555. {
  9556. //"_NOUN_": nouns,
  9557. "_PLURALNOUN_": pluralNouns,
  9558. //"_PLACE_": places,
  9559. "_VERB_": verbs,
  9560. "_ADVERB_": adverbs,
  9561. "_ADJECTIVE_": adjectives
  9562. //"_PRONOUN_": pronouns,
  9563. //"_CONJUNCTION_": conjunctions,
  9564. };
  9565. var PATTERNS = [
  9566. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9567. // BeautifulFungiOrSpaghetti
  9568. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9569. // AmazinglyScaryToy
  9570. //"_ADVERB__ADJECTIVE__NOUN_",
  9571. // NeitherTrashNorRifle
  9572. //"Neither_NOUN_Nor_NOUN_",
  9573. //"Either_NOUN_Or_NOUN_",
  9574. // EitherCopulateOrInvestigate
  9575. //"Either_VERB_Or_VERB_",
  9576. //"Neither_VERB_Nor_VERB_",
  9577. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9578. //"The_ADVERB__ADJECTIVE__NOUN_",
  9579. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9580. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9581. // WolvesComputeBadly
  9582. //"_PLURALNOUN__VERB__ADVERB_",
  9583. // UniteFacilitateAndMerge
  9584. //"_VERB__VERB_And_VERB_",
  9585. //NastyWitchesAtThePub
  9586. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9587. ];
  9588. /*
  9589. * Returns a random element from the array 'arr'
  9590. */
  9591. function randomElement(arr) {
  9592. return arr[Math.floor(Math.random() * arr.length)];
  9593. }
  9594. /*
  9595. * Returns true if the string 's' contains one of the
  9596. * template strings.
  9597. */
  9598. function hasTemplate(s) {
  9599. for (var template in CATEGORIES){
  9600. if (s.indexOf(template) >= 0){
  9601. return true;
  9602. }
  9603. }
  9604. }
  9605. /**
  9606. * Generates new room name.
  9607. */
  9608. var RoomNameGenerator = {
  9609. generateRoomWithoutSeparator: function() {
  9610. // Note that if more than one pattern is available, the choice of
  9611. // 'name' won't have a uniform distribution amongst all patterns (names
  9612. // from patterns with fewer options will have higher probability of
  9613. // being chosen that names from patterns with more options).
  9614. var name = randomElement(PATTERNS);
  9615. var word;
  9616. while (hasTemplate(name)) {
  9617. for (var template in CATEGORIES) {
  9618. word = randomElement(CATEGORIES[template]);
  9619. name = name.replace(template, word);
  9620. }
  9621. }
  9622. return name;
  9623. }
  9624. };
  9625. module.exports = RoomNameGenerator;
  9626. },{}],41:[function(require,module,exports){
  9627. /* global $, interfaceConfig */
  9628. var animateTimeout, updateTimeout;
  9629. var RoomNameGenerator = require("./RoomnameGenerator");
  9630. function enter_room() {
  9631. var val = $("#enter_room_field").val();
  9632. if(!val) {
  9633. val = $("#enter_room_field").attr("room_name");
  9634. }
  9635. if (val) {
  9636. window.location.pathname = "/" + val;
  9637. }
  9638. }
  9639. function animate(word) {
  9640. var currentVal = $("#enter_room_field").attr("placeholder");
  9641. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9642. animateTimeout = setTimeout(function() {
  9643. animate(word.substring(1, word.length))
  9644. }, 70);
  9645. }
  9646. function update_roomname() {
  9647. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9648. $("#enter_room_field").attr("room_name", word);
  9649. $("#enter_room_field").attr("placeholder", "");
  9650. clearTimeout(animateTimeout);
  9651. animate(word);
  9652. updateTimeout = setTimeout(update_roomname, 10000);
  9653. }
  9654. function setupWelcomePage() {
  9655. $("#videoconference_page").hide();
  9656. $("#domain_name").text(
  9657. window.location.protocol + "//" + window.location.host + "/");
  9658. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9659. var leftWatermarkDiv =
  9660. $("#welcome_page_header div[class='watermark leftwatermark']");
  9661. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9662. leftWatermarkDiv.css({display: 'block'});
  9663. leftWatermarkDiv.parent().get(0).href =
  9664. interfaceConfig.JITSI_WATERMARK_LINK;
  9665. }
  9666. }
  9667. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9668. var rightWatermarkDiv =
  9669. $("#welcome_page_header div[class='watermark rightwatermark']");
  9670. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9671. rightWatermarkDiv.css({display: 'block'});
  9672. rightWatermarkDiv.parent().get(0).href =
  9673. interfaceConfig.BRAND_WATERMARK_LINK;
  9674. rightWatermarkDiv.get(0).style.backgroundImage =
  9675. "url(images/rightwatermark.png)";
  9676. }
  9677. }
  9678. if (interfaceConfig.SHOW_POWERED_BY) {
  9679. $("#welcome_page_header>a[class='poweredby']")
  9680. .css({display: 'block'});
  9681. }
  9682. $("#enter_room_button").click(function() {
  9683. enter_room();
  9684. });
  9685. $("#enter_room_field").keydown(function (event) {
  9686. if (event.keyCode === 13 /* enter */) {
  9687. enter_room();
  9688. }
  9689. });
  9690. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9691. var updateTimeout;
  9692. var animateTimeout;
  9693. var selector = $("#reload_roomname");
  9694. selector.click(function () {
  9695. clearTimeout(updateTimeout);
  9696. clearTimeout(animateTimeout);
  9697. update_roomname();
  9698. });
  9699. selector.show();
  9700. update_roomname();
  9701. }
  9702. $("#disable_welcome").click(function () {
  9703. window.localStorage.welcomePageDisabled =
  9704. $("#disable_welcome").is(":checked");
  9705. });
  9706. }
  9707. module.exports = setupWelcomePage;
  9708. },{"./RoomnameGenerator":40}],42:[function(require,module,exports){
  9709. /* global $, $iq, config, interfaceConfig */
  9710. var configUtil = require('./Util');
  9711. var HttpConfig = {
  9712. /**
  9713. * Sends HTTP POST request to specified <tt>endpoint</tt>. In request
  9714. * the name of the room is included in JSON format:
  9715. * {
  9716. * "rooomName": "someroom12345"
  9717. * }
  9718. * @param endpoint the name of HTTP endpoint to which HTTP POST request will
  9719. * be sent.
  9720. * @param roomName the name of the conference room for which config will be
  9721. * requested.
  9722. * @param complete
  9723. */
  9724. obtainConfig: function (endpoint, roomName, complete) {
  9725. console.info(
  9726. "Send config request to " + endpoint + " for room: " + roomName);
  9727. $.ajax(
  9728. endpoint,
  9729. {
  9730. method: 'POST',
  9731. contentType: 'application/json',
  9732. data: JSON.stringify({"roomName": roomName}),
  9733. dataType: 'json',
  9734. error: function(jqXHR, textStatus, errorThrown) {
  9735. console.error("Get config error: ", jqXHR, errorThrown)
  9736. error = "Get config response status: " + textStatus;
  9737. complete(false, error);
  9738. },
  9739. success: function(data, textStatus, jqXHR) {
  9740. try {
  9741. configUtil.overrideConfigJSON(
  9742. config, interfaceConfig, data);
  9743. complete(true);
  9744. return;
  9745. } catch (exception) {
  9746. console.error("Parse config error: ", exception);
  9747. error = exception;
  9748. complete(false, error);
  9749. }
  9750. }
  9751. }
  9752. );
  9753. }
  9754. };
  9755. module.exports = HttpConfig;
  9756. },{"./Util":44}],43:[function(require,module,exports){
  9757. /* global $, $iq, config, interfaceConfig */
  9758. var configUtils = require('./Util');
  9759. var params = {};
  9760. function getConfigParamsFromUrl() {
  9761. if (!location.hash)
  9762. return {};
  9763. var hash = location.hash.substr(1);
  9764. var result = {};
  9765. hash.split("&").forEach(function (part) {
  9766. var item = part.split("=");
  9767. result[item[0]] = JSON.parse(
  9768. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9769. });
  9770. return result;
  9771. }
  9772. params = getConfigParamsFromUrl();
  9773. var URLProcessor = {
  9774. setConfigParametersFromUrl: function () {
  9775. // Convert 'params' to JSON object
  9776. // We have:
  9777. // {
  9778. // "config.disableAudioLevels": false,
  9779. // "config.channelLastN": -1,
  9780. // "interfaceConfig.APP_NAME": "Jitsi Meet"
  9781. // }
  9782. // We want to have:
  9783. // {
  9784. // "config": {
  9785. // "disableAudioLevels": false,
  9786. // "channelLastN": -1
  9787. // },
  9788. // interfaceConfig: {
  9789. // APP_NAME: "Jitsi Meet"
  9790. // }
  9791. // }
  9792. var configJSON = {
  9793. config: {},
  9794. interfaceConfig: {}
  9795. };
  9796. for (var key in params) {
  9797. if (typeof key !== "string") {
  9798. console.warn("Invalid config key: ", key);
  9799. continue;
  9800. }
  9801. var confObj = null, confKey;
  9802. if (key.indexOf("config.") === 0) {
  9803. confObj = configJSON.config;
  9804. confKey = key.substr("config.".length);
  9805. } else if (key.indexOf("interfaceConfig.") === 0) {
  9806. confObj = configJSON.interfaceConfig;
  9807. confKey = key.substr("interfaceConfig.".length);
  9808. }
  9809. if (!confObj)
  9810. continue;
  9811. confObj[confKey] = params[key];
  9812. }
  9813. configUtils.overrideConfigJSON(config, interfaceConfig, configJSON);
  9814. }
  9815. };
  9816. module.exports = URLProcessor;
  9817. },{"./Util":44}],44:[function(require,module,exports){
  9818. /* global $ */
  9819. var ConfigUtil = {
  9820. /**
  9821. * Method overrides JSON properties in <tt>config</tt> and
  9822. * <tt>interfaceConfig</tt> Objects with the values from <tt>newConfig</tt>
  9823. * @param config the config object for which we'll be overriding properties
  9824. * @param interfaceConfig the interfaceConfig object for which we'll be
  9825. * overriding properties.
  9826. * @param newConfig object containing configuration properties. Destination
  9827. * object is selected based on root property name:
  9828. * {
  9829. * config: {
  9830. * // config.js properties to be
  9831. * },
  9832. * interfaceConfig: {
  9833. * // interfaceConfig.js properties here
  9834. * }
  9835. * }
  9836. */
  9837. overrideConfigJSON: function (config, interfaceConfig, newConfig) {
  9838. for (var configRoot in newConfig) {
  9839. var confObj = null;
  9840. if (configRoot == "config") {
  9841. confObj = config;
  9842. } else if (configRoot == "interfaceConfig") {
  9843. confObj = interfaceConfig;
  9844. } else {
  9845. continue;
  9846. }
  9847. for (var key in newConfig[configRoot]) {
  9848. var value = newConfig[configRoot][key];
  9849. if (confObj[key] && typeof confObj[key] !== typeof value)
  9850. {
  9851. console.warn(
  9852. "The type of " + key +
  9853. " is wrong. That parameter won't be updated in: ",
  9854. confObj);
  9855. continue;
  9856. }
  9857. console.info("Overriding " + key + " with: " + value);
  9858. confObj[key] = value;
  9859. }
  9860. }
  9861. }
  9862. };
  9863. module.exports = ConfigUtil;
  9864. },{}],45:[function(require,module,exports){
  9865. /* global APP, require */
  9866. var EventEmitter = require("events");
  9867. var eventEmitter = new EventEmitter();
  9868. var CQEvents = require("../../service/connectionquality/CQEvents");
  9869. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9870. /**
  9871. * local stats
  9872. * @type {{}}
  9873. */
  9874. var stats = {};
  9875. /**
  9876. * remote stats
  9877. * @type {{}}
  9878. */
  9879. var remoteStats = {};
  9880. /**
  9881. * Interval for sending statistics to other participants
  9882. * @type {null}
  9883. */
  9884. var sendIntervalId = null;
  9885. /**
  9886. * Start statistics sending.
  9887. */
  9888. function startSendingStats() {
  9889. sendStats();
  9890. sendIntervalId = setInterval(sendStats, 10000);
  9891. }
  9892. /**
  9893. * Sends statistics to other participants
  9894. */
  9895. function sendStats() {
  9896. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9897. }
  9898. /**
  9899. * Converts statistics to format for sending through XMPP
  9900. * @param stats the statistics
  9901. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9902. */
  9903. function convertToMUCStats(stats) {
  9904. return {
  9905. "bitrate_download": stats.bitrate.download,
  9906. "bitrate_upload": stats.bitrate.upload,
  9907. "packetLoss_total": stats.packetLoss.total,
  9908. "packetLoss_download": stats.packetLoss.download,
  9909. "packetLoss_upload": stats.packetLoss.upload
  9910. };
  9911. }
  9912. /**
  9913. * Converts statistics to format used by VideoLayout
  9914. * @param stats
  9915. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9916. */
  9917. function parseMUCStats(stats) {
  9918. return {
  9919. bitrate: {
  9920. download: stats.bitrate_download,
  9921. upload: stats.bitrate_upload
  9922. },
  9923. packetLoss: {
  9924. total: stats.packetLoss_total,
  9925. download: stats.packetLoss_download,
  9926. upload: stats.packetLoss_upload
  9927. }
  9928. };
  9929. }
  9930. var ConnectionQuality = {
  9931. init: function () {
  9932. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9933. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9934. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9935. },
  9936. /**
  9937. * Updates the local statistics
  9938. * @param data new statistics
  9939. */
  9940. updateLocalStats: function (data) {
  9941. stats = data;
  9942. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9943. if (sendIntervalId == null) {
  9944. startSendingStats();
  9945. }
  9946. },
  9947. /**
  9948. * Updates remote statistics
  9949. * @param jid the jid associated with the statistics
  9950. * @param data the statistics
  9951. */
  9952. updateRemoteStats: function (jid, data) {
  9953. if (data == null || data.packetLoss_total == null) {
  9954. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9955. return;
  9956. }
  9957. remoteStats[jid] = parseMUCStats(data);
  9958. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9959. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9960. },
  9961. /**
  9962. * Stops statistics sending.
  9963. */
  9964. stopSendingStats: function () {
  9965. clearInterval(sendIntervalId);
  9966. sendIntervalId = null;
  9967. //notify UI about stopping statistics gathering
  9968. eventEmitter.emit(CQEvents.STOP);
  9969. },
  9970. /**
  9971. * Returns the local statistics.
  9972. */
  9973. getStats: function () {
  9974. return stats;
  9975. },
  9976. addListener: function (type, listener) {
  9977. eventEmitter.on(type, listener);
  9978. }
  9979. };
  9980. module.exports = ConnectionQuality;
  9981. },{"../../service/connectionquality/CQEvents":168,"../../service/xmpp/XMPPEvents":172,"events":173}],46:[function(require,module,exports){
  9982. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9983. getUserMediaWithConstraints */
  9984. /**
  9985. * Indicates that desktop stream is currently in use(for toggle purpose).
  9986. * @type {boolean}
  9987. */
  9988. var isUsingScreenStream = false;
  9989. /**
  9990. * Indicates that switch stream operation is in progress and prevent from
  9991. * triggering new events.
  9992. * @type {boolean}
  9993. */
  9994. var switchInProgress = false;
  9995. /**
  9996. * Method used to get screen sharing stream.
  9997. *
  9998. * @type {function (stream_callback, failure_callback}
  9999. */
  10000. var obtainDesktopStream = null;
  10001. /**
  10002. * Indicates whether desktop sharing extension is installed.
  10003. * @type {boolean}
  10004. */
  10005. var extInstalled = false;
  10006. /**
  10007. * Indicates whether update of desktop sharing extension is required.
  10008. * @type {boolean}
  10009. */
  10010. var extUpdateRequired = false;
  10011. var AdapterJS = require("../RTC/adapter.screenshare");
  10012. var EventEmitter = require("events");
  10013. var eventEmitter = new EventEmitter();
  10014. var DesktopSharingEventTypes
  10015. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  10016. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10017. var RTCEvents = require("../../service/RTC/RTCEvents");
  10018. /**
  10019. * Method obtains desktop stream from WebRTC 'screen' source.
  10020. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  10021. */
  10022. function obtainWebRTCScreen(streamCallback, failCallback) {
  10023. APP.RTC.getUserMediaWithConstraints(
  10024. ['screen'],
  10025. streamCallback,
  10026. failCallback
  10027. );
  10028. }
  10029. /**
  10030. * Constructs inline install URL for Chrome desktop streaming extension.
  10031. * The 'chromeExtensionId' must be defined in config.js.
  10032. * @returns {string}
  10033. */
  10034. function getWebStoreInstallUrl()
  10035. {
  10036. return "https://chrome.google.com/webstore/detail/" +
  10037. config.chromeExtensionId;
  10038. }
  10039. /**
  10040. * Checks whether extension update is required.
  10041. * @param minVersion minimal required version
  10042. * @param extVersion current extension version
  10043. * @returns {boolean}
  10044. */
  10045. function isUpdateRequired(minVersion, extVersion)
  10046. {
  10047. try
  10048. {
  10049. var s1 = minVersion.split('.');
  10050. var s2 = extVersion.split('.');
  10051. var len = Math.max(s1.length, s2.length);
  10052. for (var i = 0; i < len; i++)
  10053. {
  10054. var n1 = 0,
  10055. n2 = 0;
  10056. if (i < s1.length)
  10057. n1 = parseInt(s1[i]);
  10058. if (i < s2.length)
  10059. n2 = parseInt(s2[i]);
  10060. if (isNaN(n1) || isNaN(n2))
  10061. {
  10062. return true;
  10063. }
  10064. else if (n1 !== n2)
  10065. {
  10066. return n1 > n2;
  10067. }
  10068. }
  10069. // will happen if boths version has identical numbers in
  10070. // their components (even if one of them is longer, has more components)
  10071. return false;
  10072. }
  10073. catch (e)
  10074. {
  10075. console.error("Failed to parse extension version", e);
  10076. APP.UI.messageHandler.showError("dialog.error",
  10077. "dialog.detectext");
  10078. return true;
  10079. }
  10080. }
  10081. function checkChromeExtInstalled(callback) {
  10082. if (!chrome.runtime) {
  10083. // No API, so no extension for sure
  10084. callback(false, false);
  10085. return;
  10086. }
  10087. chrome.runtime.sendMessage(
  10088. config.chromeExtensionId,
  10089. { getVersion: true },
  10090. function (response) {
  10091. if (!response || !response.version) {
  10092. // Communication failure - assume that no endpoint exists
  10093. console.warn(
  10094. "Extension not installed?: ", chrome.runtime.lastError);
  10095. callback(false, false);
  10096. return;
  10097. }
  10098. // Check installed extension version
  10099. var extVersion = response.version;
  10100. console.log('Extension version is: ' + extVersion);
  10101. var updateRequired
  10102. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10103. callback(!updateRequired, updateRequired);
  10104. }
  10105. );
  10106. }
  10107. function doGetStreamFromExtension(streamCallback, failCallback) {
  10108. // Sends 'getStream' msg to the extension.
  10109. // Extension id must be defined in the config.
  10110. chrome.runtime.sendMessage(
  10111. config.chromeExtensionId,
  10112. { getStream: true, sources: config.desktopSharingSources },
  10113. function (response) {
  10114. if (!response) {
  10115. failCallback(chrome.runtime.lastError);
  10116. return;
  10117. }
  10118. console.log("Response from extension: " + response);
  10119. if (response.streamId) {
  10120. APP.RTC.getUserMediaWithConstraints(
  10121. ['desktop'],
  10122. function (stream) {
  10123. streamCallback(stream);
  10124. },
  10125. failCallback,
  10126. null, null, null,
  10127. response.streamId);
  10128. } else {
  10129. failCallback("Extension failed to get the stream");
  10130. }
  10131. }
  10132. );
  10133. }
  10134. /**
  10135. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10136. * stream for returned stream token.
  10137. */
  10138. function obtainScreenFromExtension(streamCallback, failCallback) {
  10139. if (extInstalled) {
  10140. doGetStreamFromExtension(streamCallback, failCallback);
  10141. } else {
  10142. if (extUpdateRequired) {
  10143. alert(
  10144. 'Jitsi Desktop Streamer requires update. ' +
  10145. 'Changes will take effect after next Chrome restart.');
  10146. }
  10147. chrome.webstore.install(
  10148. getWebStoreInstallUrl(),
  10149. function (arg) {
  10150. console.log("Extension installed successfully", arg);
  10151. extInstalled = true;
  10152. // We need to give a moment for the endpoint to become available
  10153. window.setTimeout(function () {
  10154. doGetStreamFromExtension(streamCallback, failCallback);
  10155. }, 500);
  10156. },
  10157. function (arg) {
  10158. console.log("Failed to install the extension", arg);
  10159. failCallback(arg);
  10160. APP.UI.messageHandler.showError("dialog.error",
  10161. "dialog.failtoinstall");
  10162. }
  10163. );
  10164. }
  10165. }
  10166. /**
  10167. * Call this method to toggle desktop sharing feature.
  10168. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10169. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10170. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10171. * enabled), pass any other string or nothing in order to disable this
  10172. * feature completely.
  10173. */
  10174. function setDesktopSharing(method) {
  10175. obtainDesktopStream = null;
  10176. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10177. // care about 'method' parameter
  10178. if (RTCBrowserType.isTemasysPluginUsed()) {
  10179. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10180. console.info("Screensharing not supported by this plugin version");
  10181. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10182. console.info(
  10183. "Screensharing not available with Temasys plugin on this site");
  10184. } else {
  10185. obtainDesktopStream = obtainWebRTCScreen;
  10186. console.info("Using Temasys plugin for desktop sharing");
  10187. }
  10188. } else if (RTCBrowserType.isChrome()) {
  10189. if (method == "ext") {
  10190. if (RTCBrowserType.getChromeVersion() >= 34) {
  10191. obtainDesktopStream = obtainScreenFromExtension;
  10192. console.info("Using Chrome extension for desktop sharing");
  10193. initChromeExtension();
  10194. } else {
  10195. console.info("Chrome extension not supported until ver 34");
  10196. }
  10197. } else if (method == "webrtc") {
  10198. obtainDesktopStream = obtainWebRTCScreen;
  10199. console.info("Using Chrome WebRTC for desktop sharing");
  10200. }
  10201. }
  10202. if (!obtainDesktopStream) {
  10203. console.info("Desktop sharing disabled");
  10204. }
  10205. }
  10206. /**
  10207. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10208. * config.js to support inline installs. Host site must be selected as main
  10209. * website of published extension.
  10210. */
  10211. function initInlineInstalls()
  10212. {
  10213. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10214. }
  10215. function initChromeExtension() {
  10216. // Initialize Chrome extension inline installs
  10217. initInlineInstalls();
  10218. // Check if extension is installed
  10219. checkChromeExtInstalled(function (installed, updateRequired) {
  10220. extInstalled = installed;
  10221. extUpdateRequired = updateRequired;
  10222. console.info(
  10223. "Chrome extension installed: " + extInstalled +
  10224. " updateRequired: " + extUpdateRequired);
  10225. });
  10226. }
  10227. function getVideoStreamFailed(error) {
  10228. console.error("Failed to obtain the stream to switch to", error);
  10229. switchInProgress = false;
  10230. isUsingScreenStream = false;
  10231. newStreamCreated(null);
  10232. }
  10233. function getDesktopStreamFailed(error) {
  10234. console.error("Failed to obtain the stream to switch to", error);
  10235. switchInProgress = false;
  10236. }
  10237. function streamSwitchDone() {
  10238. switchInProgress = false;
  10239. eventEmitter.emit(
  10240. DesktopSharingEventTypes.SWITCHING_DONE,
  10241. isUsingScreenStream);
  10242. }
  10243. function newStreamCreated(stream)
  10244. {
  10245. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10246. stream, isUsingScreenStream, streamSwitchDone);
  10247. }
  10248. function onEndedHandler(stream) {
  10249. if (!switchInProgress && isUsingScreenStream) {
  10250. APP.desktopsharing.toggleScreenSharing();
  10251. }
  10252. //FIXME: to be verified
  10253. if (stream.removeEventListener) {
  10254. stream.removeEventListener('ended', onEndedHandler);
  10255. } else {
  10256. stream.detachEvent('ended', onEndedHandler);
  10257. }
  10258. }
  10259. // Called when RTC finishes initialization
  10260. function onWebRtcReady() {
  10261. setDesktopSharing(config.desktopSharing);
  10262. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10263. }
  10264. module.exports = {
  10265. isUsingScreenStream: function () {
  10266. return isUsingScreenStream;
  10267. },
  10268. /**
  10269. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10270. * and enabled.
  10271. */
  10272. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10273. init: function () {
  10274. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10275. },
  10276. addListener: function (listener, type)
  10277. {
  10278. eventEmitter.on(type, listener);
  10279. },
  10280. removeListener: function (listener, type) {
  10281. eventEmitter.removeListener(type, listener);
  10282. },
  10283. /*
  10284. * Toggles screen sharing.
  10285. */
  10286. toggleScreenSharing: function () {
  10287. if (switchInProgress || !obtainDesktopStream) {
  10288. console.warn("Switch in progress or no method defined");
  10289. return;
  10290. }
  10291. switchInProgress = true;
  10292. if (!isUsingScreenStream)
  10293. {
  10294. // Switch to desktop stream
  10295. obtainDesktopStream(
  10296. function (stream) {
  10297. // We now use screen stream
  10298. isUsingScreenStream = true;
  10299. // Hook 'ended' event to restore camera
  10300. // when screen stream stops
  10301. //FIXME: to be verified
  10302. if (stream.addEventListener) {
  10303. stream.addEventListener('ended', function () {
  10304. onEndedHandler(stream);
  10305. });
  10306. } else {
  10307. stream.attachEvent('ended', function () {
  10308. onEndedHandler(stream);
  10309. });
  10310. }
  10311. newStreamCreated(stream);
  10312. },
  10313. getDesktopStreamFailed);
  10314. } else {
  10315. // Disable screen stream
  10316. APP.RTC.getUserMediaWithConstraints(
  10317. ['video'],
  10318. function (stream) {
  10319. // We are now using camera stream
  10320. isUsingScreenStream = false;
  10321. newStreamCreated(stream);
  10322. },
  10323. getVideoStreamFailed, config.resolution || '360'
  10324. );
  10325. }
  10326. }
  10327. };
  10328. },{"../../service/RTC/RTCEvents":163,"../../service/desktopsharing/DesktopSharingEventTypes":169,"../RTC/RTCBrowserType":8,"../RTC/adapter.screenshare":10,"events":173}],47:[function(require,module,exports){
  10329. /* global APP, $ */
  10330. //maps keycode to character, id of popover for given function and function
  10331. var shortcuts = {};
  10332. function initShortcutHandlers() {
  10333. shortcuts = {
  10334. 67: {
  10335. character: "C",
  10336. id: "toggleChatPopover",
  10337. function: APP.UI.toggleChat
  10338. },
  10339. 70: {
  10340. character: "F",
  10341. id: "filmstripPopover",
  10342. function: APP.UI.toggleFilmStrip
  10343. },
  10344. 77: {
  10345. character: "M",
  10346. id: "mutePopover",
  10347. function: APP.UI.toggleAudio
  10348. },
  10349. 84: {
  10350. character: "T",
  10351. function: function() {
  10352. if(!APP.RTC.localAudio.isMuted()) {
  10353. APP.UI.toggleAudio();
  10354. }
  10355. }
  10356. },
  10357. 86: {
  10358. character: "V",
  10359. id: "toggleVideoPopover",
  10360. function: APP.UI.toggleVideo
  10361. }
  10362. };
  10363. }
  10364. var KeyboardShortcut = {
  10365. init: function () {
  10366. initShortcutHandlers();
  10367. window.onkeyup = function(e) {
  10368. var keycode = e.which;
  10369. if(!($(":focus").is("input[type=text]") ||
  10370. $(":focus").is("input[type=password]") ||
  10371. $(":focus").is("textarea"))) {
  10372. if (typeof shortcuts[keycode] === "object") {
  10373. shortcuts[keycode].function();
  10374. }
  10375. else if (keycode >= "0".charCodeAt(0) &&
  10376. keycode <= "9".charCodeAt(0)) {
  10377. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10378. }
  10379. //esc while the smileys are visible hides them
  10380. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10381. APP.UI.toggleSmileys();
  10382. }
  10383. };
  10384. window.onkeydown = function(e) {
  10385. if(!($(":focus").is("input[type=text]") ||
  10386. $(":focus").is("input[type=password]") ||
  10387. $(":focus").is("textarea"))) {
  10388. if(e.which === "T".charCodeAt(0)) {
  10389. if(APP.RTC.localAudio.isMuted()) {
  10390. APP.UI.toggleAudio();
  10391. }
  10392. }
  10393. }
  10394. };
  10395. var self = this;
  10396. $('body').popover({ selector: '[data-toggle=popover]',
  10397. trigger: 'click hover',
  10398. content: function() {
  10399. return this.getAttribute("content") +
  10400. self.getShortcut(this.getAttribute("shortcut"));
  10401. }
  10402. });
  10403. },
  10404. /**
  10405. *
  10406. * @param id indicates the popover associated with the shortcut
  10407. * @returns {string} the keyboard shortcut used for the id given
  10408. */
  10409. getShortcut: function (id) {
  10410. for (var keycode in shortcuts) {
  10411. if (shortcuts.hasOwnProperty(keycode)) {
  10412. if (shortcuts[keycode].id === id) {
  10413. return " (" + shortcuts[keycode].character + ")";
  10414. }
  10415. }
  10416. }
  10417. return "";
  10418. }
  10419. };
  10420. module.exports = KeyboardShortcut;
  10421. },{}],48:[function(require,module,exports){
  10422. /* global APP, require, $ */
  10423. /**
  10424. * This module is meant to (eventually) contain and manage all information
  10425. * about members/participants of the conference, so that other modules don't
  10426. * have to do it on their own, and so that other modules can access members'
  10427. * information from a single place.
  10428. *
  10429. * Currently this module only manages information about the support of jingle
  10430. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10431. * be added as needed.
  10432. */
  10433. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10434. var Events = require("../../service/members/Events");
  10435. var EventEmitter = require("events");
  10436. var eventEmitter = new EventEmitter();
  10437. /**
  10438. * The actual container.
  10439. */
  10440. var members = {};
  10441. /**
  10442. * There is at least one member that supports DTMF (i.e. is jigasi).
  10443. */
  10444. var atLeastOneDtmf = false;
  10445. function registerListeners() {
  10446. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10447. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10448. }
  10449. /**
  10450. * Handles a new member joining the MUC.
  10451. */
  10452. function onMucMemberJoined(jid, id, displayName) {
  10453. var member = {
  10454. displayName: displayName
  10455. };
  10456. APP.xmpp.getConnection().disco.info(
  10457. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10458. members[jid] = member;
  10459. }
  10460. /**
  10461. * Handles a member leaving the MUC.
  10462. */
  10463. function onMucMemberLeft(jid) {
  10464. delete members[jid];
  10465. updateAtLeastOneDtmf();
  10466. }
  10467. /**
  10468. * Handles the reception of a disco#info packet from a particular JID.
  10469. * @param jid the JID sending the packet.
  10470. * @param iq the packet.
  10471. */
  10472. function onDiscoInfoReceived(jid, iq) {
  10473. if (!members[jid])
  10474. return;
  10475. var supportsDtmf
  10476. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10477. updateDtmf(jid, supportsDtmf);
  10478. }
  10479. /**
  10480. * Updates the 'supportsDtmf' field for a member.
  10481. * @param jid the jid of the member.
  10482. * @param newValue the new value for the 'supportsDtmf' field.
  10483. */
  10484. function updateDtmf(jid, newValue) {
  10485. var oldValue = members[jid].supportsDtmf;
  10486. members[jid].supportsDtmf = newValue;
  10487. if (newValue != oldValue) {
  10488. updateAtLeastOneDtmf();
  10489. }
  10490. }
  10491. /**
  10492. * Checks each member's 'supportsDtmf' field and updates
  10493. * 'atLastOneSupportsDtmf'.
  10494. */
  10495. function updateAtLeastOneDtmf() {
  10496. var newAtLeastOneDtmf = false;
  10497. for (var key in members) {
  10498. if (typeof members[key].supportsDtmf !== 'undefined'
  10499. && members[key].supportsDtmf) {
  10500. newAtLeastOneDtmf= true;
  10501. break;
  10502. }
  10503. }
  10504. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10505. atLeastOneDtmf = newAtLeastOneDtmf;
  10506. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10507. }
  10508. }
  10509. /**
  10510. * Exported interface.
  10511. */
  10512. var Members = {
  10513. start: function() {
  10514. registerListeners();
  10515. },
  10516. addListener: function(type, listener) {
  10517. eventEmitter.on(type, listener);
  10518. },
  10519. removeListener: function (type, listener) {
  10520. eventEmitter.removeListener(type, listener);
  10521. },
  10522. size: function () {
  10523. return Object.keys(members).length;
  10524. },
  10525. getMembers: function () {
  10526. return members;
  10527. }
  10528. };
  10529. module.exports = Members;
  10530. },{"../../service/members/Events":170,"../../service/xmpp/XMPPEvents":172,"events":173}],49:[function(require,module,exports){
  10531. var email = '';
  10532. var displayName = '';
  10533. var userId;
  10534. var language = null;
  10535. function supportsLocalStorage() {
  10536. try {
  10537. return 'localStorage' in window && window.localStorage !== null;
  10538. } catch (e) {
  10539. console.log("localstorage is not supported");
  10540. return false;
  10541. }
  10542. }
  10543. function generateUniqueId() {
  10544. function _p8() {
  10545. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10546. }
  10547. return _p8() + _p8() + _p8() + _p8();
  10548. }
  10549. if (supportsLocalStorage()) {
  10550. if (!window.localStorage.jitsiMeetId) {
  10551. window.localStorage.jitsiMeetId = generateUniqueId();
  10552. console.log("generated id", window.localStorage.jitsiMeetId);
  10553. }
  10554. userId = window.localStorage.jitsiMeetId || '';
  10555. email = window.localStorage.email || '';
  10556. displayName = window.localStorage.displayname || '';
  10557. language = window.localStorage.language;
  10558. } else {
  10559. console.log("local storage is not supported");
  10560. userId = generateUniqueId();
  10561. }
  10562. var Settings = {
  10563. setDisplayName: function (newDisplayName) {
  10564. displayName = newDisplayName;
  10565. window.localStorage.displayname = displayName;
  10566. return displayName;
  10567. },
  10568. setEmail: function (newEmail) {
  10569. email = newEmail;
  10570. window.localStorage.email = newEmail;
  10571. return email;
  10572. },
  10573. getSettings: function () {
  10574. return {
  10575. email: email,
  10576. displayName: displayName,
  10577. uid: userId,
  10578. language: language
  10579. };
  10580. },
  10581. setLanguage: function (lang) {
  10582. language = lang;
  10583. window.localStorage.language = lang;
  10584. }
  10585. };
  10586. module.exports = Settings;
  10587. },{}],50:[function(require,module,exports){
  10588. /* global config, $, APP, Strophe, callstats */
  10589. var jsSHA = require('jssha');
  10590. var io = require('socket.io-client');
  10591. var callStats = null;
  10592. function initCallback (err, msg) {
  10593. console.log("Initializing Status: err="+err+" msg="+msg);
  10594. }
  10595. var CallStats = {
  10596. init: function (jingleSession) {
  10597. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10598. return;
  10599. callStats = new callstats($, io, jsSHA);
  10600. this.session = jingleSession;
  10601. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10602. this.userID = APP.xmpp.myResource();
  10603. var location = window.location;
  10604. this.confID = location.hostname + location.pathname;
  10605. //userID is generated or given by the origin server
  10606. callStats.initialize(config.callStatsID,
  10607. config.callStatsSecret,
  10608. this.userID,
  10609. initCallback);
  10610. var usage = callStats.fabricUsage.multiplex;
  10611. callStats.addNewFabric(this.peerconnection,
  10612. Strophe.getResourceFromJid(jingleSession.peerjid),
  10613. usage,
  10614. this.confID,
  10615. this.pcCallback.bind(this));
  10616. },
  10617. pcCallback: function (err, msg) {
  10618. if (!callStats)
  10619. return;
  10620. console.log("Monitoring status: "+ err + " msg: " + msg);
  10621. callStats.sendFabricEvent(this.peerconnection,
  10622. callStats.fabricEvent.fabricSetup, this.confID);
  10623. },
  10624. sendMuteEvent: function (mute, type) {
  10625. if (!callStats)
  10626. return;
  10627. var event = null;
  10628. if (type === "video") {
  10629. event = (mute? callStats.fabricEvent.videoPause :
  10630. callStats.fabricEvent.videoResume);
  10631. }
  10632. else {
  10633. event = (mute? callStats.fabricEvent.audioMute :
  10634. callStats.fabricEvent.audioUnmute);
  10635. }
  10636. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10637. },
  10638. sendTerminateEvent: function () {
  10639. if(!callStats) {
  10640. return;
  10641. }
  10642. callStats.sendFabricEvent(this.peerconnection,
  10643. callStats.fabricEvent.fabricTerminated, this.confID);
  10644. },
  10645. sendSetupFailedEvent: function () {
  10646. if(!callStats) {
  10647. return;
  10648. }
  10649. callStats.sendFabricEvent(this.peerconnection,
  10650. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10651. }
  10652. };
  10653. module.exports = CallStats;
  10654. },{"jssha":74,"socket.io-client":112}],51:[function(require,module,exports){
  10655. /* global config */
  10656. /**
  10657. * Provides statistics for the local stream.
  10658. */
  10659. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10660. /**
  10661. * Size of the webaudio analyzer buffer.
  10662. * @type {number}
  10663. */
  10664. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10665. /**
  10666. * Value of the webaudio analyzer smoothing time parameter.
  10667. * @type {number}
  10668. */
  10669. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10670. /**
  10671. * Converts time domain data array to audio level.
  10672. * @param samples the time domain data array.
  10673. * @returns {number} the audio level
  10674. */
  10675. function timeDomainDataToAudioLevel(samples) {
  10676. var maxVolume = 0;
  10677. var length = samples.length;
  10678. for (var i = 0; i < length; i++) {
  10679. if (maxVolume < samples[i])
  10680. maxVolume = samples[i];
  10681. }
  10682. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10683. }
  10684. /**
  10685. * Animates audio level change
  10686. * @param newLevel the new audio level
  10687. * @param lastLevel the last audio level
  10688. * @returns {Number} the audio level to be set
  10689. */
  10690. function animateLevel(newLevel, lastLevel) {
  10691. var value = 0;
  10692. var diff = lastLevel - newLevel;
  10693. if(diff > 0.2) {
  10694. value = lastLevel - 0.2;
  10695. }
  10696. else if(diff < -0.4) {
  10697. value = lastLevel + 0.4;
  10698. }
  10699. else {
  10700. value = newLevel;
  10701. }
  10702. return parseFloat(value.toFixed(3));
  10703. }
  10704. /**
  10705. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10706. *
  10707. * @param stream the local stream
  10708. * @param interval stats refresh interval given in ms.
  10709. * @constructor
  10710. */
  10711. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10712. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10713. this.stream = stream;
  10714. this.intervalId = null;
  10715. this.intervalMilis = interval;
  10716. this.eventEmitter = eventEmitter;
  10717. this.audioLevel = 0;
  10718. this.statisticsService = statisticsService;
  10719. }
  10720. /**
  10721. * Starts the collecting the statistics.
  10722. */
  10723. LocalStatsCollector.prototype.start = function () {
  10724. if (config.disableAudioLevels || !window.AudioContext ||
  10725. RTCBrowserType.isTemasysPluginUsed())
  10726. return;
  10727. var context = new AudioContext();
  10728. var analyser = context.createAnalyser();
  10729. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10730. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10731. var source = context.createMediaStreamSource(this.stream);
  10732. source.connect(analyser);
  10733. var self = this;
  10734. this.intervalId = setInterval(
  10735. function () {
  10736. var array = new Uint8Array(analyser.frequencyBinCount);
  10737. analyser.getByteTimeDomainData(array);
  10738. var audioLevel = timeDomainDataToAudioLevel(array);
  10739. if (audioLevel != self.audioLevel) {
  10740. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10741. self.eventEmitter.emit(
  10742. "statistics.audioLevel",
  10743. self.statisticsService.LOCAL_JID,
  10744. self.audioLevel);
  10745. }
  10746. },
  10747. this.intervalMilis
  10748. );
  10749. };
  10750. /**
  10751. * Stops collecting the statistics.
  10752. */
  10753. LocalStatsCollector.prototype.stop = function () {
  10754. if (this.intervalId) {
  10755. clearInterval(this.intervalId);
  10756. this.intervalId = null;
  10757. }
  10758. };
  10759. module.exports = LocalStatsCollector;
  10760. },{"../RTC/RTCBrowserType":8}],52:[function(require,module,exports){
  10761. /* global require, ssrc2jid */
  10762. /* jshint -W117 */
  10763. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10764. /* Whether we support the browser we are running into for logging statistics */
  10765. var browserSupported = RTCBrowserType.isChrome() ||
  10766. RTCBrowserType.isOpera() || RTCBrowserType.isFirefox();
  10767. /**
  10768. * Calculates packet lost percent using the number of lost packets and the
  10769. * number of all packet.
  10770. * @param lostPackets the number of lost packets
  10771. * @param totalPackets the number of all packets.
  10772. * @returns {number} packet loss percent
  10773. */
  10774. function calculatePacketLoss(lostPackets, totalPackets) {
  10775. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10776. return 0;
  10777. return Math.round((lostPackets/totalPackets)*100);
  10778. }
  10779. function getStatValue(item, name) {
  10780. var browserType = RTCBrowserType.getBrowserType();
  10781. if (!keyMap[browserType][name])
  10782. throw "The property isn't supported!";
  10783. var key = keyMap[browserType][name];
  10784. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10785. item.stat(key) : item[key];
  10786. }
  10787. /**
  10788. * Peer statistics data holder.
  10789. * @constructor
  10790. */
  10791. function PeerStats()
  10792. {
  10793. this.ssrc2Loss = {};
  10794. this.ssrc2AudioLevel = {};
  10795. this.ssrc2bitrate = {};
  10796. this.ssrc2resolution = {};
  10797. }
  10798. /**
  10799. * The bandwidth
  10800. * @type {{}}
  10801. */
  10802. PeerStats.bandwidth = {};
  10803. /**
  10804. * The bit rate
  10805. * @type {{}}
  10806. */
  10807. PeerStats.bitrate = {};
  10808. /**
  10809. * The packet loss rate
  10810. * @type {{}}
  10811. */
  10812. PeerStats.packetLoss = null;
  10813. /**
  10814. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10815. * represented by this instance.
  10816. * @param ssrc audio or video RTP stream SSRC.
  10817. * @param lossRate new packet loss rate value to be set.
  10818. */
  10819. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10820. {
  10821. this.ssrc2Loss[ssrc] = lossRate;
  10822. };
  10823. /**
  10824. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10825. * represented by this instance.
  10826. * @param ssrc audio or video RTP stream SSRC.
  10827. * @param resolution new resolution value to be set.
  10828. */
  10829. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10830. {
  10831. if(resolution === null && this.ssrc2resolution[ssrc])
  10832. {
  10833. delete this.ssrc2resolution[ssrc];
  10834. }
  10835. else if(resolution !== null)
  10836. this.ssrc2resolution[ssrc] = resolution;
  10837. };
  10838. /**
  10839. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10840. * represented by this instance.
  10841. * @param ssrc audio or video RTP stream SSRC.
  10842. * @param bitrate new bitrate value to be set.
  10843. */
  10844. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10845. {
  10846. if(this.ssrc2bitrate[ssrc])
  10847. {
  10848. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10849. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10850. }
  10851. else {
  10852. this.ssrc2bitrate[ssrc] = bitrate;
  10853. }
  10854. };
  10855. /**
  10856. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10857. * the stream which belongs to the peer represented by this instance.
  10858. * @param ssrc RTP stream SSRC for which current audio level value will be
  10859. * updated.
  10860. * @param audioLevel the new audio level value to be set. Value is truncated to
  10861. * fit the range from 0 to 1.
  10862. */
  10863. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10864. {
  10865. // Range limit 0 - 1
  10866. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10867. };
  10868. function formatAudioLevel(audioLevel) {
  10869. return Math.min(Math.max(audioLevel, 0), 1);
  10870. }
  10871. /**
  10872. * Array with the transport information.
  10873. * @type {Array}
  10874. */
  10875. PeerStats.transport = [];
  10876. /**
  10877. * <tt>StatsCollector</tt> registers for stats updates of given
  10878. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10879. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10880. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10881. * instance as an event source.
  10882. *
  10883. * @param peerconnection webRTC peer connection object.
  10884. * @param interval stats refresh interval given in ms.
  10885. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10886. * called on stats update.
  10887. * @constructor
  10888. */
  10889. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10890. {
  10891. this.peerconnection = peerconnection;
  10892. this.baselineAudioLevelsReport = null;
  10893. this.currentAudioLevelsReport = null;
  10894. this.currentStatsReport = null;
  10895. this.baselineStatsReport = null;
  10896. this.audioLevelsIntervalId = null;
  10897. this.eventEmitter = eventEmitter;
  10898. /**
  10899. * Gather PeerConnection stats once every this many milliseconds.
  10900. */
  10901. this.GATHER_INTERVAL = 15000;
  10902. /**
  10903. * Log stats via the focus once every this many milliseconds.
  10904. */
  10905. this.LOG_INTERVAL = 60000;
  10906. /**
  10907. * Gather stats and store them in this.statsToBeLogged.
  10908. */
  10909. this.gatherStatsIntervalId = null;
  10910. /**
  10911. * Send the stats already saved in this.statsToBeLogged to be logged via
  10912. * the focus.
  10913. */
  10914. this.logStatsIntervalId = null;
  10915. /**
  10916. * Stores the statistics which will be send to the focus to be logged.
  10917. */
  10918. this.statsToBeLogged =
  10919. {
  10920. timestamps: [],
  10921. stats: {}
  10922. };
  10923. // Updates stats interval
  10924. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10925. this.statsIntervalId = null;
  10926. this.statsIntervalMilis = statsInterval;
  10927. // Map of jids to PeerStats
  10928. this.jid2stats = {};
  10929. }
  10930. module.exports = StatsCollector;
  10931. /**
  10932. * Stops stats updates.
  10933. */
  10934. StatsCollector.prototype.stop = function () {
  10935. if (this.audioLevelsIntervalId) {
  10936. clearInterval(this.audioLevelsIntervalId);
  10937. this.audioLevelsIntervalId = null;
  10938. }
  10939. if (this.statsIntervalId)
  10940. {
  10941. clearInterval(this.statsIntervalId);
  10942. this.statsIntervalId = null;
  10943. }
  10944. if(this.logStatsIntervalId)
  10945. {
  10946. clearInterval(this.logStatsIntervalId);
  10947. this.logStatsIntervalId = null;
  10948. }
  10949. if(this.gatherStatsIntervalId)
  10950. {
  10951. clearInterval(this.gatherStatsIntervalId);
  10952. this.gatherStatsIntervalId = null;
  10953. }
  10954. };
  10955. /**
  10956. * Callback passed to <tt>getStats</tt> method.
  10957. * @param error an error that occurred on <tt>getStats</tt> call.
  10958. */
  10959. StatsCollector.prototype.errorCallback = function (error)
  10960. {
  10961. console.error("Get stats error", error);
  10962. this.stop();
  10963. };
  10964. /**
  10965. * Starts stats updates.
  10966. */
  10967. StatsCollector.prototype.start = function ()
  10968. {
  10969. var self = this;
  10970. if (!config.disableAudioLevels) {
  10971. this.audioLevelsIntervalId = setInterval(
  10972. function () {
  10973. // Interval updates
  10974. self.peerconnection.getStats(
  10975. function (report) {
  10976. var results = null;
  10977. if (!report || !report.result ||
  10978. typeof report.result != 'function') {
  10979. results = report;
  10980. }
  10981. else {
  10982. results = report.result();
  10983. }
  10984. //console.error("Got interval report", results);
  10985. self.currentAudioLevelsReport = results;
  10986. self.processAudioLevelReport();
  10987. self.baselineAudioLevelsReport =
  10988. self.currentAudioLevelsReport;
  10989. },
  10990. self.errorCallback
  10991. );
  10992. },
  10993. self.audioLevelsIntervalMilis
  10994. );
  10995. }
  10996. if (!config.disableStats && browserSupported) {
  10997. this.statsIntervalId = setInterval(
  10998. function () {
  10999. // Interval updates
  11000. self.peerconnection.getStats(
  11001. function (report) {
  11002. var results = null;
  11003. if (!report || !report.result ||
  11004. typeof report.result != 'function') {
  11005. //firefox
  11006. results = report;
  11007. }
  11008. else {
  11009. //chrome
  11010. results = report.result();
  11011. }
  11012. //console.error("Got interval report", results);
  11013. self.currentStatsReport = results;
  11014. try {
  11015. self.processStatsReport();
  11016. }
  11017. catch (e) {
  11018. console.error("Unsupported key:" + e, e);
  11019. }
  11020. self.baselineStatsReport = self.currentStatsReport;
  11021. },
  11022. self.errorCallback
  11023. );
  11024. },
  11025. self.statsIntervalMilis
  11026. );
  11027. }
  11028. // Logging statistics does not support firefox
  11029. if (config.logStats && (browserSupported && !RTCBrowserType.isFirefox())) {
  11030. this.gatherStatsIntervalId = setInterval(
  11031. function () {
  11032. self.peerconnection.getStats(
  11033. function (report) {
  11034. self.addStatsToBeLogged(report.result());
  11035. },
  11036. function () {
  11037. }
  11038. );
  11039. },
  11040. this.GATHER_INTERVAL
  11041. );
  11042. this.logStatsIntervalId = setInterval(
  11043. function() { self.logStats(); },
  11044. this.LOG_INTERVAL);
  11045. }
  11046. };
  11047. /**
  11048. * Checks whether a certain record should be included in the logged statistics.
  11049. */
  11050. function acceptStat(reportId, reportType, statName) {
  11051. if (reportType == "googCandidatePair" && statName == "googChannelId")
  11052. return false;
  11053. if (reportType == "ssrc") {
  11054. if (statName == "googTrackId" ||
  11055. statName == "transportId" ||
  11056. statName == "ssrc")
  11057. return false;
  11058. }
  11059. return true;
  11060. }
  11061. /**
  11062. * Checks whether a certain record should be included in the logged statistics.
  11063. */
  11064. function acceptReport(id, type) {
  11065. if (id.substring(0, 15) == "googCertificate" ||
  11066. id.substring(0, 9) == "googTrack" ||
  11067. id.substring(0, 20) == "googLibjingleSession")
  11068. return false;
  11069. if (type == "googComponent")
  11070. return false;
  11071. return true;
  11072. }
  11073. /**
  11074. * Converts the stats to the format used for logging, and saves the data in
  11075. * this.statsToBeLogged.
  11076. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11077. */
  11078. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11079. var self = this;
  11080. var num_records = this.statsToBeLogged.timestamps.length;
  11081. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11082. reports.map(function (report) {
  11083. if (!acceptReport(report.id, report.type))
  11084. return;
  11085. var stat = self.statsToBeLogged.stats[report.id];
  11086. if (!stat) {
  11087. stat = self.statsToBeLogged.stats[report.id] = {};
  11088. }
  11089. stat.type = report.type;
  11090. report.names().map(function (name) {
  11091. if (!acceptStat(report.id, report.type, name))
  11092. return;
  11093. var values = stat[name];
  11094. if (!values) {
  11095. values = stat[name] = [];
  11096. }
  11097. while (values.length < num_records) {
  11098. values.push(null);
  11099. }
  11100. values.push(report.stat(name));
  11101. });
  11102. });
  11103. };
  11104. StatsCollector.prototype.logStats = function () {
  11105. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11106. return;
  11107. // Reset the stats
  11108. this.statsToBeLogged.stats = {};
  11109. this.statsToBeLogged.timestamps = [];
  11110. };
  11111. var keyMap = {};
  11112. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11113. "ssrc": "ssrc",
  11114. "packetsReceived": "packetsReceived",
  11115. "packetsLost": "packetsLost",
  11116. "packetsSent": "packetsSent",
  11117. "bytesReceived": "bytesReceived",
  11118. "bytesSent": "bytesSent"
  11119. };
  11120. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11121. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11122. "sendBandwidth": "googAvailableSendBandwidth",
  11123. "remoteAddress": "googRemoteAddress",
  11124. "transportType": "googTransportType",
  11125. "localAddress": "googLocalAddress",
  11126. "activeConnection": "googActiveConnection",
  11127. "ssrc": "ssrc",
  11128. "packetsReceived": "packetsReceived",
  11129. "packetsSent": "packetsSent",
  11130. "packetsLost": "packetsLost",
  11131. "bytesReceived": "bytesReceived",
  11132. "bytesSent": "bytesSent",
  11133. "googFrameHeightReceived": "googFrameHeightReceived",
  11134. "googFrameWidthReceived": "googFrameWidthReceived",
  11135. "googFrameHeightSent": "googFrameHeightSent",
  11136. "googFrameWidthSent": "googFrameWidthSent",
  11137. "audioInputLevel": "audioInputLevel",
  11138. "audioOutputLevel": "audioOutputLevel"
  11139. };
  11140. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11141. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11142. /**
  11143. * Stats processing logic.
  11144. */
  11145. StatsCollector.prototype.processStatsReport = function () {
  11146. if (!this.baselineStatsReport) {
  11147. return;
  11148. }
  11149. for (var idx in this.currentStatsReport) {
  11150. var now = this.currentStatsReport[idx];
  11151. try {
  11152. if (getStatValue(now, 'receiveBandwidth') ||
  11153. getStatValue(now, 'sendBandwidth')) {
  11154. PeerStats.bandwidth = {
  11155. "download": Math.round(
  11156. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11157. "upload": Math.round(
  11158. (getStatValue(now, 'sendBandwidth')) / 1000)
  11159. };
  11160. }
  11161. }
  11162. catch(e){/*not supported*/}
  11163. if(now.type == 'googCandidatePair')
  11164. {
  11165. var ip, type, localIP, active;
  11166. try {
  11167. ip = getStatValue(now, 'remoteAddress');
  11168. type = getStatValue(now, "transportType");
  11169. localIP = getStatValue(now, "localAddress");
  11170. active = getStatValue(now, "activeConnection");
  11171. }
  11172. catch(e){/*not supported*/}
  11173. if(!ip || !type || !localIP || active != "true")
  11174. continue;
  11175. var addressSaved = false;
  11176. for(var i = 0; i < PeerStats.transport.length; i++)
  11177. {
  11178. if(PeerStats.transport[i].ip == ip &&
  11179. PeerStats.transport[i].type == type &&
  11180. PeerStats.transport[i].localip == localIP)
  11181. {
  11182. addressSaved = true;
  11183. }
  11184. }
  11185. if(addressSaved)
  11186. continue;
  11187. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11188. continue;
  11189. }
  11190. if(now.type == "candidatepair")
  11191. {
  11192. if(now.state == "succeeded")
  11193. continue;
  11194. var local = this.currentStatsReport[now.localCandidateId];
  11195. var remote = this.currentStatsReport[now.remoteCandidateId];
  11196. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11197. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11198. }
  11199. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11200. now.type != "inboundrtp") {
  11201. continue;
  11202. }
  11203. var before = this.baselineStatsReport[idx];
  11204. if (!before) {
  11205. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11206. continue;
  11207. }
  11208. var ssrc = getStatValue(now, 'ssrc');
  11209. if(!ssrc)
  11210. continue;
  11211. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11212. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11213. console.warn("No jid for ssrc: " + ssrc);
  11214. continue;
  11215. }
  11216. var jidStats = this.jid2stats[jid];
  11217. if (!jidStats) {
  11218. jidStats = new PeerStats();
  11219. this.jid2stats[jid] = jidStats;
  11220. }
  11221. var isDownloadStream = true;
  11222. var key = 'packetsReceived';
  11223. var packetsNow = getStatValue(now, key);
  11224. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  11225. isDownloadStream = false;
  11226. key = 'packetsSent';
  11227. packetsNow = getStatValue(now, key);
  11228. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  11229. console.warn("No packetsReceived nor packetsSent stat found");
  11230. continue;
  11231. }
  11232. }
  11233. if (!packetsNow || packetsNow < 0)
  11234. packetsNow = 0;
  11235. var packetsBefore = getStatValue(before, key);
  11236. if (!packetsBefore || packetsBefore < 0)
  11237. packetsBefore = 0;
  11238. var packetRate = packetsNow - packetsBefore;
  11239. if (!packetRate || packetRate < 0)
  11240. packetRate = 0;
  11241. var currentLoss = getStatValue(now, 'packetsLost');
  11242. if (!currentLoss || currentLoss < 0)
  11243. currentLoss = 0;
  11244. var previousLoss = getStatValue(before, 'packetsLost');
  11245. if (!previousLoss || previousLoss < 0)
  11246. previousLoss = 0;
  11247. var lossRate = currentLoss - previousLoss;
  11248. if (!lossRate || lossRate < 0)
  11249. lossRate = 0;
  11250. var packetsTotal = (packetRate + lossRate);
  11251. jidStats.setSsrcLoss(ssrc,
  11252. {"packetsTotal": packetsTotal,
  11253. "packetsLost": lossRate,
  11254. "isDownloadStream": isDownloadStream});
  11255. var bytesReceived = 0, bytesSent = 0;
  11256. if(getStatValue(now, "bytesReceived")) {
  11257. bytesReceived = getStatValue(now, "bytesReceived") -
  11258. getStatValue(before, "bytesReceived");
  11259. }
  11260. if(getStatValue(now, "bytesSent")) {
  11261. bytesSent = getStatValue(now, "bytesSent") -
  11262. getStatValue(before, "bytesSent");
  11263. }
  11264. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11265. if(bytesReceived <= 0 || time <= 0) {
  11266. bytesReceived = 0;
  11267. } else {
  11268. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11269. }
  11270. if(bytesSent <= 0 || time <= 0) {
  11271. bytesSent = 0;
  11272. } else {
  11273. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11274. }
  11275. jidStats.setSsrcBitrate(ssrc, {
  11276. "download": bytesReceived,
  11277. "upload": bytesSent});
  11278. var resolution = {height: null, width: null};
  11279. try {
  11280. if (getStatValue(now, "googFrameHeightReceived") &&
  11281. getStatValue(now, "googFrameWidthReceived")) {
  11282. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11283. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11284. }
  11285. else if (getStatValue(now, "googFrameHeightSent") &&
  11286. getStatValue(now, "googFrameWidthSent")) {
  11287. resolution.height = getStatValue(now, "googFrameHeightSent");
  11288. resolution.width = getStatValue(now, "googFrameWidthSent");
  11289. }
  11290. }
  11291. catch(e){/*not supported*/}
  11292. if(resolution.height && resolution.width) {
  11293. jidStats.setSsrcResolution(ssrc, resolution);
  11294. } else {
  11295. jidStats.setSsrcResolution(ssrc, null);
  11296. }
  11297. }
  11298. var self = this;
  11299. // Jid stats
  11300. var totalPackets = {download: 0, upload: 0};
  11301. var lostPackets = {download: 0, upload: 0};
  11302. var bitrateDownload = 0;
  11303. var bitrateUpload = 0;
  11304. var resolutions = {};
  11305. Object.keys(this.jid2stats).forEach(
  11306. function (jid) {
  11307. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11308. function (ssrc) {
  11309. var type = "upload";
  11310. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11311. type = "download";
  11312. totalPackets[type] +=
  11313. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11314. lostPackets[type] +=
  11315. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11316. }
  11317. );
  11318. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11319. function (ssrc) {
  11320. bitrateDownload +=
  11321. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11322. bitrateUpload +=
  11323. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11324. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11325. }
  11326. );
  11327. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11328. }
  11329. );
  11330. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11331. PeerStats.packetLoss = {
  11332. total:
  11333. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11334. totalPackets.download + totalPackets.upload),
  11335. download:
  11336. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11337. upload:
  11338. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11339. };
  11340. this.eventEmitter.emit("statistics.connectionstats",
  11341. {
  11342. "bitrate": PeerStats.bitrate,
  11343. "packetLoss": PeerStats.packetLoss,
  11344. "bandwidth": PeerStats.bandwidth,
  11345. "resolution": resolutions,
  11346. "transport": PeerStats.transport
  11347. });
  11348. PeerStats.transport = [];
  11349. };
  11350. /**
  11351. * Stats processing logic.
  11352. */
  11353. StatsCollector.prototype.processAudioLevelReport = function () {
  11354. if (!this.baselineAudioLevelsReport) {
  11355. return;
  11356. }
  11357. for (var idx in this.currentAudioLevelsReport) {
  11358. var now = this.currentAudioLevelsReport[idx];
  11359. if (now.type != 'ssrc') {
  11360. continue;
  11361. }
  11362. var before = this.baselineAudioLevelsReport[idx];
  11363. if (!before) {
  11364. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11365. continue;
  11366. }
  11367. var ssrc = getStatValue(now, 'ssrc');
  11368. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11369. if (!jid) {
  11370. if((Date.now() - now.timestamp) < 3000)
  11371. console.warn("No jid for ssrc: " + ssrc);
  11372. continue;
  11373. }
  11374. var jidStats = this.jid2stats[jid];
  11375. if (!jidStats) {
  11376. jidStats = new PeerStats();
  11377. this.jid2stats[jid] = jidStats;
  11378. }
  11379. // Audio level
  11380. var audioLevel = null;
  11381. try {
  11382. audioLevel = getStatValue(now, 'audioInputLevel');
  11383. if (!audioLevel)
  11384. audioLevel = getStatValue(now, 'audioOutputLevel');
  11385. }
  11386. catch(e) {/*not supported*/
  11387. console.warn("Audio Levels are not available in the statistics.");
  11388. clearInterval(this.audioLevelsIntervalId);
  11389. return;
  11390. }
  11391. if (audioLevel) {
  11392. // TODO: can't find specs about what this value really is,
  11393. // but it seems to vary between 0 and around 32k.
  11394. audioLevel = audioLevel / 32767;
  11395. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11396. if(jid != APP.xmpp.myJid())
  11397. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11398. }
  11399. }
  11400. };
  11401. },{"../RTC/RTCBrowserType":8}],53:[function(require,module,exports){
  11402. /* global require, APP */
  11403. /**
  11404. * Created by hristo on 8/4/14.
  11405. */
  11406. var LocalStats = require("./LocalStatsCollector.js");
  11407. var RTPStats = require("./RTPStatsCollector.js");
  11408. var EventEmitter = require("events");
  11409. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11410. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11411. var CallStats = require("./CallStats");
  11412. var RTCEvents = require("../../service/RTC/RTCEvents");
  11413. var eventEmitter = new EventEmitter();
  11414. var localStats = null;
  11415. var rtpStats = null;
  11416. function stopLocal() {
  11417. if (localStats) {
  11418. localStats.stop();
  11419. localStats = null;
  11420. }
  11421. }
  11422. function stopRemote() {
  11423. if (rtpStats) {
  11424. rtpStats.stop();
  11425. eventEmitter.emit("statistics.stop");
  11426. rtpStats = null;
  11427. }
  11428. }
  11429. function startRemoteStats (peerconnection) {
  11430. if (rtpStats) {
  11431. rtpStats.stop();
  11432. }
  11433. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11434. rtpStats.start();
  11435. }
  11436. function onStreamCreated(stream) {
  11437. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11438. return;
  11439. }
  11440. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11441. eventEmitter);
  11442. localStats.start();
  11443. }
  11444. function onDisposeConference(onUnload) {
  11445. CallStats.sendTerminateEvent();
  11446. stopRemote();
  11447. if(onUnload) {
  11448. stopLocal();
  11449. eventEmitter.removeAllListeners();
  11450. }
  11451. }
  11452. var statistics = {
  11453. /**
  11454. * Indicates that this audio level is for local jid.
  11455. * @type {string}
  11456. */
  11457. LOCAL_JID: 'local',
  11458. addAudioLevelListener: function(listener)
  11459. {
  11460. eventEmitter.on("statistics.audioLevel", listener);
  11461. },
  11462. removeAudioLevelListener: function(listener)
  11463. {
  11464. eventEmitter.removeListener("statistics.audioLevel", listener);
  11465. },
  11466. addConnectionStatsListener: function(listener)
  11467. {
  11468. eventEmitter.on("statistics.connectionstats", listener);
  11469. },
  11470. removeConnectionStatsListener: function(listener)
  11471. {
  11472. eventEmitter.removeListener("statistics.connectionstats", listener);
  11473. },
  11474. addRemoteStatsStopListener: function(listener)
  11475. {
  11476. eventEmitter.on("statistics.stop", listener);
  11477. },
  11478. removeRemoteStatsStopListener: function(listener)
  11479. {
  11480. eventEmitter.removeListener("statistics.stop", listener);
  11481. },
  11482. stop: function () {
  11483. stopLocal();
  11484. stopRemote();
  11485. if(eventEmitter)
  11486. {
  11487. eventEmitter.removeAllListeners();
  11488. }
  11489. },
  11490. stopRemoteStatistics: function()
  11491. {
  11492. stopRemote();
  11493. },
  11494. start: function () {
  11495. APP.RTC.addStreamListener(onStreamCreated,
  11496. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11497. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11498. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11499. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11500. startRemoteStats(event.peerconnection);
  11501. // CallStats.init(event);
  11502. });
  11503. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11504. CallStats.init(session);
  11505. });
  11506. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11507. CallStats.sendMuteEvent(mute, "audio");
  11508. });
  11509. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11510. CallStats.sendSetupFailedEvent();
  11511. });
  11512. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11513. CallStats.sendMuteEvent(mute, "video");
  11514. });
  11515. }
  11516. };
  11517. module.exports = statistics;
  11518. },{"../../service/RTC/RTCEvents":163,"../../service/RTC/StreamEventTypes.js":165,"../../service/xmpp/XMPPEvents":172,"./CallStats":50,"./LocalStatsCollector.js":51,"./RTPStatsCollector.js":52,"events":173}],54:[function(require,module,exports){
  11519. /* global $, require, config, interfaceConfig */
  11520. var i18n = require("i18next-client");
  11521. var languages = require("../../service/translation/languages");
  11522. var Settings = require("../settings/Settings");
  11523. var DEFAULT_LANG = languages.EN;
  11524. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11525. return value.replace("__app__", interfaceConfig.APP_NAME);
  11526. });
  11527. var defaultOptions = {
  11528. detectLngQS: "lang",
  11529. useCookie: false,
  11530. fallbackLng: DEFAULT_LANG,
  11531. load: "unspecific",
  11532. resGetPath: 'lang/__ns__-__lng__.json',
  11533. ns: {
  11534. namespaces: ['main', 'languages'],
  11535. defaultNs: 'main'
  11536. },
  11537. lngWhitelist : languages.getLanguages(),
  11538. fallbackOnNull: true,
  11539. fallbackOnEmpty: true,
  11540. useDataAttrOptions: true,
  11541. app: interfaceConfig.APP_NAME,
  11542. getAsync: false,
  11543. defaultValueFromContent: false,
  11544. customLoad: function(lng, ns, options, done) {
  11545. var resPath = "lang/__ns__-__lng__.json";
  11546. if(lng === languages.EN)
  11547. resPath = "lang/__ns__.json";
  11548. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11549. i18n.functions.ajax({
  11550. url: url,
  11551. success: function(data, status, xhr) {
  11552. i18n.functions.log('loaded: ' + url);
  11553. done(null, data);
  11554. },
  11555. error : function(xhr, status, error) {
  11556. if ((status && status == 200) ||
  11557. (xhr && xhr.status && xhr.status == 200)) {
  11558. // file loaded but invalid json, stop waste time !
  11559. i18n.functions.error('There is a typo in: ' + url);
  11560. } else if ((status && status == 404) ||
  11561. (xhr && xhr.status && xhr.status == 404)) {
  11562. i18n.functions.log('Does not exist: ' + url);
  11563. } else {
  11564. var theStatus = status ? status :
  11565. ((xhr && xhr.status) ? xhr.status : null);
  11566. i18n.functions.log(theStatus + ' when loading ' + url);
  11567. }
  11568. done(error, {});
  11569. },
  11570. dataType: "json",
  11571. async : options.getAsync
  11572. });
  11573. }
  11574. // options for caching
  11575. // useLocalStorage: true,
  11576. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11577. };
  11578. function initCompleted(t) {
  11579. $("[data-i18n]").i18n();
  11580. }
  11581. function checkForParameter() {
  11582. var query = window.location.search.substring(1);
  11583. var vars = query.split("&");
  11584. for (var i=0;i<vars.length;i++) {
  11585. var pair = vars[i].split("=");
  11586. if(pair[0] == "lang")
  11587. {
  11588. return pair[1];
  11589. }
  11590. }
  11591. return null;
  11592. }
  11593. module.exports = {
  11594. init: function (lang) {
  11595. var options = defaultOptions;
  11596. if(!lang)
  11597. {
  11598. lang = checkForParameter();
  11599. if(!lang)
  11600. {
  11601. var settings = Settings.getSettings();
  11602. if(settings)
  11603. lang = settings.language;
  11604. if(!lang && config.defaultLanguage)
  11605. {
  11606. lang = config.defaultLanguage;
  11607. }
  11608. }
  11609. }
  11610. if(lang) {
  11611. options.lng = lang;
  11612. }
  11613. i18n.init(options, initCompleted);
  11614. },
  11615. translateString: function (key, options) {
  11616. return i18n.t(key, options);
  11617. },
  11618. setLanguage: function (lang) {
  11619. if(!lang)
  11620. lang = DEFAULT_LANG;
  11621. i18n.setLng(lang, defaultOptions, initCompleted);
  11622. },
  11623. getCurrentLanguage: function () {
  11624. return i18n.lng();
  11625. },
  11626. translateElement: function (selector) {
  11627. selector.i18n();
  11628. },
  11629. generateTranslationHTML: function (key, options) {
  11630. var str = "<span data-i18n=\"" + key + "\"";
  11631. if(options)
  11632. {
  11633. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11634. }
  11635. str += ">";
  11636. str += this.translateString(key, options);
  11637. str += "</span>";
  11638. return str;
  11639. }
  11640. };
  11641. },{"../../service/translation/languages":171,"../settings/Settings":49,"i18next-client":73}],55:[function(require,module,exports){
  11642. /*
  11643. * JingleSession provides an API to manage a single Jingle session. We will
  11644. * have different implementations depending on the underlying interface used
  11645. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11646. */
  11647. function JingleSession(me, sid, connection, service, eventEmitter) {
  11648. /**
  11649. * Our JID.
  11650. */
  11651. this.me = me;
  11652. /**
  11653. * The Jingle session identifier.
  11654. */
  11655. this.sid = sid;
  11656. /**
  11657. * The XMPP connection.
  11658. */
  11659. this.connection = connection;
  11660. /**
  11661. * The XMPP service.
  11662. */
  11663. this.service = service;
  11664. /**
  11665. * The event emitter.
  11666. */
  11667. this.eventEmitter = eventEmitter;
  11668. /**
  11669. * Whether to use dripping or not. Dripping is sending trickle candidates
  11670. * not one-by-one.
  11671. * Note: currently we do not support 'false'.
  11672. */
  11673. this.usedrip = true;
  11674. /**
  11675. * When dripping is used, stores ICE candidates which are to be sent.
  11676. */
  11677. this.drip_container = [];
  11678. // Media constraints. Is this WebRTC only?
  11679. this.media_constraints = null;
  11680. // ICE servers config (RTCConfiguration?).
  11681. this.ice_config = {};
  11682. }
  11683. /**
  11684. * Prepares this object to initiate a session.
  11685. * @param peerjid the JID of the remote peer.
  11686. * @param isInitiator whether we will be the Jingle initiator.
  11687. * @param media_constraints
  11688. * @param ice_config
  11689. */
  11690. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11691. media_constraints, ice_config) {
  11692. this.media_constraints = media_constraints;
  11693. this.ice_config = ice_config;
  11694. if (this.state !== null) {
  11695. console.error('attempt to initiate on session ' + this.sid +
  11696. 'in state ' + this.state);
  11697. return;
  11698. }
  11699. this.state = 'pending';
  11700. this.initiator = isInitiator ? this.me : peerjid;
  11701. this.responder = !isInitiator ? this.me : peerjid;
  11702. this.peerjid = peerjid;
  11703. this.doInitialize();
  11704. };
  11705. /**
  11706. * Finishes initialization.
  11707. */
  11708. JingleSession.prototype.doInitialize = function() {};
  11709. /**
  11710. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11711. * Note: currently only used on transport-info
  11712. */
  11713. JingleSession.prototype.addIceCandidates = function(contents) {};
  11714. /**
  11715. * Handles an 'add-source' event.
  11716. *
  11717. * @param contents an array of Jingle 'content' elements.
  11718. */
  11719. JingleSession.prototype.addSources = function(contents) {};
  11720. /**
  11721. * Handles a 'remove-source' event.
  11722. *
  11723. * @param contents an array of Jingle 'content' elements.
  11724. */
  11725. JingleSession.prototype.removeSources = function(contents) {};
  11726. /**
  11727. * Terminates this Jingle session (stops sending media and closes the streams?)
  11728. */
  11729. JingleSession.prototype.terminate = function() {};
  11730. /**
  11731. * Sends a Jingle session-terminate message to the peer and terminates the
  11732. * session.
  11733. * @param reason
  11734. * @param text
  11735. */
  11736. JingleSession.prototype.sendTerminate = function(reason, text) {};
  11737. /**
  11738. * Handles an offer from the remote peer (prepares to accept a session).
  11739. * @param jingle the 'jingle' XML element.
  11740. */
  11741. JingleSession.prototype.setOffer = function(jingle) {};
  11742. /**
  11743. * Handles an answer from the remote peer (prepares to accept a session).
  11744. * @param jingle the 'jingle' XML element.
  11745. */
  11746. JingleSession.prototype.setAnswer = function(jingle) {};
  11747. module.exports = JingleSession;
  11748. },{}],56:[function(require,module,exports){
  11749. /* jshint -W117 */
  11750. var JingleSession = require("./JingleSession");
  11751. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11752. var SDPDiffer = require("./SDPDiffer");
  11753. var SDPUtil = require("./SDPUtil");
  11754. var SDP = require("./SDP");
  11755. var async = require("async");
  11756. var transform = require("sdp-transform");
  11757. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11758. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11759. var SSRCReplacement = require("./LocalSSRCReplacement");
  11760. // Jingle stuff
  11761. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  11762. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  11763. this.initiator = null;
  11764. this.responder = null;
  11765. this.peerjid = null;
  11766. this.state = null;
  11767. this.localSDP = null;
  11768. this.remoteSDP = null;
  11769. this.relayedStreams = [];
  11770. this.pc_constraints = null;
  11771. this.usetrickle = true;
  11772. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11773. this.hadstuncandidate = false;
  11774. this.hadturncandidate = false;
  11775. this.lasticecandidate = false;
  11776. this.statsinterval = null;
  11777. this.reason = null;
  11778. this.addssrc = [];
  11779. this.removessrc = [];
  11780. this.pendingop = null;
  11781. this.switchstreams = false;
  11782. this.wait = true;
  11783. this.localStreamsSSRC = null;
  11784. this.ssrcOwners = {};
  11785. this.ssrcVideoTypes = {};
  11786. this.eventEmitter = eventEmitter;
  11787. /**
  11788. * The indicator which determines whether the (local) video has been muted
  11789. * in response to a user command in contrast to an automatic decision made
  11790. * by the application logic.
  11791. */
  11792. this.videoMuteByUser = false;
  11793. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11794. // We start with the queue paused. We resume it when the signaling state is
  11795. // stable and the ice connection state is connected.
  11796. this.modifySourcesQueue.pause();
  11797. }
  11798. JingleSessionPC.prototype = JingleSession.prototype;
  11799. JingleSessionPC.prototype.constructor = JingleSessionPC;
  11800. JingleSessionPC.prototype.setOffer = function(offer) {
  11801. this.setRemoteDescription(offer, 'offer');
  11802. };
  11803. JingleSessionPC.prototype.setAnswer = function(answer) {
  11804. this.setRemoteDescription(answer, 'answer');
  11805. };
  11806. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  11807. var signalingState = this.peerconnection.signalingState;
  11808. var iceConnectionState = this.peerconnection.iceConnectionState;
  11809. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11810. this.modifySourcesQueue.resume();
  11811. } else {
  11812. this.modifySourcesQueue.pause();
  11813. }
  11814. };
  11815. JingleSessionPC.prototype.doInitialize = function () {
  11816. var self = this;
  11817. this.hadstuncandidate = false;
  11818. this.hadturncandidate = false;
  11819. this.lasticecandidate = false;
  11820. // True if reconnect is in progress
  11821. this.isreconnect = false;
  11822. // Set to true if the connection was ever stable
  11823. this.wasstable = false;
  11824. this.peerconnection = new TraceablePeerConnection(
  11825. this.connection.jingle.ice_config,
  11826. this.connection.jingle.pc_constraints,
  11827. this);
  11828. this.peerconnection.onicecandidate = function (event) {
  11829. self.sendIceCandidate(event.candidate);
  11830. };
  11831. this.peerconnection.onaddstream = function (event) {
  11832. if (event.stream.id !== 'default') {
  11833. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11834. self.remoteStreamAdded(event);
  11835. } else {
  11836. // This is a recvonly stream. Clients that implement Unified Plan,
  11837. // such as Firefox use recvonly "streams/channels/tracks" for
  11838. // receiving remote stream/tracks, as opposed to Plan B where there
  11839. // are only 3 channels: audio, video and data.
  11840. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11841. }
  11842. };
  11843. this.peerconnection.onremovestream = function (event) {
  11844. // Remove the stream from remoteStreams
  11845. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11846. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11847. };
  11848. this.peerconnection.onsignalingstatechange = function (event) {
  11849. if (!(self && self.peerconnection)) return;
  11850. console.info("Signaling: " + this.peerconnection.signalingState);
  11851. if (self.peerconnection.signalingState === 'stable') {
  11852. self.wasstable = true;
  11853. }
  11854. self.updateModifySourcesQueue();
  11855. };
  11856. /**
  11857. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  11858. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  11859. * RTCPeerConnection.iceConnectionState changes.
  11860. *
  11861. * @param event the event containing information about the change
  11862. */
  11863. this.peerconnection.oniceconnectionstatechange = function (event) {
  11864. if (!(self && self.peerconnection)) return;
  11865. console.info("Ice: " + self.peerconnection.iceConnectionState);
  11866. self.updateModifySourcesQueue();
  11867. switch (self.peerconnection.iceConnectionState) {
  11868. case 'connected':
  11869. // Informs interested parties that the connection has been restored.
  11870. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  11871. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  11872. self.isreconnect = false;
  11873. break;
  11874. case 'disconnected':
  11875. self.isreconnect = true;
  11876. // Informs interested parties that the connection has been interrupted.
  11877. if (self.wasstable)
  11878. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  11879. break;
  11880. case 'failed':
  11881. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11882. break;
  11883. }
  11884. onIceConnectionStateChange(self.sid, self);
  11885. };
  11886. this.peerconnection.onnegotiationneeded = function (event) {
  11887. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11888. };
  11889. // add any local and relayed stream
  11890. APP.RTC.localStreams.forEach(function(stream) {
  11891. self.peerconnection.addStream(stream.getOriginalStream());
  11892. });
  11893. this.relayedStreams.forEach(function(stream) {
  11894. self.peerconnection.addStream(stream);
  11895. });
  11896. };
  11897. function onIceConnectionStateChange(sid, session) {
  11898. switch (session.peerconnection.iceConnectionState) {
  11899. case 'checking':
  11900. session.timeChecking = (new Date()).getTime();
  11901. session.firstconnect = true;
  11902. break;
  11903. case 'completed': // on caller side
  11904. case 'connected':
  11905. if (session.firstconnect) {
  11906. session.firstconnect = false;
  11907. var metadata = {};
  11908. metadata.setupTime
  11909. = (new Date()).getTime() - session.timeChecking;
  11910. session.peerconnection.getStats(function (res) {
  11911. if(res && res.result) {
  11912. res.result().forEach(function (report) {
  11913. if (report.type == 'googCandidatePair' &&
  11914. report.stat('googActiveConnection') == 'true') {
  11915. metadata.localCandidateType
  11916. = report.stat('googLocalCandidateType');
  11917. metadata.remoteCandidateType
  11918. = report.stat('googRemoteCandidateType');
  11919. // log pair as well so we can get nice pie
  11920. // charts
  11921. metadata.candidatePair
  11922. = report.stat('googLocalCandidateType') +
  11923. ';' +
  11924. report.stat('googRemoteCandidateType');
  11925. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11926. {
  11927. metadata.ipv6 = true;
  11928. }
  11929. }
  11930. });
  11931. }
  11932. });
  11933. }
  11934. break;
  11935. }
  11936. }
  11937. JingleSessionPC.prototype.accept = function () {
  11938. this.state = 'active';
  11939. var pranswer = this.peerconnection.localDescription;
  11940. if (!pranswer || pranswer.type != 'pranswer') {
  11941. return;
  11942. }
  11943. console.log('going from pranswer to answer');
  11944. if (this.usetrickle) {
  11945. // remove candidates already sent from session-accept
  11946. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11947. for (var i = 0; i < lines.length; i++) {
  11948. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11949. }
  11950. }
  11951. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11952. // FIXME: change any inactive to sendrecv or whatever they were originally
  11953. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11954. }
  11955. var prsdp = new SDP(pranswer.sdp);
  11956. var accept = $iq({to: this.peerjid,
  11957. type: 'set'})
  11958. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11959. action: 'session-accept',
  11960. initiator: this.initiator,
  11961. responder: this.responder,
  11962. sid: this.sid });
  11963. // FIXME why do we generate session-accept in 3 different places ?
  11964. prsdp.toJingle(
  11965. accept,
  11966. this.initiator == this.me ? 'initiator' : 'responder',
  11967. this.localStreamsSSRC);
  11968. var sdp = this.peerconnection.localDescription.sdp;
  11969. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11970. // FIXME: change any inactive to sendrecv or whatever they were originally
  11971. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11972. }
  11973. var self = this;
  11974. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11975. function () {
  11976. //console.log('setLocalDescription success');
  11977. self.setLocalDescription();
  11978. SSRCReplacement.processSessionInit(accept);
  11979. self.connection.sendIQ(accept,
  11980. function () {
  11981. var ack = {};
  11982. ack.source = 'answer';
  11983. $(document).trigger('ack.jingle', [self.sid, ack]);
  11984. },
  11985. function (stanza) {
  11986. var error = ($(stanza).find('error').length) ? {
  11987. code: $(stanza).find('error').attr('code'),
  11988. reason: $(stanza).find('error :first')[0].tagName
  11989. }:{};
  11990. error.source = 'answer';
  11991. JingleSessionPC.onJingleError(self.sid, error);
  11992. },
  11993. 10000);
  11994. },
  11995. function (e) {
  11996. console.error('setLocalDescription failed', e);
  11997. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11998. }
  11999. );
  12000. };
  12001. JingleSessionPC.prototype.terminate = function (reason) {
  12002. this.state = 'ended';
  12003. this.reason = reason;
  12004. this.peerconnection.close();
  12005. if (this.statsinterval !== null) {
  12006. window.clearInterval(this.statsinterval);
  12007. this.statsinterval = null;
  12008. }
  12009. };
  12010. JingleSessionPC.prototype.active = function () {
  12011. return this.state == 'active';
  12012. };
  12013. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  12014. var self = this;
  12015. if (candidate && !this.lasticecandidate) {
  12016. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  12017. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  12018. if (!(ice && jcand)) {
  12019. console.error('failed to get ice && jcand');
  12020. return;
  12021. }
  12022. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12023. if (jcand.type === 'srflx') {
  12024. this.hadstuncandidate = true;
  12025. } else if (jcand.type === 'relay') {
  12026. this.hadturncandidate = true;
  12027. }
  12028. if (this.usetrickle) {
  12029. if (this.usedrip) {
  12030. if (this.drip_container.length === 0) {
  12031. // start 20ms callout
  12032. window.setTimeout(function () {
  12033. if (self.drip_container.length === 0) return;
  12034. self.sendIceCandidates(self.drip_container);
  12035. self.drip_container = [];
  12036. }, 20);
  12037. }
  12038. this.drip_container.push(candidate);
  12039. return;
  12040. } else {
  12041. self.sendIceCandidate([candidate]);
  12042. }
  12043. }
  12044. } else {
  12045. //console.log('sendIceCandidate: last candidate.');
  12046. if (!this.usetrickle) {
  12047. //console.log('should send full offer now...');
  12048. //FIXME why do we generate session-accept in 3 different places ?
  12049. var init = $iq({to: this.peerjid,
  12050. type: 'set'})
  12051. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12052. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  12053. initiator: this.initiator,
  12054. sid: this.sid});
  12055. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  12056. var sendJingle = function (ssrc) {
  12057. if(!ssrc)
  12058. ssrc = {};
  12059. self.localSDP.toJingle(
  12060. init,
  12061. self.initiator == self.me ? 'initiator' : 'responder',
  12062. ssrc);
  12063. SSRCReplacement.processSessionInit(init);
  12064. self.connection.sendIQ(init,
  12065. function () {
  12066. //console.log('session initiate ack');
  12067. var ack = {};
  12068. ack.source = 'offer';
  12069. $(document).trigger('ack.jingle', [self.sid, ack]);
  12070. },
  12071. function (stanza) {
  12072. self.state = 'error';
  12073. self.peerconnection.close();
  12074. var error = ($(stanza).find('error').length) ? {
  12075. code: $(stanza).find('error').attr('code'),
  12076. reason: $(stanza).find('error :first')[0].tagName,
  12077. }:{};
  12078. error.source = 'offer';
  12079. JingleSessionPC.onJingleError(self.sid, error);
  12080. },
  12081. 10000);
  12082. };
  12083. sendJingle();
  12084. }
  12085. this.lasticecandidate = true;
  12086. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12087. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12088. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12089. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12090. }
  12091. }
  12092. };
  12093. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  12094. console.log('sendIceCandidates', candidates);
  12095. var cand = $iq({to: this.peerjid, type: 'set'})
  12096. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12097. action: 'transport-info',
  12098. initiator: this.initiator,
  12099. sid: this.sid});
  12100. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12101. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12102. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12103. if (cands.length > 0) {
  12104. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12105. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12106. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12107. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12108. }).c('transport', ice);
  12109. for (var i = 0; i < cands.length; i++) {
  12110. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12111. }
  12112. // add fingerprint
  12113. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12114. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12115. tmp.required = true;
  12116. cand.c(
  12117. 'fingerprint',
  12118. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12119. .t(tmp.fingerprint);
  12120. delete tmp.fingerprint;
  12121. cand.attrs(tmp);
  12122. cand.up();
  12123. }
  12124. cand.up(); // transport
  12125. cand.up(); // content
  12126. }
  12127. }
  12128. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12129. //console.log('was this the last candidate', this.lasticecandidate);
  12130. this.connection.sendIQ(cand,
  12131. function () {
  12132. var ack = {};
  12133. ack.source = 'transportinfo';
  12134. $(document).trigger('ack.jingle', [this.sid, ack]);
  12135. },
  12136. function (stanza) {
  12137. var error = ($(stanza).find('error').length) ? {
  12138. code: $(stanza).find('error').attr('code'),
  12139. reason: $(stanza).find('error :first')[0].tagName,
  12140. }:{};
  12141. error.source = 'transportinfo';
  12142. JingleSessionPC.onJingleError(this.sid, error);
  12143. },
  12144. 10000);
  12145. };
  12146. JingleSessionPC.prototype.sendOffer = function () {
  12147. //console.log('sendOffer...');
  12148. var self = this;
  12149. this.peerconnection.createOffer(function (sdp) {
  12150. self.createdOffer(sdp);
  12151. },
  12152. function (e) {
  12153. console.error('createOffer failed', e);
  12154. },
  12155. this.media_constraints
  12156. );
  12157. };
  12158. // FIXME createdOffer is never used in jitsi-meet
  12159. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12160. //console.log('createdOffer', sdp);
  12161. var self = this;
  12162. this.localSDP = new SDP(sdp.sdp);
  12163. //this.localSDP.mangle();
  12164. var sendJingle = function () {
  12165. var init = $iq({to: this.peerjid,
  12166. type: 'set'})
  12167. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12168. action: 'session-initiate',
  12169. initiator: this.initiator,
  12170. sid: this.sid});
  12171. self.localSDP.toJingle(
  12172. init,
  12173. this.initiator == this.me ? 'initiator' : 'responder',
  12174. this.localStreamsSSRC);
  12175. SSRCReplacement.processSessionInit(init);
  12176. self.connection.sendIQ(init,
  12177. function () {
  12178. var ack = {};
  12179. ack.source = 'offer';
  12180. $(document).trigger('ack.jingle', [self.sid, ack]);
  12181. },
  12182. function (stanza) {
  12183. self.state = 'error';
  12184. self.peerconnection.close();
  12185. var error = ($(stanza).find('error').length) ? {
  12186. code: $(stanza).find('error').attr('code'),
  12187. reason: $(stanza).find('error :first')[0].tagName,
  12188. }:{};
  12189. error.source = 'offer';
  12190. JingleSessionPC.onJingleError(self.sid, error);
  12191. },
  12192. 10000);
  12193. }
  12194. sdp.sdp = this.localSDP.raw;
  12195. this.peerconnection.setLocalDescription(sdp,
  12196. function () {
  12197. if(self.usetrickle)
  12198. {
  12199. sendJingle();
  12200. }
  12201. self.setLocalDescription();
  12202. //console.log('setLocalDescription success');
  12203. },
  12204. function (e) {
  12205. console.error('setLocalDescription failed', e);
  12206. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12207. }
  12208. );
  12209. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12210. for (var i = 0; i < cands.length; i++) {
  12211. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12212. if (cand.type == 'srflx') {
  12213. this.hadstuncandidate = true;
  12214. } else if (cand.type == 'relay') {
  12215. this.hadturncandidate = true;
  12216. }
  12217. }
  12218. };
  12219. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12220. var self = this;
  12221. $(contents).each(function (idx, content) {
  12222. var name = $(content).attr('name');
  12223. var mediaType = this.getAttribute('name');
  12224. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12225. ssrcs.each(function () {
  12226. var ssrc = this.getAttribute('ssrc');
  12227. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12228. function () {
  12229. var owner = this.getAttribute('owner');
  12230. self.ssrcOwners[ssrc] = owner;
  12231. }
  12232. );
  12233. });
  12234. });
  12235. };
  12236. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12237. return this.ssrcOwners[ssrc];
  12238. };
  12239. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12240. //console.log('setting remote description... ', desctype);
  12241. this.remoteSDP = new SDP('');
  12242. this.remoteSDP.fromJingle(elem);
  12243. this.readSsrcInfo($(elem).find(">content"));
  12244. if (this.peerconnection.remoteDescription !== null) {
  12245. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12246. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12247. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12248. for (var i = 0; i < pranswer.media.length; i++) {
  12249. // make sure we have ice ufrag and pwd
  12250. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12251. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12252. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12253. } else {
  12254. console.warn('no ice ufrag?');
  12255. }
  12256. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12257. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12258. } else {
  12259. console.warn('no ice pwd?');
  12260. }
  12261. }
  12262. // copy over candidates
  12263. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12264. for (var j = 0; j < lines.length; j++) {
  12265. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12266. }
  12267. }
  12268. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12269. }
  12270. }
  12271. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12272. this.peerconnection.setRemoteDescription(remotedesc,
  12273. function () {
  12274. //console.log('setRemoteDescription success');
  12275. },
  12276. function (e) {
  12277. console.error('setRemoteDescription error', e);
  12278. JingleSessionPC.onJingleFatalError(self, e);
  12279. }
  12280. );
  12281. };
  12282. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12283. var self = this;
  12284. if (this.peerconnection.signalingState == 'closed') {
  12285. return;
  12286. }
  12287. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12288. console.log('trickle ice candidate arriving before session accept...');
  12289. // create a PRANSWER for setRemoteDescription
  12290. if (!this.remoteSDP) {
  12291. var cobbled = 'v=0\r\n' +
  12292. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12293. 's=-\r\n' +
  12294. 't=0 0\r\n';
  12295. // first, take some things from the local description
  12296. for (var i = 0; i < this.localSDP.media.length; i++) {
  12297. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12298. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12299. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12300. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12301. }
  12302. cobbled += 'a=inactive\r\n';
  12303. }
  12304. this.remoteSDP = new SDP(cobbled);
  12305. }
  12306. // then add things like ice and dtls from remote candidate
  12307. elem.each(function () {
  12308. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12309. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12310. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12311. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12312. var tmp = $(this).find('transport');
  12313. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12314. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12315. tmp = $(this).find('transport>fingerprint');
  12316. if (tmp.length) {
  12317. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12318. } else {
  12319. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12320. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12321. }
  12322. break;
  12323. }
  12324. }
  12325. }
  12326. });
  12327. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12328. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12329. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12330. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12331. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12332. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12333. }).length == this.remoteSDP.media.length;
  12334. if (iscomplete) {
  12335. console.log('setting pranswer');
  12336. try {
  12337. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12338. function() {
  12339. },
  12340. function(e) {
  12341. console.log('setRemoteDescription pranswer failed', e.toString());
  12342. });
  12343. } catch (e) {
  12344. console.error('setting pranswer failed', e);
  12345. }
  12346. } else {
  12347. //console.log('not yet setting pranswer');
  12348. }
  12349. }
  12350. // operate on each content element
  12351. elem.each(function () {
  12352. // would love to deactivate this, but firefox still requires it
  12353. var idx = -1;
  12354. var i;
  12355. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12356. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12357. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12358. idx = i;
  12359. break;
  12360. }
  12361. }
  12362. if (idx == -1) { // fall back to localdescription
  12363. for (i = 0; i < self.localSDP.media.length; i++) {
  12364. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12365. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12366. idx = i;
  12367. break;
  12368. }
  12369. }
  12370. }
  12371. var name = $(this).attr('name');
  12372. // TODO: check ice-pwd and ice-ufrag?
  12373. $(this).find('transport>candidate').each(function () {
  12374. var line, candidate;
  12375. line = SDPUtil.candidateFromJingle(this);
  12376. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12377. sdpMid: name,
  12378. candidate: line});
  12379. try {
  12380. self.peerconnection.addIceCandidate(candidate);
  12381. } catch (e) {
  12382. console.error('addIceCandidate failed', e.toString(), line);
  12383. }
  12384. });
  12385. });
  12386. };
  12387. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12388. //console.log('createAnswer', provisional);
  12389. var self = this;
  12390. this.peerconnection.createAnswer(
  12391. function (sdp) {
  12392. self.createdAnswer(sdp, provisional);
  12393. },
  12394. function (e) {
  12395. console.error('createAnswer failed', e);
  12396. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12397. },
  12398. this.media_constraints
  12399. );
  12400. };
  12401. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12402. //console.log('createAnswer callback');
  12403. var self = this;
  12404. this.localSDP = new SDP(sdp.sdp);
  12405. //this.localSDP.mangle();
  12406. this.usepranswer = provisional === true;
  12407. if (this.usetrickle) {
  12408. if (this.usepranswer) {
  12409. sdp.type = 'pranswer';
  12410. for (var i = 0; i < this.localSDP.media.length; i++) {
  12411. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12412. }
  12413. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12414. }
  12415. }
  12416. var self = this;
  12417. var sendJingle = function (ssrcs) {
  12418. // FIXME why do we generate session-accept in 3 different places ?
  12419. var accept = $iq({to: self.peerjid,
  12420. type: 'set'})
  12421. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12422. action: 'session-accept',
  12423. initiator: self.initiator,
  12424. responder: self.responder,
  12425. sid: self.sid });
  12426. self.localSDP.toJingle(
  12427. accept,
  12428. self.initiator == self.me ? 'initiator' : 'responder',
  12429. ssrcs);
  12430. SSRCReplacement.processSessionInit(accept);
  12431. self.connection.sendIQ(accept,
  12432. function () {
  12433. var ack = {};
  12434. ack.source = 'answer';
  12435. $(document).trigger('ack.jingle', [self.sid, ack]);
  12436. },
  12437. function (stanza) {
  12438. var error = ($(stanza).find('error').length) ? {
  12439. code: $(stanza).find('error').attr('code'),
  12440. reason: $(stanza).find('error :first')[0].tagName,
  12441. }:{};
  12442. error.source = 'answer';
  12443. JingleSessionPC.onJingleError(self.sid, error);
  12444. },
  12445. 10000);
  12446. }
  12447. sdp.sdp = this.localSDP.raw;
  12448. this.peerconnection.setLocalDescription(sdp,
  12449. function () {
  12450. //console.log('setLocalDescription success');
  12451. if (self.usetrickle && !self.usepranswer) {
  12452. sendJingle();
  12453. }
  12454. self.setLocalDescription();
  12455. },
  12456. function (e) {
  12457. console.error('setLocalDescription failed', e);
  12458. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12459. }
  12460. );
  12461. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12462. for (var j = 0; j < cands.length; j++) {
  12463. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12464. if (cand.type == 'srflx') {
  12465. this.hadstuncandidate = true;
  12466. } else if (cand.type == 'relay') {
  12467. this.hadturncandidate = true;
  12468. }
  12469. }
  12470. };
  12471. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12472. var self = this,
  12473. term = $iq({to: this.peerjid,
  12474. type: 'set'})
  12475. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12476. action: 'session-terminate',
  12477. initiator: this.initiator,
  12478. sid: this.sid})
  12479. .c('reason')
  12480. .c(reason || 'success');
  12481. if (text) {
  12482. term.up().c('text').t(text);
  12483. }
  12484. this.connection.sendIQ(term,
  12485. function () {
  12486. self.peerconnection.close();
  12487. self.peerconnection = null;
  12488. self.terminate();
  12489. var ack = {};
  12490. ack.source = 'terminate';
  12491. $(document).trigger('ack.jingle', [self.sid, ack]);
  12492. },
  12493. function (stanza) {
  12494. var error = ($(stanza).find('error').length) ? {
  12495. code: $(stanza).find('error').attr('code'),
  12496. reason: $(stanza).find('error :first')[0].tagName,
  12497. }:{};
  12498. $(document).trigger('ack.jingle', [self.sid, error]);
  12499. },
  12500. 10000);
  12501. if (this.statsinterval !== null) {
  12502. window.clearInterval(this.statsinterval);
  12503. this.statsinterval = null;
  12504. }
  12505. };
  12506. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12507. var self = this;
  12508. // FIXME: dirty waiting
  12509. if (!this.peerconnection.localDescription)
  12510. {
  12511. console.warn("addSource - localDescription not ready yet")
  12512. setTimeout(function()
  12513. {
  12514. self.addSource(elem, fromJid);
  12515. },
  12516. 200
  12517. );
  12518. return;
  12519. }
  12520. console.log('addssrc', new Date().getTime());
  12521. console.log('ice', this.peerconnection.iceConnectionState);
  12522. this.readSsrcInfo(elem);
  12523. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12524. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12525. $(elem).each(function (idx, content) {
  12526. var name = $(content).attr('name');
  12527. var lines = '';
  12528. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12529. var semantics = this.getAttribute('semantics');
  12530. var ssrcs = $(this).find('>source').map(function () {
  12531. return this.getAttribute('ssrc');
  12532. }).get();
  12533. if (ssrcs.length != 0) {
  12534. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12535. }
  12536. });
  12537. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12538. tmp.each(function () {
  12539. var ssrc = $(this).attr('ssrc');
  12540. if(mySdp.containsSSRC(ssrc)){
  12541. /**
  12542. * This happens when multiple participants change their streams at the same time and
  12543. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12544. * addssrc are scheduled for update IQ. See
  12545. */
  12546. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12547. return;
  12548. }
  12549. if (sdp.containsSSRC(ssrc)) {
  12550. console.warn("Source-add request for existing SSRC: " + ssrc);
  12551. return;
  12552. }
  12553. $(this).find('>parameter').each(function () {
  12554. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12555. if ($(this).attr('value') && $(this).attr('value').length)
  12556. lines += ':' + $(this).attr('value');
  12557. lines += '\r\n';
  12558. });
  12559. });
  12560. sdp.media.forEach(function(media, idx) {
  12561. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12562. return;
  12563. sdp.media[idx] += lines;
  12564. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12565. self.addssrc[idx] += lines;
  12566. });
  12567. sdp.raw = sdp.session + sdp.media.join('');
  12568. });
  12569. this.modifySourcesQueue.push(function() {
  12570. // When a source is added and if this is FF, a new channel is allocated
  12571. // for receiving the added source. We need to diffuse the SSRC of this
  12572. // new recvonly channel to the rest of the peers.
  12573. console.log('modify sources done');
  12574. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12575. console.log("SDPs", mySdp, newSdp);
  12576. self.notifyMySSRCUpdate(mySdp, newSdp);
  12577. });
  12578. };
  12579. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12580. var self = this;
  12581. // FIXME: dirty waiting
  12582. if (!this.peerconnection.localDescription)
  12583. {
  12584. console.warn("removeSource - localDescription not ready yet")
  12585. setTimeout(function()
  12586. {
  12587. self.removeSource(elem, fromJid);
  12588. },
  12589. 200
  12590. );
  12591. return;
  12592. }
  12593. console.log('removessrc', new Date().getTime());
  12594. console.log('ice', this.peerconnection.iceConnectionState);
  12595. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12596. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12597. $(elem).each(function (idx, content) {
  12598. var name = $(content).attr('name');
  12599. var lines = '';
  12600. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12601. var semantics = this.getAttribute('semantics');
  12602. var ssrcs = $(this).find('>source').map(function () {
  12603. return this.getAttribute('ssrc');
  12604. }).get();
  12605. if (ssrcs.length != 0) {
  12606. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12607. }
  12608. });
  12609. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12610. tmp.each(function () {
  12611. var ssrc = $(this).attr('ssrc');
  12612. // This should never happen, but can be useful for bug detection
  12613. if(mySdp.containsSSRC(ssrc)){
  12614. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12615. return;
  12616. }
  12617. $(this).find('>parameter').each(function () {
  12618. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12619. if ($(this).attr('value') && $(this).attr('value').length)
  12620. lines += ':' + $(this).attr('value');
  12621. lines += '\r\n';
  12622. });
  12623. });
  12624. sdp.media.forEach(function(media, idx) {
  12625. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12626. return;
  12627. sdp.media[idx] += lines;
  12628. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12629. self.removessrc[idx] += lines;
  12630. });
  12631. sdp.raw = sdp.session + sdp.media.join('');
  12632. });
  12633. this.modifySourcesQueue.push(function() {
  12634. // When a source is removed and if this is FF, the recvonly channel that
  12635. // receives the remote stream is deactivated . We need to diffuse the
  12636. // recvonly SSRC removal to the rest of the peers.
  12637. console.log('modify sources done');
  12638. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12639. console.log("SDPs", mySdp, newSdp);
  12640. self.notifyMySSRCUpdate(mySdp, newSdp);
  12641. });
  12642. };
  12643. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12644. var self = this;
  12645. if (this.peerconnection.signalingState == 'closed') return;
  12646. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12647. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12648. this.setLocalDescription();
  12649. if(successCallback){
  12650. successCallback();
  12651. }
  12652. queueCallback();
  12653. return;
  12654. }
  12655. // Reset switch streams flag
  12656. this.switchstreams = false;
  12657. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12658. // add sources
  12659. this.addssrc.forEach(function(lines, idx) {
  12660. sdp.media[idx] += lines;
  12661. });
  12662. this.addssrc = [];
  12663. // remove sources
  12664. this.removessrc.forEach(function(lines, idx) {
  12665. lines = lines.split('\r\n');
  12666. lines.pop(); // remove empty last element;
  12667. lines.forEach(function(line) {
  12668. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12669. });
  12670. });
  12671. this.removessrc = [];
  12672. sdp.raw = sdp.session + sdp.media.join('');
  12673. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12674. function() {
  12675. if(self.signalingState == 'closed') {
  12676. console.error("createAnswer attempt on closed state");
  12677. queueCallback("createAnswer attempt on closed state");
  12678. return;
  12679. }
  12680. self.peerconnection.createAnswer(
  12681. function(modifiedAnswer) {
  12682. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12683. if (self.pendingop !== null) {
  12684. var sdp = new SDP(modifiedAnswer.sdp);
  12685. if (sdp.media.length > 1) {
  12686. switch(self.pendingop) {
  12687. case 'mute':
  12688. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12689. break;
  12690. case 'unmute':
  12691. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12692. break;
  12693. }
  12694. sdp.raw = sdp.session + sdp.media.join('');
  12695. modifiedAnswer.sdp = sdp.raw;
  12696. }
  12697. self.pendingop = null;
  12698. }
  12699. // FIXME: pushing down an answer while ice connection state
  12700. // is still checking is bad...
  12701. //console.log(self.peerconnection.iceConnectionState);
  12702. // trying to work around another chrome bug
  12703. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12704. self.peerconnection.setLocalDescription(modifiedAnswer,
  12705. function() {
  12706. //console.log('modified setLocalDescription ok');
  12707. self.setLocalDescription();
  12708. if(successCallback){
  12709. successCallback();
  12710. }
  12711. queueCallback();
  12712. },
  12713. function(error) {
  12714. console.error('modified setLocalDescription failed', error);
  12715. queueCallback(error);
  12716. }
  12717. );
  12718. },
  12719. function(error) {
  12720. console.error('modified answer failed', error);
  12721. queueCallback(error);
  12722. }
  12723. );
  12724. },
  12725. function(error) {
  12726. console.error('modify failed', error);
  12727. queueCallback(error);
  12728. }
  12729. );
  12730. };
  12731. /**
  12732. * Switches video streams.
  12733. * @param new_stream new stream that will be used as video of this session.
  12734. * @param oldStream old video stream of this session.
  12735. * @param success_callback callback executed after successful stream switch.
  12736. */
  12737. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12738. var self = this;
  12739. // Remember SDP to figure out added/removed SSRCs
  12740. var oldSdp = null;
  12741. if(self.peerconnection) {
  12742. if(self.peerconnection.localDescription) {
  12743. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12744. }
  12745. self.peerconnection.removeStream(oldStream, true);
  12746. if(new_stream)
  12747. self.peerconnection.addStream(new_stream);
  12748. }
  12749. // Conference is not active
  12750. if(!oldSdp || !self.peerconnection) {
  12751. success_callback();
  12752. return;
  12753. }
  12754. self.switchstreams = true;
  12755. self.modifySourcesQueue.push(function() {
  12756. console.log('modify sources done');
  12757. success_callback();
  12758. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12759. console.log("SDPs", oldSdp, newSdp);
  12760. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12761. });
  12762. };
  12763. /**
  12764. * Figures out added/removed ssrcs and send update IQs.
  12765. * @param old_sdp SDP object for old description.
  12766. * @param new_sdp SDP object for new description.
  12767. */
  12768. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12769. if (!(this.peerconnection.signalingState == 'stable' &&
  12770. this.peerconnection.iceConnectionState == 'connected')){
  12771. console.log("Too early to send updates");
  12772. return;
  12773. }
  12774. // send source-remove IQ.
  12775. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12776. var remove = $iq({to: this.peerjid, type: 'set'})
  12777. .c('jingle', {
  12778. xmlns: 'urn:xmpp:jingle:1',
  12779. action: 'source-remove',
  12780. initiator: this.initiator,
  12781. sid: this.sid
  12782. }
  12783. );
  12784. var removed = sdpDiffer.toJingle(remove);
  12785. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12786. // it in the current form
  12787. if (removed)
  12788. remove = SSRCReplacement.processSourceRemove(remove);
  12789. if (removed && remove) {
  12790. console.info("Sending source-remove", remove);
  12791. this.connection.sendIQ(remove,
  12792. function (res) {
  12793. console.info('got remove result', res);
  12794. },
  12795. function (err) {
  12796. console.error('got remove error', err);
  12797. }
  12798. );
  12799. } else {
  12800. console.log('removal not necessary');
  12801. }
  12802. // send source-add IQ.
  12803. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12804. var add = $iq({to: this.peerjid, type: 'set'})
  12805. .c('jingle', {
  12806. xmlns: 'urn:xmpp:jingle:1',
  12807. action: 'source-add',
  12808. initiator: this.initiator,
  12809. sid: this.sid
  12810. }
  12811. );
  12812. var added = sdpDiffer.toJingle(add);
  12813. // Let 'source-add' IQ through the hack and see if we're allowed to send
  12814. // it in the current form
  12815. if (added)
  12816. add = SSRCReplacement.processSourceAdd(add);
  12817. if (added && add) {
  12818. console.info("Sending source-add", add);
  12819. this.connection.sendIQ(add,
  12820. function (res) {
  12821. console.info('got add result', res);
  12822. },
  12823. function (err) {
  12824. console.error('got add error', err);
  12825. }
  12826. );
  12827. } else {
  12828. console.log('addition not necessary');
  12829. }
  12830. };
  12831. /**
  12832. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12833. *
  12834. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12835. * tracks; otherwise, <tt>false</tt>
  12836. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12837. * tracks have been enabled/disabled. The function may, optionally, return
  12838. * another function which is to be invoked after the whole mute/unmute operation
  12839. * has completed successfully.
  12840. * @param options an object which specifies optional arguments such as the
  12841. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12842. * specifies whether the method was initiated in response to a user command (in
  12843. * contrast to an automatic decision made by the application logic)
  12844. */
  12845. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  12846. var byUser;
  12847. if (options) {
  12848. byUser = options.byUser;
  12849. if (typeof byUser === 'undefined') {
  12850. byUser = true;
  12851. }
  12852. } else {
  12853. byUser = true;
  12854. }
  12855. // The user's command to mute the (local) video takes precedence over any
  12856. // automatic decision made by the application logic.
  12857. if (byUser) {
  12858. this.videoMuteByUser = mute;
  12859. } else if (this.videoMuteByUser) {
  12860. return;
  12861. }
  12862. this.hardMuteVideo(mute);
  12863. var self = this;
  12864. var oldSdp = null;
  12865. if(self.peerconnection) {
  12866. if(self.peerconnection.localDescription) {
  12867. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12868. }
  12869. }
  12870. this.modifySourcesQueue.push(function() {
  12871. console.log('modify sources done');
  12872. callback(mute);
  12873. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12874. console.log("SDPs", oldSdp, newSdp);
  12875. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12876. });
  12877. };
  12878. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  12879. this.pendingop = muted ? 'mute' : 'unmute';
  12880. };
  12881. JingleSessionPC.prototype.sendMute = function (muted, content) {
  12882. var info = $iq({to: this.peerjid,
  12883. type: 'set'})
  12884. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12885. action: 'session-info',
  12886. initiator: this.initiator,
  12887. sid: this.sid });
  12888. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12889. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12890. if (content) {
  12891. info.attrs({'name': content});
  12892. }
  12893. this.connection.send(info);
  12894. };
  12895. JingleSessionPC.prototype.sendRinging = function () {
  12896. var info = $iq({to: this.peerjid,
  12897. type: 'set'})
  12898. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12899. action: 'session-info',
  12900. initiator: this.initiator,
  12901. sid: this.sid });
  12902. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12903. this.connection.send(info);
  12904. };
  12905. JingleSessionPC.prototype.getStats = function (interval) {
  12906. var self = this;
  12907. var recv = {audio: 0, video: 0};
  12908. var lost = {audio: 0, video: 0};
  12909. var lastrecv = {audio: 0, video: 0};
  12910. var lastlost = {audio: 0, video: 0};
  12911. var loss = {audio: 0, video: 0};
  12912. var delta = {audio: 0, video: 0};
  12913. this.statsinterval = window.setInterval(function () {
  12914. if (self && self.peerconnection && self.peerconnection.getStats) {
  12915. self.peerconnection.getStats(function (stats) {
  12916. var results = stats.result();
  12917. // TODO: there are so much statistics you can get from this..
  12918. for (var i = 0; i < results.length; ++i) {
  12919. if (results[i].type == 'ssrc') {
  12920. var packetsrecv = results[i].stat('packetsReceived');
  12921. var packetslost = results[i].stat('packetsLost');
  12922. if (packetsrecv && packetslost) {
  12923. packetsrecv = parseInt(packetsrecv, 10);
  12924. packetslost = parseInt(packetslost, 10);
  12925. if (results[i].stat('googFrameRateReceived')) {
  12926. lastlost.video = lost.video;
  12927. lastrecv.video = recv.video;
  12928. recv.video = packetsrecv;
  12929. lost.video = packetslost;
  12930. } else {
  12931. lastlost.audio = lost.audio;
  12932. lastrecv.audio = recv.audio;
  12933. recv.audio = packetsrecv;
  12934. lost.audio = packetslost;
  12935. }
  12936. }
  12937. }
  12938. }
  12939. delta.audio = recv.audio - lastrecv.audio;
  12940. delta.video = recv.video - lastrecv.video;
  12941. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12942. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12943. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12944. });
  12945. }
  12946. }, interval || 3000);
  12947. return this.statsinterval;
  12948. };
  12949. JingleSessionPC.onJingleError = function (session, error)
  12950. {
  12951. console.error("Jingle error", error);
  12952. }
  12953. JingleSessionPC.onJingleFatalError = function (session, error)
  12954. {
  12955. this.service.sessionTerminated = true;
  12956. this.connection.emuc.doLeave();
  12957. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12958. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12959. }
  12960. JingleSessionPC.prototype.setLocalDescription = function () {
  12961. var self = this;
  12962. var newssrcs = [];
  12963. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12964. session.media.forEach(function (media) {
  12965. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12966. // TODO(gp) maybe exclude FID streams?
  12967. media.ssrcs.forEach(function (ssrc) {
  12968. if (ssrc.attribute !== 'cname') {
  12969. return;
  12970. }
  12971. newssrcs.push({
  12972. 'ssrc': ssrc.id,
  12973. 'type': media.type
  12974. });
  12975. });
  12976. }
  12977. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12978. {
  12979. newssrcs.push({
  12980. 'ssrc': self.localStreamsSSRC[media.type],
  12981. 'type': media.type
  12982. });
  12983. }
  12984. });
  12985. console.log('new ssrcs', newssrcs);
  12986. // Bind us as local SSRCs owner
  12987. if (newssrcs.length > 0) {
  12988. for (var i = 1; i <= newssrcs.length; i ++) {
  12989. var ssrc = newssrcs[i-1].ssrc;
  12990. var myJid = self.connection.emuc.myroomjid;
  12991. self.ssrcOwners[ssrc] = myJid;
  12992. }
  12993. }
  12994. }
  12995. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12996. // TODO: is this hack (along with the XMPPEvent-s used only for it) still needed
  12997. // now that we announce an SSRC for receive-only streams?
  12998. function sendKeyframe(pc) {
  12999. console.log('sendkeyframe', pc.iceConnectionState);
  13000. if (pc.iceConnectionState !== 'connected') return; // safe...
  13001. pc.setRemoteDescription(
  13002. pc.remoteDescription,
  13003. function () {
  13004. pc.createAnswer(
  13005. function (modifiedAnswer) {
  13006. pc.setLocalDescription(
  13007. modifiedAnswer,
  13008. function () {
  13009. // noop
  13010. },
  13011. function (error) {
  13012. console.log('triggerKeyframe setLocalDescription failed', error);
  13013. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  13014. }
  13015. );
  13016. },
  13017. function (error) {
  13018. console.log('triggerKeyframe createAnswer failed', error);
  13019. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  13020. }
  13021. );
  13022. },
  13023. function (error) {
  13024. console.log('triggerKeyframe setRemoteDescription failed', error);
  13025. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  13026. }
  13027. );
  13028. }
  13029. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  13030. var self = this;
  13031. var thessrc;
  13032. var streamId = APP.RTC.getStreamID(data.stream);
  13033. // look up an associated JID for a stream id
  13034. if (!streamId) {
  13035. console.error("No stream ID for", data.stream);
  13036. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  13037. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  13038. var ssrclines
  13039. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  13040. ssrclines = ssrclines.filter(function (line) {
  13041. // NOTE(gp) previously we filtered on the mslabel, but that property
  13042. // is not always present.
  13043. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  13044. if (RTCBrowserType.isTemasysPluginUsed()) {
  13045. return ((line.indexOf('mslabel:' + streamId) !== -1));
  13046. } else {
  13047. return ((line.indexOf('msid:' + streamId) !== -1));
  13048. }
  13049. });
  13050. if (ssrclines.length) {
  13051. thessrc = ssrclines[0].substring(7).split(' ')[0];
  13052. if (!self.ssrcOwners[thessrc]) {
  13053. console.error("No SSRC owner known for: " + thessrc);
  13054. return;
  13055. }
  13056. data.peerjid = self.ssrcOwners[thessrc];
  13057. console.log('associated jid', self.ssrcOwners[thessrc]);
  13058. } else {
  13059. console.error("No SSRC lines for ", streamId);
  13060. }
  13061. }
  13062. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13063. var isVideo = data.stream.getVideoTracks().length > 0;
  13064. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13065. // TODO: is this hack still needed now that we announce an SSRC for
  13066. // receive-only streams?
  13067. if (isVideo &&
  13068. data.peerjid && this.peerjid === data.peerjid &&
  13069. data.stream.getVideoTracks().length === 0 &&
  13070. APP.RTC.localVideo.getTracks().length > 0) {
  13071. window.setTimeout(function () {
  13072. sendKeyframe(self.peerconnection);
  13073. }, 3000);
  13074. }
  13075. }
  13076. module.exports = JingleSessionPC;
  13077. },{"../../service/xmpp/XMPPEvents":172,"../RTC/RTCBrowserType":8,"./JingleSession":55,"./LocalSSRCReplacement":57,"./SDP":58,"./SDPDiffer":59,"./SDPUtil":60,"./TraceablePeerConnection":61,"async":72,"sdp-transform":109}],57:[function(require,module,exports){
  13078. /* global $ */
  13079. /*
  13080. Here we do modifications of local video SSRCs. There are 2 situations we have
  13081. to handle:
  13082. 1. We generate SSRC for local recvonly video stream. This is the case when we
  13083. have no local camera and it is not generated automatically, but SSRC=1 is
  13084. used implicitly. If that happens RTCP packets will be dropped by the JVB
  13085. and we won't be able to request video key frames correctly.
  13086. 2. A hack to re-use SSRC of the first video stream for any new stream created
  13087. in future. It turned out that Chrome may keep on using the SSRC of removed
  13088. video stream in RTCP even though a new one has been created. So we just
  13089. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  13090. notifications are blocked once first video SSRC is advertised to the focus.
  13091. What this hack does:
  13092. 1. Stores the SSRC of the first video stream created by
  13093. a) scanning Jingle session-accept/session-invite for existing video SSRC
  13094. b) watching for 'source-add' for new video stream if it has not been
  13095. created in step a)
  13096. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  13097. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  13098. returned to the other parts of the application.
  13099. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  13100. blocks those notifications. This makes Jicofo and all participants think
  13101. that it exists all the time even if the video stream has been removed or
  13102. replaced locally. Thanks to that there is no additional signaling activity
  13103. on video mute or when switching to the desktop stream.
  13104. */
  13105. var SDP = require('./SDP');
  13106. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13107. /**
  13108. * The hack is enabled on all browsers except FF by default
  13109. * FIXME finish the hack once removeStream method is implemented in FF
  13110. * @type {boolean}
  13111. */
  13112. var isEnabled = !RTCBrowserType.isFirefox();
  13113. /**
  13114. * Stored SSRC of local video stream.
  13115. */
  13116. var localVideoSSRC;
  13117. /**
  13118. * SSRC used for recvonly video stream when we have no local camera.
  13119. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13120. * instead of 1.
  13121. */
  13122. var localRecvOnlySSRC;
  13123. /**
  13124. * cname for <tt>localRecvOnlySSRC</tt>
  13125. */
  13126. var localRecvOnlyCName;
  13127. /**
  13128. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13129. * from given Jingle IQ.
  13130. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13131. * @param actionName display name of the action which will be printed in log
  13132. * messages.
  13133. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13134. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13135. * other SSRCs left to be signaled after removing it.
  13136. */
  13137. var filterOutSource = function (modifyIq, actionName) {
  13138. var modifyIqTree = $(modifyIq.tree());
  13139. if (!localVideoSSRC)
  13140. return modifyIqTree[0];
  13141. var videoSSRC = modifyIqTree.find(
  13142. '>jingle>content[name="video"]' +
  13143. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13144. if (!videoSSRC.length) {
  13145. return modifyIqTree[0];
  13146. }
  13147. console.info(
  13148. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13149. videoSSRC.remove();
  13150. // Check if any sources still left to be added/removed
  13151. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13152. return modifyIqTree[0];
  13153. } else {
  13154. return null;
  13155. }
  13156. };
  13157. /**
  13158. * Scans given Jingle IQ for video SSRC and stores it.
  13159. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13160. */
  13161. var storeLocalVideoSSRC = function (jingleIq) {
  13162. var videoSSRCs =
  13163. $(jingleIq.tree())
  13164. .find('>jingle>content[name="video"]>description>source');
  13165. videoSSRCs.each(function (idx, ssrcElem) {
  13166. if (localVideoSSRC)
  13167. return;
  13168. // We consider SSRC real only if it has msid attribute
  13169. // recvonly streams in FF do not have it as well as local SSRCs
  13170. // we generate for recvonly streams in Chrome
  13171. var ssrSel = $(ssrcElem);
  13172. var msid = ssrSel.find('>parameter[name="msid"]');
  13173. if (msid.length) {
  13174. var ssrcVal = ssrSel.attr('ssrc');
  13175. if (ssrcVal) {
  13176. localVideoSSRC = ssrcVal;
  13177. console.info('Stored local video SSRC' +
  13178. ' for future re-use: ' + localVideoSSRC);
  13179. }
  13180. }
  13181. });
  13182. };
  13183. /**
  13184. * Generates new SSRC for local video recvonly stream.
  13185. * FIXME what about eventual SSRC collision ?
  13186. */
  13187. function generateRecvonlySSRC() {
  13188. //
  13189. localRecvOnlySSRC =
  13190. Math.random().toString(10).substring(2, 11);
  13191. localRecvOnlyCName =
  13192. Math.random().toString(36).substring(2);
  13193. console.info(
  13194. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13195. ", cname: " + localRecvOnlyCName);
  13196. }
  13197. var LocalSSRCReplacement = {
  13198. /**
  13199. * Method must be called before 'session-initiate' or 'session-invite' is
  13200. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13201. *
  13202. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13203. * which will be scanned for local video SSRC.
  13204. */
  13205. processSessionInit: function (sessionInit) {
  13206. if (!isEnabled)
  13207. return;
  13208. if (localVideoSSRC) {
  13209. console.error("Local SSRC stored already: " + localVideoSSRC);
  13210. return;
  13211. }
  13212. storeLocalVideoSSRC(sessionInit);
  13213. },
  13214. /**
  13215. * If we have local video SSRC stored searched given
  13216. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13217. * with the stored one.
  13218. * @param localDescription local description object that will have local
  13219. * video SSRC replaced with the stored one
  13220. * @returns modified <tt>localDescription</tt> object.
  13221. */
  13222. mungeLocalVideoSSRC: function (localDescription) {
  13223. if (!isEnabled)
  13224. return localDescription;
  13225. if (!localDescription) {
  13226. console.warn("localDescription is null or undefined");
  13227. return localDescription;
  13228. }
  13229. // IF we have local video SSRC stored make sure it is replaced
  13230. // with old SSRC
  13231. if (localVideoSSRC) {
  13232. var newSdp = new SDP(localDescription.sdp);
  13233. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13234. !newSdp.containsSSRC(localVideoSSRC)) {
  13235. // Get new video SSRC
  13236. var map = newSdp.getMediaSsrcMap();
  13237. var videoPart = map[1];
  13238. var videoSSRCs = videoPart.ssrcs;
  13239. var newSSRC = Object.keys(videoSSRCs)[0];
  13240. console.info(
  13241. "Replacing new video SSRC: " + newSSRC +
  13242. " with " + localVideoSSRC);
  13243. localDescription.sdp =
  13244. newSdp.raw.replace(
  13245. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13246. 'a=ssrc:' + localVideoSSRC);
  13247. }
  13248. } else {
  13249. // Make sure we have any SSRC for recvonly video stream
  13250. var sdp = new SDP(localDescription.sdp);
  13251. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13252. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13253. if (!localRecvOnlySSRC) {
  13254. generateRecvonlySSRC();
  13255. }
  13256. console.info('No SSRC in video recvonly stream' +
  13257. ' - adding SSRC: ' + localRecvOnlySSRC);
  13258. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13259. ' cname:' + localRecvOnlyCName + '\r\n';
  13260. localDescription.sdp = sdp.session + sdp.media.join('');
  13261. }
  13262. }
  13263. return localDescription;
  13264. },
  13265. /**
  13266. * Method must be called before 'source-add' notification is sent. In case
  13267. * we have local video SSRC advertised already it will be removed from the
  13268. * notification. If no other SSRCs are described by given IQ null will be
  13269. * returned which means that there is no point in sending the notification.
  13270. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13271. * @returns modified 'source-add' IQ which can be sent to the focus or
  13272. * <tt>null</tt> if no notification shall be sent. It is no longer
  13273. * a Strophe IQ Builder instance, but DOM element tree.
  13274. */
  13275. processSourceAdd: function (sourceAdd) {
  13276. if (!isEnabled)
  13277. return sourceAdd;
  13278. if (!localVideoSSRC) {
  13279. // Store local SSRC if available
  13280. storeLocalVideoSSRC(sourceAdd);
  13281. return sourceAdd;
  13282. } else {
  13283. return filterOutSource(sourceAdd, 'source-add');
  13284. }
  13285. },
  13286. /**
  13287. * Method must be called before 'source-remove' notification is sent.
  13288. * Removes local video SSRC from the notification. If there are no other
  13289. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13290. * means that there is no point in sending the notification.
  13291. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13292. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13293. * <tt>null</tt> if no notification shall be sent. It is no longer
  13294. * a Strophe IQ Builder instance, but DOM element tree.
  13295. */
  13296. processSourceRemove: function (sourceRemove) {
  13297. if (!isEnabled)
  13298. return sourceRemove;
  13299. return filterOutSource(sourceRemove, 'source-remove');
  13300. },
  13301. /**
  13302. * Turns the hack on or off
  13303. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13304. * to disable it
  13305. */
  13306. setEnabled: function (enabled) {
  13307. isEnabled = enabled;
  13308. }
  13309. };
  13310. module.exports = LocalSSRCReplacement;
  13311. },{"../RTC/RTCBrowserType":8,"./SDP":58}],58:[function(require,module,exports){
  13312. /* jshint -W117 */
  13313. var SDPUtil = require("./SDPUtil");
  13314. // SDP STUFF
  13315. function SDP(sdp) {
  13316. this.media = sdp.split('\r\nm=');
  13317. for (var i = 1; i < this.media.length; i++) {
  13318. this.media[i] = 'm=' + this.media[i];
  13319. if (i != this.media.length - 1) {
  13320. this.media[i] += '\r\n';
  13321. }
  13322. }
  13323. this.session = this.media.shift() + '\r\n';
  13324. this.raw = this.session + this.media.join('');
  13325. }
  13326. /**
  13327. * Returns map of MediaChannel mapped per channel idx.
  13328. */
  13329. SDP.prototype.getMediaSsrcMap = function() {
  13330. var self = this;
  13331. var media_ssrcs = {};
  13332. var tmp;
  13333. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13334. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13335. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13336. var media = {
  13337. mediaindex: mediaindex,
  13338. mid: mid,
  13339. ssrcs: {},
  13340. ssrcGroups: []
  13341. };
  13342. media_ssrcs[mediaindex] = media;
  13343. tmp.forEach(function (line) {
  13344. var linessrc = line.substring(7).split(' ')[0];
  13345. // allocate new ChannelSsrc
  13346. if(!media.ssrcs[linessrc]) {
  13347. media.ssrcs[linessrc] = {
  13348. ssrc: linessrc,
  13349. lines: []
  13350. };
  13351. }
  13352. media.ssrcs[linessrc].lines.push(line);
  13353. });
  13354. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13355. tmp.forEach(function(line){
  13356. var semantics = line.substr(0, idx).substr(13);
  13357. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13358. if (ssrcs.length != 0) {
  13359. media.ssrcGroups.push({
  13360. semantics: semantics,
  13361. ssrcs: ssrcs
  13362. });
  13363. }
  13364. });
  13365. }
  13366. return media_ssrcs;
  13367. };
  13368. /**
  13369. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13370. * @param ssrc the ssrc to check.
  13371. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13372. */
  13373. SDP.prototype.containsSSRC = function(ssrc) {
  13374. var medias = this.getMediaSsrcMap();
  13375. var contains = false;
  13376. Object.keys(medias).forEach(function(mediaindex){
  13377. var media = medias[mediaindex];
  13378. //console.log("Check", channel, ssrc);
  13379. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13380. contains = true;
  13381. }
  13382. });
  13383. return contains;
  13384. };
  13385. // remove iSAC and CN from SDP
  13386. SDP.prototype.mangle = function () {
  13387. var i, j, mline, lines, rtpmap, newdesc;
  13388. for (i = 0; i < this.media.length; i++) {
  13389. lines = this.media[i].split('\r\n');
  13390. lines.pop(); // remove empty last element
  13391. mline = SDPUtil.parse_mline(lines.shift());
  13392. if (mline.media != 'audio')
  13393. continue;
  13394. newdesc = '';
  13395. mline.fmt.length = 0;
  13396. for (j = 0; j < lines.length; j++) {
  13397. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13398. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13399. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13400. continue;
  13401. mline.fmt.push(rtpmap.id);
  13402. newdesc += lines[j] + '\r\n';
  13403. } else {
  13404. newdesc += lines[j] + '\r\n';
  13405. }
  13406. }
  13407. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13408. this.media[i] += newdesc;
  13409. }
  13410. this.raw = this.session + this.media.join('');
  13411. };
  13412. // remove lines matching prefix from session section
  13413. SDP.prototype.removeSessionLines = function(prefix) {
  13414. var self = this;
  13415. var lines = SDPUtil.find_lines(this.session, prefix);
  13416. lines.forEach(function(line) {
  13417. self.session = self.session.replace(line + '\r\n', '');
  13418. });
  13419. this.raw = this.session + this.media.join('');
  13420. return lines;
  13421. }
  13422. // remove lines matching prefix from a media section specified by mediaindex
  13423. // TODO: non-numeric mediaindex could match mid
  13424. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13425. var self = this;
  13426. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13427. lines.forEach(function(line) {
  13428. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13429. });
  13430. this.raw = this.session + this.media.join('');
  13431. return lines;
  13432. }
  13433. // add content's to a jingle element
  13434. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13435. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13436. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13437. var self = this;
  13438. // new bundle plan
  13439. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13440. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13441. for (i = 0; i < lines.length; i++) {
  13442. tmp = lines[i].split(' ');
  13443. var semantics = tmp.shift().substr(8);
  13444. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13445. for (j = 0; j < tmp.length; j++) {
  13446. elem.c('content', {name: tmp[j]}).up();
  13447. }
  13448. elem.up();
  13449. }
  13450. }
  13451. for (i = 0; i < this.media.length; i++) {
  13452. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13453. if (!(mline.media === 'audio' ||
  13454. mline.media === 'video' ||
  13455. mline.media === 'application'))
  13456. {
  13457. continue;
  13458. }
  13459. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13460. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13461. } else {
  13462. if(ssrcs && ssrcs[mline.media])
  13463. {
  13464. ssrc = ssrcs[mline.media];
  13465. }
  13466. else
  13467. ssrc = false;
  13468. }
  13469. elem.c('content', {creator: thecreator, name: mline.media});
  13470. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13471. // prefer identifier from a=mid if present
  13472. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13473. elem.attrs({ name: mid });
  13474. }
  13475. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13476. {
  13477. elem.c('description',
  13478. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13479. media: mline.media });
  13480. if (ssrc) {
  13481. elem.attrs({ssrc: ssrc});
  13482. }
  13483. for (j = 0; j < mline.fmt.length; j++) {
  13484. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13485. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13486. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13487. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13488. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13489. for (k = 0; k < tmp.length; k++) {
  13490. elem.c('parameter', tmp[k]).up();
  13491. }
  13492. }
  13493. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13494. elem.up();
  13495. }
  13496. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13497. elem.c('encryption', {required: 1});
  13498. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13499. crypto.forEach(function(line) {
  13500. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13501. });
  13502. elem.up(); // end of encryption
  13503. }
  13504. if (ssrc) {
  13505. // new style mapping
  13506. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13507. // FIXME: group by ssrc and support multiple different ssrcs
  13508. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13509. if(ssrclines.length > 0) {
  13510. ssrclines.forEach(function (line) {
  13511. idx = line.indexOf(' ');
  13512. var linessrc = line.substr(0, idx).substr(7);
  13513. if (linessrc != ssrc) {
  13514. elem.up();
  13515. ssrc = linessrc;
  13516. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13517. }
  13518. var kv = line.substr(idx + 1);
  13519. elem.c('parameter');
  13520. if (kv.indexOf(':') == -1) {
  13521. elem.attrs({ name: kv });
  13522. } else {
  13523. var k = kv.split(':', 2)[0];
  13524. elem.attrs({ name: k });
  13525. var v = kv.split(':', 2)[1];
  13526. v = SDPUtil.filter_special_chars(v);
  13527. elem.attrs({ value: v });
  13528. }
  13529. elem.up();
  13530. });
  13531. }
  13532. else
  13533. {
  13534. elem.up();
  13535. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13536. elem.c('parameter');
  13537. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13538. elem.up();
  13539. var msid = null;
  13540. if(mline.media == "audio")
  13541. {
  13542. msid = APP.RTC.localAudio.getId();
  13543. }
  13544. else
  13545. {
  13546. msid = APP.RTC.localVideo.getId();
  13547. }
  13548. if(msid != null)
  13549. {
  13550. msid = SDPUtil.filter_special_chars(msid);
  13551. elem.c('parameter');
  13552. elem.attrs({name: "msid", value:msid});
  13553. elem.up();
  13554. elem.c('parameter');
  13555. elem.attrs({name: "mslabel", value:msid});
  13556. elem.up();
  13557. elem.c('parameter');
  13558. elem.attrs({name: "label", value:msid});
  13559. elem.up();
  13560. }
  13561. }
  13562. elem.up();
  13563. // XEP-0339 handle ssrc-group attributes
  13564. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13565. ssrc_group_lines.forEach(function(line) {
  13566. idx = line.indexOf(' ');
  13567. var semantics = line.substr(0, idx).substr(13);
  13568. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13569. if (ssrcs.length != 0) {
  13570. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13571. ssrcs.forEach(function(ssrc) {
  13572. elem.c('source', { ssrc: ssrc })
  13573. .up();
  13574. });
  13575. elem.up();
  13576. }
  13577. });
  13578. }
  13579. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13580. elem.c('rtcp-mux').up();
  13581. }
  13582. // XEP-0293 -- map a=rtcp-fb:*
  13583. this.RtcpFbToJingle(i, elem, '*');
  13584. // XEP-0294
  13585. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13586. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13587. for (j = 0; j < lines.length; j++) {
  13588. tmp = SDPUtil.parse_extmap(lines[j]);
  13589. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13590. uri: tmp.uri,
  13591. id: tmp.value });
  13592. if (tmp.hasOwnProperty('direction')) {
  13593. switch (tmp.direction) {
  13594. case 'sendonly':
  13595. elem.attrs({senders: 'responder'});
  13596. break;
  13597. case 'recvonly':
  13598. elem.attrs({senders: 'initiator'});
  13599. break;
  13600. case 'sendrecv':
  13601. elem.attrs({senders: 'both'});
  13602. break;
  13603. case 'inactive':
  13604. elem.attrs({senders: 'none'});
  13605. break;
  13606. }
  13607. }
  13608. // TODO: handle params
  13609. elem.up();
  13610. }
  13611. }
  13612. elem.up(); // end of description
  13613. }
  13614. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13615. this.TransportToJingle(i, elem);
  13616. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13617. elem.attrs({senders: 'both'});
  13618. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13619. elem.attrs({senders: 'initiator'});
  13620. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13621. elem.attrs({senders: 'responder'});
  13622. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13623. elem.attrs({senders: 'none'});
  13624. }
  13625. if (mline.port == '0') {
  13626. // estos hack to reject an m-line
  13627. elem.attrs({senders: 'rejected'});
  13628. }
  13629. elem.up(); // end of content
  13630. }
  13631. elem.up();
  13632. return elem;
  13633. };
  13634. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13635. var i = mediaindex;
  13636. var tmp;
  13637. var self = this;
  13638. elem.c('transport');
  13639. // XEP-0343 DTLS/SCTP
  13640. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13641. {
  13642. var sctpmap = SDPUtil.find_line(
  13643. this.media[i], 'a=sctpmap:', self.session);
  13644. if (sctpmap)
  13645. {
  13646. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13647. elem.c('sctpmap',
  13648. {
  13649. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13650. number: sctpAttrs[0], /* SCTP port */
  13651. protocol: sctpAttrs[1], /* protocol */
  13652. });
  13653. // Optional stream count attribute
  13654. if (sctpAttrs.length > 2)
  13655. elem.attrs({ streams: sctpAttrs[2]});
  13656. elem.up();
  13657. }
  13658. }
  13659. // XEP-0320
  13660. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13661. fingerprints.forEach(function(line) {
  13662. tmp = SDPUtil.parse_fingerprint(line);
  13663. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13664. elem.c('fingerprint').t(tmp.fingerprint);
  13665. delete tmp.fingerprint;
  13666. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13667. if (line) {
  13668. tmp.setup = line.substr(8);
  13669. }
  13670. elem.attrs(tmp);
  13671. elem.up(); // end of fingerprint
  13672. });
  13673. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13674. if (tmp) {
  13675. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13676. elem.attrs(tmp);
  13677. // XEP-0176
  13678. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13679. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13680. lines.forEach(function (line) {
  13681. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13682. });
  13683. }
  13684. }
  13685. elem.up(); // end of transport
  13686. }
  13687. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13688. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13689. lines.forEach(function (line) {
  13690. var tmp = SDPUtil.parse_rtcpfb(line);
  13691. if (tmp.type == 'trr-int') {
  13692. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13693. elem.up();
  13694. } else {
  13695. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13696. if (tmp.params.length > 0) {
  13697. elem.attrs({'subtype': tmp.params[0]});
  13698. }
  13699. elem.up();
  13700. }
  13701. });
  13702. };
  13703. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13704. var media = '';
  13705. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13706. if (tmp.length) {
  13707. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13708. if (tmp.attr('value')) {
  13709. media += tmp.attr('value');
  13710. } else {
  13711. media += '0';
  13712. }
  13713. media += '\r\n';
  13714. }
  13715. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13716. tmp.each(function () {
  13717. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13718. if ($(this).attr('subtype')) {
  13719. media += ' ' + $(this).attr('subtype');
  13720. }
  13721. media += '\r\n';
  13722. });
  13723. return media;
  13724. };
  13725. // construct an SDP from a jingle stanza
  13726. SDP.prototype.fromJingle = function (jingle) {
  13727. var self = this;
  13728. this.raw = 'v=0\r\n' +
  13729. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13730. 's=-\r\n' +
  13731. 't=0 0\r\n';
  13732. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13733. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13734. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13735. var contents = $(group).find('>content').map(function (idx, content) {
  13736. return content.getAttribute('name');
  13737. }).get();
  13738. if (contents.length > 0) {
  13739. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13740. }
  13741. });
  13742. }
  13743. this.session = this.raw;
  13744. jingle.find('>content').each(function () {
  13745. var m = self.jingle2media($(this));
  13746. self.media.push(m);
  13747. });
  13748. // reconstruct msid-semantic -- apparently not necessary
  13749. /*
  13750. var msid = SDPUtil.parse_ssrc(this.raw);
  13751. if (msid.hasOwnProperty('mslabel')) {
  13752. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13753. }
  13754. */
  13755. this.raw = this.session + this.media.join('');
  13756. };
  13757. // translate a jingle content element into an an SDP media part
  13758. SDP.prototype.jingle2media = function (content) {
  13759. var media = '',
  13760. desc = content.find('description'),
  13761. ssrc = desc.attr('ssrc'),
  13762. self = this,
  13763. tmp;
  13764. var sctp = content.find(
  13765. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13766. tmp = { media: desc.attr('media') };
  13767. tmp.port = '1';
  13768. if (content.attr('senders') == 'rejected') {
  13769. // estos hack to reject an m-line.
  13770. tmp.port = '0';
  13771. }
  13772. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13773. if (sctp.length)
  13774. tmp.proto = 'DTLS/SCTP';
  13775. else
  13776. tmp.proto = 'RTP/SAVPF';
  13777. } else {
  13778. tmp.proto = 'RTP/AVPF';
  13779. }
  13780. if (!sctp.length)
  13781. {
  13782. tmp.fmt = desc.find('payload-type').map(
  13783. function () { return this.getAttribute('id'); }).get();
  13784. media += SDPUtil.build_mline(tmp) + '\r\n';
  13785. }
  13786. else
  13787. {
  13788. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13789. media += 'a=sctpmap:' + sctp.attr('number') +
  13790. ' ' + sctp.attr('protocol');
  13791. var streamCount = sctp.attr('streams');
  13792. if (streamCount)
  13793. media += ' ' + streamCount + '\r\n';
  13794. else
  13795. media += '\r\n';
  13796. }
  13797. media += 'c=IN IP4 0.0.0.0\r\n';
  13798. if (!sctp.length)
  13799. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13800. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13801. if (tmp.length) {
  13802. if (tmp.attr('ufrag')) {
  13803. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13804. }
  13805. if (tmp.attr('pwd')) {
  13806. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13807. }
  13808. tmp.find('>fingerprint').each(function () {
  13809. // FIXME: check namespace at some point
  13810. media += 'a=fingerprint:' + this.getAttribute('hash');
  13811. media += ' ' + $(this).text();
  13812. media += '\r\n';
  13813. if (this.getAttribute('setup')) {
  13814. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13815. }
  13816. });
  13817. }
  13818. switch (content.attr('senders')) {
  13819. case 'initiator':
  13820. media += 'a=sendonly\r\n';
  13821. break;
  13822. case 'responder':
  13823. media += 'a=recvonly\r\n';
  13824. break;
  13825. case 'none':
  13826. media += 'a=inactive\r\n';
  13827. break;
  13828. case 'both':
  13829. media += 'a=sendrecv\r\n';
  13830. break;
  13831. }
  13832. media += 'a=mid:' + content.attr('name') + '\r\n';
  13833. // <description><rtcp-mux/></description>
  13834. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13835. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13836. if (desc.find('rtcp-mux').length) {
  13837. media += 'a=rtcp-mux\r\n';
  13838. }
  13839. if (desc.find('encryption').length) {
  13840. desc.find('encryption>crypto').each(function () {
  13841. media += 'a=crypto:' + this.getAttribute('tag');
  13842. media += ' ' + this.getAttribute('crypto-suite');
  13843. media += ' ' + this.getAttribute('key-params');
  13844. if (this.getAttribute('session-params')) {
  13845. media += ' ' + this.getAttribute('session-params');
  13846. }
  13847. media += '\r\n';
  13848. });
  13849. }
  13850. desc.find('payload-type').each(function () {
  13851. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13852. if ($(this).find('>parameter').length) {
  13853. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13854. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13855. media += '\r\n';
  13856. }
  13857. // xep-0293
  13858. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13859. });
  13860. // xep-0293
  13861. media += self.RtcpFbFromJingle(desc, '*');
  13862. // xep-0294
  13863. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13864. tmp.each(function () {
  13865. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13866. });
  13867. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13868. media += SDPUtil.candidateFromJingle(this);
  13869. });
  13870. // XEP-0339 handle ssrc-group attributes
  13871. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13872. var semantics = this.getAttribute('semantics');
  13873. var ssrcs = $(this).find('>source').map(function() {
  13874. return this.getAttribute('ssrc');
  13875. }).get();
  13876. if (ssrcs.length != 0) {
  13877. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13878. }
  13879. });
  13880. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13881. tmp.each(function () {
  13882. var ssrc = this.getAttribute('ssrc');
  13883. $(this).find('>parameter').each(function () {
  13884. var name = this.getAttribute('name');
  13885. var value = this.getAttribute('value');
  13886. value = SDPUtil.filter_special_chars(value);
  13887. media += 'a=ssrc:' + ssrc + ' ' + name;
  13888. if (value && value.length)
  13889. media += ':' + value;
  13890. media += '\r\n';
  13891. });
  13892. });
  13893. return media;
  13894. };
  13895. module.exports = SDP;
  13896. },{"./SDPUtil":60}],59:[function(require,module,exports){
  13897. var SDPUtil = require("./SDPUtil");
  13898. function SDPDiffer(mySDP, otherSDP) {
  13899. this.mySDP = mySDP;
  13900. this.otherSDP = otherSDP;
  13901. }
  13902. /**
  13903. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13904. * @param otherSdp the other SDP to check ssrc with.
  13905. */
  13906. SDPDiffer.prototype.getNewMedia = function() {
  13907. // this could be useful in Array.prototype.
  13908. function arrayEquals(array) {
  13909. // if the other array is a falsy value, return
  13910. if (!array)
  13911. return false;
  13912. // compare lengths - can save a lot of time
  13913. if (this.length != array.length)
  13914. return false;
  13915. for (var i = 0, l=this.length; i < l; i++) {
  13916. // Check if we have nested arrays
  13917. if (this[i] instanceof Array && array[i] instanceof Array) {
  13918. // recurse into the nested arrays
  13919. if (!this[i].equals(array[i]))
  13920. return false;
  13921. }
  13922. else if (this[i] != array[i]) {
  13923. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13924. return false;
  13925. }
  13926. }
  13927. return true;
  13928. }
  13929. var myMedias = this.mySDP.getMediaSsrcMap();
  13930. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13931. var newMedia = {};
  13932. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13933. var myMedia = myMedias[othersMediaIdx];
  13934. var othersMedia = othersMedias[othersMediaIdx];
  13935. if(!myMedia && othersMedia) {
  13936. // Add whole channel
  13937. newMedia[othersMediaIdx] = othersMedia;
  13938. return;
  13939. }
  13940. // Look for new ssrcs accross the channel
  13941. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13942. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13943. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13944. if(!newMedia[othersMediaIdx]){
  13945. newMedia[othersMediaIdx] = {
  13946. mediaindex: othersMedia.mediaindex,
  13947. mid: othersMedia.mid,
  13948. ssrcs: {},
  13949. ssrcGroups: []
  13950. };
  13951. }
  13952. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13953. }
  13954. });
  13955. // Look for new ssrc groups across the channels
  13956. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13957. // try to match the other ssrc-group with an ssrc-group of ours
  13958. var matched = false;
  13959. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13960. var mySsrcGroup = myMedia.ssrcGroups[i];
  13961. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13962. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13963. matched = true;
  13964. break;
  13965. }
  13966. }
  13967. if (!matched) {
  13968. // Allocate channel if we've found an ssrc-group that doesn't
  13969. // exist in our channel
  13970. if(!newMedia[othersMediaIdx]){
  13971. newMedia[othersMediaIdx] = {
  13972. mediaindex: othersMedia.mediaindex,
  13973. mid: othersMedia.mid,
  13974. ssrcs: {},
  13975. ssrcGroups: []
  13976. };
  13977. }
  13978. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13979. }
  13980. });
  13981. });
  13982. return newMedia;
  13983. };
  13984. /**
  13985. * Sends SSRC update IQ.
  13986. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13987. * @param sid session identifier that will be put into the IQ.
  13988. * @param initiator initiator identifier.
  13989. * @param toJid destination Jid
  13990. * @param isAdd indicates if this is remove or add operation.
  13991. */
  13992. SDPDiffer.prototype.toJingle = function(modify) {
  13993. var sdpMediaSsrcs = this.getNewMedia();
  13994. var self = this;
  13995. // FIXME: only announce video ssrcs since we mix audio and dont need
  13996. // the audio ssrcs therefore
  13997. var modified = false;
  13998. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13999. modified = true;
  14000. var media = sdpMediaSsrcs[mediaindex];
  14001. modify.c('content', {name: media.mid});
  14002. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  14003. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  14004. // generate sources from lines
  14005. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  14006. var mediaSsrc = media.ssrcs[ssrcNum];
  14007. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  14008. modify.attrs({ssrc: mediaSsrc.ssrc});
  14009. // iterate over ssrc lines
  14010. mediaSsrc.lines.forEach(function (line) {
  14011. var idx = line.indexOf(' ');
  14012. var kv = line.substr(idx + 1);
  14013. modify.c('parameter');
  14014. if (kv.indexOf(':') == -1) {
  14015. modify.attrs({ name: kv });
  14016. } else {
  14017. var nv = kv.split(':', 2);
  14018. var name = nv[0];
  14019. var value = SDPUtil.filter_special_chars(nv[1]);
  14020. modify.attrs({ name: name });
  14021. modify.attrs({ value: value });
  14022. }
  14023. modify.up(); // end of parameter
  14024. });
  14025. modify.up(); // end of source
  14026. });
  14027. // generate source groups from lines
  14028. media.ssrcGroups.forEach(function(ssrcGroup) {
  14029. if (ssrcGroup.ssrcs.length != 0) {
  14030. modify.c('ssrc-group', {
  14031. semantics: ssrcGroup.semantics,
  14032. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  14033. });
  14034. ssrcGroup.ssrcs.forEach(function (ssrc) {
  14035. modify.c('source', { ssrc: ssrc })
  14036. .up(); // end of source
  14037. });
  14038. modify.up(); // end of ssrc-group
  14039. }
  14040. });
  14041. modify.up(); // end of description
  14042. modify.up(); // end of content
  14043. });
  14044. return modified;
  14045. };
  14046. module.exports = SDPDiffer;
  14047. },{"./SDPUtil":60}],60:[function(require,module,exports){
  14048. SDPUtil = {
  14049. filter_special_chars: function (text) {
  14050. return text.replace(/[\\\/\{,\}\+]/g, "");
  14051. },
  14052. iceparams: function (mediadesc, sessiondesc) {
  14053. var data = null;
  14054. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  14055. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  14056. data = {
  14057. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  14058. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  14059. };
  14060. }
  14061. return data;
  14062. },
  14063. parse_iceufrag: function (line) {
  14064. return line.substring(12);
  14065. },
  14066. build_iceufrag: function (frag) {
  14067. return 'a=ice-ufrag:' + frag;
  14068. },
  14069. parse_icepwd: function (line) {
  14070. return line.substring(10);
  14071. },
  14072. build_icepwd: function (pwd) {
  14073. return 'a=ice-pwd:' + pwd;
  14074. },
  14075. parse_mid: function (line) {
  14076. return line.substring(6);
  14077. },
  14078. parse_mline: function (line) {
  14079. var parts = line.substring(2).split(' '),
  14080. data = {};
  14081. data.media = parts.shift();
  14082. data.port = parts.shift();
  14083. data.proto = parts.shift();
  14084. if (parts[parts.length - 1] === '') { // trailing whitespace
  14085. parts.pop();
  14086. }
  14087. data.fmt = parts;
  14088. return data;
  14089. },
  14090. build_mline: function (mline) {
  14091. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  14092. },
  14093. parse_rtpmap: function (line) {
  14094. var parts = line.substring(9).split(' '),
  14095. data = {};
  14096. data.id = parts.shift();
  14097. parts = parts[0].split('/');
  14098. data.name = parts.shift();
  14099. data.clockrate = parts.shift();
  14100. data.channels = parts.length ? parts.shift() : '1';
  14101. return data;
  14102. },
  14103. /**
  14104. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  14105. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  14106. * @returns [SCTP port number, protocol, streams]
  14107. */
  14108. parse_sctpmap: function (line)
  14109. {
  14110. var parts = line.substring(10).split(' ');
  14111. var sctpPort = parts[0];
  14112. var protocol = parts[1];
  14113. // Stream count is optional
  14114. var streamCount = parts.length > 2 ? parts[2] : null;
  14115. return [sctpPort, protocol, streamCount];// SCTP port
  14116. },
  14117. build_rtpmap: function (el) {
  14118. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14119. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14120. line += '/' + el.getAttribute('channels');
  14121. }
  14122. return line;
  14123. },
  14124. parse_crypto: function (line) {
  14125. var parts = line.substring(9).split(' '),
  14126. data = {};
  14127. data.tag = parts.shift();
  14128. data['crypto-suite'] = parts.shift();
  14129. data['key-params'] = parts.shift();
  14130. if (parts.length) {
  14131. data['session-params'] = parts.join(' ');
  14132. }
  14133. return data;
  14134. },
  14135. parse_fingerprint: function (line) { // RFC 4572
  14136. var parts = line.substring(14).split(' '),
  14137. data = {};
  14138. data.hash = parts.shift();
  14139. data.fingerprint = parts.shift();
  14140. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14141. return data;
  14142. },
  14143. parse_fmtp: function (line) {
  14144. var parts = line.split(' '),
  14145. i, key, value,
  14146. data = [];
  14147. parts.shift();
  14148. parts = parts.join(' ').split(';');
  14149. for (i = 0; i < parts.length; i++) {
  14150. key = parts[i].split('=')[0];
  14151. while (key.length && key[0] == ' ') {
  14152. key = key.substring(1);
  14153. }
  14154. value = parts[i].split('=')[1];
  14155. if (key && value) {
  14156. data.push({name: key, value: value});
  14157. } else if (key) {
  14158. // rfc 4733 (DTMF) style stuff
  14159. data.push({name: '', value: key});
  14160. }
  14161. }
  14162. return data;
  14163. },
  14164. parse_icecandidate: function (line) {
  14165. var candidate = {},
  14166. elems = line.split(' ');
  14167. candidate.foundation = elems[0].substring(12);
  14168. candidate.component = elems[1];
  14169. candidate.protocol = elems[2].toLowerCase();
  14170. candidate.priority = elems[3];
  14171. candidate.ip = elems[4];
  14172. candidate.port = elems[5];
  14173. // elems[6] => "typ"
  14174. candidate.type = elems[7];
  14175. candidate.generation = 0; // default value, may be overwritten below
  14176. for (var i = 8; i < elems.length; i += 2) {
  14177. switch (elems[i]) {
  14178. case 'raddr':
  14179. candidate['rel-addr'] = elems[i + 1];
  14180. break;
  14181. case 'rport':
  14182. candidate['rel-port'] = elems[i + 1];
  14183. break;
  14184. case 'generation':
  14185. candidate.generation = elems[i + 1];
  14186. break;
  14187. case 'tcptype':
  14188. candidate.tcptype = elems[i + 1];
  14189. break;
  14190. default: // TODO
  14191. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14192. }
  14193. }
  14194. candidate.network = '1';
  14195. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14196. return candidate;
  14197. },
  14198. build_icecandidate: function (cand) {
  14199. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14200. line += ' ';
  14201. switch (cand.type) {
  14202. case 'srflx':
  14203. case 'prflx':
  14204. case 'relay':
  14205. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14206. line += 'raddr';
  14207. line += ' ';
  14208. line += cand['rel-addr'];
  14209. line += ' ';
  14210. line += 'rport';
  14211. line += ' ';
  14212. line += cand['rel-port'];
  14213. line += ' ';
  14214. }
  14215. break;
  14216. }
  14217. if (cand.hasOwnAttribute('tcptype')) {
  14218. line += 'tcptype';
  14219. line += ' ';
  14220. line += cand.tcptype;
  14221. line += ' ';
  14222. }
  14223. line += 'generation';
  14224. line += ' ';
  14225. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14226. return line;
  14227. },
  14228. parse_ssrc: function (desc) {
  14229. // proprietary mapping of a=ssrc lines
  14230. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14231. // and parse according to that
  14232. var lines = desc.split('\r\n'),
  14233. data = {};
  14234. for (var i = 0; i < lines.length; i++) {
  14235. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14236. var idx = lines[i].indexOf(' ');
  14237. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14238. }
  14239. }
  14240. return data;
  14241. },
  14242. parse_rtcpfb: function (line) {
  14243. var parts = line.substr(10).split(' ');
  14244. var data = {};
  14245. data.pt = parts.shift();
  14246. data.type = parts.shift();
  14247. data.params = parts;
  14248. return data;
  14249. },
  14250. parse_extmap: function (line) {
  14251. var parts = line.substr(9).split(' ');
  14252. var data = {};
  14253. data.value = parts.shift();
  14254. if (data.value.indexOf('/') != -1) {
  14255. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14256. data.value = data.value.substr(0, data.value.indexOf('/'));
  14257. } else {
  14258. data.direction = 'both';
  14259. }
  14260. data.uri = parts.shift();
  14261. data.params = parts;
  14262. return data;
  14263. },
  14264. find_line: function (haystack, needle, sessionpart) {
  14265. var lines = haystack.split('\r\n');
  14266. for (var i = 0; i < lines.length; i++) {
  14267. if (lines[i].substring(0, needle.length) == needle) {
  14268. return lines[i];
  14269. }
  14270. }
  14271. if (!sessionpart) {
  14272. return false;
  14273. }
  14274. // search session part
  14275. lines = sessionpart.split('\r\n');
  14276. for (var j = 0; j < lines.length; j++) {
  14277. if (lines[j].substring(0, needle.length) == needle) {
  14278. return lines[j];
  14279. }
  14280. }
  14281. return false;
  14282. },
  14283. find_lines: function (haystack, needle, sessionpart) {
  14284. var lines = haystack.split('\r\n'),
  14285. needles = [];
  14286. for (var i = 0; i < lines.length; i++) {
  14287. if (lines[i].substring(0, needle.length) == needle)
  14288. needles.push(lines[i]);
  14289. }
  14290. if (needles.length || !sessionpart) {
  14291. return needles;
  14292. }
  14293. // search session part
  14294. lines = sessionpart.split('\r\n');
  14295. for (var j = 0; j < lines.length; j++) {
  14296. if (lines[j].substring(0, needle.length) == needle) {
  14297. needles.push(lines[j]);
  14298. }
  14299. }
  14300. return needles;
  14301. },
  14302. candidateToJingle: function (line) {
  14303. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14304. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14305. if (line.indexOf('candidate:') === 0) {
  14306. line = 'a=' + line;
  14307. } else if (line.substring(0, 12) != 'a=candidate:') {
  14308. console.log('parseCandidate called with a line that is not a candidate line');
  14309. console.log(line);
  14310. return null;
  14311. }
  14312. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14313. line = line.substring(0, line.length - 2);
  14314. var candidate = {},
  14315. elems = line.split(' '),
  14316. i;
  14317. if (elems[6] != 'typ') {
  14318. console.log('did not find typ in the right place');
  14319. console.log(line);
  14320. return null;
  14321. }
  14322. candidate.foundation = elems[0].substring(12);
  14323. candidate.component = elems[1];
  14324. candidate.protocol = elems[2].toLowerCase();
  14325. candidate.priority = elems[3];
  14326. candidate.ip = elems[4];
  14327. candidate.port = elems[5];
  14328. // elems[6] => "typ"
  14329. candidate.type = elems[7];
  14330. candidate.generation = '0'; // default, may be overwritten below
  14331. for (i = 8; i < elems.length; i += 2) {
  14332. switch (elems[i]) {
  14333. case 'raddr':
  14334. candidate['rel-addr'] = elems[i + 1];
  14335. break;
  14336. case 'rport':
  14337. candidate['rel-port'] = elems[i + 1];
  14338. break;
  14339. case 'generation':
  14340. candidate.generation = elems[i + 1];
  14341. break;
  14342. case 'tcptype':
  14343. candidate.tcptype = elems[i + 1];
  14344. break;
  14345. default: // TODO
  14346. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14347. }
  14348. }
  14349. candidate.network = '1';
  14350. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14351. return candidate;
  14352. },
  14353. candidateFromJingle: function (cand) {
  14354. var line = 'a=candidate:';
  14355. line += cand.getAttribute('foundation');
  14356. line += ' ';
  14357. line += cand.getAttribute('component');
  14358. line += ' ';
  14359. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14360. line += ' ';
  14361. line += cand.getAttribute('priority');
  14362. line += ' ';
  14363. line += cand.getAttribute('ip');
  14364. line += ' ';
  14365. line += cand.getAttribute('port');
  14366. line += ' ';
  14367. line += 'typ';
  14368. line += ' ' + cand.getAttribute('type');
  14369. line += ' ';
  14370. switch (cand.getAttribute('type')) {
  14371. case 'srflx':
  14372. case 'prflx':
  14373. case 'relay':
  14374. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14375. line += 'raddr';
  14376. line += ' ';
  14377. line += cand.getAttribute('rel-addr');
  14378. line += ' ';
  14379. line += 'rport';
  14380. line += ' ';
  14381. line += cand.getAttribute('rel-port');
  14382. line += ' ';
  14383. }
  14384. break;
  14385. }
  14386. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14387. line += 'tcptype';
  14388. line += ' ';
  14389. line += cand.getAttribute('tcptype');
  14390. line += ' ';
  14391. }
  14392. line += 'generation';
  14393. line += ' ';
  14394. line += cand.getAttribute('generation') || '0';
  14395. return line + '\r\n';
  14396. }
  14397. };
  14398. module.exports = SDPUtil;
  14399. },{}],61:[function(require,module,exports){
  14400. var RTC = require('../RTC/RTC');
  14401. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14402. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14403. var SSRCReplacement = require("./LocalSSRCReplacement");
  14404. function TraceablePeerConnection(ice_config, constraints, session) {
  14405. var self = this;
  14406. var RTCPeerConnectionType = null;
  14407. if (RTCBrowserType.isFirefox()) {
  14408. RTCPeerConnectionType = mozRTCPeerConnection;
  14409. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14410. RTCPeerConnectionType = RTCPeerConnection;
  14411. } else {
  14412. RTCPeerConnectionType = webkitRTCPeerConnection;
  14413. }
  14414. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14415. this.updateLog = [];
  14416. this.stats = {};
  14417. this.statsinterval = null;
  14418. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14419. var Interop = require('sdp-interop').Interop;
  14420. this.interop = new Interop();
  14421. var Simulcast = require('sdp-simulcast');
  14422. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14423. // override as desired
  14424. this.trace = function (what, info) {
  14425. /*console.warn('WTRACE', what, info);
  14426. if (info && RTCBrowserType.isIExplorer()) {
  14427. if (info.length > 1024) {
  14428. console.warn('WTRACE', what, info.substr(1024));
  14429. }
  14430. if (info.length > 2048) {
  14431. console.warn('WTRACE', what, info.substr(2048));
  14432. }
  14433. }*/
  14434. self.updateLog.push({
  14435. time: new Date(),
  14436. type: what,
  14437. value: info || ""
  14438. });
  14439. };
  14440. this.onicecandidate = null;
  14441. this.peerconnection.onicecandidate = function (event) {
  14442. // FIXME: this causes stack overflow with Temasys Plugin
  14443. if (!RTCBrowserType.isTemasysPluginUsed())
  14444. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14445. if (self.onicecandidate !== null) {
  14446. self.onicecandidate(event);
  14447. }
  14448. };
  14449. this.onaddstream = null;
  14450. this.peerconnection.onaddstream = function (event) {
  14451. self.trace('onaddstream', event.stream.id);
  14452. if (self.onaddstream !== null) {
  14453. self.onaddstream(event);
  14454. }
  14455. };
  14456. this.onremovestream = null;
  14457. this.peerconnection.onremovestream = function (event) {
  14458. self.trace('onremovestream', event.stream.id);
  14459. if (self.onremovestream !== null) {
  14460. self.onremovestream(event);
  14461. }
  14462. };
  14463. this.onsignalingstatechange = null;
  14464. this.peerconnection.onsignalingstatechange = function (event) {
  14465. self.trace('onsignalingstatechange', self.signalingState);
  14466. if (self.onsignalingstatechange !== null) {
  14467. self.onsignalingstatechange(event);
  14468. }
  14469. };
  14470. this.oniceconnectionstatechange = null;
  14471. this.peerconnection.oniceconnectionstatechange = function (event) {
  14472. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14473. if (self.oniceconnectionstatechange !== null) {
  14474. self.oniceconnectionstatechange(event);
  14475. }
  14476. };
  14477. this.onnegotiationneeded = null;
  14478. this.peerconnection.onnegotiationneeded = function (event) {
  14479. self.trace('onnegotiationneeded');
  14480. if (self.onnegotiationneeded !== null) {
  14481. self.onnegotiationneeded(event);
  14482. }
  14483. };
  14484. self.ondatachannel = null;
  14485. this.peerconnection.ondatachannel = function (event) {
  14486. self.trace('ondatachannel', event);
  14487. if (self.ondatachannel !== null) {
  14488. self.ondatachannel(event);
  14489. }
  14490. };
  14491. // XXX: do all non-firefox browsers which we support also support this?
  14492. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14493. this.statsinterval = window.setInterval(function() {
  14494. self.peerconnection.getStats(function(stats) {
  14495. var results = stats.result();
  14496. var now = new Date();
  14497. for (var i = 0; i < results.length; ++i) {
  14498. results[i].names().forEach(function (name) {
  14499. var id = results[i].id + '-' + name;
  14500. if (!self.stats[id]) {
  14501. self.stats[id] = {
  14502. startTime: now,
  14503. endTime: now,
  14504. values: [],
  14505. times: []
  14506. };
  14507. }
  14508. self.stats[id].values.push(results[i].stat(name));
  14509. self.stats[id].times.push(now.getTime());
  14510. if (self.stats[id].values.length > self.maxstats) {
  14511. self.stats[id].values.shift();
  14512. self.stats[id].times.shift();
  14513. }
  14514. self.stats[id].endTime = now;
  14515. });
  14516. }
  14517. });
  14518. }, 1000);
  14519. }
  14520. }
  14521. /**
  14522. * Returns a string representation of a SessionDescription object.
  14523. */
  14524. var dumpSDP = function(description) {
  14525. if (typeof description === 'undefined' || description == null) {
  14526. return '';
  14527. }
  14528. return 'type: ' + description.type + '\r\n' + description.sdp;
  14529. };
  14530. /**
  14531. * Takes a SessionDescription object and returns a "normalized" version.
  14532. * Currently it only takes care of ordering the a=ssrc lines.
  14533. */
  14534. var normalizePlanB = function(desc) {
  14535. if (typeof desc !== 'object' || desc === null ||
  14536. typeof desc.sdp !== 'string') {
  14537. console.warn('An empty description was passed as an argument.');
  14538. return desc;
  14539. }
  14540. var transform = require('sdp-transform');
  14541. var session = transform.parse(desc.sdp);
  14542. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14543. Array.isArray(session.media)) {
  14544. session.media.forEach(function (mLine) {
  14545. // Chrome appears to be picky about the order in which a=ssrc lines
  14546. // are listed in an m-line when rtx is enabled (and thus there are
  14547. // a=ssrc-group lines with FID semantics). Specifically if we have
  14548. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14549. // the "a=ssrc:S1" lines, SRD fails.
  14550. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14551. // first.
  14552. var firstSsrcs = [];
  14553. var newSsrcLines = [];
  14554. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14555. mLine.ssrcGroups.forEach(function (group) {
  14556. if (typeof group.semantics !== 'undefined' &&
  14557. group.semantics === 'FID') {
  14558. if (typeof group.ssrcs !== 'undefined') {
  14559. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14560. }
  14561. }
  14562. });
  14563. }
  14564. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14565. for (var i = 0; i<mLine.ssrcs.length; i++){
  14566. if (typeof mLine.ssrcs[i] === 'object'
  14567. && typeof mLine.ssrcs[i].id !== 'undefined'
  14568. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14569. newSsrcLines.push(mLine.ssrcs[i]);
  14570. delete mLine.ssrcs[i];
  14571. }
  14572. }
  14573. for (var i = 0; i<mLine.ssrcs.length; i++){
  14574. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14575. newSsrcLines.push(mLine.ssrcs[i]);
  14576. }
  14577. }
  14578. mLine.ssrcs = newSsrcLines;
  14579. }
  14580. });
  14581. }
  14582. var resStr = transform.write(session);
  14583. return new RTCSessionDescription({
  14584. type: desc.type,
  14585. sdp: resStr
  14586. });
  14587. };
  14588. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14589. TraceablePeerConnection.prototype.__defineGetter__(
  14590. 'signalingState',
  14591. function() { return this.peerconnection.signalingState; });
  14592. TraceablePeerConnection.prototype.__defineGetter__(
  14593. 'iceConnectionState',
  14594. function() { return this.peerconnection.iceConnectionState; });
  14595. TraceablePeerConnection.prototype.__defineGetter__(
  14596. 'localDescription',
  14597. function() {
  14598. var desc = this.peerconnection.localDescription;
  14599. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14600. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14601. // if we're running on FF, transform to Plan B first.
  14602. if (RTCBrowserType.usesUnifiedPlan()) {
  14603. desc = this.interop.toPlanB(desc);
  14604. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14605. }
  14606. return desc;
  14607. });
  14608. TraceablePeerConnection.prototype.__defineGetter__(
  14609. 'remoteDescription',
  14610. function() {
  14611. var desc = this.peerconnection.remoteDescription;
  14612. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14613. // if we're running on FF, transform to Plan B first.
  14614. if (RTCBrowserType.usesUnifiedPlan()) {
  14615. desc = this.interop.toPlanB(desc);
  14616. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14617. }
  14618. return desc;
  14619. });
  14620. }
  14621. TraceablePeerConnection.prototype.addStream = function (stream) {
  14622. this.trace('addStream', stream.id);
  14623. try
  14624. {
  14625. this.peerconnection.addStream(stream);
  14626. }
  14627. catch (e)
  14628. {
  14629. console.error(e);
  14630. }
  14631. };
  14632. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14633. this.trace('removeStream', stream.id);
  14634. if(stopStreams) {
  14635. stream.getAudioTracks().forEach(function (track) {
  14636. // stop() not supported with IE
  14637. if (track.stop) {
  14638. track.stop();
  14639. }
  14640. });
  14641. stream.getVideoTracks().forEach(function (track) {
  14642. // stop() not supported with IE
  14643. if (track.stop) {
  14644. track.stop();
  14645. }
  14646. });
  14647. if (stream.stop) {
  14648. stream.stop();
  14649. }
  14650. }
  14651. try {
  14652. // FF doesn't support this yet.
  14653. if (this.peerconnection.removeStream)
  14654. this.peerconnection.removeStream(stream);
  14655. } catch (e) {
  14656. console.error(e);
  14657. }
  14658. };
  14659. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14660. this.trace('createDataChannel', label, opts);
  14661. return this.peerconnection.createDataChannel(label, opts);
  14662. };
  14663. TraceablePeerConnection.prototype.setLocalDescription
  14664. = function (description, successCallback, failureCallback) {
  14665. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14666. // if we're running on FF, transform to Plan A first.
  14667. if (RTCBrowserType.usesUnifiedPlan()) {
  14668. description = this.interop.toUnifiedPlan(description);
  14669. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14670. }
  14671. var self = this;
  14672. this.peerconnection.setLocalDescription(description,
  14673. function () {
  14674. self.trace('setLocalDescriptionOnSuccess');
  14675. successCallback();
  14676. },
  14677. function (err) {
  14678. self.trace('setLocalDescriptionOnFailure', err);
  14679. failureCallback(err);
  14680. }
  14681. );
  14682. /*
  14683. if (this.statsinterval === null && this.maxstats > 0) {
  14684. // start gathering stats
  14685. }
  14686. */
  14687. };
  14688. TraceablePeerConnection.prototype.setRemoteDescription
  14689. = function (description, successCallback, failureCallback) {
  14690. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14691. // TODO the focus should squeze or explode the remote simulcast
  14692. description = this.simulcast.mungeRemoteDescription(description);
  14693. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14694. // if we're running on FF, transform to Plan A first.
  14695. if (RTCBrowserType.usesUnifiedPlan()) {
  14696. description = this.interop.toUnifiedPlan(description);
  14697. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14698. }
  14699. if (RTCBrowserType.usesPlanB()) {
  14700. description = normalizePlanB(description);
  14701. }
  14702. var self = this;
  14703. this.peerconnection.setRemoteDescription(description,
  14704. function () {
  14705. self.trace('setRemoteDescriptionOnSuccess');
  14706. successCallback();
  14707. },
  14708. function (err) {
  14709. self.trace('setRemoteDescriptionOnFailure', err);
  14710. failureCallback(err);
  14711. }
  14712. );
  14713. /*
  14714. if (this.statsinterval === null && this.maxstats > 0) {
  14715. // start gathering stats
  14716. }
  14717. */
  14718. };
  14719. TraceablePeerConnection.prototype.close = function () {
  14720. this.trace('stop');
  14721. if (this.statsinterval !== null) {
  14722. window.clearInterval(this.statsinterval);
  14723. this.statsinterval = null;
  14724. }
  14725. this.peerconnection.close();
  14726. };
  14727. TraceablePeerConnection.prototype.createOffer
  14728. = function (successCallback, failureCallback, constraints) {
  14729. var self = this;
  14730. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14731. this.peerconnection.createOffer(
  14732. function (offer) {
  14733. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14734. // NOTE this is not tested because in meet the focus generates the
  14735. // offer.
  14736. // if we're running on FF, transform to Plan B first.
  14737. if (RTCBrowserType.usesUnifiedPlan()) {
  14738. offer = self.interop.toPlanB(offer);
  14739. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14740. }
  14741. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  14742. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14743. offer = self.simulcast.mungeLocalDescription(offer);
  14744. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14745. }
  14746. successCallback(offer);
  14747. },
  14748. function(err) {
  14749. self.trace('createOfferOnFailure', err);
  14750. failureCallback(err);
  14751. },
  14752. constraints
  14753. );
  14754. };
  14755. TraceablePeerConnection.prototype.createAnswer
  14756. = function (successCallback, failureCallback, constraints) {
  14757. var self = this;
  14758. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14759. this.peerconnection.createAnswer(
  14760. function (answer) {
  14761. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14762. // if we're running on FF, transform to Plan A first.
  14763. if (RTCBrowserType.usesUnifiedPlan()) {
  14764. answer = self.interop.toPlanB(answer);
  14765. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14766. }
  14767. // munge local video SSRC
  14768. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  14769. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14770. answer = self.simulcast.mungeLocalDescription(answer);
  14771. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14772. }
  14773. successCallback(answer);
  14774. },
  14775. function(err) {
  14776. self.trace('createAnswerOnFailure', err);
  14777. failureCallback(err);
  14778. },
  14779. constraints
  14780. );
  14781. };
  14782. TraceablePeerConnection.prototype.addIceCandidate
  14783. = function (candidate, successCallback, failureCallback) {
  14784. //var self = this;
  14785. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14786. this.peerconnection.addIceCandidate(candidate);
  14787. /* maybe later
  14788. this.peerconnection.addIceCandidate(candidate,
  14789. function () {
  14790. self.trace('addIceCandidateOnSuccess');
  14791. successCallback();
  14792. },
  14793. function (err) {
  14794. self.trace('addIceCandidateOnFailure', err);
  14795. failureCallback(err);
  14796. }
  14797. );
  14798. */
  14799. };
  14800. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14801. // TODO: Is this the correct way to handle Opera, Temasys?
  14802. if (RTCBrowserType.isFirefox()) {
  14803. // ignore for now...
  14804. if(!errback)
  14805. errback = function () {};
  14806. this.peerconnection.getStats(null, callback, errback);
  14807. } else {
  14808. this.peerconnection.getStats(callback);
  14809. }
  14810. };
  14811. module.exports = TraceablePeerConnection;
  14812. },{"../../service/xmpp/XMPPEvents":172,"../RTC/RTC":7,"../RTC/RTCBrowserType.js":8,"./LocalSSRCReplacement":57,"sdp-interop":95,"sdp-simulcast":102,"sdp-transform":109}],62:[function(require,module,exports){
  14813. /* global $, $iq, APP, config, messageHandler,
  14814. roomName, sessionTerminated, Strophe, Util */
  14815. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14816. var Settings = require("../settings/Settings");
  14817. var AuthenticationEvents
  14818. = require("../../service/authentication/AuthenticationEvents");
  14819. /**
  14820. * Contains logic responsible for enabling/disabling functionality available
  14821. * only to moderator users.
  14822. */
  14823. var connection = null;
  14824. var focusUserJid;
  14825. function createExpBackoffTimer(step) {
  14826. var count = 1;
  14827. return function (reset) {
  14828. // Reset call
  14829. if (reset) {
  14830. count = 1;
  14831. return;
  14832. }
  14833. // Calculate next timeout
  14834. var timeout = Math.pow(2, count - 1);
  14835. count += 1;
  14836. return timeout * step;
  14837. };
  14838. }
  14839. var getNextTimeout = createExpBackoffTimer(1000);
  14840. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14841. // External authentication stuff
  14842. var externalAuthEnabled = false;
  14843. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14844. // it will be enabled automatically if focus detects the component through
  14845. // service discovery.
  14846. var sipGatewayEnabled;
  14847. var eventEmitter = null;
  14848. var Moderator = {
  14849. isModerator: function () {
  14850. return connection && connection.emuc.isModerator();
  14851. },
  14852. isPeerModerator: function (peerJid) {
  14853. return connection &&
  14854. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14855. },
  14856. isExternalAuthEnabled: function () {
  14857. return externalAuthEnabled;
  14858. },
  14859. isSipGatewayEnabled: function () {
  14860. return sipGatewayEnabled;
  14861. },
  14862. setConnection: function (con) {
  14863. connection = con;
  14864. },
  14865. init: function (xmpp, emitter) {
  14866. this.xmppService = xmpp;
  14867. eventEmitter = emitter;
  14868. sipGatewayEnabled =
  14869. config.hosts && config.hosts.call_control !== undefined;
  14870. // Message listener that talks to POPUP window
  14871. function listener(event) {
  14872. if (event.data && event.data.sessionId) {
  14873. if (event.origin !== window.location.origin) {
  14874. console.warn("Ignoring sessionId from different origin: " +
  14875. event.origin);
  14876. return;
  14877. }
  14878. localStorage.setItem('sessionId', event.data.sessionId);
  14879. // After popup is closed we will authenticate
  14880. }
  14881. }
  14882. // Register
  14883. if (window.addEventListener) {
  14884. window.addEventListener("message", listener, false);
  14885. } else {
  14886. window.attachEvent("onmessage", listener);
  14887. }
  14888. },
  14889. onMucMemberLeft: function (jid) {
  14890. console.info("Someone left is it focus ? " + jid);
  14891. var resource = Strophe.getResourceFromJid(jid);
  14892. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14893. console.info(
  14894. "Focus has left the room - leaving conference");
  14895. //hangUp();
  14896. // We'd rather reload to have everything re-initialized
  14897. // FIXME: show some message before reload
  14898. location.reload();
  14899. }
  14900. },
  14901. setFocusUserJid: function (focusJid) {
  14902. if (!focusUserJid) {
  14903. focusUserJid = focusJid;
  14904. console.info("Focus jid set to: " + focusUserJid);
  14905. }
  14906. },
  14907. getFocusUserJid: function () {
  14908. return focusUserJid;
  14909. },
  14910. getFocusComponent: function () {
  14911. // Get focus component address
  14912. var focusComponent = config.hosts.focus;
  14913. // If not specified use default: 'focus.domain'
  14914. if (!focusComponent) {
  14915. focusComponent = 'focus.' + config.hosts.domain;
  14916. }
  14917. return focusComponent;
  14918. },
  14919. createConferenceIq: function (roomName) {
  14920. // Generate create conference IQ
  14921. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14922. // Session Id used for authentication
  14923. var sessionId = localStorage.getItem('sessionId');
  14924. var machineUID = Settings.getSettings().uid;
  14925. console.info(
  14926. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14927. elem.c('conference', {
  14928. xmlns: 'http://jitsi.org/protocol/focus',
  14929. room: roomName,
  14930. 'machine-uid': machineUID
  14931. });
  14932. if (sessionId) {
  14933. elem.attrs({ 'session-id': sessionId});
  14934. }
  14935. if (config.hosts.bridge !== undefined) {
  14936. elem.c(
  14937. 'property',
  14938. { name: 'bridge', value: config.hosts.bridge})
  14939. .up();
  14940. }
  14941. // Tell the focus we have Jigasi configured
  14942. if (config.hosts.call_control !== undefined) {
  14943. elem.c(
  14944. 'property',
  14945. { name: 'call_control', value: config.hosts.call_control})
  14946. .up();
  14947. }
  14948. if (config.channelLastN !== undefined) {
  14949. elem.c(
  14950. 'property',
  14951. { name: 'channelLastN', value: config.channelLastN})
  14952. .up();
  14953. }
  14954. if (config.adaptiveLastN !== undefined) {
  14955. elem.c(
  14956. 'property',
  14957. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14958. .up();
  14959. }
  14960. if (config.adaptiveSimulcast !== undefined) {
  14961. elem.c(
  14962. 'property',
  14963. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14964. .up();
  14965. }
  14966. if (config.openSctp !== undefined) {
  14967. elem.c(
  14968. 'property',
  14969. { name: 'openSctp', value: config.openSctp})
  14970. .up();
  14971. }
  14972. if(config.startAudioMuted !== undefined)
  14973. {
  14974. elem.c(
  14975. 'property',
  14976. { name: 'startAudioMuted', value: config.startAudioMuted})
  14977. .up();
  14978. }
  14979. if(config.startVideoMuted !== undefined)
  14980. {
  14981. elem.c(
  14982. 'property',
  14983. { name: 'startVideoMuted', value: config.startVideoMuted})
  14984. .up();
  14985. }
  14986. elem.c(
  14987. 'property',
  14988. { name: 'simulcastMode', value: 'rewriting'})
  14989. .up();
  14990. elem.up();
  14991. return elem;
  14992. },
  14993. parseSessionId: function (resultIq) {
  14994. var sessionId = $(resultIq).find('conference').attr('session-id');
  14995. if (sessionId) {
  14996. console.info('Received sessionId: ' + sessionId);
  14997. localStorage.setItem('sessionId', sessionId);
  14998. }
  14999. },
  15000. parseConfigOptions: function (resultIq) {
  15001. Moderator.setFocusUserJid(
  15002. $(resultIq).find('conference').attr('focusjid'));
  15003. var authenticationEnabled
  15004. = $(resultIq).find(
  15005. '>conference>property' +
  15006. '[name=\'authentication\'][value=\'true\']').length > 0;
  15007. console.info("Authentication enabled: " + authenticationEnabled);
  15008. externalAuthEnabled = $(resultIq).find(
  15009. '>conference>property' +
  15010. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  15011. console.info('External authentication enabled: ' + externalAuthEnabled);
  15012. if (!externalAuthEnabled) {
  15013. // We expect to receive sessionId in 'internal' authentication mode
  15014. Moderator.parseSessionId(resultIq);
  15015. }
  15016. var authIdentity = $(resultIq).find('>conference').attr('identity');
  15017. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  15018. authenticationEnabled, authIdentity);
  15019. // Check if focus has auto-detected Jigasi component(this will be also
  15020. // included if we have passed our host from the config)
  15021. if ($(resultIq).find(
  15022. '>conference>property' +
  15023. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  15024. sipGatewayEnabled = true;
  15025. }
  15026. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  15027. },
  15028. // FIXME: we need to show the fact that we're waiting for the focus
  15029. // to the user(or that focus is not available)
  15030. allocateConferenceFocus: function (roomName, callback) {
  15031. // Try to use focus user JID from the config
  15032. Moderator.setFocusUserJid(config.focusUserJid);
  15033. // Send create conference IQ
  15034. var iq = Moderator.createConferenceIq(roomName);
  15035. var self = this;
  15036. connection.sendIQ(
  15037. iq,
  15038. function (result) {
  15039. // Setup config options
  15040. Moderator.parseConfigOptions(result);
  15041. if ('true' === $(result).find('conference').attr('ready')) {
  15042. // Reset both timers
  15043. getNextTimeout(true);
  15044. getNextErrorTimeout(true);
  15045. // Exec callback
  15046. callback();
  15047. } else {
  15048. var waitMs = getNextTimeout();
  15049. console.info("Waiting for the focus... " + waitMs);
  15050. // Reset error timeout
  15051. getNextErrorTimeout(true);
  15052. window.setTimeout(
  15053. function () {
  15054. Moderator.allocateConferenceFocus(
  15055. roomName, callback);
  15056. }, waitMs);
  15057. }
  15058. },
  15059. function (error) {
  15060. // Invalid session ? remove and try again
  15061. // without session ID to get a new one
  15062. var invalidSession
  15063. = $(error).find('>error>session-invalid').length;
  15064. if (invalidSession) {
  15065. console.info("Session expired! - removing");
  15066. localStorage.removeItem("sessionId");
  15067. }
  15068. if ($(error).find('>error>graceful-shutdown').length) {
  15069. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  15070. return;
  15071. }
  15072. // Check for error returned by the reservation system
  15073. var reservationErr = $(error).find('>error>reservation-error');
  15074. if (reservationErr.length) {
  15075. // Trigger error event
  15076. var errorCode = reservationErr.attr('error-code');
  15077. var errorMsg;
  15078. if ($(error).find('>error>text')) {
  15079. errorMsg = $(error).find('>error>text').text();
  15080. }
  15081. eventEmitter.emit(
  15082. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  15083. return;
  15084. }
  15085. // Not authorized to create new room
  15086. if ($(error).find('>error>not-authorized').length) {
  15087. console.warn("Unauthorized to start the conference", error);
  15088. var toDomain
  15089. = Strophe.getDomainFromJid(error.getAttribute('to'));
  15090. if (toDomain !== config.hosts.anonymousdomain) {
  15091. // FIXME: "is external" should come either from
  15092. // the focus or config.js
  15093. externalAuthEnabled = true;
  15094. }
  15095. eventEmitter.emit(
  15096. XMPPEvents.AUTHENTICATION_REQUIRED,
  15097. function () {
  15098. Moderator.allocateConferenceFocus(
  15099. roomName, callback);
  15100. });
  15101. return;
  15102. }
  15103. var waitMs = getNextErrorTimeout();
  15104. console.error("Focus error, retry after " + waitMs, error);
  15105. // Show message
  15106. var focusComponent = Moderator.getFocusComponent();
  15107. var retrySec = waitMs / 1000;
  15108. // FIXME: message is duplicated ?
  15109. // Do not show in case of session invalid
  15110. // which means just a retry
  15111. if (!invalidSession) {
  15112. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15113. focusComponent, retrySec);
  15114. }
  15115. // Reset response timeout
  15116. getNextTimeout(true);
  15117. window.setTimeout(
  15118. function () {
  15119. Moderator.allocateConferenceFocus(roomName, callback);
  15120. }, waitMs);
  15121. }
  15122. );
  15123. },
  15124. getLoginUrl: function (roomName, urlCallback) {
  15125. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15126. iq.c('login-url', {
  15127. xmlns: 'http://jitsi.org/protocol/focus',
  15128. room: roomName,
  15129. 'machine-uid': Settings.getSettings().uid
  15130. });
  15131. connection.sendIQ(
  15132. iq,
  15133. function (result) {
  15134. var url = $(result).find('login-url').attr('url');
  15135. url = url = decodeURIComponent(url);
  15136. if (url) {
  15137. console.info("Got auth url: " + url);
  15138. urlCallback(url);
  15139. } else {
  15140. console.error(
  15141. "Failed to get auth url from the focus", result);
  15142. }
  15143. },
  15144. function (error) {
  15145. console.error("Get auth url error", error);
  15146. }
  15147. );
  15148. },
  15149. getPopupLoginUrl: function (roomName, urlCallback) {
  15150. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15151. iq.c('login-url', {
  15152. xmlns: 'http://jitsi.org/protocol/focus',
  15153. room: roomName,
  15154. 'machine-uid': Settings.getSettings().uid,
  15155. popup: true
  15156. });
  15157. connection.sendIQ(
  15158. iq,
  15159. function (result) {
  15160. var url = $(result).find('login-url').attr('url');
  15161. url = url = decodeURIComponent(url);
  15162. if (url) {
  15163. console.info("Got POPUP auth url: " + url);
  15164. urlCallback(url);
  15165. } else {
  15166. console.error(
  15167. "Failed to get POPUP auth url from the focus", result);
  15168. }
  15169. },
  15170. function (error) {
  15171. console.error('Get POPUP auth url error', error);
  15172. }
  15173. );
  15174. },
  15175. logout: function (callback) {
  15176. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15177. var sessionId = localStorage.getItem('sessionId');
  15178. if (!sessionId) {
  15179. callback();
  15180. return;
  15181. }
  15182. iq.c('logout', {
  15183. xmlns: 'http://jitsi.org/protocol/focus',
  15184. 'session-id': sessionId
  15185. });
  15186. connection.sendIQ(
  15187. iq,
  15188. function (result) {
  15189. var logoutUrl = $(result).find('logout').attr('logout-url');
  15190. if (logoutUrl) {
  15191. logoutUrl = decodeURIComponent(logoutUrl);
  15192. }
  15193. console.info("Log out OK, url: " + logoutUrl, result);
  15194. localStorage.removeItem('sessionId');
  15195. callback(logoutUrl);
  15196. },
  15197. function (error) {
  15198. console.error("Logout error", error);
  15199. }
  15200. );
  15201. }
  15202. };
  15203. module.exports = Moderator;
  15204. },{"../../service/authentication/AuthenticationEvents":167,"../../service/xmpp/XMPPEvents":172,"../settings/Settings":49}],63:[function(require,module,exports){
  15205. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15206. Toolbar, Util */
  15207. var Moderator = require("./moderator");
  15208. var recordingToken = null;
  15209. var recordingEnabled;
  15210. /**
  15211. * Whether to use a jirecon component for recording, or use the videobridge
  15212. * through COLIBRI.
  15213. */
  15214. var useJirecon;
  15215. /**
  15216. * The ID of the jirecon recording session. Jirecon generates it when we
  15217. * initially start recording, and it needs to be used in subsequent requests
  15218. * to jirecon.
  15219. */
  15220. var jireconRid = null;
  15221. /**
  15222. * The callback to update the recording button. Currently used from colibri
  15223. * after receiving a pending status.
  15224. */
  15225. var recordingStateChangeCallback = null;
  15226. function setRecordingToken(token) {
  15227. recordingToken = token;
  15228. }
  15229. function setRecordingJirecon(state, token, callback, connection) {
  15230. if (state == recordingEnabled){
  15231. return;
  15232. }
  15233. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15234. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15235. action: (state === 'on') ? 'start' : 'stop',
  15236. mucjid: connection.emuc.roomjid});
  15237. if (state === 'off'){
  15238. iq.attrs({rid: jireconRid});
  15239. }
  15240. console.log('Start recording');
  15241. connection.sendIQ(
  15242. iq,
  15243. function (result) {
  15244. // TODO wait for an IQ with the real status, since this is
  15245. // provisional?
  15246. jireconRid = $(result).find('recording').attr('rid');
  15247. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15248. '(jirecon)' + result);
  15249. recordingEnabled = state;
  15250. if (state === 'off'){
  15251. jireconRid = null;
  15252. }
  15253. callback(state);
  15254. },
  15255. function (error) {
  15256. console.log('Failed to start recording, error: ', error);
  15257. callback(recordingEnabled);
  15258. });
  15259. }
  15260. // Sends a COLIBRI message which enables or disables (according to 'state')
  15261. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15262. // with the new recording state, according to the IQ.
  15263. function setRecordingColibri(state, token, callback, connection) {
  15264. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15265. elem.c('conference', {
  15266. xmlns: 'http://jitsi.org/protocol/colibri'
  15267. });
  15268. elem.c('recording', {state: state, token: token});
  15269. connection.sendIQ(elem,
  15270. function (result) {
  15271. console.log('Set recording "', state, '". Result:', result);
  15272. var recordingElem = $(result).find('>conference>recording');
  15273. var newState = recordingElem.attr('state');
  15274. recordingEnabled = newState;
  15275. callback(newState);
  15276. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15277. recordingStateChangeCallback = callback;
  15278. connection.addHandler(function(iq){
  15279. var state = $(iq).find('recording').attr('state');
  15280. if (state)
  15281. recordingStateChangeCallback(state);
  15282. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15283. }
  15284. },
  15285. function (error) {
  15286. console.warn(error);
  15287. callback(recordingEnabled);
  15288. }
  15289. );
  15290. }
  15291. function setRecording(state, token, callback, connection) {
  15292. if (useJirecon){
  15293. setRecordingJirecon(state, token, callback, connection);
  15294. } else {
  15295. setRecordingColibri(state, token, callback, connection);
  15296. }
  15297. }
  15298. var Recording = {
  15299. init: function () {
  15300. useJirecon = config.hosts &&
  15301. (typeof config.hosts.jirecon != "undefined");
  15302. },
  15303. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15304. if (!Moderator.isModerator()) {
  15305. console.log(
  15306. 'non-focus, or conference not yet organized:' +
  15307. ' not enabling recording');
  15308. return;
  15309. }
  15310. var self = this;
  15311. // Jirecon does not (currently) support a token.
  15312. if (!recordingToken && !useJirecon) {
  15313. tokenEmptyCallback(function (value) {
  15314. setRecordingToken(value);
  15315. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15316. });
  15317. return;
  15318. }
  15319. var oldState = recordingEnabled;
  15320. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15321. setRecording(newState,
  15322. recordingToken,
  15323. function (state) {
  15324. console.log("New recording state: ", state);
  15325. if (state === oldState) {
  15326. // FIXME: new focus:
  15327. // this will not work when moderator changes
  15328. // during active session. Then it will assume that
  15329. // recording status has changed to true, but it might have
  15330. // been already true(and we only received actual status from
  15331. // the focus).
  15332. //
  15333. // SO we start with status null, so that it is initialized
  15334. // here and will fail only after second click, so if invalid
  15335. // token was used we have to press the button twice before
  15336. // current status will be fetched and token will be reset.
  15337. //
  15338. // Reliable way would be to return authentication error.
  15339. // Or status update when moderator connects.
  15340. // Or we have to stop recording session when current
  15341. // moderator leaves the room.
  15342. // Failed to change, reset the token because it might
  15343. // have been wrong
  15344. setRecordingToken(null);
  15345. }
  15346. recordingStateChangeCallback(state);
  15347. },
  15348. connection
  15349. );
  15350. }
  15351. };
  15352. module.exports = Recording;
  15353. },{"./moderator":62}],64:[function(require,module,exports){
  15354. /* jshint -W117 */
  15355. /* a simple MUC connection plugin
  15356. * can only handle a single MUC room
  15357. */
  15358. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15359. var Moderator = require("./moderator");
  15360. module.exports = function(XMPP, eventEmitter) {
  15361. Strophe.addConnectionPlugin('emuc', {
  15362. connection: null,
  15363. roomjid: null,
  15364. myroomjid: null,
  15365. members: {},
  15366. list_members: [], // so we can elect a new focus
  15367. presMap: {},
  15368. preziMap: {},
  15369. lastPresenceMap: {},
  15370. joined: false,
  15371. isOwner: false,
  15372. role: null,
  15373. focusMucJid: null,
  15374. bridgeIsDown: false,
  15375. init: function (conn) {
  15376. this.connection = conn;
  15377. },
  15378. initPresenceMap: function (myroomjid) {
  15379. this.presMap['to'] = myroomjid;
  15380. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15381. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15382. this.addAudioInfoToPresence(true);
  15383. }
  15384. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15385. this.addVideoInfoToPresence(true);
  15386. }
  15387. },
  15388. doJoin: function (jid, password) {
  15389. this.myroomjid = jid;
  15390. console.info("Joined MUC as " + this.myroomjid);
  15391. this.initPresenceMap(this.myroomjid);
  15392. if (!this.roomjid) {
  15393. this.roomjid = Strophe.getBareJidFromJid(jid);
  15394. // add handlers (just once)
  15395. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15396. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15397. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15398. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15399. }
  15400. if (password !== undefined) {
  15401. this.presMap['password'] = password;
  15402. }
  15403. this.sendPresence();
  15404. },
  15405. doLeave: function () {
  15406. console.log("do leave", this.myroomjid);
  15407. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15408. this.presMap.length = 0;
  15409. this.connection.send(pres);
  15410. },
  15411. createNonAnonymousRoom: function () {
  15412. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15413. var getForm = $iq({type: 'get', to: this.roomjid})
  15414. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15415. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15416. var self = this;
  15417. this.connection.sendIQ(getForm, function (form) {
  15418. if (!$(form).find(
  15419. '>query>x[xmlns="jabber:x:data"]' +
  15420. '>field[var="muc#roomconfig_whois"]').length) {
  15421. console.error('non-anonymous rooms not supported');
  15422. return;
  15423. }
  15424. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15425. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15426. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15427. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15428. .c('value')
  15429. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15430. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15431. .c('value').t('anyone').up().up();
  15432. self.connection.sendIQ(formSubmit);
  15433. }, function (error) {
  15434. console.error("Error getting room configuration form");
  15435. });
  15436. },
  15437. onPresence: function (pres) {
  15438. var from = pres.getAttribute('from');
  15439. // What is this for? A workaround for something?
  15440. if (pres.getAttribute('type')) {
  15441. return true;
  15442. }
  15443. // Parse etherpad tag.
  15444. var etherpad = $(pres).find('>etherpad');
  15445. if (etherpad.length) {
  15446. if (config.etherpad_base) {
  15447. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15448. }
  15449. }
  15450. var url;
  15451. // Parse prezi tag.
  15452. var presentation = $(pres).find('>prezi');
  15453. if (presentation.length) {
  15454. url = presentation.attr('url');
  15455. var current = presentation.find('>current').text();
  15456. console.log('presentation info received from', from, url);
  15457. if (this.preziMap[from] == null) {
  15458. this.preziMap[from] = url;
  15459. $(document).trigger('presentationadded.muc', [from, url, current]);
  15460. }
  15461. else {
  15462. $(document).trigger('gotoslide.muc', [from, url, current]);
  15463. }
  15464. }
  15465. else if (this.preziMap[from] != null) {
  15466. url = this.preziMap[from];
  15467. delete this.preziMap[from];
  15468. $(document).trigger('presentationremoved.muc', [from, url]);
  15469. }
  15470. // store the last presence for participant
  15471. this.lastPresenceMap[from] = {};
  15472. // Parse audio info tag.
  15473. var audioMuted = $(pres).find('>audiomuted');
  15474. if (audioMuted.length) {
  15475. eventEmitter.emit(XMPPEvents.PARTICIPANT_AUDIO_MUTED,
  15476. from, (audioMuted.text() === "true"));
  15477. }
  15478. // Parse video info tag.
  15479. var videoMuted = $(pres).find('>videomuted');
  15480. if (videoMuted.length) {
  15481. var value = (videoMuted.text() === "true");
  15482. this.lastPresenceMap[from].videoMuted = value;
  15483. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_MUTED, from, value);
  15484. }
  15485. var startMuted = $(pres).find('>startmuted');
  15486. if (startMuted.length && Moderator.isPeerModerator(from)) {
  15487. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15488. startMuted.attr("audio") === "true",
  15489. startMuted.attr("video") === "true");
  15490. }
  15491. var devices = $(pres).find('>devices');
  15492. if(devices.length)
  15493. {
  15494. var audio = devices.find('>audio');
  15495. var video = devices.find('>video');
  15496. var devicesValues = {audio: false, video: false};
  15497. if(audio.length && audio.text() === "true")
  15498. {
  15499. devicesValues.audio = true;
  15500. }
  15501. if(video.length && video.text() === "true")
  15502. {
  15503. devicesValues.video = true;
  15504. }
  15505. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15506. Strophe.getResourceFromJid(from), devicesValues);
  15507. }
  15508. var videoType = $(pres).find('>videoType');
  15509. if (videoType.length)
  15510. {
  15511. if (videoType.text().length)
  15512. {
  15513. eventEmitter.emit(XMPPEvents.PARTICIPANT_VIDEO_TYPE_CHANGED,
  15514. Strophe.getResourceFromJid(from), videoType.text());
  15515. }
  15516. }
  15517. var stats = $(pres).find('>stats');
  15518. if (stats.length) {
  15519. var statsObj = {};
  15520. Strophe.forEachChild(stats[0], "stat", function (el) {
  15521. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15522. });
  15523. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15524. }
  15525. // Parse status.
  15526. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15527. this.isOwner = true;
  15528. this.createNonAnonymousRoom();
  15529. }
  15530. // Parse roles.
  15531. var member = {};
  15532. member.show = $(pres).find('>show').text();
  15533. member.status = $(pres).find('>status').text();
  15534. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15535. member.affiliation = tmp.attr('affiliation');
  15536. member.role = tmp.attr('role');
  15537. // Focus recognition
  15538. member.jid = tmp.attr('jid');
  15539. member.isFocus = false;
  15540. if (member.jid
  15541. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15542. member.isFocus = true;
  15543. }
  15544. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15545. member.displayName = (nicktag.length > 0 ? nicktag.text() : null);
  15546. if (from == this.myroomjid) {
  15547. if (member.affiliation == 'owner') this.isOwner = true;
  15548. if (this.role !== member.role) {
  15549. this.role = member.role;
  15550. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15551. from, member, pres, Moderator.isModerator());
  15552. }
  15553. if (!this.joined) {
  15554. this.joined = true;
  15555. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15556. this.list_members.push(from);
  15557. }
  15558. } else if (this.members[from] === undefined) {
  15559. // new participant
  15560. this.members[from] = member;
  15561. this.list_members.push(from);
  15562. console.log('entered', from, member);
  15563. if (member.isFocus) {
  15564. this.focusMucJid = from;
  15565. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15566. }
  15567. else {
  15568. var id = $(pres).find('>userId').text();
  15569. var email = $(pres).find('>email');
  15570. if (email.length > 0) {
  15571. id = email.text();
  15572. }
  15573. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15574. }
  15575. } else {
  15576. // Presence update for existing participant
  15577. // Watch role change:
  15578. if (this.members[from].role != member.role) {
  15579. this.members[from].role = member.role;
  15580. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15581. member.role, member.displayName);
  15582. }
  15583. }
  15584. // Always trigger presence to update bindings
  15585. this.parsePresence(from, member, pres);
  15586. // Trigger status message update
  15587. if (member.status) {
  15588. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15589. }
  15590. return true;
  15591. },
  15592. onPresenceUnavailable: function (pres) {
  15593. var from = pres.getAttribute('from');
  15594. // room destroyed ?
  15595. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15596. '>destroy').length) {
  15597. var reason;
  15598. var reasonSelect = $(pres).find(
  15599. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15600. '>destroy>reason');
  15601. if (reasonSelect.length) {
  15602. reason = reasonSelect.text();
  15603. }
  15604. XMPP.disposeConference(false);
  15605. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15606. return true;
  15607. }
  15608. // Status code 110 indicates that this notification is "self-presence".
  15609. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15610. delete this.members[from];
  15611. this.list_members.splice(this.list_members.indexOf(from), 1);
  15612. this.onParticipantLeft(from);
  15613. }
  15614. // If the status code is 110 this means we're leaving and we would like
  15615. // to remove everyone else from our view, so we trigger the event.
  15616. else if (this.list_members.length > 1) {
  15617. for (var i = 0; i < this.list_members.length; i++) {
  15618. var member = this.list_members[i];
  15619. delete this.members[i];
  15620. this.list_members.splice(i, 1);
  15621. this.onParticipantLeft(member);
  15622. }
  15623. }
  15624. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15625. $(document).trigger('kicked.muc', [from]);
  15626. if (this.myroomjid === from) {
  15627. XMPP.disposeConference(false);
  15628. eventEmitter.emit(XMPPEvents.KICKED);
  15629. }
  15630. }
  15631. if (this.lastPresenceMap[from] != null) {
  15632. delete this.lastPresenceMap[from];
  15633. }
  15634. return true;
  15635. },
  15636. onPresenceError: function (pres) {
  15637. var from = pres.getAttribute('from');
  15638. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15639. console.log('on password required', from);
  15640. var self = this;
  15641. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15642. self.doJoin(from, value);
  15643. });
  15644. } else if ($(pres).find(
  15645. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15646. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15647. if (toDomain === config.hosts.anonymousdomain) {
  15648. // enter the room by replying with 'not-authorized'. This would
  15649. // result in reconnection from authorized domain.
  15650. // We're either missing Jicofo/Prosody config for anonymous
  15651. // domains or something is wrong.
  15652. // XMPP.promptLogin();
  15653. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15654. } else {
  15655. console.warn('onPresError ', pres);
  15656. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15657. }
  15658. } else {
  15659. console.warn('onPresError ', pres);
  15660. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15661. }
  15662. return true;
  15663. },
  15664. sendMessage: function (body, nickname) {
  15665. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15666. msg.c('body', body).up();
  15667. if (nickname) {
  15668. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15669. }
  15670. this.connection.send(msg);
  15671. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15672. },
  15673. setSubject: function (subject) {
  15674. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15675. msg.c('subject', subject);
  15676. this.connection.send(msg);
  15677. console.log("topic changed to " + subject);
  15678. },
  15679. onMessage: function (msg) {
  15680. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15681. var from = msg.getAttribute('from');
  15682. var nick =
  15683. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15684. .text() ||
  15685. Strophe.getResourceFromJid(from);
  15686. var txt = $(msg).find('>body').text();
  15687. var type = msg.getAttribute("type");
  15688. if (type == "error") {
  15689. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15690. $(msg).find('>text').text(), txt);
  15691. return true;
  15692. }
  15693. var subject = $(msg).find('>subject');
  15694. if (subject.length) {
  15695. var subjectText = subject.text();
  15696. if (subjectText || subjectText == "") {
  15697. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15698. console.log("Subject is changed to " + subjectText);
  15699. }
  15700. }
  15701. // xep-0203 delay
  15702. var stamp = $(msg).find('>delay').attr('stamp');
  15703. if (!stamp) {
  15704. // or xep-0091 delay, UTC timestamp
  15705. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15706. if (stamp) {
  15707. // the format is CCYYMMDDThh:mm:ss
  15708. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15709. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15710. }
  15711. }
  15712. if (txt) {
  15713. console.log('chat', nick, txt);
  15714. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15715. from, nick, txt, this.myroomjid, stamp);
  15716. }
  15717. return true;
  15718. },
  15719. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15720. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15721. var ob = this;
  15722. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15723. function (res) {
  15724. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15725. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15726. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15727. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15728. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15729. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15730. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15731. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15732. ob.connection.sendIQ(formsubmit,
  15733. onSuccess,
  15734. onError);
  15735. } else {
  15736. onNotSupported();
  15737. }
  15738. }, onError);
  15739. },
  15740. kick: function (jid) {
  15741. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15742. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15743. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15744. .c('reason').t('You have been kicked.').up().up().up();
  15745. this.connection.sendIQ(
  15746. kickIQ,
  15747. function (result) {
  15748. console.log('Kick participant with jid: ', jid, result);
  15749. },
  15750. function (error) {
  15751. console.log('Kick participant error: ', error);
  15752. });
  15753. },
  15754. sendPresence: function () {
  15755. if (!this.presMap['to']) {
  15756. // Too early to send presence - not initialized
  15757. return;
  15758. }
  15759. var pres = $pres({to: this.presMap['to'] });
  15760. pres.c('x', {xmlns: this.presMap['xns']});
  15761. if (this.presMap['password']) {
  15762. pres.c('password').t(this.presMap['password']).up();
  15763. }
  15764. pres.up();
  15765. // Send XEP-0115 'c' stanza that contains our capabilities info
  15766. if (this.connection.caps) {
  15767. this.connection.caps.node = config.clientNode;
  15768. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15769. }
  15770. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15771. .t(navigator.userAgent).up();
  15772. if (this.presMap['bridgeIsDown']) {
  15773. pres.c('bridgeIsDown').up();
  15774. }
  15775. if (this.presMap['email']) {
  15776. pres.c('email').t(this.presMap['email']).up();
  15777. }
  15778. if (this.presMap['userId']) {
  15779. pres.c('userId').t(this.presMap['userId']).up();
  15780. }
  15781. if (this.presMap['displayName']) {
  15782. // XEP-0172
  15783. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15784. .t(this.presMap['displayName']).up();
  15785. }
  15786. if(this.presMap["devices"])
  15787. {
  15788. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15789. .c('video').t(this.presMap['devices'].video).up().up();
  15790. }
  15791. if (this.presMap['audions']) {
  15792. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15793. .t(this.presMap['audiomuted']).up();
  15794. }
  15795. if (this.presMap['videons']) {
  15796. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15797. .t(this.presMap['videomuted']).up();
  15798. }
  15799. if (this.presMap['videoTypeNs']) {
  15800. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15801. .t(this.presMap['videoType']).up();
  15802. }
  15803. if (this.presMap['statsns']) {
  15804. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15805. for (var stat in this.presMap["stats"])
  15806. if (this.presMap["stats"][stat] != null)
  15807. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15808. pres.up();
  15809. }
  15810. if (this.presMap['prezins']) {
  15811. pres.c('prezi',
  15812. {xmlns: this.presMap['prezins'],
  15813. 'url': this.presMap['preziurl']})
  15814. .c('current').t(this.presMap['prezicurrent']).up().up();
  15815. }
  15816. if(this.presMap["startMuted"] !== undefined)
  15817. {
  15818. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15819. video: this.presMap["startMuted"].video,
  15820. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15821. delete this.presMap["startMuted"];
  15822. }
  15823. pres.up();
  15824. this.connection.send(pres);
  15825. },
  15826. addDisplayNameToPresence: function (displayName) {
  15827. this.presMap['displayName'] = displayName;
  15828. },
  15829. addDevicesToPresence: function (devices) {
  15830. this.presMap['devices'] = devices;
  15831. },
  15832. /**
  15833. * Adds the info about the type of our video stream.
  15834. * @param videoType 'camera' or 'screen'
  15835. */
  15836. addVideoTypeToPresence: function (videoType) {
  15837. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  15838. this.presMap['videoType'] = videoType;
  15839. },
  15840. addPreziToPresence: function (url, currentSlide) {
  15841. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15842. this.presMap['preziurl'] = url;
  15843. this.presMap['prezicurrent'] = currentSlide;
  15844. },
  15845. removePreziFromPresence: function () {
  15846. delete this.presMap['prezins'];
  15847. delete this.presMap['preziurl'];
  15848. delete this.presMap['prezicurrent'];
  15849. },
  15850. addCurrentSlideToPresence: function (currentSlide) {
  15851. this.presMap['prezicurrent'] = currentSlide;
  15852. },
  15853. getPrezi: function (roomjid) {
  15854. return this.preziMap[roomjid];
  15855. },
  15856. addAudioInfoToPresence: function (isMuted) {
  15857. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15858. this.presMap['audiomuted'] = isMuted.toString();
  15859. },
  15860. addVideoInfoToPresence: function (isMuted) {
  15861. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15862. this.presMap['videomuted'] = isMuted.toString();
  15863. },
  15864. addConnectionInfoToPresence: function (stats) {
  15865. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15866. this.presMap['stats'] = stats;
  15867. },
  15868. findJidFromResource: function (resourceJid) {
  15869. if (resourceJid &&
  15870. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15871. return this.myroomjid;
  15872. }
  15873. var peerJid = null;
  15874. Object.keys(this.members).some(function (jid) {
  15875. peerJid = jid;
  15876. return Strophe.getResourceFromJid(jid) === resourceJid;
  15877. });
  15878. return peerJid;
  15879. },
  15880. addBridgeIsDownToPresence: function () {
  15881. this.presMap['bridgeIsDown'] = true;
  15882. },
  15883. addEmailToPresence: function (email) {
  15884. this.presMap['email'] = email;
  15885. },
  15886. addUserIdToPresence: function (userId) {
  15887. this.presMap['userId'] = userId;
  15888. },
  15889. addStartMutedToPresence: function (audio, video) {
  15890. this.presMap["startMuted"] = {audio: audio, video: video};
  15891. },
  15892. isModerator: function () {
  15893. return this.role === 'moderator';
  15894. },
  15895. getMemberRole: function (peerJid) {
  15896. if (this.members[peerJid]) {
  15897. return this.members[peerJid].role;
  15898. }
  15899. return null;
  15900. },
  15901. onParticipantLeft: function (jid) {
  15902. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15903. this.connection.jingle.terminateByJid(jid);
  15904. if (this.getPrezi(jid)) {
  15905. $(document).trigger('presentationremoved.muc',
  15906. [jid, this.getPrezi(jid)]);
  15907. }
  15908. Moderator.onMucMemberLeft(jid);
  15909. },
  15910. parsePresence: function (from, member, pres) {
  15911. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  15912. this.bridgeIsDown = true;
  15913. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15914. }
  15915. if(member.isFocus)
  15916. return;
  15917. var displayName = !config.displayJids
  15918. ? member.displayName : Strophe.getResourceFromJid(from);
  15919. if (displayName && displayName.length > 0) {
  15920. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15921. }
  15922. var id = $(pres).find('>userID').text();
  15923. var email = $(pres).find('>email');
  15924. if (email.length > 0) {
  15925. id = email.text();
  15926. }
  15927. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15928. }
  15929. });
  15930. };
  15931. },{"../../service/xmpp/XMPPEvents":172,"./moderator":62}],65:[function(require,module,exports){
  15932. /* jshint -W117 */
  15933. var JingleSession = require("./JingleSessionPC");
  15934. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15935. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15936. module.exports = function(XMPP, eventEmitter) {
  15937. Strophe.addConnectionPlugin('jingle', {
  15938. connection: null,
  15939. sessions: {},
  15940. jid2session: {},
  15941. ice_config: {iceServers: []},
  15942. pc_constraints: {},
  15943. activecall: null,
  15944. media_constraints: {
  15945. mandatory: {
  15946. 'OfferToReceiveAudio': true,
  15947. 'OfferToReceiveVideo': true
  15948. }
  15949. // MozDontOfferDataChannel: true when this is firefox
  15950. },
  15951. init: function (conn) {
  15952. this.connection = conn;
  15953. if (this.connection.disco) {
  15954. // http://xmpp.org/extensions/xep-0167.html#support
  15955. // http://xmpp.org/extensions/xep-0176.html#support
  15956. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15957. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15958. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15959. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15960. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15961. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15962. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15963. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15964. || RTCBrowserType.isTemasysPluginUsed()) {
  15965. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15966. }
  15967. // this is dealt with by SDP O/A so we don't need to announce this
  15968. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15969. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15970. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15971. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15972. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15973. }
  15974. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15975. },
  15976. onJingle: function (iq) {
  15977. var sid = $(iq).find('jingle').attr('sid');
  15978. var action = $(iq).find('jingle').attr('action');
  15979. var fromJid = iq.getAttribute('from');
  15980. // send ack first
  15981. var ack = $iq({type: 'result',
  15982. to: fromJid,
  15983. id: iq.getAttribute('id')
  15984. });
  15985. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15986. var sess = this.sessions[sid];
  15987. if ('session-initiate' != action) {
  15988. if (sess === null) {
  15989. ack.type = 'error';
  15990. ack.c('error', {type: 'cancel'})
  15991. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15992. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15993. this.connection.send(ack);
  15994. return true;
  15995. }
  15996. // local jid is not checked
  15997. if (fromJid != sess.peerjid) {
  15998. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15999. ack.type = 'error';
  16000. ack.c('error', {type: 'cancel'})
  16001. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16002. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16003. this.connection.send(ack);
  16004. return true;
  16005. }
  16006. } else if (sess !== undefined) {
  16007. // existing session with same session id
  16008. // this might be out-of-order if the sess.peerjid is the same as from
  16009. ack.type = 'error';
  16010. ack.c('error', {type: 'cancel'})
  16011. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  16012. console.warn('duplicate session id', sid);
  16013. this.connection.send(ack);
  16014. return true;
  16015. }
  16016. // FIXME: check for a defined action
  16017. this.connection.send(ack);
  16018. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  16019. switch (action) {
  16020. case 'session-initiate':
  16021. var startMuted = $(iq).find('jingle>startmuted');
  16022. if (startMuted && startMuted.length > 0) {
  16023. var audioMuted = startMuted.attr("audio");
  16024. var videoMuted = startMuted.attr("video");
  16025. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  16026. audioMuted === "true", videoMuted === "true");
  16027. }
  16028. sess = new JingleSession(
  16029. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  16030. this.connection, XMPP, eventEmitter);
  16031. // configure session
  16032. sess.media_constraints = this.media_constraints;
  16033. sess.pc_constraints = this.pc_constraints;
  16034. sess.ice_config = this.ice_config;
  16035. sess.initialize(fromJid, false);
  16036. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  16037. sess.setOffer($(iq).find('>jingle'));
  16038. this.sessions[sess.sid] = sess;
  16039. this.jid2session[sess.peerjid] = sess;
  16040. // the callback should either
  16041. // .sendAnswer and .accept
  16042. // or .sendTerminate -- not necessarily synchronous
  16043. // TODO: do we check activecall == null?
  16044. this.connection.jingle.activecall = sess;
  16045. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  16046. // TODO: check affiliation and/or role
  16047. console.log('emuc data for', sess.peerjid,
  16048. this.connection.emuc.members[sess.peerjid]);
  16049. sess.sendAnswer();
  16050. sess.accept();
  16051. break;
  16052. case 'session-accept':
  16053. sess.setAnswer($(iq).find('>jingle'));
  16054. sess.accept();
  16055. $(document).trigger('callaccepted.jingle', [sess.sid]);
  16056. break;
  16057. case 'session-terminate':
  16058. // If this is not the focus sending the terminate, we have
  16059. // nothing more to do here.
  16060. if (Object.keys(this.sessions).length < 1
  16061. || !(this.sessions[Object.keys(this.sessions)[0]]
  16062. instanceof JingleSession))
  16063. {
  16064. break;
  16065. }
  16066. console.log('terminating...', sess.sid);
  16067. sess.terminate();
  16068. this.terminate(sess.sid);
  16069. if ($(iq).find('>jingle>reason').length) {
  16070. $(document).trigger('callterminated.jingle', [
  16071. sess.sid,
  16072. sess.peerjid,
  16073. $(iq).find('>jingle>reason>:first')[0].tagName,
  16074. $(iq).find('>jingle>reason>text').text()
  16075. ]);
  16076. } else {
  16077. $(document).trigger('callterminated.jingle',
  16078. [sess.sid, sess.peerjid]);
  16079. }
  16080. break;
  16081. case 'transport-info':
  16082. sess.addIceCandidate($(iq).find('>jingle>content'));
  16083. break;
  16084. case 'session-info':
  16085. var affected;
  16086. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16087. $(document).trigger('ringing.jingle', [sess.sid]);
  16088. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16089. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16090. $(document).trigger('mute.jingle', [sess.sid, affected]);
  16091. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16092. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16093. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  16094. }
  16095. break;
  16096. case 'addsource': // FIXME: proprietary, un-jingleish
  16097. case 'source-add': // FIXME: proprietary
  16098. sess.addSource($(iq).find('>jingle>content'), fromJid);
  16099. break;
  16100. case 'removesource': // FIXME: proprietary, un-jingleish
  16101. case 'source-remove': // FIXME: proprietary
  16102. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  16103. break;
  16104. default:
  16105. console.warn('jingle action not implemented', action);
  16106. break;
  16107. }
  16108. return true;
  16109. },
  16110. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  16111. var sess = new JingleSession(myjid || this.connection.jid,
  16112. Math.random().toString(36).substr(2, 12), // random string
  16113. this.connection, XMPP, eventEmitter);
  16114. // configure session
  16115. sess.media_constraints = this.media_constraints;
  16116. sess.pc_constraints = this.pc_constraints;
  16117. sess.ice_config = this.ice_config;
  16118. sess.initialize(peerjid, true);
  16119. this.sessions[sess.sid] = sess;
  16120. this.jid2session[sess.peerjid] = sess;
  16121. sess.sendOffer();
  16122. return sess;
  16123. },
  16124. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16125. if (sid === null || sid === undefined) {
  16126. for (sid in this.sessions) {
  16127. if (this.sessions[sid].state != 'ended') {
  16128. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16129. this.sessions[sid].terminate();
  16130. }
  16131. delete this.jid2session[this.sessions[sid].peerjid];
  16132. delete this.sessions[sid];
  16133. }
  16134. } else if (this.sessions.hasOwnProperty(sid)) {
  16135. if (this.sessions[sid].state != 'ended') {
  16136. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16137. this.sessions[sid].terminate();
  16138. }
  16139. delete this.jid2session[this.sessions[sid].peerjid];
  16140. delete this.sessions[sid];
  16141. }
  16142. },
  16143. // Used to terminate a session when an unavailable presence is received.
  16144. terminateByJid: function (jid) {
  16145. if (this.jid2session.hasOwnProperty(jid)) {
  16146. var sess = this.jid2session[jid];
  16147. if (sess) {
  16148. sess.terminate();
  16149. console.log('peer went away silently', jid);
  16150. delete this.sessions[sess.sid];
  16151. delete this.jid2session[jid];
  16152. $(document).trigger('callterminated.jingle',
  16153. [sess.sid, jid], 'gone');
  16154. }
  16155. }
  16156. },
  16157. terminateRemoteByJid: function (jid, reason) {
  16158. if (this.jid2session.hasOwnProperty(jid)) {
  16159. var sess = this.jid2session[jid];
  16160. if (sess) {
  16161. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16162. sess.terminate();
  16163. console.log('terminate peer with jid', sess.sid, jid);
  16164. delete this.sessions[sess.sid];
  16165. delete this.jid2session[jid];
  16166. $(document).trigger('callterminated.jingle',
  16167. [sess.sid, jid, 'kicked']);
  16168. }
  16169. }
  16170. },
  16171. getStunAndTurnCredentials: function () {
  16172. // get stun and turn configuration from server via xep-0215
  16173. // uses time-limited credentials as described in
  16174. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16175. //
  16176. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16177. // for a prosody module which implements this
  16178. //
  16179. // currently, this doesn't work with updateIce and therefore credentials with a long
  16180. // validity have to be fetched before creating the peerconnection
  16181. // TODO: implement refresh via updateIce as described in
  16182. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16183. var self = this;
  16184. this.connection.sendIQ(
  16185. $iq({type: 'get', to: this.connection.domain})
  16186. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16187. function (res) {
  16188. var iceservers = [];
  16189. $(res).find('>services>service').each(function (idx, el) {
  16190. el = $(el);
  16191. var dict = {};
  16192. var type = el.attr('type');
  16193. switch (type) {
  16194. case 'stun':
  16195. dict.url = 'stun:' + el.attr('host');
  16196. if (el.attr('port')) {
  16197. dict.url += ':' + el.attr('port');
  16198. }
  16199. iceservers.push(dict);
  16200. break;
  16201. case 'turn':
  16202. case 'turns':
  16203. dict.url = type + ':';
  16204. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16205. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16206. dict.url += el.attr('username') + '@';
  16207. } else {
  16208. dict.username = el.attr('username'); // only works in M28
  16209. }
  16210. }
  16211. dict.url += el.attr('host');
  16212. if (el.attr('port') && el.attr('port') != '3478') {
  16213. dict.url += ':' + el.attr('port');
  16214. }
  16215. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16216. dict.url += '?transport=' + el.attr('transport');
  16217. }
  16218. if (el.attr('password')) {
  16219. dict.credential = el.attr('password');
  16220. }
  16221. iceservers.push(dict);
  16222. break;
  16223. }
  16224. });
  16225. self.ice_config.iceServers = iceservers;
  16226. },
  16227. function (err) {
  16228. console.warn('getting turn credentials failed', err);
  16229. console.warn('is mod_turncredentials or similar installed?');
  16230. }
  16231. );
  16232. // implement push?
  16233. },
  16234. /**
  16235. * Returns the data saved in 'updateLog' in a format to be logged.
  16236. */
  16237. getLog: function () {
  16238. var data = {};
  16239. var self = this;
  16240. Object.keys(this.sessions).forEach(function (sid) {
  16241. var session = self.sessions[sid];
  16242. if (session.peerconnection && session.peerconnection.updateLog) {
  16243. // FIXME: should probably be a .dump call
  16244. data["jingle_" + session.sid] = {
  16245. updateLog: session.peerconnection.updateLog,
  16246. stats: session.peerconnection.stats,
  16247. url: window.location.href
  16248. };
  16249. }
  16250. });
  16251. return data;
  16252. }
  16253. });
  16254. };
  16255. },{"../../service/xmpp/XMPPEvents":172,"../RTC/RTCBrowserType":8,"./JingleSessionPC":56}],66:[function(require,module,exports){
  16256. /* global Strophe */
  16257. module.exports = function () {
  16258. Strophe.addConnectionPlugin('logger', {
  16259. // logs raw stanzas and makes them available for download as JSON
  16260. connection: null,
  16261. log: [],
  16262. init: function (conn) {
  16263. this.connection = conn;
  16264. this.connection.rawInput = this.log_incoming.bind(this);
  16265. this.connection.rawOutput = this.log_outgoing.bind(this);
  16266. },
  16267. log_incoming: function (stanza) {
  16268. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16269. },
  16270. log_outgoing: function (stanza) {
  16271. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16272. }
  16273. });
  16274. };
  16275. },{}],67:[function(require,module,exports){
  16276. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16277. setAudioMuted, Strophe */
  16278. /**
  16279. * Moderate connection plugin.
  16280. */
  16281. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16282. module.exports = function (XMPP, eventEmitter) {
  16283. Strophe.addConnectionPlugin('moderate', {
  16284. connection: null,
  16285. init: function (conn) {
  16286. this.connection = conn;
  16287. this.connection.addHandler(this.onMute.bind(this),
  16288. 'http://jitsi.org/jitmeet/audio',
  16289. 'iq',
  16290. 'set',
  16291. null,
  16292. null);
  16293. },
  16294. setMute: function (jid, mute) {
  16295. console.info("set mute", mute);
  16296. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16297. .c('mute', {
  16298. xmlns: 'http://jitsi.org/jitmeet/audio',
  16299. jid: jid
  16300. })
  16301. .t(mute.toString())
  16302. .up();
  16303. this.connection.sendIQ(
  16304. iqToFocus,
  16305. function (result) {
  16306. console.log('set mute', result);
  16307. },
  16308. function (error) {
  16309. console.log('set mute error', error);
  16310. });
  16311. },
  16312. onMute: function (iq) {
  16313. var from = iq.getAttribute('from');
  16314. if (from !== this.connection.emuc.focusMucJid) {
  16315. console.warn("Ignored mute from non focus peer");
  16316. return false;
  16317. }
  16318. var mute = $(iq).find('mute');
  16319. if (mute.length) {
  16320. var doMuteAudio = mute.text() === "true";
  16321. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16322. XMPP.forceMuted = doMuteAudio;
  16323. }
  16324. return true;
  16325. },
  16326. eject: function (jid) {
  16327. // We're not the focus, so can't terminate
  16328. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16329. this.connection.emuc.kick(jid);
  16330. }
  16331. });
  16332. }
  16333. },{"../../service/xmpp/XMPPEvents":172}],68:[function(require,module,exports){
  16334. /* global $, $iq, Strophe */
  16335. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16336. /**
  16337. * Ping every 20 sec
  16338. */
  16339. var PING_INTERVAL = 20000;
  16340. /**
  16341. * Ping timeout error after 15 sec of waiting.
  16342. */
  16343. var PING_TIMEOUT = 15000;
  16344. /**
  16345. * Will close the connection after 3 consecutive ping errors.
  16346. */
  16347. var PING_THRESHOLD = 3;
  16348. /**
  16349. * XEP-0199 ping plugin.
  16350. *
  16351. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  16352. */
  16353. module.exports = function (XMPP, eventEmitter) {
  16354. Strophe.addConnectionPlugin('ping', {
  16355. connection: null,
  16356. failedPings: 0,
  16357. /**
  16358. * Initializes the plugin. Method called by Strophe.
  16359. * @param connection Strophe connection instance.
  16360. */
  16361. init: function (connection) {
  16362. this.connection = connection;
  16363. Strophe.addNamespace('PING', "urn:xmpp:ping");
  16364. },
  16365. /**
  16366. * Sends "ping" to given <tt>jid</tt>
  16367. * @param jid the JID to which ping request will be sent.
  16368. * @param success callback called on success.
  16369. * @param error callback called on error.
  16370. * @param timeout ms how long are we going to wait for the response. On
  16371. * timeout <tt>error<//t> callback is called with undefined error
  16372. * argument.
  16373. */
  16374. ping: function (jid, success, error, timeout) {
  16375. var iq = $iq({type: 'get', to: jid});
  16376. iq.c('ping', {xmlns: Strophe.NS.PING});
  16377. this.connection.sendIQ(iq, success, error, timeout);
  16378. },
  16379. /**
  16380. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  16381. * @param jid the JID to be checked for ping support.
  16382. * @param callback function with boolean argument which will be
  16383. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  16384. */
  16385. hasPingSupport: function (jid, callback) {
  16386. this.connection.disco.info(
  16387. jid, null,
  16388. function (result) {
  16389. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  16390. callback(ping.length > 0);
  16391. },
  16392. function (error) {
  16393. console.error("Ping feature discovery error", error);
  16394. callback(false);
  16395. }
  16396. );
  16397. },
  16398. /**
  16399. * Starts to send ping in given interval to specified remote JID.
  16400. * This plugin supports only one such task and <tt>stopInterval</tt>
  16401. * must be called before starting a new one.
  16402. * @param remoteJid remote JID to which ping requests will be sent to.
  16403. * @param interval task interval in ms.
  16404. */
  16405. startInterval: function (remoteJid, interval) {
  16406. if (this.intervalId) {
  16407. console.error("Ping task scheduled already");
  16408. return;
  16409. }
  16410. if (!interval)
  16411. interval = PING_INTERVAL;
  16412. var self = this;
  16413. this.intervalId = window.setInterval(function () {
  16414. self.ping(remoteJid,
  16415. function (result) {
  16416. // Ping OK
  16417. self.failedPings = 0;
  16418. },
  16419. function (error) {
  16420. self.failedPings += 1;
  16421. console.error(
  16422. "Ping " + (error ? "error" : "timeout"), error);
  16423. if (self.failedPings >= PING_THRESHOLD) {
  16424. self.connection.disconnect();
  16425. }
  16426. }, PING_TIMEOUT);
  16427. }, interval);
  16428. console.info("XMPP pings will be sent every " + interval + " ms");
  16429. },
  16430. /**
  16431. * Stops current "ping" interval task.
  16432. */
  16433. stopInterval: function () {
  16434. if (this.intervalId) {
  16435. window.clearInterval(this.intervalId);
  16436. this.intervalId = null;
  16437. this.failedPings = 0;
  16438. console.info("Ping interval cleared");
  16439. }
  16440. }
  16441. });
  16442. };
  16443. },{"../../service/xmpp/XMPPEvents":172}],69:[function(require,module,exports){
  16444. /* jshint -W117 */
  16445. module.exports = function() {
  16446. Strophe.addConnectionPlugin('rayo',
  16447. {
  16448. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16449. connection: null,
  16450. init: function (conn) {
  16451. this.connection = conn;
  16452. if (this.connection.disco) {
  16453. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16454. }
  16455. this.connection.addHandler(
  16456. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16457. },
  16458. onRayo: function (iq) {
  16459. console.info("Rayo IQ", iq);
  16460. },
  16461. dial: function (to, from, roomName, roomPass) {
  16462. var self = this;
  16463. var req = $iq(
  16464. {
  16465. type: 'set',
  16466. to: this.connection.emuc.focusMucJid
  16467. }
  16468. );
  16469. req.c('dial',
  16470. {
  16471. xmlns: this.RAYO_XMLNS,
  16472. to: to,
  16473. from: from
  16474. });
  16475. req.c('header',
  16476. {
  16477. name: 'JvbRoomName',
  16478. value: roomName
  16479. }).up();
  16480. if (roomPass !== null && roomPass.length) {
  16481. req.c('header',
  16482. {
  16483. name: 'JvbRoomPassword',
  16484. value: roomPass
  16485. }).up();
  16486. }
  16487. this.connection.sendIQ(
  16488. req,
  16489. function (result) {
  16490. console.info('Dial result ', result);
  16491. var resource = $(result).find('ref').attr('uri');
  16492. this.call_resource = resource.substr('xmpp:'.length);
  16493. console.info(
  16494. "Received call resource: " + this.call_resource);
  16495. },
  16496. function (error) {
  16497. console.info('Dial error ', error);
  16498. }
  16499. );
  16500. },
  16501. hang_up: function () {
  16502. if (!this.call_resource) {
  16503. console.warn("No call in progress");
  16504. return;
  16505. }
  16506. var self = this;
  16507. var req = $iq(
  16508. {
  16509. type: 'set',
  16510. to: this.call_resource
  16511. }
  16512. );
  16513. req.c('hangup',
  16514. {
  16515. xmlns: this.RAYO_XMLNS
  16516. });
  16517. this.connection.sendIQ(
  16518. req,
  16519. function (result) {
  16520. console.info('Hangup result ', result);
  16521. self.call_resource = null;
  16522. },
  16523. function (error) {
  16524. console.info('Hangup error ', error);
  16525. self.call_resource = null;
  16526. }
  16527. );
  16528. }
  16529. }
  16530. );
  16531. };
  16532. },{}],70:[function(require,module,exports){
  16533. /**
  16534. * Strophe logger implementation. Logs from level WARN and above.
  16535. */
  16536. module.exports = function () {
  16537. Strophe.log = function (level, msg) {
  16538. switch (level) {
  16539. case Strophe.LogLevel.WARN:
  16540. console.warn("Strophe: " + msg);
  16541. break;
  16542. case Strophe.LogLevel.ERROR:
  16543. case Strophe.LogLevel.FATAL:
  16544. console.error("Strophe: " + msg);
  16545. break;
  16546. }
  16547. };
  16548. Strophe.getStatusString = function (status) {
  16549. switch (status) {
  16550. case Strophe.Status.ERROR:
  16551. return "ERROR";
  16552. case Strophe.Status.CONNECTING:
  16553. return "CONNECTING";
  16554. case Strophe.Status.CONNFAIL:
  16555. return "CONNFAIL";
  16556. case Strophe.Status.AUTHENTICATING:
  16557. return "AUTHENTICATING";
  16558. case Strophe.Status.AUTHFAIL:
  16559. return "AUTHFAIL";
  16560. case Strophe.Status.CONNECTED:
  16561. return "CONNECTED";
  16562. case Strophe.Status.DISCONNECTED:
  16563. return "DISCONNECTED";
  16564. case Strophe.Status.DISCONNECTING:
  16565. return "DISCONNECTING";
  16566. case Strophe.Status.ATTACHED:
  16567. return "ATTACHED";
  16568. default:
  16569. return "unknown";
  16570. }
  16571. };
  16572. };
  16573. },{}],71:[function(require,module,exports){
  16574. /* global $, APP, config, Strophe*/
  16575. var Moderator = require("./moderator");
  16576. var EventEmitter = require("events");
  16577. var Recording = require("./recording");
  16578. var SDP = require("./SDP");
  16579. var SDPUtil = require("./SDPUtil");
  16580. var Settings = require("../settings/Settings");
  16581. var Pako = require("pako");
  16582. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16583. var RTCEvents = require("../../service/RTC/RTCEvents");
  16584. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16585. var retry = require('retry');
  16586. var eventEmitter = new EventEmitter();
  16587. var connection = null;
  16588. var authenticatedUser = false;
  16589. function connect(jid, password) {
  16590. var faultTolerantConnect = retry.operation({
  16591. retries: 3
  16592. });
  16593. // fault tolerant connect
  16594. faultTolerantConnect.attempt(function () {
  16595. connection = XMPP.createConnection();
  16596. Moderator.setConnection(connection);
  16597. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16598. if (config.useIPv6) {
  16599. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16600. if (!connection.jingle.pc_constraints.optional)
  16601. connection.jingle.pc_constraints.optional = [];
  16602. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16603. }
  16604. // Include user info in MUC presence
  16605. var settings = Settings.getSettings();
  16606. if (settings.email) {
  16607. connection.emuc.addEmailToPresence(settings.email);
  16608. }
  16609. if (settings.uid) {
  16610. connection.emuc.addUserIdToPresence(settings.uid);
  16611. }
  16612. if (settings.displayName) {
  16613. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16614. }
  16615. // connection.connect() starts the connection process.
  16616. //
  16617. // As the connection process proceeds, the user supplied callback will
  16618. // be triggered multiple times with status updates. The callback should
  16619. // take two arguments - the status code and the error condition.
  16620. //
  16621. // The status code will be one of the values in the Strophe.Status
  16622. // constants. The error condition will be one of the conditions defined
  16623. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16624. //
  16625. // The Parameters wait, hold and route are optional and only relevant
  16626. // for BOSH connections. Please see XEP 124 for a more detailed
  16627. // explanation of the optional parameters.
  16628. //
  16629. // Connection status constants for use by the connection handler
  16630. // callback.
  16631. //
  16632. // Status.ERROR - An error has occurred (websockets specific)
  16633. // Status.CONNECTING - The connection is currently being made
  16634. // Status.CONNFAIL - The connection attempt failed
  16635. // Status.AUTHENTICATING - The connection is authenticating
  16636. // Status.AUTHFAIL - The authentication attempt failed
  16637. // Status.CONNECTED - The connection has succeeded
  16638. // Status.DISCONNECTED - The connection has been terminated
  16639. // Status.DISCONNECTING - The connection is currently being terminated
  16640. // Status.ATTACHED - The connection has been attached
  16641. var anonymousConnectionFailed = false;
  16642. var connectionFailed = false;
  16643. var lastErrorMsg;
  16644. connection.connect(jid, password, function (status, msg) {
  16645. console.log('Strophe status changed to',
  16646. Strophe.getStatusString(status), msg);
  16647. if (status === Strophe.Status.CONNECTED) {
  16648. if (config.useStunTurn) {
  16649. connection.jingle.getStunAndTurnCredentials();
  16650. }
  16651. console.info("My Jabber ID: " + connection.jid);
  16652. // Schedule ping ?
  16653. var pingJid = connection.domain;
  16654. connection.ping.hasPingSupport(
  16655. pingJid,
  16656. function (hasPing) {
  16657. if (hasPing)
  16658. connection.ping.startInterval(pingJid);
  16659. else
  16660. console.warn("Ping NOT supported by " + pingJid);
  16661. }
  16662. );
  16663. if (password)
  16664. authenticatedUser = true;
  16665. maybeDoJoin();
  16666. } else if (status === Strophe.Status.CONNFAIL) {
  16667. if (msg === 'x-strophe-bad-non-anon-jid') {
  16668. anonymousConnectionFailed = true;
  16669. } else {
  16670. connectionFailed = true;
  16671. }
  16672. lastErrorMsg = msg;
  16673. } else if (status === Strophe.Status.DISCONNECTED) {
  16674. // Stop ping interval
  16675. connection.ping.stopInterval();
  16676. if (anonymousConnectionFailed) {
  16677. // prompt user for username and password
  16678. XMPP.promptLogin();
  16679. } else {
  16680. // Strophe already has built-in HTTP/BOSH error handling and
  16681. // request retry logic. Requests are resent automatically
  16682. // until their error count reaches 5. Strophe.js disconnects
  16683. // if the error count is > 5. We are not replicating this
  16684. // here.
  16685. //
  16686. // The "problem" is that failed HTTP/BOSH requests don't
  16687. // trigger a callback with a status update, so when a
  16688. // callback with status Strophe.Status.DISCONNECTED arrives,
  16689. // we can't be sure if it's a graceful disconnect or if it's
  16690. // triggered by some HTTP/BOSH error.
  16691. //
  16692. // But that's a minor issue in Jitsi Meet as we never
  16693. // disconnect anyway, not even when the user closes the
  16694. // browser window (which is kind of wrong, but the point is
  16695. // that we should never ever get disconnected).
  16696. //
  16697. // On the other hand, failed connections due to XMPP layer
  16698. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16699. //
  16700. // Here we implement retry logic for failed connections due
  16701. // to XMPP layer errors and we display an error to the user
  16702. // if we get disconnected from the XMPP server permanently.
  16703. // If the connection failed, retry.
  16704. if (connectionFailed &&
  16705. faultTolerantConnect.retry("connection-failed")) {
  16706. return;
  16707. }
  16708. // If we failed to connect to the XMPP server, fire an event
  16709. // to let all the interested module now about it.
  16710. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16711. msg ? msg : lastErrorMsg);
  16712. }
  16713. } else if (status === Strophe.Status.AUTHFAIL) {
  16714. // wrong password or username, prompt user
  16715. XMPP.promptLogin();
  16716. }
  16717. });
  16718. });
  16719. }
  16720. function maybeDoJoin() {
  16721. if (connection && connection.connected &&
  16722. Strophe.getResourceFromJid(connection.jid) &&
  16723. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16724. // .connected is true while connecting?
  16725. doJoin();
  16726. }
  16727. }
  16728. function doJoin() {
  16729. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16730. }
  16731. function initStrophePlugins()
  16732. {
  16733. require("./strophe.emuc")(XMPP, eventEmitter);
  16734. require("./strophe.jingle")(XMPP, eventEmitter);
  16735. require("./strophe.moderate")(XMPP, eventEmitter);
  16736. require("./strophe.util")();
  16737. require("./strophe.ping")(XMPP, eventEmitter);
  16738. require("./strophe.rayo")();
  16739. require("./strophe.logger")();
  16740. }
  16741. /**
  16742. * If given <tt>localStream</tt> is video one this method will advertise it's
  16743. * video type in MUC presence.
  16744. * @param localStream new or modified <tt>LocalStream</tt>.
  16745. */
  16746. function broadcastLocalVideoType(localStream) {
  16747. if (localStream.videoType)
  16748. XMPP.addToPresence('videoType', localStream.videoType);
  16749. }
  16750. function registerListeners() {
  16751. APP.RTC.addStreamListener(
  16752. function (localStream) {
  16753. maybeDoJoin();
  16754. broadcastLocalVideoType(localStream);
  16755. },
  16756. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16757. );
  16758. APP.RTC.addStreamListener(
  16759. broadcastLocalVideoType,
  16760. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16761. );
  16762. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16763. XMPP.addToPresence("devices", devices);
  16764. });
  16765. }
  16766. var unload = (function () {
  16767. var unloaded = false;
  16768. return function () {
  16769. if (unloaded) { return; }
  16770. unloaded = true;
  16771. if (connection && connection.connected) {
  16772. // ensure signout
  16773. $.ajax({
  16774. type: 'POST',
  16775. url: config.bosh,
  16776. async: false,
  16777. cache: false,
  16778. contentType: 'application/xml',
  16779. data: "<body rid='" +
  16780. (connection.rid || connection._proto.rid) +
  16781. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16782. (connection.sid || connection._proto.sid) +
  16783. "' type='terminate'>" +
  16784. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16785. "</body>",
  16786. success: function (data) {
  16787. console.log('signed out');
  16788. console.log(data);
  16789. },
  16790. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16791. console.log('signout error',
  16792. textStatus + ' (' + errorThrown + ')');
  16793. }
  16794. });
  16795. }
  16796. XMPP.disposeConference(true);
  16797. };
  16798. })();
  16799. function setupEvents() {
  16800. // In recent versions of FF the 'beforeunload' event is not fired when the
  16801. // window or the tab is closed. It is only fired when we leave the page
  16802. // (change URL). If this participant doesn't unload properly, then it
  16803. // becomes a ghost for the rest of the participants that stay in the
  16804. // conference. Thankfully handling the 'unload' event in addition to the
  16805. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16806. // method at least once.
  16807. //
  16808. // The 'unload' method can safely be run multiple times, it will actually do
  16809. // something only the first time that it's run, so we're don't have to worry
  16810. // about browsers that fire both events.
  16811. $(window).bind('beforeunload', unload);
  16812. $(window).bind('unload', unload);
  16813. }
  16814. var XMPP = {
  16815. getConnection: function(){ return connection; },
  16816. sessionTerminated: false,
  16817. /**
  16818. * XMPP connection status
  16819. */
  16820. Status: Strophe.Status,
  16821. /**
  16822. * Remembers if we were muted by the focus.
  16823. * @type {boolean}
  16824. */
  16825. forceMuted: false,
  16826. start: function () {
  16827. setupEvents();
  16828. initStrophePlugins();
  16829. registerListeners();
  16830. Moderator.init(this, eventEmitter);
  16831. Recording.init();
  16832. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16833. // Force authenticated domain if room is appended with '?login=true'
  16834. if (config.hosts.anonymousdomain &&
  16835. window.location.search.indexOf("login=true") !== -1) {
  16836. configDomain = config.hosts.domain;
  16837. }
  16838. var jid = configDomain || window.location.hostname;
  16839. connect(jid, null);
  16840. },
  16841. createConnection: function () {
  16842. var bosh = config.bosh || '/http-bind';
  16843. return new Strophe.Connection(bosh);
  16844. },
  16845. getStatusString: function (status) {
  16846. return Strophe.getStatusString(status);
  16847. },
  16848. promptLogin: function () {
  16849. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16850. },
  16851. joinRoom: function(roomName, useNicks, nick) {
  16852. var roomjid = roomName;
  16853. if (useNicks) {
  16854. if (nick) {
  16855. roomjid += '/' + nick;
  16856. } else {
  16857. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16858. }
  16859. } else {
  16860. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16861. if(!authenticatedUser)
  16862. tmpJid = tmpJid.substr(0, 8);
  16863. roomjid += '/' + tmpJid;
  16864. }
  16865. connection.emuc.doJoin(roomjid);
  16866. },
  16867. myJid: function () {
  16868. if(!connection)
  16869. return null;
  16870. return connection.emuc.myroomjid;
  16871. },
  16872. myResource: function () {
  16873. if(!connection || ! connection.emuc.myroomjid)
  16874. return null;
  16875. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16876. },
  16877. getLastPresence: function (from) {
  16878. if(!connection)
  16879. return null;
  16880. return connection.emuc.lastPresenceMap[from];
  16881. },
  16882. disposeConference: function (onUnload) {
  16883. var handler = connection.jingle.activecall;
  16884. if (handler && handler.peerconnection) {
  16885. // FIXME: probably removing streams is not required and close() should
  16886. // be enough
  16887. if (APP.RTC.localAudio) {
  16888. handler.peerconnection.removeStream(
  16889. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16890. }
  16891. if (APP.RTC.localVideo) {
  16892. handler.peerconnection.removeStream(
  16893. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16894. }
  16895. handler.peerconnection.close();
  16896. }
  16897. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16898. connection.jingle.activecall = null;
  16899. if (!onUnload) {
  16900. this.sessionTerminated = true;
  16901. connection.emuc.doLeave();
  16902. }
  16903. },
  16904. addListener: function(type, listener) {
  16905. eventEmitter.on(type, listener);
  16906. },
  16907. removeListener: function (type, listener) {
  16908. eventEmitter.removeListener(type, listener);
  16909. },
  16910. allocateConferenceFocus: function(roomName, callback) {
  16911. Moderator.allocateConferenceFocus(roomName, callback);
  16912. },
  16913. getLoginUrl: function (roomName, callback) {
  16914. Moderator.getLoginUrl(roomName, callback);
  16915. },
  16916. getPopupLoginUrl: function (roomName, callback) {
  16917. Moderator.getPopupLoginUrl(roomName, callback);
  16918. },
  16919. isModerator: function () {
  16920. return Moderator.isModerator();
  16921. },
  16922. isSipGatewayEnabled: function () {
  16923. return Moderator.isSipGatewayEnabled();
  16924. },
  16925. isExternalAuthEnabled: function () {
  16926. return Moderator.isExternalAuthEnabled();
  16927. },
  16928. isConferenceInProgress: function () {
  16929. return connection && connection.jingle.activecall &&
  16930. connection.jingle.activecall.peerconnection;
  16931. },
  16932. switchStreams: function (stream, oldStream, callback, isAudio) {
  16933. if (this.isConferenceInProgress()) {
  16934. // FIXME: will block switchInProgress on true value in case of exception
  16935. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16936. } else {
  16937. // We are done immediately
  16938. console.warn("No conference handler or conference not started yet");
  16939. callback();
  16940. }
  16941. },
  16942. sendVideoInfoPresence: function (mute) {
  16943. if(!connection)
  16944. return;
  16945. connection.emuc.addVideoInfoToPresence(mute);
  16946. connection.emuc.sendPresence();
  16947. },
  16948. setVideoMute: function (mute, callback, options) {
  16949. if(!connection)
  16950. return;
  16951. var self = this;
  16952. var localCallback = function (mute) {
  16953. self.sendVideoInfoPresence(mute);
  16954. return callback(mute);
  16955. };
  16956. if(connection.jingle.activecall)
  16957. {
  16958. connection.jingle.activecall.setVideoMute(
  16959. mute, localCallback, options);
  16960. }
  16961. else {
  16962. localCallback(mute);
  16963. }
  16964. },
  16965. setAudioMute: function (mute, callback) {
  16966. if (!(connection && APP.RTC.localAudio)) {
  16967. return false;
  16968. }
  16969. if (this.forceMuted && !mute) {
  16970. console.info("Asking focus for unmute");
  16971. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16972. // FIXME: wait for result before resetting muted status
  16973. this.forceMuted = false;
  16974. }
  16975. if (mute == APP.RTC.localAudio.isMuted()) {
  16976. // Nothing to do
  16977. return true;
  16978. }
  16979. APP.RTC.localAudio.setMute(mute);
  16980. this.sendAudioInfoPresence(mute, callback);
  16981. return true;
  16982. },
  16983. sendAudioInfoPresence: function(mute, callback) {
  16984. if(connection) {
  16985. connection.emuc.addAudioInfoToPresence(mute);
  16986. connection.emuc.sendPresence();
  16987. }
  16988. callback();
  16989. return true;
  16990. },
  16991. toggleRecording: function (tokenEmptyCallback,
  16992. recordingStateChangeCallback) {
  16993. Recording.toggleRecording(tokenEmptyCallback,
  16994. recordingStateChangeCallback, connection);
  16995. },
  16996. addToPresence: function (name, value, dontSend) {
  16997. switch (name) {
  16998. case "displayName":
  16999. connection.emuc.addDisplayNameToPresence(value);
  17000. break;
  17001. case "prezi":
  17002. connection.emuc.addPreziToPresence(value, 0);
  17003. break;
  17004. case "preziSlide":
  17005. connection.emuc.addCurrentSlideToPresence(value);
  17006. break;
  17007. case "connectionQuality":
  17008. connection.emuc.addConnectionInfoToPresence(value);
  17009. break;
  17010. case "email":
  17011. connection.emuc.addEmailToPresence(value);
  17012. break;
  17013. case "devices":
  17014. connection.emuc.addDevicesToPresence(value);
  17015. break;
  17016. case "videoType":
  17017. connection.emuc.addVideoTypeToPresence(value);
  17018. break;
  17019. case "startMuted":
  17020. if(!Moderator.isModerator())
  17021. return;
  17022. connection.emuc.addStartMutedToPresence(value[0],
  17023. value[1]);
  17024. break;
  17025. default :
  17026. console.log("Unknown tag for presence: " + name);
  17027. return;
  17028. }
  17029. if (!dontSend)
  17030. connection.emuc.sendPresence();
  17031. },
  17032. /**
  17033. * Sends 'data' as a log message to the focus. Returns true iff a message
  17034. * was sent.
  17035. * @param data
  17036. * @returns {boolean} true iff a message was sent.
  17037. */
  17038. sendLogs: function (data) {
  17039. if(!connection.emuc.focusMucJid)
  17040. return false;
  17041. var deflate = true;
  17042. var content = JSON.stringify(data);
  17043. if (deflate) {
  17044. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  17045. }
  17046. content = Base64.encode(content);
  17047. // XEP-0337-ish
  17048. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  17049. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  17050. id: 'PeerConnectionStats'});
  17051. message.c('message').t(content).up();
  17052. if (deflate) {
  17053. message.c('tag', {name: "deflated", value: "true"}).up();
  17054. }
  17055. message.up();
  17056. connection.send(message);
  17057. return true;
  17058. },
  17059. // Gets the logs from strophe.jingle.
  17060. getJingleLog: function () {
  17061. return connection.jingle ? connection.jingle.getLog() : {};
  17062. },
  17063. // Gets the logs from strophe.
  17064. getXmppLog: function () {
  17065. return connection.logger ? connection.logger.log : null;
  17066. },
  17067. getPrezi: function () {
  17068. return connection.emuc.getPrezi(this.myJid());
  17069. },
  17070. removePreziFromPresence: function () {
  17071. connection.emuc.removePreziFromPresence();
  17072. connection.emuc.sendPresence();
  17073. },
  17074. sendChatMessage: function (message, nickname) {
  17075. connection.emuc.sendMessage(message, nickname);
  17076. },
  17077. setSubject: function (topic) {
  17078. connection.emuc.setSubject(topic);
  17079. },
  17080. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  17081. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  17082. },
  17083. dial: function (to, from, roomName,roomPass) {
  17084. connection.rayo.dial(to, from, roomName,roomPass);
  17085. },
  17086. setMute: function (jid, mute) {
  17087. connection.moderate.setMute(jid, mute);
  17088. },
  17089. eject: function (jid) {
  17090. connection.moderate.eject(jid);
  17091. },
  17092. logout: function (callback) {
  17093. Moderator.logout(callback);
  17094. },
  17095. findJidFromResource: function (resource) {
  17096. return connection.emuc.findJidFromResource(resource);
  17097. },
  17098. getMembers: function () {
  17099. return connection.emuc.members;
  17100. },
  17101. getJidFromSSRC: function (ssrc) {
  17102. if (!this.isConferenceInProgress())
  17103. return null;
  17104. return connection.jingle.activecall.getSsrcOwner(ssrc);
  17105. },
  17106. // Returns true iff we have joined the MUC.
  17107. isMUCJoined: function () {
  17108. return connection.emuc.joined;
  17109. },
  17110. getSessions: function () {
  17111. return connection.jingle.sessions;
  17112. },
  17113. removeStream: function (stream) {
  17114. if (!this.isConferenceInProgress())
  17115. return;
  17116. connection.jingle.activecall.peerconnection.removeStream(stream);
  17117. },
  17118. filter_special_chars: function (text) {
  17119. return SDPUtil.filter_special_chars(text);
  17120. }
  17121. };
  17122. module.exports = XMPP;
  17123. },{"../../service/RTC/RTCEvents":163,"../../service/RTC/StreamEventTypes":165,"../../service/xmpp/XMPPEvents":172,"../settings/Settings":49,"./SDP":58,"./SDPUtil":60,"./moderator":62,"./recording":63,"./strophe.emuc":64,"./strophe.jingle":65,"./strophe.logger":66,"./strophe.moderate":67,"./strophe.ping":68,"./strophe.rayo":69,"./strophe.util":70,"events":173,"pako":75,"retry":91}],72:[function(require,module,exports){
  17124. (function (process){
  17125. /*!
  17126. * async
  17127. * https://github.com/caolan/async
  17128. *
  17129. * Copyright 2010-2014 Caolan McMahon
  17130. * Released under the MIT license
  17131. */
  17132. /*jshint onevar: false, indent:4 */
  17133. /*global setImmediate: false, setTimeout: false, console: false */
  17134. (function () {
  17135. var async = {};
  17136. // global on the server, window in the browser
  17137. var root, previous_async;
  17138. root = this;
  17139. if (root != null) {
  17140. previous_async = root.async;
  17141. }
  17142. async.noConflict = function () {
  17143. root.async = previous_async;
  17144. return async;
  17145. };
  17146. function only_once(fn) {
  17147. var called = false;
  17148. return function() {
  17149. if (called) throw new Error("Callback was already called.");
  17150. called = true;
  17151. fn.apply(root, arguments);
  17152. }
  17153. }
  17154. //// cross-browser compatiblity functions ////
  17155. var _toString = Object.prototype.toString;
  17156. var _isArray = Array.isArray || function (obj) {
  17157. return _toString.call(obj) === '[object Array]';
  17158. };
  17159. var _each = function (arr, iterator) {
  17160. if (arr.forEach) {
  17161. return arr.forEach(iterator);
  17162. }
  17163. for (var i = 0; i < arr.length; i += 1) {
  17164. iterator(arr[i], i, arr);
  17165. }
  17166. };
  17167. var _map = function (arr, iterator) {
  17168. if (arr.map) {
  17169. return arr.map(iterator);
  17170. }
  17171. var results = [];
  17172. _each(arr, function (x, i, a) {
  17173. results.push(iterator(x, i, a));
  17174. });
  17175. return results;
  17176. };
  17177. var _reduce = function (arr, iterator, memo) {
  17178. if (arr.reduce) {
  17179. return arr.reduce(iterator, memo);
  17180. }
  17181. _each(arr, function (x, i, a) {
  17182. memo = iterator(memo, x, i, a);
  17183. });
  17184. return memo;
  17185. };
  17186. var _keys = function (obj) {
  17187. if (Object.keys) {
  17188. return Object.keys(obj);
  17189. }
  17190. var keys = [];
  17191. for (var k in obj) {
  17192. if (obj.hasOwnProperty(k)) {
  17193. keys.push(k);
  17194. }
  17195. }
  17196. return keys;
  17197. };
  17198. //// exported async module functions ////
  17199. //// nextTick implementation with browser-compatible fallback ////
  17200. if (typeof process === 'undefined' || !(process.nextTick)) {
  17201. if (typeof setImmediate === 'function') {
  17202. async.nextTick = function (fn) {
  17203. // not a direct alias for IE10 compatibility
  17204. setImmediate(fn);
  17205. };
  17206. async.setImmediate = async.nextTick;
  17207. }
  17208. else {
  17209. async.nextTick = function (fn) {
  17210. setTimeout(fn, 0);
  17211. };
  17212. async.setImmediate = async.nextTick;
  17213. }
  17214. }
  17215. else {
  17216. async.nextTick = process.nextTick;
  17217. if (typeof setImmediate !== 'undefined') {
  17218. async.setImmediate = function (fn) {
  17219. // not a direct alias for IE10 compatibility
  17220. setImmediate(fn);
  17221. };
  17222. }
  17223. else {
  17224. async.setImmediate = async.nextTick;
  17225. }
  17226. }
  17227. async.each = function (arr, iterator, callback) {
  17228. callback = callback || function () {};
  17229. if (!arr.length) {
  17230. return callback();
  17231. }
  17232. var completed = 0;
  17233. _each(arr, function (x) {
  17234. iterator(x, only_once(done) );
  17235. });
  17236. function done(err) {
  17237. if (err) {
  17238. callback(err);
  17239. callback = function () {};
  17240. }
  17241. else {
  17242. completed += 1;
  17243. if (completed >= arr.length) {
  17244. callback();
  17245. }
  17246. }
  17247. }
  17248. };
  17249. async.forEach = async.each;
  17250. async.eachSeries = function (arr, iterator, callback) {
  17251. callback = callback || function () {};
  17252. if (!arr.length) {
  17253. return callback();
  17254. }
  17255. var completed = 0;
  17256. var iterate = function () {
  17257. iterator(arr[completed], function (err) {
  17258. if (err) {
  17259. callback(err);
  17260. callback = function () {};
  17261. }
  17262. else {
  17263. completed += 1;
  17264. if (completed >= arr.length) {
  17265. callback();
  17266. }
  17267. else {
  17268. iterate();
  17269. }
  17270. }
  17271. });
  17272. };
  17273. iterate();
  17274. };
  17275. async.forEachSeries = async.eachSeries;
  17276. async.eachLimit = function (arr, limit, iterator, callback) {
  17277. var fn = _eachLimit(limit);
  17278. fn.apply(null, [arr, iterator, callback]);
  17279. };
  17280. async.forEachLimit = async.eachLimit;
  17281. var _eachLimit = function (limit) {
  17282. return function (arr, iterator, callback) {
  17283. callback = callback || function () {};
  17284. if (!arr.length || limit <= 0) {
  17285. return callback();
  17286. }
  17287. var completed = 0;
  17288. var started = 0;
  17289. var running = 0;
  17290. (function replenish () {
  17291. if (completed >= arr.length) {
  17292. return callback();
  17293. }
  17294. while (running < limit && started < arr.length) {
  17295. started += 1;
  17296. running += 1;
  17297. iterator(arr[started - 1], function (err) {
  17298. if (err) {
  17299. callback(err);
  17300. callback = function () {};
  17301. }
  17302. else {
  17303. completed += 1;
  17304. running -= 1;
  17305. if (completed >= arr.length) {
  17306. callback();
  17307. }
  17308. else {
  17309. replenish();
  17310. }
  17311. }
  17312. });
  17313. }
  17314. })();
  17315. };
  17316. };
  17317. var doParallel = function (fn) {
  17318. return function () {
  17319. var args = Array.prototype.slice.call(arguments);
  17320. return fn.apply(null, [async.each].concat(args));
  17321. };
  17322. };
  17323. var doParallelLimit = function(limit, fn) {
  17324. return function () {
  17325. var args = Array.prototype.slice.call(arguments);
  17326. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17327. };
  17328. };
  17329. var doSeries = function (fn) {
  17330. return function () {
  17331. var args = Array.prototype.slice.call(arguments);
  17332. return fn.apply(null, [async.eachSeries].concat(args));
  17333. };
  17334. };
  17335. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17336. arr = _map(arr, function (x, i) {
  17337. return {index: i, value: x};
  17338. });
  17339. if (!callback) {
  17340. eachfn(arr, function (x, callback) {
  17341. iterator(x.value, function (err) {
  17342. callback(err);
  17343. });
  17344. });
  17345. } else {
  17346. var results = [];
  17347. eachfn(arr, function (x, callback) {
  17348. iterator(x.value, function (err, v) {
  17349. results[x.index] = v;
  17350. callback(err);
  17351. });
  17352. }, function (err) {
  17353. callback(err, results);
  17354. });
  17355. }
  17356. };
  17357. async.map = doParallel(_asyncMap);
  17358. async.mapSeries = doSeries(_asyncMap);
  17359. async.mapLimit = function (arr, limit, iterator, callback) {
  17360. return _mapLimit(limit)(arr, iterator, callback);
  17361. };
  17362. var _mapLimit = function(limit) {
  17363. return doParallelLimit(limit, _asyncMap);
  17364. };
  17365. // reduce only has a series version, as doing reduce in parallel won't
  17366. // work in many situations.
  17367. async.reduce = function (arr, memo, iterator, callback) {
  17368. async.eachSeries(arr, function (x, callback) {
  17369. iterator(memo, x, function (err, v) {
  17370. memo = v;
  17371. callback(err);
  17372. });
  17373. }, function (err) {
  17374. callback(err, memo);
  17375. });
  17376. };
  17377. // inject alias
  17378. async.inject = async.reduce;
  17379. // foldl alias
  17380. async.foldl = async.reduce;
  17381. async.reduceRight = function (arr, memo, iterator, callback) {
  17382. var reversed = _map(arr, function (x) {
  17383. return x;
  17384. }).reverse();
  17385. async.reduce(reversed, memo, iterator, callback);
  17386. };
  17387. // foldr alias
  17388. async.foldr = async.reduceRight;
  17389. var _filter = function (eachfn, arr, iterator, callback) {
  17390. var results = [];
  17391. arr = _map(arr, function (x, i) {
  17392. return {index: i, value: x};
  17393. });
  17394. eachfn(arr, function (x, callback) {
  17395. iterator(x.value, function (v) {
  17396. if (v) {
  17397. results.push(x);
  17398. }
  17399. callback();
  17400. });
  17401. }, function (err) {
  17402. callback(_map(results.sort(function (a, b) {
  17403. return a.index - b.index;
  17404. }), function (x) {
  17405. return x.value;
  17406. }));
  17407. });
  17408. };
  17409. async.filter = doParallel(_filter);
  17410. async.filterSeries = doSeries(_filter);
  17411. // select alias
  17412. async.select = async.filter;
  17413. async.selectSeries = async.filterSeries;
  17414. var _reject = function (eachfn, arr, iterator, callback) {
  17415. var results = [];
  17416. arr = _map(arr, function (x, i) {
  17417. return {index: i, value: x};
  17418. });
  17419. eachfn(arr, function (x, callback) {
  17420. iterator(x.value, function (v) {
  17421. if (!v) {
  17422. results.push(x);
  17423. }
  17424. callback();
  17425. });
  17426. }, function (err) {
  17427. callback(_map(results.sort(function (a, b) {
  17428. return a.index - b.index;
  17429. }), function (x) {
  17430. return x.value;
  17431. }));
  17432. });
  17433. };
  17434. async.reject = doParallel(_reject);
  17435. async.rejectSeries = doSeries(_reject);
  17436. var _detect = function (eachfn, arr, iterator, main_callback) {
  17437. eachfn(arr, function (x, callback) {
  17438. iterator(x, function (result) {
  17439. if (result) {
  17440. main_callback(x);
  17441. main_callback = function () {};
  17442. }
  17443. else {
  17444. callback();
  17445. }
  17446. });
  17447. }, function (err) {
  17448. main_callback();
  17449. });
  17450. };
  17451. async.detect = doParallel(_detect);
  17452. async.detectSeries = doSeries(_detect);
  17453. async.some = function (arr, iterator, main_callback) {
  17454. async.each(arr, function (x, callback) {
  17455. iterator(x, function (v) {
  17456. if (v) {
  17457. main_callback(true);
  17458. main_callback = function () {};
  17459. }
  17460. callback();
  17461. });
  17462. }, function (err) {
  17463. main_callback(false);
  17464. });
  17465. };
  17466. // any alias
  17467. async.any = async.some;
  17468. async.every = function (arr, iterator, main_callback) {
  17469. async.each(arr, function (x, callback) {
  17470. iterator(x, function (v) {
  17471. if (!v) {
  17472. main_callback(false);
  17473. main_callback = function () {};
  17474. }
  17475. callback();
  17476. });
  17477. }, function (err) {
  17478. main_callback(true);
  17479. });
  17480. };
  17481. // all alias
  17482. async.all = async.every;
  17483. async.sortBy = function (arr, iterator, callback) {
  17484. async.map(arr, function (x, callback) {
  17485. iterator(x, function (err, criteria) {
  17486. if (err) {
  17487. callback(err);
  17488. }
  17489. else {
  17490. callback(null, {value: x, criteria: criteria});
  17491. }
  17492. });
  17493. }, function (err, results) {
  17494. if (err) {
  17495. return callback(err);
  17496. }
  17497. else {
  17498. var fn = function (left, right) {
  17499. var a = left.criteria, b = right.criteria;
  17500. return a < b ? -1 : a > b ? 1 : 0;
  17501. };
  17502. callback(null, _map(results.sort(fn), function (x) {
  17503. return x.value;
  17504. }));
  17505. }
  17506. });
  17507. };
  17508. async.auto = function (tasks, callback) {
  17509. callback = callback || function () {};
  17510. var keys = _keys(tasks);
  17511. var remainingTasks = keys.length
  17512. if (!remainingTasks) {
  17513. return callback();
  17514. }
  17515. var results = {};
  17516. var listeners = [];
  17517. var addListener = function (fn) {
  17518. listeners.unshift(fn);
  17519. };
  17520. var removeListener = function (fn) {
  17521. for (var i = 0; i < listeners.length; i += 1) {
  17522. if (listeners[i] === fn) {
  17523. listeners.splice(i, 1);
  17524. return;
  17525. }
  17526. }
  17527. };
  17528. var taskComplete = function () {
  17529. remainingTasks--
  17530. _each(listeners.slice(0), function (fn) {
  17531. fn();
  17532. });
  17533. };
  17534. addListener(function () {
  17535. if (!remainingTasks) {
  17536. var theCallback = callback;
  17537. // prevent final callback from calling itself if it errors
  17538. callback = function () {};
  17539. theCallback(null, results);
  17540. }
  17541. });
  17542. _each(keys, function (k) {
  17543. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17544. var taskCallback = function (err) {
  17545. var args = Array.prototype.slice.call(arguments, 1);
  17546. if (args.length <= 1) {
  17547. args = args[0];
  17548. }
  17549. if (err) {
  17550. var safeResults = {};
  17551. _each(_keys(results), function(rkey) {
  17552. safeResults[rkey] = results[rkey];
  17553. });
  17554. safeResults[k] = args;
  17555. callback(err, safeResults);
  17556. // stop subsequent errors hitting callback multiple times
  17557. callback = function () {};
  17558. }
  17559. else {
  17560. results[k] = args;
  17561. async.setImmediate(taskComplete);
  17562. }
  17563. };
  17564. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17565. var ready = function () {
  17566. return _reduce(requires, function (a, x) {
  17567. return (a && results.hasOwnProperty(x));
  17568. }, true) && !results.hasOwnProperty(k);
  17569. };
  17570. if (ready()) {
  17571. task[task.length - 1](taskCallback, results);
  17572. }
  17573. else {
  17574. var listener = function () {
  17575. if (ready()) {
  17576. removeListener(listener);
  17577. task[task.length - 1](taskCallback, results);
  17578. }
  17579. };
  17580. addListener(listener);
  17581. }
  17582. });
  17583. };
  17584. async.retry = function(times, task, callback) {
  17585. var DEFAULT_TIMES = 5;
  17586. var attempts = [];
  17587. // Use defaults if times not passed
  17588. if (typeof times === 'function') {
  17589. callback = task;
  17590. task = times;
  17591. times = DEFAULT_TIMES;
  17592. }
  17593. // Make sure times is a number
  17594. times = parseInt(times, 10) || DEFAULT_TIMES;
  17595. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17596. var retryAttempt = function(task, finalAttempt) {
  17597. return function(seriesCallback) {
  17598. task(function(err, result){
  17599. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17600. }, wrappedResults);
  17601. };
  17602. };
  17603. while (times) {
  17604. attempts.push(retryAttempt(task, !(times-=1)));
  17605. }
  17606. async.series(attempts, function(done, data){
  17607. data = data[data.length - 1];
  17608. (wrappedCallback || callback)(data.err, data.result);
  17609. });
  17610. }
  17611. // If a callback is passed, run this as a controll flow
  17612. return callback ? wrappedTask() : wrappedTask
  17613. };
  17614. async.waterfall = function (tasks, callback) {
  17615. callback = callback || function () {};
  17616. if (!_isArray(tasks)) {
  17617. var err = new Error('First argument to waterfall must be an array of functions');
  17618. return callback(err);
  17619. }
  17620. if (!tasks.length) {
  17621. return callback();
  17622. }
  17623. var wrapIterator = function (iterator) {
  17624. return function (err) {
  17625. if (err) {
  17626. callback.apply(null, arguments);
  17627. callback = function () {};
  17628. }
  17629. else {
  17630. var args = Array.prototype.slice.call(arguments, 1);
  17631. var next = iterator.next();
  17632. if (next) {
  17633. args.push(wrapIterator(next));
  17634. }
  17635. else {
  17636. args.push(callback);
  17637. }
  17638. async.setImmediate(function () {
  17639. iterator.apply(null, args);
  17640. });
  17641. }
  17642. };
  17643. };
  17644. wrapIterator(async.iterator(tasks))();
  17645. };
  17646. var _parallel = function(eachfn, tasks, callback) {
  17647. callback = callback || function () {};
  17648. if (_isArray(tasks)) {
  17649. eachfn.map(tasks, function (fn, callback) {
  17650. if (fn) {
  17651. fn(function (err) {
  17652. var args = Array.prototype.slice.call(arguments, 1);
  17653. if (args.length <= 1) {
  17654. args = args[0];
  17655. }
  17656. callback.call(null, err, args);
  17657. });
  17658. }
  17659. }, callback);
  17660. }
  17661. else {
  17662. var results = {};
  17663. eachfn.each(_keys(tasks), function (k, callback) {
  17664. tasks[k](function (err) {
  17665. var args = Array.prototype.slice.call(arguments, 1);
  17666. if (args.length <= 1) {
  17667. args = args[0];
  17668. }
  17669. results[k] = args;
  17670. callback(err);
  17671. });
  17672. }, function (err) {
  17673. callback(err, results);
  17674. });
  17675. }
  17676. };
  17677. async.parallel = function (tasks, callback) {
  17678. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17679. };
  17680. async.parallelLimit = function(tasks, limit, callback) {
  17681. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17682. };
  17683. async.series = function (tasks, callback) {
  17684. callback = callback || function () {};
  17685. if (_isArray(tasks)) {
  17686. async.mapSeries(tasks, function (fn, callback) {
  17687. if (fn) {
  17688. fn(function (err) {
  17689. var args = Array.prototype.slice.call(arguments, 1);
  17690. if (args.length <= 1) {
  17691. args = args[0];
  17692. }
  17693. callback.call(null, err, args);
  17694. });
  17695. }
  17696. }, callback);
  17697. }
  17698. else {
  17699. var results = {};
  17700. async.eachSeries(_keys(tasks), function (k, callback) {
  17701. tasks[k](function (err) {
  17702. var args = Array.prototype.slice.call(arguments, 1);
  17703. if (args.length <= 1) {
  17704. args = args[0];
  17705. }
  17706. results[k] = args;
  17707. callback(err);
  17708. });
  17709. }, function (err) {
  17710. callback(err, results);
  17711. });
  17712. }
  17713. };
  17714. async.iterator = function (tasks) {
  17715. var makeCallback = function (index) {
  17716. var fn = function () {
  17717. if (tasks.length) {
  17718. tasks[index].apply(null, arguments);
  17719. }
  17720. return fn.next();
  17721. };
  17722. fn.next = function () {
  17723. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17724. };
  17725. return fn;
  17726. };
  17727. return makeCallback(0);
  17728. };
  17729. async.apply = function (fn) {
  17730. var args = Array.prototype.slice.call(arguments, 1);
  17731. return function () {
  17732. return fn.apply(
  17733. null, args.concat(Array.prototype.slice.call(arguments))
  17734. );
  17735. };
  17736. };
  17737. var _concat = function (eachfn, arr, fn, callback) {
  17738. var r = [];
  17739. eachfn(arr, function (x, cb) {
  17740. fn(x, function (err, y) {
  17741. r = r.concat(y || []);
  17742. cb(err);
  17743. });
  17744. }, function (err) {
  17745. callback(err, r);
  17746. });
  17747. };
  17748. async.concat = doParallel(_concat);
  17749. async.concatSeries = doSeries(_concat);
  17750. async.whilst = function (test, iterator, callback) {
  17751. if (test()) {
  17752. iterator(function (err) {
  17753. if (err) {
  17754. return callback(err);
  17755. }
  17756. async.whilst(test, iterator, callback);
  17757. });
  17758. }
  17759. else {
  17760. callback();
  17761. }
  17762. };
  17763. async.doWhilst = function (iterator, test, callback) {
  17764. iterator(function (err) {
  17765. if (err) {
  17766. return callback(err);
  17767. }
  17768. var args = Array.prototype.slice.call(arguments, 1);
  17769. if (test.apply(null, args)) {
  17770. async.doWhilst(iterator, test, callback);
  17771. }
  17772. else {
  17773. callback();
  17774. }
  17775. });
  17776. };
  17777. async.until = function (test, iterator, callback) {
  17778. if (!test()) {
  17779. iterator(function (err) {
  17780. if (err) {
  17781. return callback(err);
  17782. }
  17783. async.until(test, iterator, callback);
  17784. });
  17785. }
  17786. else {
  17787. callback();
  17788. }
  17789. };
  17790. async.doUntil = function (iterator, test, callback) {
  17791. iterator(function (err) {
  17792. if (err) {
  17793. return callback(err);
  17794. }
  17795. var args = Array.prototype.slice.call(arguments, 1);
  17796. if (!test.apply(null, args)) {
  17797. async.doUntil(iterator, test, callback);
  17798. }
  17799. else {
  17800. callback();
  17801. }
  17802. });
  17803. };
  17804. async.queue = function (worker, concurrency) {
  17805. if (concurrency === undefined) {
  17806. concurrency = 1;
  17807. }
  17808. function _insert(q, data, pos, callback) {
  17809. if (!q.started){
  17810. q.started = true;
  17811. }
  17812. if (!_isArray(data)) {
  17813. data = [data];
  17814. }
  17815. if(data.length == 0) {
  17816. // call drain immediately if there are no tasks
  17817. return async.setImmediate(function() {
  17818. if (q.drain) {
  17819. q.drain();
  17820. }
  17821. });
  17822. }
  17823. _each(data, function(task) {
  17824. var item = {
  17825. data: task,
  17826. callback: typeof callback === 'function' ? callback : null
  17827. };
  17828. if (pos) {
  17829. q.tasks.unshift(item);
  17830. } else {
  17831. q.tasks.push(item);
  17832. }
  17833. if (q.saturated && q.tasks.length === q.concurrency) {
  17834. q.saturated();
  17835. }
  17836. async.setImmediate(q.process);
  17837. });
  17838. }
  17839. var workers = 0;
  17840. var q = {
  17841. tasks: [],
  17842. concurrency: concurrency,
  17843. saturated: null,
  17844. empty: null,
  17845. drain: null,
  17846. started: false,
  17847. paused: false,
  17848. push: function (data, callback) {
  17849. _insert(q, data, false, callback);
  17850. },
  17851. kill: function () {
  17852. q.drain = null;
  17853. q.tasks = [];
  17854. },
  17855. unshift: function (data, callback) {
  17856. _insert(q, data, true, callback);
  17857. },
  17858. process: function () {
  17859. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17860. var task = q.tasks.shift();
  17861. if (q.empty && q.tasks.length === 0) {
  17862. q.empty();
  17863. }
  17864. workers += 1;
  17865. var next = function () {
  17866. workers -= 1;
  17867. if (task.callback) {
  17868. task.callback.apply(task, arguments);
  17869. }
  17870. if (q.drain && q.tasks.length + workers === 0) {
  17871. q.drain();
  17872. }
  17873. q.process();
  17874. };
  17875. var cb = only_once(next);
  17876. worker(task.data, cb);
  17877. }
  17878. },
  17879. length: function () {
  17880. return q.tasks.length;
  17881. },
  17882. running: function () {
  17883. return workers;
  17884. },
  17885. idle: function() {
  17886. return q.tasks.length + workers === 0;
  17887. },
  17888. pause: function () {
  17889. if (q.paused === true) { return; }
  17890. q.paused = true;
  17891. q.process();
  17892. },
  17893. resume: function () {
  17894. if (q.paused === false) { return; }
  17895. q.paused = false;
  17896. q.process();
  17897. }
  17898. };
  17899. return q;
  17900. };
  17901. async.priorityQueue = function (worker, concurrency) {
  17902. function _compareTasks(a, b){
  17903. return a.priority - b.priority;
  17904. };
  17905. function _binarySearch(sequence, item, compare) {
  17906. var beg = -1,
  17907. end = sequence.length - 1;
  17908. while (beg < end) {
  17909. var mid = beg + ((end - beg + 1) >>> 1);
  17910. if (compare(item, sequence[mid]) >= 0) {
  17911. beg = mid;
  17912. } else {
  17913. end = mid - 1;
  17914. }
  17915. }
  17916. return beg;
  17917. }
  17918. function _insert(q, data, priority, callback) {
  17919. if (!q.started){
  17920. q.started = true;
  17921. }
  17922. if (!_isArray(data)) {
  17923. data = [data];
  17924. }
  17925. if(data.length == 0) {
  17926. // call drain immediately if there are no tasks
  17927. return async.setImmediate(function() {
  17928. if (q.drain) {
  17929. q.drain();
  17930. }
  17931. });
  17932. }
  17933. _each(data, function(task) {
  17934. var item = {
  17935. data: task,
  17936. priority: priority,
  17937. callback: typeof callback === 'function' ? callback : null
  17938. };
  17939. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17940. if (q.saturated && q.tasks.length === q.concurrency) {
  17941. q.saturated();
  17942. }
  17943. async.setImmediate(q.process);
  17944. });
  17945. }
  17946. // Start with a normal queue
  17947. var q = async.queue(worker, concurrency);
  17948. // Override push to accept second parameter representing priority
  17949. q.push = function (data, priority, callback) {
  17950. _insert(q, data, priority, callback);
  17951. };
  17952. // Remove unshift function
  17953. delete q.unshift;
  17954. return q;
  17955. };
  17956. async.cargo = function (worker, payload) {
  17957. var working = false,
  17958. tasks = [];
  17959. var cargo = {
  17960. tasks: tasks,
  17961. payload: payload,
  17962. saturated: null,
  17963. empty: null,
  17964. drain: null,
  17965. drained: true,
  17966. push: function (data, callback) {
  17967. if (!_isArray(data)) {
  17968. data = [data];
  17969. }
  17970. _each(data, function(task) {
  17971. tasks.push({
  17972. data: task,
  17973. callback: typeof callback === 'function' ? callback : null
  17974. });
  17975. cargo.drained = false;
  17976. if (cargo.saturated && tasks.length === payload) {
  17977. cargo.saturated();
  17978. }
  17979. });
  17980. async.setImmediate(cargo.process);
  17981. },
  17982. process: function process() {
  17983. if (working) return;
  17984. if (tasks.length === 0) {
  17985. if(cargo.drain && !cargo.drained) cargo.drain();
  17986. cargo.drained = true;
  17987. return;
  17988. }
  17989. var ts = typeof payload === 'number'
  17990. ? tasks.splice(0, payload)
  17991. : tasks.splice(0, tasks.length);
  17992. var ds = _map(ts, function (task) {
  17993. return task.data;
  17994. });
  17995. if(cargo.empty) cargo.empty();
  17996. working = true;
  17997. worker(ds, function () {
  17998. working = false;
  17999. var args = arguments;
  18000. _each(ts, function (data) {
  18001. if (data.callback) {
  18002. data.callback.apply(null, args);
  18003. }
  18004. });
  18005. process();
  18006. });
  18007. },
  18008. length: function () {
  18009. return tasks.length;
  18010. },
  18011. running: function () {
  18012. return working;
  18013. }
  18014. };
  18015. return cargo;
  18016. };
  18017. var _console_fn = function (name) {
  18018. return function (fn) {
  18019. var args = Array.prototype.slice.call(arguments, 1);
  18020. fn.apply(null, args.concat([function (err) {
  18021. var args = Array.prototype.slice.call(arguments, 1);
  18022. if (typeof console !== 'undefined') {
  18023. if (err) {
  18024. if (console.error) {
  18025. console.error(err);
  18026. }
  18027. }
  18028. else if (console[name]) {
  18029. _each(args, function (x) {
  18030. console[name](x);
  18031. });
  18032. }
  18033. }
  18034. }]));
  18035. };
  18036. };
  18037. async.log = _console_fn('log');
  18038. async.dir = _console_fn('dir');
  18039. /*async.info = _console_fn('info');
  18040. async.warn = _console_fn('warn');
  18041. async.error = _console_fn('error');*/
  18042. async.memoize = function (fn, hasher) {
  18043. var memo = {};
  18044. var queues = {};
  18045. hasher = hasher || function (x) {
  18046. return x;
  18047. };
  18048. var memoized = function () {
  18049. var args = Array.prototype.slice.call(arguments);
  18050. var callback = args.pop();
  18051. var key = hasher.apply(null, args);
  18052. if (key in memo) {
  18053. async.nextTick(function () {
  18054. callback.apply(null, memo[key]);
  18055. });
  18056. }
  18057. else if (key in queues) {
  18058. queues[key].push(callback);
  18059. }
  18060. else {
  18061. queues[key] = [callback];
  18062. fn.apply(null, args.concat([function () {
  18063. memo[key] = arguments;
  18064. var q = queues[key];
  18065. delete queues[key];
  18066. for (var i = 0, l = q.length; i < l; i++) {
  18067. q[i].apply(null, arguments);
  18068. }
  18069. }]));
  18070. }
  18071. };
  18072. memoized.memo = memo;
  18073. memoized.unmemoized = fn;
  18074. return memoized;
  18075. };
  18076. async.unmemoize = function (fn) {
  18077. return function () {
  18078. return (fn.unmemoized || fn).apply(null, arguments);
  18079. };
  18080. };
  18081. async.times = function (count, iterator, callback) {
  18082. var counter = [];
  18083. for (var i = 0; i < count; i++) {
  18084. counter.push(i);
  18085. }
  18086. return async.map(counter, iterator, callback);
  18087. };
  18088. async.timesSeries = function (count, iterator, callback) {
  18089. var counter = [];
  18090. for (var i = 0; i < count; i++) {
  18091. counter.push(i);
  18092. }
  18093. return async.mapSeries(counter, iterator, callback);
  18094. };
  18095. async.seq = function (/* functions... */) {
  18096. var fns = arguments;
  18097. return function () {
  18098. var that = this;
  18099. var args = Array.prototype.slice.call(arguments);
  18100. var callback = args.pop();
  18101. async.reduce(fns, args, function (newargs, fn, cb) {
  18102. fn.apply(that, newargs.concat([function () {
  18103. var err = arguments[0];
  18104. var nextargs = Array.prototype.slice.call(arguments, 1);
  18105. cb(err, nextargs);
  18106. }]))
  18107. },
  18108. function (err, results) {
  18109. callback.apply(that, [err].concat(results));
  18110. });
  18111. };
  18112. };
  18113. async.compose = function (/* functions... */) {
  18114. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  18115. };
  18116. var _applyEach = function (eachfn, fns /*args...*/) {
  18117. var go = function () {
  18118. var that = this;
  18119. var args = Array.prototype.slice.call(arguments);
  18120. var callback = args.pop();
  18121. return eachfn(fns, function (fn, cb) {
  18122. fn.apply(that, args.concat([cb]));
  18123. },
  18124. callback);
  18125. };
  18126. if (arguments.length > 2) {
  18127. var args = Array.prototype.slice.call(arguments, 2);
  18128. return go.apply(this, args);
  18129. }
  18130. else {
  18131. return go;
  18132. }
  18133. };
  18134. async.applyEach = doParallel(_applyEach);
  18135. async.applyEachSeries = doSeries(_applyEach);
  18136. async.forever = function (fn, callback) {
  18137. function next(err) {
  18138. if (err) {
  18139. if (callback) {
  18140. return callback(err);
  18141. }
  18142. throw err;
  18143. }
  18144. fn(next);
  18145. }
  18146. next();
  18147. };
  18148. // Node.js
  18149. if (typeof module !== 'undefined' && module.exports) {
  18150. module.exports = async;
  18151. }
  18152. // AMD / RequireJS
  18153. else if (typeof define !== 'undefined' && define.amd) {
  18154. define([], function () {
  18155. return async;
  18156. });
  18157. }
  18158. // included directly via <script> tag
  18159. else {
  18160. root.async = async;
  18161. }
  18162. }());
  18163. }).call(this,require('_process'))
  18164. },{"_process":174}],73:[function(require,module,exports){
  18165. // i18next, v1.7.7
  18166. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  18167. // Distributed under MIT license
  18168. // http://i18next.com
  18169. (function() {
  18170. // add indexOf to non ECMA-262 standard compliant browsers
  18171. if (!Array.prototype.indexOf) {
  18172. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  18173. "use strict";
  18174. if (this == null) {
  18175. throw new TypeError();
  18176. }
  18177. var t = Object(this);
  18178. var len = t.length >>> 0;
  18179. if (len === 0) {
  18180. return -1;
  18181. }
  18182. var n = 0;
  18183. if (arguments.length > 0) {
  18184. n = Number(arguments[1]);
  18185. if (n != n) { // shortcut for verifying if it's NaN
  18186. n = 0;
  18187. } else if (n != 0 && n != Infinity && n != -Infinity) {
  18188. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18189. }
  18190. }
  18191. if (n >= len) {
  18192. return -1;
  18193. }
  18194. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  18195. for (; k < len; k++) {
  18196. if (k in t && t[k] === searchElement) {
  18197. return k;
  18198. }
  18199. }
  18200. return -1;
  18201. }
  18202. }
  18203. // add lastIndexOf to non ECMA-262 standard compliant browsers
  18204. if (!Array.prototype.lastIndexOf) {
  18205. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  18206. "use strict";
  18207. if (this == null) {
  18208. throw new TypeError();
  18209. }
  18210. var t = Object(this);
  18211. var len = t.length >>> 0;
  18212. if (len === 0) {
  18213. return -1;
  18214. }
  18215. var n = len;
  18216. if (arguments.length > 1) {
  18217. n = Number(arguments[1]);
  18218. if (n != n) {
  18219. n = 0;
  18220. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  18221. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18222. }
  18223. }
  18224. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  18225. for (; k >= 0; k--) {
  18226. if (k in t && t[k] === searchElement) {
  18227. return k;
  18228. }
  18229. }
  18230. return -1;
  18231. };
  18232. }
  18233. // Add string trim for IE8.
  18234. if (typeof String.prototype.trim !== 'function') {
  18235. String.prototype.trim = function() {
  18236. return this.replace(/^\s+|\s+$/g, '');
  18237. }
  18238. }
  18239. var root = this
  18240. , $ = root.jQuery || root.Zepto
  18241. , i18n = {}
  18242. , resStore = {}
  18243. , currentLng
  18244. , replacementCounter = 0
  18245. , languages = []
  18246. , initialized = false
  18247. , sync = {};
  18248. // Export the i18next object for **CommonJS**.
  18249. // If we're not in CommonJS, add `i18n` to the
  18250. // global object or to jquery.
  18251. if (typeof module !== 'undefined' && module.exports) {
  18252. if (!$) {
  18253. try {
  18254. $ = require('jquery');
  18255. } catch(e) {
  18256. // just ignore
  18257. }
  18258. }
  18259. if ($) {
  18260. $.i18n = $.i18n || i18n;
  18261. }
  18262. module.exports = i18n;
  18263. } else {
  18264. if ($) {
  18265. $.i18n = $.i18n || i18n;
  18266. }
  18267. root.i18n = root.i18n || i18n;
  18268. }
  18269. sync = {
  18270. load: function(lngs, options, cb) {
  18271. if (options.useLocalStorage) {
  18272. sync._loadLocal(lngs, options, function(err, store) {
  18273. var missingLngs = [];
  18274. for (var i = 0, len = lngs.length; i < len; i++) {
  18275. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18276. }
  18277. if (missingLngs.length > 0) {
  18278. sync._fetch(missingLngs, options, function(err, fetched) {
  18279. f.extend(store, fetched);
  18280. sync._storeLocal(fetched);
  18281. cb(null, store);
  18282. });
  18283. } else {
  18284. cb(null, store);
  18285. }
  18286. });
  18287. } else {
  18288. sync._fetch(lngs, options, function(err, store){
  18289. cb(null, store);
  18290. });
  18291. }
  18292. },
  18293. _loadLocal: function(lngs, options, cb) {
  18294. var store = {}
  18295. , nowMS = new Date().getTime();
  18296. if(window.localStorage) {
  18297. var todo = lngs.length;
  18298. f.each(lngs, function(key, lng) {
  18299. var local = window.localStorage.getItem('res_' + lng);
  18300. if (local) {
  18301. local = JSON.parse(local);
  18302. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18303. store[lng] = local;
  18304. }
  18305. }
  18306. todo--; // wait for all done befor callback
  18307. if (todo === 0) cb(null, store);
  18308. });
  18309. }
  18310. },
  18311. _storeLocal: function(store) {
  18312. if(window.localStorage) {
  18313. for (var m in store) {
  18314. store[m].i18nStamp = new Date().getTime();
  18315. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18316. }
  18317. }
  18318. return;
  18319. },
  18320. _fetch: function(lngs, options, cb) {
  18321. var ns = options.ns
  18322. , store = {};
  18323. if (!options.dynamicLoad) {
  18324. var todo = ns.namespaces.length * lngs.length
  18325. , errors;
  18326. // load each file individual
  18327. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18328. f.each(lngs, function(lngIndex, lngValue) {
  18329. // Call this once our translation has returned.
  18330. var loadComplete = function(err, data) {
  18331. if (err) {
  18332. errors = errors || [];
  18333. errors.push(err);
  18334. }
  18335. store[lngValue] = store[lngValue] || {};
  18336. store[lngValue][nsValue] = data;
  18337. todo--; // wait for all done befor callback
  18338. if (todo === 0) cb(errors, store);
  18339. };
  18340. if(typeof options.customLoad == 'function'){
  18341. // Use the specified custom callback.
  18342. options.customLoad(lngValue, nsValue, options, loadComplete);
  18343. } else {
  18344. //~ // Use our inbuilt sync.
  18345. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18346. }
  18347. });
  18348. });
  18349. } else {
  18350. // Call this once our translation has returned.
  18351. var loadComplete = function(err, data) {
  18352. cb(null, data);
  18353. };
  18354. if(typeof options.customLoad == 'function'){
  18355. // Use the specified custom callback.
  18356. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18357. } else {
  18358. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18359. // load all needed stuff once
  18360. f.ajax({
  18361. url: url,
  18362. success: function(data, status, xhr) {
  18363. f.log('loaded: ' + url);
  18364. loadComplete(null, data);
  18365. },
  18366. error : function(xhr, status, error) {
  18367. f.log('failed loading: ' + url);
  18368. loadComplete('failed loading resource.json error: ' + error);
  18369. },
  18370. dataType: "json",
  18371. async : options.getAsync
  18372. });
  18373. }
  18374. }
  18375. },
  18376. _fetchOne: function(lng, ns, options, done) {
  18377. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18378. f.ajax({
  18379. url: url,
  18380. success: function(data, status, xhr) {
  18381. f.log('loaded: ' + url);
  18382. done(null, data);
  18383. },
  18384. error : function(xhr, status, error) {
  18385. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18386. // file loaded but invalid json, stop waste time !
  18387. f.error('There is a typo in: ' + url);
  18388. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18389. f.log('Does not exist: ' + url);
  18390. } else {
  18391. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18392. f.log(theStatus + ' when loading ' + url);
  18393. }
  18394. done(error, {});
  18395. },
  18396. dataType: "json",
  18397. async : options.getAsync
  18398. });
  18399. },
  18400. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18401. var payload = {};
  18402. payload[key] = defaultValue;
  18403. var urls = [];
  18404. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18405. for (var i = 0; i < o.fallbackLng.length; i++) {
  18406. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18407. }
  18408. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18409. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18410. } else if (o.sendMissingTo === 'all') {
  18411. for (var i = 0, l = lngs.length; i < l; i++) {
  18412. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18413. }
  18414. }
  18415. for (var y = 0, len = urls.length; y < len; y++) {
  18416. var item = urls[y];
  18417. f.ajax({
  18418. url: item.url,
  18419. type: o.sendType,
  18420. data: payload,
  18421. success: function(data, status, xhr) {
  18422. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18423. // add key to resStore
  18424. var keys = key.split('.');
  18425. var x = 0;
  18426. var value = resStore[item.lng][ns];
  18427. while (keys[x]) {
  18428. if (x === keys.length - 1) {
  18429. value = value[keys[x]] = defaultValue;
  18430. } else {
  18431. value = value[keys[x]] = value[keys[x]] || {};
  18432. }
  18433. x++;
  18434. }
  18435. },
  18436. error : function(xhr, status, error) {
  18437. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18438. },
  18439. dataType: "json",
  18440. async : o.postAsync
  18441. });
  18442. }
  18443. },
  18444. reload: reload
  18445. };
  18446. // defaults
  18447. var o = {
  18448. lng: undefined,
  18449. load: 'all',
  18450. preload: [],
  18451. lowerCaseLng: false,
  18452. returnObjectTrees: false,
  18453. fallbackLng: ['dev'],
  18454. fallbackNS: [],
  18455. detectLngQS: 'setLng',
  18456. detectLngFromLocalStorage: false,
  18457. ns: 'translation',
  18458. fallbackOnNull: true,
  18459. fallbackOnEmpty: false,
  18460. fallbackToDefaultNS: false,
  18461. nsseparator: ':',
  18462. keyseparator: '.',
  18463. selectorAttr: 'data-i18n',
  18464. debug: false,
  18465. resGetPath: 'locales/__lng__/__ns__.json',
  18466. resPostPath: 'locales/add/__lng__/__ns__',
  18467. getAsync: true,
  18468. postAsync: true,
  18469. resStore: undefined,
  18470. useLocalStorage: false,
  18471. localStorageExpirationTime: 7*24*60*60*1000,
  18472. dynamicLoad: false,
  18473. sendMissing: false,
  18474. sendMissingTo: 'fallback', // current | all
  18475. sendType: 'POST',
  18476. interpolationPrefix: '__',
  18477. interpolationSuffix: '__',
  18478. defaultVariables: false,
  18479. reusePrefix: '$t(',
  18480. reuseSuffix: ')',
  18481. pluralSuffix: '_plural',
  18482. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18483. contextNotFound: ['context_not_found', Math.random()].join(''),
  18484. escapeInterpolation: false,
  18485. indefiniteSuffix: '_indefinite',
  18486. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18487. setJqueryExt: true,
  18488. defaultValueFromContent: true,
  18489. useDataAttrOptions: false,
  18490. cookieExpirationTime: undefined,
  18491. useCookie: true,
  18492. cookieName: 'i18next',
  18493. cookieDomain: undefined,
  18494. objectTreeKeyHandler: undefined,
  18495. postProcess: undefined,
  18496. parseMissingKey: undefined,
  18497. missingKeyHandler: sync.postMissing,
  18498. shortcutFunction: 'sprintf' // or: defaultValue
  18499. };
  18500. function _extend(target, source) {
  18501. if (!source || typeof source === 'function') {
  18502. return target;
  18503. }
  18504. for (var attr in source) { target[attr] = source[attr]; }
  18505. return target;
  18506. }
  18507. function _deepExtend(target, source) {
  18508. for (var prop in source)
  18509. if (prop in target)
  18510. _deepExtend(target[prop], source[prop]);
  18511. else
  18512. target[prop] = source[prop];
  18513. return target;
  18514. }
  18515. function _each(object, callback, args) {
  18516. var name, i = 0,
  18517. length = object.length,
  18518. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18519. if (args) {
  18520. if (isObj) {
  18521. for (name in object) {
  18522. if (callback.apply(object[name], args) === false) {
  18523. break;
  18524. }
  18525. }
  18526. } else {
  18527. for ( ; i < length; ) {
  18528. if (callback.apply(object[i++], args) === false) {
  18529. break;
  18530. }
  18531. }
  18532. }
  18533. // A special, fast, case for the most common use of each
  18534. } else {
  18535. if (isObj) {
  18536. for (name in object) {
  18537. if (callback.call(object[name], name, object[name]) === false) {
  18538. break;
  18539. }
  18540. }
  18541. } else {
  18542. for ( ; i < length; ) {
  18543. if (callback.call(object[i], i, object[i++]) === false) {
  18544. break;
  18545. }
  18546. }
  18547. }
  18548. }
  18549. return object;
  18550. }
  18551. var _entityMap = {
  18552. "&": "&amp;",
  18553. "<": "&lt;",
  18554. ">": "&gt;",
  18555. '"': '&quot;',
  18556. "'": '&#39;',
  18557. "/": '&#x2F;'
  18558. };
  18559. function _escape(data) {
  18560. if (typeof data === 'string') {
  18561. return data.replace(/[&<>"'\/]/g, function (s) {
  18562. return _entityMap[s];
  18563. });
  18564. }else{
  18565. return data;
  18566. }
  18567. }
  18568. function _ajax(options) {
  18569. // v0.5.0 of https://github.com/goloroden/http.js
  18570. var getXhr = function (callback) {
  18571. // Use the native XHR object if the browser supports it.
  18572. if (window.XMLHttpRequest) {
  18573. return callback(null, new XMLHttpRequest());
  18574. } else if (window.ActiveXObject) {
  18575. // In Internet Explorer check for ActiveX versions of the XHR object.
  18576. try {
  18577. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18578. } catch (e) {
  18579. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18580. }
  18581. }
  18582. // If no XHR support was found, throw an error.
  18583. return callback(new Error());
  18584. };
  18585. var encodeUsingUrlEncoding = function (data) {
  18586. if(typeof data === 'string') {
  18587. return data;
  18588. }
  18589. var result = [];
  18590. for(var dataItem in data) {
  18591. if(data.hasOwnProperty(dataItem)) {
  18592. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18593. }
  18594. }
  18595. return result.join('&');
  18596. };
  18597. var utf8 = function (text) {
  18598. text = text.replace(/\r\n/g, '\n');
  18599. var result = '';
  18600. for(var i = 0; i < text.length; i++) {
  18601. var c = text.charCodeAt(i);
  18602. if(c < 128) {
  18603. result += String.fromCharCode(c);
  18604. } else if((c > 127) && (c < 2048)) {
  18605. result += String.fromCharCode((c >> 6) | 192);
  18606. result += String.fromCharCode((c & 63) | 128);
  18607. } else {
  18608. result += String.fromCharCode((c >> 12) | 224);
  18609. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18610. result += String.fromCharCode((c & 63) | 128);
  18611. }
  18612. }
  18613. return result;
  18614. };
  18615. var base64 = function (text) {
  18616. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18617. text = utf8(text);
  18618. var result = '',
  18619. chr1, chr2, chr3,
  18620. enc1, enc2, enc3, enc4,
  18621. i = 0;
  18622. do {
  18623. chr1 = text.charCodeAt(i++);
  18624. chr2 = text.charCodeAt(i++);
  18625. chr3 = text.charCodeAt(i++);
  18626. enc1 = chr1 >> 2;
  18627. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18628. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18629. enc4 = chr3 & 63;
  18630. if(isNaN(chr2)) {
  18631. enc3 = enc4 = 64;
  18632. } else if(isNaN(chr3)) {
  18633. enc4 = 64;
  18634. }
  18635. result +=
  18636. keyStr.charAt(enc1) +
  18637. keyStr.charAt(enc2) +
  18638. keyStr.charAt(enc3) +
  18639. keyStr.charAt(enc4);
  18640. chr1 = chr2 = chr3 = '';
  18641. enc1 = enc2 = enc3 = enc4 = '';
  18642. } while(i < text.length);
  18643. return result;
  18644. };
  18645. var mergeHeaders = function () {
  18646. // Use the first header object as base.
  18647. var result = arguments[0];
  18648. // Iterate through the remaining header objects and add them.
  18649. for(var i = 1; i < arguments.length; i++) {
  18650. var currentHeaders = arguments[i];
  18651. for(var header in currentHeaders) {
  18652. if(currentHeaders.hasOwnProperty(header)) {
  18653. result[header] = currentHeaders[header];
  18654. }
  18655. }
  18656. }
  18657. // Return the merged headers.
  18658. return result;
  18659. };
  18660. var ajax = function (method, url, options, callback) {
  18661. // Adjust parameters.
  18662. if(typeof options === 'function') {
  18663. callback = options;
  18664. options = {};
  18665. }
  18666. // Set default parameter values.
  18667. options.cache = options.cache || false;
  18668. options.data = options.data || {};
  18669. options.headers = options.headers || {};
  18670. options.jsonp = options.jsonp || false;
  18671. options.async = options.async === undefined ? true : options.async;
  18672. // Merge the various header objects.
  18673. var headers = mergeHeaders({
  18674. 'accept': '*/*',
  18675. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18676. }, ajax.headers, options.headers);
  18677. // Encode the data according to the content-type.
  18678. var payload;
  18679. if (headers['content-type'] === 'application/json') {
  18680. payload = JSON.stringify(options.data);
  18681. } else {
  18682. payload = encodeUsingUrlEncoding(options.data);
  18683. }
  18684. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18685. // if neccessary.
  18686. if(method === 'GET') {
  18687. // Setup the query string.
  18688. var queryString = [];
  18689. if(payload) {
  18690. queryString.push(payload);
  18691. payload = null;
  18692. }
  18693. // Handle caching.
  18694. if(!options.cache) {
  18695. queryString.push('_=' + (new Date()).getTime());
  18696. }
  18697. // If neccessary prepare the query string for a JSONP call.
  18698. if(options.jsonp) {
  18699. queryString.push('callback=' + options.jsonp);
  18700. queryString.push('jsonp=' + options.jsonp);
  18701. }
  18702. // Merge the query string and attach it to the url.
  18703. queryString = queryString.join('&');
  18704. if (queryString.length > 1) {
  18705. if (url.indexOf('?') > -1) {
  18706. url += '&' + queryString;
  18707. } else {
  18708. url += '?' + queryString;
  18709. }
  18710. }
  18711. // Make a JSONP call if neccessary.
  18712. if(options.jsonp) {
  18713. var head = document.getElementsByTagName('head')[0];
  18714. var script = document.createElement('script');
  18715. script.type = 'text/javascript';
  18716. script.src = url;
  18717. head.appendChild(script);
  18718. return;
  18719. }
  18720. }
  18721. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18722. getXhr(function (err, xhr) {
  18723. if(err) return callback(err);
  18724. // Open the request.
  18725. xhr.open(method, url, options.async);
  18726. // Set the request headers.
  18727. for(var header in headers) {
  18728. if(headers.hasOwnProperty(header)) {
  18729. xhr.setRequestHeader(header, headers[header]);
  18730. }
  18731. }
  18732. // Handle the request events.
  18733. xhr.onreadystatechange = function () {
  18734. if(xhr.readyState === 4) {
  18735. var data = xhr.responseText || '';
  18736. // If no callback is given, return.
  18737. if(!callback) {
  18738. return;
  18739. }
  18740. // Return an object that provides access to the data as text and JSON.
  18741. callback(xhr.status, {
  18742. text: function () {
  18743. return data;
  18744. },
  18745. json: function () {
  18746. try {
  18747. return JSON.parse(data)
  18748. } catch (e) {
  18749. f.error('Can not parse JSON. URL: ' + url);
  18750. return {};
  18751. }
  18752. }
  18753. });
  18754. }
  18755. };
  18756. // Actually send the XHR request.
  18757. xhr.send(payload);
  18758. });
  18759. };
  18760. // Define the external interface.
  18761. var http = {
  18762. authBasic: function (username, password) {
  18763. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18764. },
  18765. connect: function (url, options, callback) {
  18766. return ajax('CONNECT', url, options, callback);
  18767. },
  18768. del: function (url, options, callback) {
  18769. return ajax('DELETE', url, options, callback);
  18770. },
  18771. get: function (url, options, callback) {
  18772. return ajax('GET', url, options, callback);
  18773. },
  18774. head: function (url, options, callback) {
  18775. return ajax('HEAD', url, options, callback);
  18776. },
  18777. headers: function (headers) {
  18778. ajax.headers = headers || {};
  18779. },
  18780. isAllowed: function (url, verb, callback) {
  18781. this.options(url, function (status, data) {
  18782. callback(data.text().indexOf(verb) !== -1);
  18783. });
  18784. },
  18785. options: function (url, options, callback) {
  18786. return ajax('OPTIONS', url, options, callback);
  18787. },
  18788. patch: function (url, options, callback) {
  18789. return ajax('PATCH', url, options, callback);
  18790. },
  18791. post: function (url, options, callback) {
  18792. return ajax('POST', url, options, callback);
  18793. },
  18794. put: function (url, options, callback) {
  18795. return ajax('PUT', url, options, callback);
  18796. },
  18797. trace: function (url, options, callback) {
  18798. return ajax('TRACE', url, options, callback);
  18799. }
  18800. };
  18801. var methode = options.type ? options.type.toLowerCase() : 'get';
  18802. http[methode](options.url, options, function (status, data) {
  18803. // file: protocol always gives status code 0, so check for data
  18804. if (status === 200 || (status === 0 && data.text())) {
  18805. options.success(data.json(), status, null);
  18806. } else {
  18807. options.error(data.text(), status, null);
  18808. }
  18809. });
  18810. }
  18811. var _cookie = {
  18812. create: function(name,value,minutes,domain) {
  18813. var expires;
  18814. if (minutes) {
  18815. var date = new Date();
  18816. date.setTime(date.getTime()+(minutes*60*1000));
  18817. expires = "; expires="+date.toGMTString();
  18818. }
  18819. else expires = "";
  18820. domain = (domain)? "domain="+domain+";" : "";
  18821. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18822. },
  18823. read: function(name) {
  18824. var nameEQ = name + "=";
  18825. var ca = document.cookie.split(';');
  18826. for(var i=0;i < ca.length;i++) {
  18827. var c = ca[i];
  18828. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18829. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18830. }
  18831. return null;
  18832. },
  18833. remove: function(name) {
  18834. this.create(name,"",-1);
  18835. }
  18836. };
  18837. var cookie_noop = {
  18838. create: function(name,value,minutes,domain) {},
  18839. read: function(name) { return null; },
  18840. remove: function(name) {}
  18841. };
  18842. // move dependent functions to a container so that
  18843. // they can be overriden easier in no jquery environment (node.js)
  18844. var f = {
  18845. extend: $ ? $.extend : _extend,
  18846. deepExtend: _deepExtend,
  18847. each: $ ? $.each : _each,
  18848. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18849. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18850. detectLanguage: detectLanguage,
  18851. escape: _escape,
  18852. log: function(str) {
  18853. if (o.debug && typeof console !== "undefined") console.log(str);
  18854. },
  18855. error: function(str) {
  18856. if (typeof console !== "undefined") console.error(str);
  18857. },
  18858. getCountyIndexOfLng: function(lng) {
  18859. var lng_index = 0;
  18860. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18861. return lng_index;
  18862. },
  18863. toLanguages: function(lng) {
  18864. var log = this.log;
  18865. function applyCase(l) {
  18866. var ret = l;
  18867. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18868. var parts = l.split('-');
  18869. ret = o.lowerCaseLng ?
  18870. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18871. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18872. } else {
  18873. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18874. }
  18875. return ret;
  18876. }
  18877. var languages = [];
  18878. var whitelist = o.lngWhitelist || false;
  18879. var addLanguage = function(language){
  18880. //reject langs not whitelisted
  18881. if(!whitelist || whitelist.indexOf(language) > -1){
  18882. languages.push(language);
  18883. }else{
  18884. log('rejecting non-whitelisted language: ' + language);
  18885. }
  18886. };
  18887. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18888. var parts = lng.split('-');
  18889. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18890. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18891. } else {
  18892. addLanguage(applyCase(lng));
  18893. }
  18894. for (var i = 0; i < o.fallbackLng.length; i++) {
  18895. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18896. }
  18897. return languages;
  18898. },
  18899. regexEscape: function(str) {
  18900. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18901. },
  18902. regexReplacementEscape: function(strOrFn) {
  18903. if (typeof strOrFn === 'string') {
  18904. return strOrFn.replace(/\$/g, "$$$$");
  18905. } else {
  18906. return strOrFn;
  18907. }
  18908. },
  18909. localStorage: {
  18910. setItem: function(key, value) {
  18911. if (window.localStorage) {
  18912. try {
  18913. window.localStorage.setItem(key, value);
  18914. } catch (e) {
  18915. f.log('failed to set value for key "' + key + '" to localStorage.');
  18916. }
  18917. }
  18918. }
  18919. }
  18920. };
  18921. function init(options, cb) {
  18922. if (typeof options === 'function') {
  18923. cb = options;
  18924. options = {};
  18925. }
  18926. options = options || {};
  18927. // override defaults with passed in options
  18928. f.extend(o, options);
  18929. delete o.fixLng; /* passed in each time */
  18930. // override functions: .log(), .detectLanguage(), etc
  18931. if (o.functions) {
  18932. delete o.functions;
  18933. f.extend(f, options.functions);
  18934. }
  18935. // create namespace object if namespace is passed in as string
  18936. if (typeof o.ns == 'string') {
  18937. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18938. }
  18939. // fallback namespaces
  18940. if (typeof o.fallbackNS == 'string') {
  18941. o.fallbackNS = [o.fallbackNS];
  18942. }
  18943. // fallback languages
  18944. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18945. o.fallbackLng = [o.fallbackLng];
  18946. }
  18947. // escape prefix/suffix
  18948. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18949. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18950. if (!o.lng) o.lng = f.detectLanguage();
  18951. languages = f.toLanguages(o.lng);
  18952. currentLng = languages[0];
  18953. f.log('currentLng set to: ' + currentLng);
  18954. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18955. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18956. }
  18957. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18958. f.localStorage.setItem('i18next_lng', currentLng);
  18959. }
  18960. var lngTranslate = translate;
  18961. if (options.fixLng) {
  18962. lngTranslate = function(key, options) {
  18963. options = options || {};
  18964. options.lng = options.lng || lngTranslate.lng;
  18965. return translate(key, options);
  18966. };
  18967. lngTranslate.lng = currentLng;
  18968. }
  18969. pluralExtensions.setCurrentLng(currentLng);
  18970. // add JQuery extensions
  18971. if ($ && o.setJqueryExt) addJqueryFunct();
  18972. // jQuery deferred
  18973. var deferred;
  18974. if ($ && $.Deferred) {
  18975. deferred = $.Deferred();
  18976. }
  18977. // return immidiatly if res are passed in
  18978. if (o.resStore) {
  18979. resStore = o.resStore;
  18980. initialized = true;
  18981. if (cb) cb(lngTranslate);
  18982. if (deferred) deferred.resolve(lngTranslate);
  18983. if (deferred) return deferred.promise();
  18984. return;
  18985. }
  18986. // languages to load
  18987. var lngsToLoad = f.toLanguages(o.lng);
  18988. if (typeof o.preload === 'string') o.preload = [o.preload];
  18989. for (var i = 0, l = o.preload.length; i < l; i++) {
  18990. var pres = f.toLanguages(o.preload[i]);
  18991. for (var y = 0, len = pres.length; y < len; y++) {
  18992. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18993. lngsToLoad.push(pres[y]);
  18994. }
  18995. }
  18996. }
  18997. // else load them
  18998. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18999. resStore = store;
  19000. initialized = true;
  19001. if (cb) cb(lngTranslate);
  19002. if (deferred) deferred.resolve(lngTranslate);
  19003. });
  19004. if (deferred) return deferred.promise();
  19005. }
  19006. function preload(lngs, cb) {
  19007. if (typeof lngs === 'string') lngs = [lngs];
  19008. for (var i = 0, l = lngs.length; i < l; i++) {
  19009. if (o.preload.indexOf(lngs[i]) < 0) {
  19010. o.preload.push(lngs[i]);
  19011. }
  19012. }
  19013. return init(cb);
  19014. }
  19015. function addResourceBundle(lng, ns, resources, deep) {
  19016. if (typeof ns !== 'string') {
  19017. resources = ns;
  19018. ns = o.ns.defaultNs;
  19019. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19020. o.ns.namespaces.push(ns);
  19021. }
  19022. resStore[lng] = resStore[lng] || {};
  19023. resStore[lng][ns] = resStore[lng][ns] || {};
  19024. if (deep) {
  19025. f.deepExtend(resStore[lng][ns], resources);
  19026. } else {
  19027. f.extend(resStore[lng][ns], resources);
  19028. }
  19029. }
  19030. function hasResourceBundle(lng, ns) {
  19031. if (typeof ns !== 'string') {
  19032. ns = o.ns.defaultNs;
  19033. }
  19034. resStore[lng] = resStore[lng] || {};
  19035. var res = resStore[lng][ns] || {};
  19036. var hasValues = false;
  19037. for(var prop in res) {
  19038. if (res.hasOwnProperty(prop)) {
  19039. hasValues = true;
  19040. }
  19041. }
  19042. return hasValues;
  19043. }
  19044. function removeResourceBundle(lng, ns) {
  19045. if (typeof ns !== 'string') {
  19046. ns = o.ns.defaultNs;
  19047. }
  19048. resStore[lng] = resStore[lng] || {};
  19049. resStore[lng][ns] = {};
  19050. }
  19051. function addResource(lng, ns, key, value) {
  19052. if (typeof ns !== 'string') {
  19053. resource = ns;
  19054. ns = o.ns.defaultNs;
  19055. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19056. o.ns.namespaces.push(ns);
  19057. }
  19058. resStore[lng] = resStore[lng] || {};
  19059. resStore[lng][ns] = resStore[lng][ns] || {};
  19060. var keys = key.split(o.keyseparator);
  19061. var x = 0;
  19062. var node = resStore[lng][ns];
  19063. var origRef = node;
  19064. while (keys[x]) {
  19065. if (x == keys.length - 1)
  19066. node[keys[x]] = value;
  19067. else {
  19068. if (node[keys[x]] == null)
  19069. node[keys[x]] = {};
  19070. node = node[keys[x]];
  19071. }
  19072. x++;
  19073. }
  19074. }
  19075. function addResources(lng, ns, resources) {
  19076. if (typeof ns !== 'string') {
  19077. resource = ns;
  19078. ns = o.ns.defaultNs;
  19079. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19080. o.ns.namespaces.push(ns);
  19081. }
  19082. for (var m in resources) {
  19083. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  19084. }
  19085. }
  19086. function setDefaultNamespace(ns) {
  19087. o.ns.defaultNs = ns;
  19088. }
  19089. function loadNamespace(namespace, cb) {
  19090. loadNamespaces([namespace], cb);
  19091. }
  19092. function loadNamespaces(namespaces, cb) {
  19093. var opts = {
  19094. dynamicLoad: o.dynamicLoad,
  19095. resGetPath: o.resGetPath,
  19096. getAsync: o.getAsync,
  19097. customLoad: o.customLoad,
  19098. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  19099. };
  19100. // languages to load
  19101. var lngsToLoad = f.toLanguages(o.lng);
  19102. if (typeof o.preload === 'string') o.preload = [o.preload];
  19103. for (var i = 0, l = o.preload.length; i < l; i++) {
  19104. var pres = f.toLanguages(o.preload[i]);
  19105. for (var y = 0, len = pres.length; y < len; y++) {
  19106. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19107. lngsToLoad.push(pres[y]);
  19108. }
  19109. }
  19110. }
  19111. // check if we have to load
  19112. var lngNeedLoad = [];
  19113. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  19114. var needLoad = false;
  19115. var resSet = resStore[lngsToLoad[a]];
  19116. if (resSet) {
  19117. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  19118. if (!resSet[namespaces[b]]) needLoad = true;
  19119. }
  19120. } else {
  19121. needLoad = true;
  19122. }
  19123. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  19124. }
  19125. if (lngNeedLoad.length) {
  19126. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  19127. var todo = namespaces.length * lngNeedLoad.length;
  19128. // load each file individual
  19129. f.each(namespaces, function(nsIndex, nsValue) {
  19130. // append namespace to namespace array
  19131. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  19132. o.ns.namespaces.push(nsValue);
  19133. }
  19134. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  19135. resStore[lngValue] = resStore[lngValue] || {};
  19136. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  19137. todo--; // wait for all done befor callback
  19138. if (todo === 0 && cb) {
  19139. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  19140. cb();
  19141. }
  19142. });
  19143. });
  19144. });
  19145. } else {
  19146. if (cb) cb();
  19147. }
  19148. }
  19149. function setLng(lng, options, cb) {
  19150. if (typeof options === 'function') {
  19151. cb = options;
  19152. options = {};
  19153. } else if (!options) {
  19154. options = {};
  19155. }
  19156. options.lng = lng;
  19157. return init(options, cb);
  19158. }
  19159. function lng() {
  19160. return currentLng;
  19161. }
  19162. function reload(cb) {
  19163. resStore = {};
  19164. setLng(currentLng, cb);
  19165. }
  19166. function addJqueryFunct() {
  19167. // $.t shortcut
  19168. $.t = $.t || translate;
  19169. function parse(ele, key, options) {
  19170. if (key.length === 0) return;
  19171. var attr = 'text';
  19172. if (key.indexOf('[') === 0) {
  19173. var parts = key.split(']');
  19174. key = parts[1];
  19175. attr = parts[0].substr(1, parts[0].length-1);
  19176. }
  19177. if (key.indexOf(';') === key.length-1) {
  19178. key = key.substr(0, key.length-2);
  19179. }
  19180. var optionsToUse;
  19181. if (attr === 'html') {
  19182. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19183. ele.html($.t(key, optionsToUse));
  19184. } else if (attr === 'text') {
  19185. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  19186. ele.text($.t(key, optionsToUse));
  19187. } else if (attr === 'prepend') {
  19188. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19189. ele.prepend($.t(key, optionsToUse));
  19190. } else if (attr === 'append') {
  19191. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19192. ele.append($.t(key, optionsToUse));
  19193. } else if (attr.indexOf("data-") === 0) {
  19194. var dataAttr = attr.substr(("data-").length);
  19195. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  19196. var translated = $.t(key, optionsToUse);
  19197. //we change into the data cache
  19198. ele.data(dataAttr, translated);
  19199. //we change into the dom
  19200. ele.attr(attr, translated);
  19201. } else {
  19202. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  19203. ele.attr(attr, $.t(key, optionsToUse));
  19204. }
  19205. }
  19206. function localize(ele, options) {
  19207. var key = ele.attr(o.selectorAttr);
  19208. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  19209. if (!key) return;
  19210. var target = ele
  19211. , targetSelector = ele.data("i18n-target");
  19212. if (targetSelector) {
  19213. target = ele.find(targetSelector) || ele;
  19214. }
  19215. if (!options && o.useDataAttrOptions === true) {
  19216. options = ele.data("i18n-options");
  19217. }
  19218. options = options || {};
  19219. if (key.indexOf(';') >= 0) {
  19220. var keys = key.split(';');
  19221. $.each(keys, function(m, k) {
  19222. if (k !== '') parse(target, k, options);
  19223. });
  19224. } else {
  19225. parse(target, key, options);
  19226. }
  19227. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  19228. }
  19229. // fn
  19230. $.fn.i18n = function (options) {
  19231. return this.each(function() {
  19232. // localize element itself
  19233. localize($(this), options);
  19234. // localize childs
  19235. var elements = $(this).find('[' + o.selectorAttr + ']');
  19236. elements.each(function() {
  19237. localize($(this), options);
  19238. });
  19239. });
  19240. };
  19241. }
  19242. function applyReplacement(str, replacementHash, nestedKey, options) {
  19243. if (!str) return str;
  19244. options = options || replacementHash; // first call uses replacement hash combined with options
  19245. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  19246. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  19247. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  19248. , unEscapingSuffix = 'HTML'+suffix;
  19249. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  19250. f.each(hash, function(key, value) {
  19251. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19252. if (typeof value === 'object' && value !== null) {
  19253. str = applyReplacement(str, value, nextKey, options);
  19254. } else {
  19255. if (options.escapeInterpolation || o.escapeInterpolation) {
  19256. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19257. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19258. } else {
  19259. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19260. }
  19261. // str = options.escapeInterpolation;
  19262. }
  19263. });
  19264. return str;
  19265. }
  19266. // append it to functions
  19267. f.applyReplacement = applyReplacement;
  19268. function applyReuse(translated, options) {
  19269. var comma = ',';
  19270. var options_open = '{';
  19271. var options_close = '}';
  19272. var opts = f.extend({}, options);
  19273. delete opts.postProcess;
  19274. while (translated.indexOf(o.reusePrefix) != -1) {
  19275. replacementCounter++;
  19276. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19277. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19278. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19279. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19280. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19281. if (index_of_end_of_closing <= index_of_opening) {
  19282. f.error('there is an missing closing in following translation value', translated);
  19283. return '';
  19284. }
  19285. if (token_without_symbols.indexOf(comma) != -1) {
  19286. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19287. if (token_without_symbols.indexOf(options_open, index_of_token_end_of_closing) != -1 && token_without_symbols.indexOf(options_close, index_of_token_end_of_closing) != -1) {
  19288. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19289. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19290. try {
  19291. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19292. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19293. } catch (e) {
  19294. }
  19295. }
  19296. }
  19297. var translated_token = _translate(token_without_symbols, opts);
  19298. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19299. }
  19300. return translated;
  19301. }
  19302. function hasContext(options) {
  19303. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19304. }
  19305. function needsPlural(options, lng) {
  19306. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19307. }
  19308. function needsIndefiniteArticle(options) {
  19309. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19310. }
  19311. function exists(key, options) {
  19312. options = options || {};
  19313. var notFound = _getDefaultValue(key, options)
  19314. , found = _find(key, options);
  19315. return found !== undefined || found === notFound;
  19316. }
  19317. function translate(key, options) {
  19318. options = options || {};
  19319. if (!initialized) {
  19320. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19321. return options.defaultValue || '';
  19322. };
  19323. replacementCounter = 0;
  19324. return _translate.apply(null, arguments);
  19325. }
  19326. function _getDefaultValue(key, options) {
  19327. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19328. }
  19329. function _injectSprintfProcessor() {
  19330. var values = [];
  19331. // mh: build array from second argument onwards
  19332. for (var i = 1; i < arguments.length; i++) {
  19333. values.push(arguments[i]);
  19334. }
  19335. return {
  19336. postProcess: 'sprintf',
  19337. sprintf: values
  19338. };
  19339. }
  19340. function _translate(potentialKeys, options) {
  19341. if (options && typeof options !== 'object') {
  19342. if (o.shortcutFunction === 'sprintf') {
  19343. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19344. options = _injectSprintfProcessor.apply(null, arguments);
  19345. } else if (o.shortcutFunction === 'defaultValue') {
  19346. options = {
  19347. defaultValue: options
  19348. }
  19349. }
  19350. } else {
  19351. options = options || {};
  19352. }
  19353. if (typeof o.defaultVariables === 'object') {
  19354. options = f.extend({}, o.defaultVariables, options);
  19355. }
  19356. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19357. if (typeof potentialKeys === 'string') {
  19358. potentialKeys = [potentialKeys];
  19359. }
  19360. var key = potentialKeys[0];
  19361. if (potentialKeys.length > 1) {
  19362. for (var i = 0; i < potentialKeys.length; i++) {
  19363. key = potentialKeys[i];
  19364. if (exists(key, options)) {
  19365. break;
  19366. }
  19367. }
  19368. }
  19369. var notFound = _getDefaultValue(key, options)
  19370. , found = _find(key, options)
  19371. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19372. , ns = options.ns || o.ns.defaultNs
  19373. , parts;
  19374. // split ns and key
  19375. if (key.indexOf(o.nsseparator) > -1) {
  19376. parts = key.split(o.nsseparator);
  19377. ns = parts[0];
  19378. key = parts[1];
  19379. }
  19380. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19381. if (options.lng) {
  19382. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19383. } else {
  19384. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19385. }
  19386. }
  19387. var postProcessor = options.postProcess || o.postProcess;
  19388. if (found !== undefined && postProcessor) {
  19389. if (postProcessors[postProcessor]) {
  19390. found = postProcessors[postProcessor](found, key, options);
  19391. }
  19392. }
  19393. // process notFound if function exists
  19394. var splitNotFound = notFound;
  19395. if (notFound.indexOf(o.nsseparator) > -1) {
  19396. parts = notFound.split(o.nsseparator);
  19397. splitNotFound = parts[1];
  19398. }
  19399. if (splitNotFound === key && o.parseMissingKey) {
  19400. notFound = o.parseMissingKey(notFound);
  19401. }
  19402. if (found === undefined) {
  19403. notFound = applyReplacement(notFound, options);
  19404. notFound = applyReuse(notFound, options);
  19405. if (postProcessor && postProcessors[postProcessor]) {
  19406. var val = _getDefaultValue(key, options);
  19407. found = postProcessors[postProcessor](val, key, options);
  19408. }
  19409. }
  19410. return (found !== undefined) ? found : notFound;
  19411. }
  19412. function _find(key, options) {
  19413. options = options || {};
  19414. var optionWithoutCount, translated
  19415. , notFound = _getDefaultValue(key, options)
  19416. , lngs = languages;
  19417. if (!resStore) { return notFound; } // no resStore to translate from
  19418. // CI mode
  19419. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19420. // passed in lng
  19421. if (options.lngs) lngs = options.lngs;
  19422. if (options.lng) {
  19423. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19424. if (!resStore[lngs[0]]) {
  19425. var oldAsync = o.getAsync;
  19426. o.getAsync = false;
  19427. i18n.sync.load(lngs, o, function(err, store) {
  19428. f.extend(resStore, store);
  19429. o.getAsync = oldAsync;
  19430. });
  19431. }
  19432. }
  19433. var ns = options.ns || o.ns.defaultNs;
  19434. if (key.indexOf(o.nsseparator) > -1) {
  19435. var parts = key.split(o.nsseparator);
  19436. ns = parts[0];
  19437. key = parts[1];
  19438. }
  19439. if (hasContext(options)) {
  19440. optionWithoutCount = f.extend({}, options);
  19441. delete optionWithoutCount.context;
  19442. optionWithoutCount.defaultValue = o.contextNotFound;
  19443. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19444. translated = translate(contextKey, optionWithoutCount);
  19445. if (translated != o.contextNotFound) {
  19446. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19447. } // else continue translation with original/nonContext key
  19448. }
  19449. if (needsPlural(options, lngs[0])) {
  19450. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19451. delete optionWithoutCount.count;
  19452. delete optionWithoutCount.lng;
  19453. optionWithoutCount.defaultValue = o.pluralNotFound;
  19454. var pluralKey;
  19455. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19456. pluralKey = ns + o.nsseparator + key;
  19457. } else {
  19458. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19459. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19460. if (pluralExtension >= 0) {
  19461. pluralKey = pluralKey + '_' + pluralExtension;
  19462. } else if (pluralExtension === 1) {
  19463. pluralKey = ns + o.nsseparator + key; // singular
  19464. }
  19465. }
  19466. translated = translate(pluralKey, optionWithoutCount);
  19467. if (translated != o.pluralNotFound) {
  19468. return applyReplacement(translated, {
  19469. count: options.count,
  19470. interpolationPrefix: options.interpolationPrefix,
  19471. interpolationSuffix: options.interpolationSuffix
  19472. }); // apply replacement for count only
  19473. } else if (lngs.length > 1) {
  19474. // remove failed lng
  19475. var clone = lngs.slice();
  19476. clone.shift();
  19477. options = f.extend(options, { lngs: clone });
  19478. delete options.lng;
  19479. // retry with fallbacks
  19480. translated = translate(ns + o.nsseparator + key, options);
  19481. if (translated != o.pluralNotFound) return translated;
  19482. } else {
  19483. return translated;
  19484. }
  19485. }
  19486. if (needsIndefiniteArticle(options)) {
  19487. var optionsWithoutIndef = f.extend({}, options);
  19488. delete optionsWithoutIndef.indefinite_article;
  19489. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19490. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19491. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19492. translated = translate(indefiniteKey, optionsWithoutIndef);
  19493. if (translated != o.indefiniteNotFound) {
  19494. return translated;
  19495. }
  19496. }
  19497. var found;
  19498. var keys = key.split(o.keyseparator);
  19499. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19500. if (found !== undefined) break;
  19501. var l = lngs[i];
  19502. var x = 0;
  19503. var value = resStore[l] && resStore[l][ns];
  19504. while (keys[x]) {
  19505. value = value && value[keys[x]];
  19506. x++;
  19507. }
  19508. if (value !== undefined) {
  19509. var valueType = Object.prototype.toString.apply(value);
  19510. if (typeof value === 'string') {
  19511. value = applyReplacement(value, options);
  19512. value = applyReuse(value, options);
  19513. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19514. value = value.join('\n');
  19515. value = applyReplacement(value, options);
  19516. value = applyReuse(value, options);
  19517. } else if (value === null && o.fallbackOnNull === true) {
  19518. value = undefined;
  19519. } else if (value !== null) {
  19520. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19521. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19522. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19523. } else {
  19524. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19525. 'returned an object instead of string.';
  19526. f.log(value);
  19527. }
  19528. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19529. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19530. f.each(value, function(m) {
  19531. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19532. });
  19533. value = copy;
  19534. }
  19535. }
  19536. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19537. value = undefined;
  19538. found = value;
  19539. }
  19540. }
  19541. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19542. // set flag for fallback lookup - avoid recursion
  19543. options.isFallbackLookup = true;
  19544. if (o.fallbackNS.length) {
  19545. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19546. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19547. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19548. /* compare value without namespace */
  19549. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19550. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19551. if (foundValue !== notFoundValue) break;
  19552. }
  19553. }
  19554. } else {
  19555. found = _find(key, options); // fallback to default NS
  19556. }
  19557. options.isFallbackLookup = false;
  19558. }
  19559. return found;
  19560. }
  19561. function detectLanguage() {
  19562. var detectedLng;
  19563. var whitelist = o.lngWhitelist || [];
  19564. var userLngChoices = [];
  19565. // get from qs
  19566. var qsParm = [];
  19567. if (typeof window !== 'undefined') {
  19568. (function() {
  19569. var query = window.location.search.substring(1);
  19570. var params = query.split('&');
  19571. for (var i=0; i<params.length; i++) {
  19572. var pos = params[i].indexOf('=');
  19573. if (pos > 0) {
  19574. var key = params[i].substring(0,pos);
  19575. if (key == o.detectLngQS) {
  19576. userLngChoices.push(params[i].substring(pos+1));
  19577. }
  19578. }
  19579. }
  19580. })();
  19581. }
  19582. // get from cookie
  19583. if (o.useCookie && typeof document !== 'undefined') {
  19584. var c = f.cookie.read(o.cookieName);
  19585. if (c) userLngChoices.push(c);
  19586. }
  19587. // get from localStorage
  19588. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19589. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19590. }
  19591. // get from navigator
  19592. if (typeof navigator !== 'undefined') {
  19593. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19594. for (var i=0;i<navigator.languages.length;i++) {
  19595. userLngChoices.push(navigator.languages[i]);
  19596. }
  19597. }
  19598. if (navigator.userLanguage) {
  19599. userLngChoices.push(navigator.userLanguage);
  19600. }
  19601. if (navigator.language) {
  19602. userLngChoices.push(navigator.language);
  19603. }
  19604. }
  19605. (function() {
  19606. for (var i=0;i<userLngChoices.length;i++) {
  19607. var lng = userLngChoices[i];
  19608. if (lng.indexOf('-') > -1) {
  19609. var parts = lng.split('-');
  19610. lng = o.lowerCaseLng ?
  19611. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19612. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19613. }
  19614. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19615. detectedLng = lng;
  19616. break;
  19617. }
  19618. }
  19619. })();
  19620. //fallback
  19621. if (!detectedLng){
  19622. detectedLng = o.fallbackLng[0];
  19623. }
  19624. return detectedLng;
  19625. }
  19626. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19627. /* [code, name, numbers, pluralsType] */
  19628. var _rules = [
  19629. ["ach", "Acholi", [1,2], 1],
  19630. ["af", "Afrikaans",[1,2], 2],
  19631. ["ak", "Akan", [1,2], 1],
  19632. ["am", "Amharic", [1,2], 1],
  19633. ["an", "Aragonese",[1,2], 2],
  19634. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19635. ["arn", "Mapudungun",[1,2], 1],
  19636. ["ast", "Asturian", [1,2], 2],
  19637. ["ay", "Aymará", [1], 3],
  19638. ["az", "Azerbaijani",[1,2],2],
  19639. ["be", "Belarusian",[1,2,5],4],
  19640. ["bg", "Bulgarian",[1,2], 2],
  19641. ["bn", "Bengali", [1,2], 2],
  19642. ["bo", "Tibetan", [1], 3],
  19643. ["br", "Breton", [1,2], 1],
  19644. ["bs", "Bosnian", [1,2,5],4],
  19645. ["ca", "Catalan", [1,2], 2],
  19646. ["cgg", "Chiga", [1], 3],
  19647. ["cs", "Czech", [1,2,5],6],
  19648. ["csb", "Kashubian",[1,2,5],7],
  19649. ["cy", "Welsh", [1,2,3,8],8],
  19650. ["da", "Danish", [1,2], 2],
  19651. ["de", "German", [1,2], 2],
  19652. ["dev", "Development Fallback", [1,2], 2],
  19653. ["dz", "Dzongkha", [1], 3],
  19654. ["el", "Greek", [1,2], 2],
  19655. ["en", "English", [1,2], 2],
  19656. ["eo", "Esperanto",[1,2], 2],
  19657. ["es", "Spanish", [1,2], 2],
  19658. ["es_ar","Argentinean Spanish", [1,2], 2],
  19659. ["et", "Estonian", [1,2], 2],
  19660. ["eu", "Basque", [1,2], 2],
  19661. ["fa", "Persian", [1], 3],
  19662. ["fi", "Finnish", [1,2], 2],
  19663. ["fil", "Filipino", [1,2], 1],
  19664. ["fo", "Faroese", [1,2], 2],
  19665. ["fr", "French", [1,2], 9],
  19666. ["fur", "Friulian", [1,2], 2],
  19667. ["fy", "Frisian", [1,2], 2],
  19668. ["ga", "Irish", [1,2,3,7,11],10],
  19669. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19670. ["gl", "Galician", [1,2], 2],
  19671. ["gu", "Gujarati", [1,2], 2],
  19672. ["gun", "Gun", [1,2], 1],
  19673. ["ha", "Hausa", [1,2], 2],
  19674. ["he", "Hebrew", [1,2], 2],
  19675. ["hi", "Hindi", [1,2], 2],
  19676. ["hr", "Croatian", [1,2,5],4],
  19677. ["hu", "Hungarian",[1,2], 2],
  19678. ["hy", "Armenian", [1,2], 2],
  19679. ["ia", "Interlingua",[1,2],2],
  19680. ["id", "Indonesian",[1], 3],
  19681. ["is", "Icelandic",[1,2], 12],
  19682. ["it", "Italian", [1,2], 2],
  19683. ["ja", "Japanese", [1], 3],
  19684. ["jbo", "Lojban", [1], 3],
  19685. ["jv", "Javanese", [0,1], 13],
  19686. ["ka", "Georgian", [1], 3],
  19687. ["kk", "Kazakh", [1], 3],
  19688. ["km", "Khmer", [1], 3],
  19689. ["kn", "Kannada", [1,2], 2],
  19690. ["ko", "Korean", [1], 3],
  19691. ["ku", "Kurdish", [1,2], 2],
  19692. ["kw", "Cornish", [1,2,3,4],14],
  19693. ["ky", "Kyrgyz", [1], 3],
  19694. ["lb", "Letzeburgesch",[1,2],2],
  19695. ["ln", "Lingala", [1,2], 1],
  19696. ["lo", "Lao", [1], 3],
  19697. ["lt", "Lithuanian",[1,2,10],15],
  19698. ["lv", "Latvian", [1,2,0],16],
  19699. ["mai", "Maithili", [1,2], 2],
  19700. ["mfe", "Mauritian Creole",[1,2],1],
  19701. ["mg", "Malagasy", [1,2], 1],
  19702. ["mi", "Maori", [1,2], 1],
  19703. ["mk", "Macedonian",[1,2],17],
  19704. ["ml", "Malayalam",[1,2], 2],
  19705. ["mn", "Mongolian",[1,2], 2],
  19706. ["mnk", "Mandinka", [0,1,2],18],
  19707. ["mr", "Marathi", [1,2], 2],
  19708. ["ms", "Malay", [1], 3],
  19709. ["mt", "Maltese", [1,2,11,20],19],
  19710. ["nah", "Nahuatl", [1,2], 2],
  19711. ["nap", "Neapolitan",[1,2], 2],
  19712. ["nb", "Norwegian Bokmal",[1,2],2],
  19713. ["ne", "Nepali", [1,2], 2],
  19714. ["nl", "Dutch", [1,2], 2],
  19715. ["nn", "Norwegian Nynorsk",[1,2],2],
  19716. ["no", "Norwegian",[1,2], 2],
  19717. ["nso", "Northern Sotho",[1,2],2],
  19718. ["oc", "Occitan", [1,2], 1],
  19719. ["or", "Oriya", [2,1], 2],
  19720. ["pa", "Punjabi", [1,2], 2],
  19721. ["pap", "Papiamento",[1,2], 2],
  19722. ["pl", "Polish", [1,2,5],7],
  19723. ["pms", "Piemontese",[1,2], 2],
  19724. ["ps", "Pashto", [1,2], 2],
  19725. ["pt", "Portuguese",[1,2], 2],
  19726. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19727. ["rm", "Romansh", [1,2], 2],
  19728. ["ro", "Romanian", [1,2,20],20],
  19729. ["ru", "Russian", [1,2,5],4],
  19730. ["sah", "Yakut", [1], 3],
  19731. ["sco", "Scots", [1,2], 2],
  19732. ["se", "Northern Sami",[1,2], 2],
  19733. ["si", "Sinhala", [1,2], 2],
  19734. ["sk", "Slovak", [1,2,5],6],
  19735. ["sl", "Slovenian",[5,1,2,3],21],
  19736. ["so", "Somali", [1,2], 2],
  19737. ["son", "Songhay", [1,2], 2],
  19738. ["sq", "Albanian", [1,2], 2],
  19739. ["sr", "Serbian", [1,2,5],4],
  19740. ["su", "Sundanese",[1], 3],
  19741. ["sv", "Swedish", [1,2], 2],
  19742. ["sw", "Swahili", [1,2], 2],
  19743. ["ta", "Tamil", [1,2], 2],
  19744. ["te", "Telugu", [1,2], 2],
  19745. ["tg", "Tajik", [1,2], 1],
  19746. ["th", "Thai", [1], 3],
  19747. ["ti", "Tigrinya", [1,2], 1],
  19748. ["tk", "Turkmen", [1,2], 2],
  19749. ["tr", "Turkish", [1,2], 1],
  19750. ["tt", "Tatar", [1], 3],
  19751. ["ug", "Uyghur", [1], 3],
  19752. ["uk", "Ukrainian",[1,2,5],4],
  19753. ["ur", "Urdu", [1,2], 2],
  19754. ["uz", "Uzbek", [1,2], 1],
  19755. ["vi", "Vietnamese",[1], 3],
  19756. ["wa", "Walloon", [1,2], 1],
  19757. ["wo", "Wolof", [1], 3],
  19758. ["yo", "Yoruba", [1,2], 2],
  19759. ["zh", "Chinese", [1], 3]
  19760. ];
  19761. var _rulesPluralsTypes = {
  19762. 1: function(n) {return Number(n > 1);},
  19763. 2: function(n) {return Number(n != 1);},
  19764. 3: function(n) {return 0;},
  19765. 4: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19766. 5: function(n) {return Number(n===0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5);},
  19767. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19768. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19769. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19770. 9: function(n) {return Number(n >= 2);},
  19771. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19772. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19773. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19774. 13: function(n) {return Number(n !== 0);},
  19775. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19776. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19777. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19778. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19779. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19780. 19: function(n) {return Number(n==1 ? 0 : n===0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3);},
  19781. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19782. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19783. };
  19784. var pluralExtensions = {
  19785. rules: (function () {
  19786. var l, rules = {};
  19787. for (l=_rules.length; l-- ;) {
  19788. rules[_rules[l][0]] = {
  19789. name: _rules[l][1],
  19790. numbers: _rules[l][2],
  19791. plurals: _rulesPluralsTypes[_rules[l][3]]
  19792. }
  19793. }
  19794. return rules;
  19795. }()),
  19796. // you can add your own pluralExtensions
  19797. addRule: function(lng, obj) {
  19798. pluralExtensions.rules[lng] = obj;
  19799. },
  19800. setCurrentLng: function(lng) {
  19801. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19802. var parts = lng.split('-');
  19803. pluralExtensions.currentRule = {
  19804. lng: lng,
  19805. rule: pluralExtensions.rules[parts[0]]
  19806. };
  19807. }
  19808. },
  19809. needsPlural: function(lng, count) {
  19810. var parts = lng.split('-');
  19811. var ext;
  19812. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19813. ext = pluralExtensions.currentRule.rule;
  19814. } else {
  19815. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19816. }
  19817. if (ext && ext.numbers.length <= 1) {
  19818. return false;
  19819. } else {
  19820. return this.get(lng, count) !== 1;
  19821. }
  19822. },
  19823. get: function(lng, count) {
  19824. var parts = lng.split('-');
  19825. function getResult(l, c) {
  19826. var ext;
  19827. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19828. ext = pluralExtensions.currentRule.rule;
  19829. } else {
  19830. ext = pluralExtensions.rules[l];
  19831. }
  19832. if (ext) {
  19833. var i;
  19834. if (ext.noAbs) {
  19835. i = ext.plurals(c);
  19836. } else {
  19837. i = ext.plurals(Math.abs(c));
  19838. }
  19839. var number = ext.numbers[i];
  19840. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19841. if (number === 2) {
  19842. number = -1; // regular plural
  19843. } else if (number === 1) {
  19844. number = 1; // singular
  19845. }
  19846. }//console.log(count + '-' + number);
  19847. return number;
  19848. } else {
  19849. return c === 1 ? '1' : '-1';
  19850. }
  19851. }
  19852. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19853. }
  19854. };
  19855. var postProcessors = {};
  19856. var addPostProcessor = function(name, fc) {
  19857. postProcessors[name] = fc;
  19858. };
  19859. // sprintf support
  19860. var sprintf = (function() {
  19861. function get_type(variable) {
  19862. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19863. }
  19864. function str_repeat(input, multiplier) {
  19865. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19866. return output.join('');
  19867. }
  19868. var str_format = function() {
  19869. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19870. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19871. }
  19872. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19873. };
  19874. str_format.format = function(parse_tree, argv) {
  19875. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19876. for (i = 0; i < tree_length; i++) {
  19877. node_type = get_type(parse_tree[i]);
  19878. if (node_type === 'string') {
  19879. output.push(parse_tree[i]);
  19880. }
  19881. else if (node_type === 'array') {
  19882. match = parse_tree[i]; // convenience purposes only
  19883. if (match[2]) { // keyword argument
  19884. arg = argv[cursor];
  19885. for (k = 0; k < match[2].length; k++) {
  19886. if (!arg.hasOwnProperty(match[2][k])) {
  19887. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19888. }
  19889. arg = arg[match[2][k]];
  19890. }
  19891. }
  19892. else if (match[1]) { // positional argument (explicit)
  19893. arg = argv[match[1]];
  19894. }
  19895. else { // positional argument (implicit)
  19896. arg = argv[cursor++];
  19897. }
  19898. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19899. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19900. }
  19901. switch (match[8]) {
  19902. case 'b': arg = arg.toString(2); break;
  19903. case 'c': arg = String.fromCharCode(arg); break;
  19904. case 'd': arg = parseInt(arg, 10); break;
  19905. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19906. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19907. case 'o': arg = arg.toString(8); break;
  19908. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19909. case 'u': arg = Math.abs(arg); break;
  19910. case 'x': arg = arg.toString(16); break;
  19911. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19912. }
  19913. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19914. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19915. pad_length = match[6] - String(arg).length;
  19916. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19917. output.push(match[5] ? arg + pad : pad + arg);
  19918. }
  19919. }
  19920. return output.join('');
  19921. };
  19922. str_format.cache = {};
  19923. str_format.parse = function(fmt) {
  19924. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19925. while (_fmt) {
  19926. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19927. parse_tree.push(match[0]);
  19928. }
  19929. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19930. parse_tree.push('%');
  19931. }
  19932. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19933. if (match[2]) {
  19934. arg_names |= 1;
  19935. var field_list = [], replacement_field = match[2], field_match = [];
  19936. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19937. field_list.push(field_match[1]);
  19938. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19939. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19940. field_list.push(field_match[1]);
  19941. }
  19942. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19943. field_list.push(field_match[1]);
  19944. }
  19945. else {
  19946. throw('[sprintf] huh?');
  19947. }
  19948. }
  19949. }
  19950. else {
  19951. throw('[sprintf] huh?');
  19952. }
  19953. match[2] = field_list;
  19954. }
  19955. else {
  19956. arg_names |= 2;
  19957. }
  19958. if (arg_names === 3) {
  19959. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19960. }
  19961. parse_tree.push(match);
  19962. }
  19963. else {
  19964. throw('[sprintf] huh?');
  19965. }
  19966. _fmt = _fmt.substring(match[0].length);
  19967. }
  19968. return parse_tree;
  19969. };
  19970. return str_format;
  19971. })();
  19972. var vsprintf = function(fmt, argv) {
  19973. argv.unshift(fmt);
  19974. return sprintf.apply(null, argv);
  19975. };
  19976. addPostProcessor("sprintf", function(val, key, opts) {
  19977. if (!opts.sprintf) return val;
  19978. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19979. return vsprintf(val, opts.sprintf);
  19980. } else if (typeof opts.sprintf === 'object') {
  19981. return sprintf(val, opts.sprintf);
  19982. }
  19983. return val;
  19984. });
  19985. // public api interface
  19986. i18n.init = init;
  19987. i18n.setLng = setLng;
  19988. i18n.preload = preload;
  19989. i18n.addResourceBundle = addResourceBundle;
  19990. i18n.hasResourceBundle = hasResourceBundle;
  19991. i18n.addResource = addResource;
  19992. i18n.addResources = addResources;
  19993. i18n.removeResourceBundle = removeResourceBundle;
  19994. i18n.loadNamespace = loadNamespace;
  19995. i18n.loadNamespaces = loadNamespaces;
  19996. i18n.setDefaultNamespace = setDefaultNamespace;
  19997. i18n.t = translate;
  19998. i18n.translate = translate;
  19999. i18n.exists = exists;
  20000. i18n.detectLanguage = f.detectLanguage;
  20001. i18n.pluralExtensions = pluralExtensions;
  20002. i18n.sync = sync;
  20003. i18n.functions = f;
  20004. i18n.lng = lng;
  20005. i18n.addPostProcessor = addPostProcessor;
  20006. i18n.options = o;
  20007. })();
  20008. },{"jquery":"jquery"}],74:[function(require,module,exports){
  20009. /*
  20010. A JavaScript implementation of the SHA family of hashes, as
  20011. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  20012. as defined in FIPS PUB 198a
  20013. Copyright Brian Turek 2008-2013
  20014. Distributed under the BSD License
  20015. See http://caligatio.github.com/jsSHA/ for more information
  20016. Several functions taken from Paul Johnston
  20017. */
  20018. (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"!==
  20019. 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";
  20020. 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"===
  20021. 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|
  20022. (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,
  20023. 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,
  20024. 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=
  20025. {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):
  20026. 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,
  20027. 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>>>
  20028. 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>>>
  20029. 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>>>
  20030. 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-
  20031. 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,
  20032. 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,
  20033. 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],
  20034. 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),
  20035. 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),
  20036. 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,
  20037. 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,
  20038. 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?
  20039. 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,
  20040. 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);
  20041. },{}],75:[function(require,module,exports){
  20042. // Top level file is just a mixin of submodules & constants
  20043. 'use strict';
  20044. var assign = require('./lib/utils/common').assign;
  20045. var deflate = require('./lib/deflate');
  20046. var inflate = require('./lib/inflate');
  20047. var constants = require('./lib/zlib/constants');
  20048. var pako = {};
  20049. assign(pako, deflate, inflate, constants);
  20050. module.exports = pako;
  20051. },{"./lib/deflate":76,"./lib/inflate":77,"./lib/utils/common":78,"./lib/zlib/constants":81}],76:[function(require,module,exports){
  20052. 'use strict';
  20053. var zlib_deflate = require('./zlib/deflate.js');
  20054. var utils = require('./utils/common');
  20055. var strings = require('./utils/strings');
  20056. var msg = require('./zlib/messages');
  20057. var zstream = require('./zlib/zstream');
  20058. var toString = Object.prototype.toString;
  20059. /* Public constants ==========================================================*/
  20060. /* ===========================================================================*/
  20061. var Z_NO_FLUSH = 0;
  20062. var Z_FINISH = 4;
  20063. var Z_OK = 0;
  20064. var Z_STREAM_END = 1;
  20065. var Z_SYNC_FLUSH = 2;
  20066. var Z_DEFAULT_COMPRESSION = -1;
  20067. var Z_DEFAULT_STRATEGY = 0;
  20068. var Z_DEFLATED = 8;
  20069. /* ===========================================================================*/
  20070. /**
  20071. * class Deflate
  20072. *
  20073. * Generic JS-style wrapper for zlib calls. If you don't need
  20074. * streaming behaviour - use more simple functions: [[deflate]],
  20075. * [[deflateRaw]] and [[gzip]].
  20076. **/
  20077. /* internal
  20078. * Deflate.chunks -> Array
  20079. *
  20080. * Chunks of output data, if [[Deflate#onData]] not overriden.
  20081. **/
  20082. /**
  20083. * Deflate.result -> Uint8Array|Array
  20084. *
  20085. * Compressed result, generated by default [[Deflate#onData]]
  20086. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  20087. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  20088. * push a chunk with explicit flush (call [[Deflate#push]] with
  20089. * `Z_SYNC_FLUSH` param).
  20090. **/
  20091. /**
  20092. * Deflate.err -> Number
  20093. *
  20094. * Error code after deflate finished. 0 (Z_OK) on success.
  20095. * You will not need it in real life, because deflate errors
  20096. * are possible only on wrong options or bad `onData` / `onEnd`
  20097. * custom handlers.
  20098. **/
  20099. /**
  20100. * Deflate.msg -> String
  20101. *
  20102. * Error message, if [[Deflate.err]] != 0
  20103. **/
  20104. /**
  20105. * new Deflate(options)
  20106. * - options (Object): zlib deflate options.
  20107. *
  20108. * Creates new deflator instance with specified params. Throws exception
  20109. * on bad params. Supported options:
  20110. *
  20111. * - `level`
  20112. * - `windowBits`
  20113. * - `memLevel`
  20114. * - `strategy`
  20115. *
  20116. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20117. * for more information on these.
  20118. *
  20119. * Additional options, for internal needs:
  20120. *
  20121. * - `chunkSize` - size of generated data chunks (16K by default)
  20122. * - `raw` (Boolean) - do raw deflate
  20123. * - `gzip` (Boolean) - create gzip wrapper
  20124. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20125. * (each char code [0..255])
  20126. * - `header` (Object) - custom header for gzip
  20127. * - `text` (Boolean) - true if compressed data believed to be text
  20128. * - `time` (Number) - modification time, unix timestamp
  20129. * - `os` (Number) - operation system code
  20130. * - `extra` (Array) - array of bytes with extra data (max 65536)
  20131. * - `name` (String) - file name (binary string)
  20132. * - `comment` (String) - comment (binary string)
  20133. * - `hcrc` (Boolean) - true if header crc should be added
  20134. *
  20135. * ##### Example:
  20136. *
  20137. * ```javascript
  20138. * var pako = require('pako')
  20139. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20140. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20141. *
  20142. * var deflate = new pako.Deflate({ level: 3});
  20143. *
  20144. * deflate.push(chunk1, false);
  20145. * deflate.push(chunk2, true); // true -> last chunk
  20146. *
  20147. * if (deflate.err) { throw new Error(deflate.err); }
  20148. *
  20149. * console.log(deflate.result);
  20150. * ```
  20151. **/
  20152. var Deflate = function(options) {
  20153. this.options = utils.assign({
  20154. level: Z_DEFAULT_COMPRESSION,
  20155. method: Z_DEFLATED,
  20156. chunkSize: 16384,
  20157. windowBits: 15,
  20158. memLevel: 8,
  20159. strategy: Z_DEFAULT_STRATEGY,
  20160. to: ''
  20161. }, options || {});
  20162. var opt = this.options;
  20163. if (opt.raw && (opt.windowBits > 0)) {
  20164. opt.windowBits = -opt.windowBits;
  20165. }
  20166. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  20167. opt.windowBits += 16;
  20168. }
  20169. this.err = 0; // error code, if happens (0 = Z_OK)
  20170. this.msg = ''; // error message
  20171. this.ended = false; // used to avoid multiple onEnd() calls
  20172. this.chunks = []; // chunks of compressed data
  20173. this.strm = new zstream();
  20174. this.strm.avail_out = 0;
  20175. var status = zlib_deflate.deflateInit2(
  20176. this.strm,
  20177. opt.level,
  20178. opt.method,
  20179. opt.windowBits,
  20180. opt.memLevel,
  20181. opt.strategy
  20182. );
  20183. if (status !== Z_OK) {
  20184. throw new Error(msg[status]);
  20185. }
  20186. if (opt.header) {
  20187. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  20188. }
  20189. };
  20190. /**
  20191. * Deflate#push(data[, mode]) -> Boolean
  20192. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  20193. * converted to utf8 byte sequence.
  20194. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20195. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20196. *
  20197. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  20198. * new compressed chunks. Returns `true` on success. The last data block must have
  20199. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20200. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20201. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  20202. *
  20203. * On fail call [[Deflate#onEnd]] with error code and return false.
  20204. *
  20205. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20206. * array format is detected automatically). Also, don't skip last param and always
  20207. * use the same type in your code (boolean or number). That will improve JS speed.
  20208. *
  20209. * For regular `Array`-s make sure all elements are [0..255].
  20210. *
  20211. * ##### Example
  20212. *
  20213. * ```javascript
  20214. * push(chunk, false); // push one of data chunks
  20215. * ...
  20216. * push(chunk, true); // push last chunk
  20217. * ```
  20218. **/
  20219. Deflate.prototype.push = function(data, mode) {
  20220. var strm = this.strm;
  20221. var chunkSize = this.options.chunkSize;
  20222. var status, _mode;
  20223. if (this.ended) { return false; }
  20224. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  20225. // Convert data if needed
  20226. if (typeof data === 'string') {
  20227. // If we need to compress text, change encoding to utf8.
  20228. strm.input = strings.string2buf(data);
  20229. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20230. strm.input = new Uint8Array(data);
  20231. } else {
  20232. strm.input = data;
  20233. }
  20234. strm.next_in = 0;
  20235. strm.avail_in = strm.input.length;
  20236. do {
  20237. if (strm.avail_out === 0) {
  20238. strm.output = new utils.Buf8(chunkSize);
  20239. strm.next_out = 0;
  20240. strm.avail_out = chunkSize;
  20241. }
  20242. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  20243. if (status !== Z_STREAM_END && status !== Z_OK) {
  20244. this.onEnd(status);
  20245. this.ended = true;
  20246. return false;
  20247. }
  20248. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  20249. if (this.options.to === 'string') {
  20250. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  20251. } else {
  20252. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20253. }
  20254. }
  20255. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  20256. // Finalize on the last chunk.
  20257. if (_mode === Z_FINISH) {
  20258. status = zlib_deflate.deflateEnd(this.strm);
  20259. this.onEnd(status);
  20260. this.ended = true;
  20261. return status === Z_OK;
  20262. }
  20263. // callback interim results if Z_SYNC_FLUSH.
  20264. if (_mode === Z_SYNC_FLUSH) {
  20265. this.onEnd(Z_OK);
  20266. strm.avail_out = 0;
  20267. return true;
  20268. }
  20269. return true;
  20270. };
  20271. /**
  20272. * Deflate#onData(chunk) -> Void
  20273. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20274. * on js engine support. When string output requested, each chunk
  20275. * will be string.
  20276. *
  20277. * By default, stores data blocks in `chunks[]` property and glue
  20278. * those in `onEnd`. Override this handler, if you need another behaviour.
  20279. **/
  20280. Deflate.prototype.onData = function(chunk) {
  20281. this.chunks.push(chunk);
  20282. };
  20283. /**
  20284. * Deflate#onEnd(status) -> Void
  20285. * - status (Number): deflate status. 0 (Z_OK) on success,
  20286. * other if not.
  20287. *
  20288. * Called once after you tell deflate that the input stream is
  20289. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20290. * or if an error happened. By default - join collected chunks,
  20291. * free memory and fill `results` / `err` properties.
  20292. **/
  20293. Deflate.prototype.onEnd = function(status) {
  20294. // On success - join
  20295. if (status === Z_OK) {
  20296. if (this.options.to === 'string') {
  20297. this.result = this.chunks.join('');
  20298. } else {
  20299. this.result = utils.flattenChunks(this.chunks);
  20300. }
  20301. }
  20302. this.chunks = [];
  20303. this.err = status;
  20304. this.msg = this.strm.msg;
  20305. };
  20306. /**
  20307. * deflate(data[, options]) -> Uint8Array|Array|String
  20308. * - data (Uint8Array|Array|String): input data to compress.
  20309. * - options (Object): zlib deflate options.
  20310. *
  20311. * Compress `data` with deflate alrorythm and `options`.
  20312. *
  20313. * Supported options are:
  20314. *
  20315. * - level
  20316. * - windowBits
  20317. * - memLevel
  20318. * - strategy
  20319. *
  20320. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20321. * for more information on these.
  20322. *
  20323. * Sugar (options):
  20324. *
  20325. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20326. * negative windowBits implicitly.
  20327. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20328. * (each char code [0..255])
  20329. *
  20330. * ##### Example:
  20331. *
  20332. * ```javascript
  20333. * var pako = require('pako')
  20334. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20335. *
  20336. * console.log(pako.deflate(data));
  20337. * ```
  20338. **/
  20339. function deflate(input, options) {
  20340. var deflator = new Deflate(options);
  20341. deflator.push(input, true);
  20342. // That will never happens, if you don't cheat with options :)
  20343. if (deflator.err) { throw deflator.msg; }
  20344. return deflator.result;
  20345. }
  20346. /**
  20347. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20348. * - data (Uint8Array|Array|String): input data to compress.
  20349. * - options (Object): zlib deflate options.
  20350. *
  20351. * The same as [[deflate]], but creates raw data, without wrapper
  20352. * (header and adler32 crc).
  20353. **/
  20354. function deflateRaw(input, options) {
  20355. options = options || {};
  20356. options.raw = true;
  20357. return deflate(input, options);
  20358. }
  20359. /**
  20360. * gzip(data[, options]) -> Uint8Array|Array|String
  20361. * - data (Uint8Array|Array|String): input data to compress.
  20362. * - options (Object): zlib deflate options.
  20363. *
  20364. * The same as [[deflate]], but create gzip wrapper instead of
  20365. * deflate one.
  20366. **/
  20367. function gzip(input, options) {
  20368. options = options || {};
  20369. options.gzip = true;
  20370. return deflate(input, options);
  20371. }
  20372. exports.Deflate = Deflate;
  20373. exports.deflate = deflate;
  20374. exports.deflateRaw = deflateRaw;
  20375. exports.gzip = gzip;
  20376. },{"./utils/common":78,"./utils/strings":79,"./zlib/deflate.js":83,"./zlib/messages":88,"./zlib/zstream":90}],77:[function(require,module,exports){
  20377. 'use strict';
  20378. var zlib_inflate = require('./zlib/inflate.js');
  20379. var utils = require('./utils/common');
  20380. var strings = require('./utils/strings');
  20381. var c = require('./zlib/constants');
  20382. var msg = require('./zlib/messages');
  20383. var zstream = require('./zlib/zstream');
  20384. var gzheader = require('./zlib/gzheader');
  20385. var toString = Object.prototype.toString;
  20386. /**
  20387. * class Inflate
  20388. *
  20389. * Generic JS-style wrapper for zlib calls. If you don't need
  20390. * streaming behaviour - use more simple functions: [[inflate]]
  20391. * and [[inflateRaw]].
  20392. **/
  20393. /* internal
  20394. * inflate.chunks -> Array
  20395. *
  20396. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20397. **/
  20398. /**
  20399. * Inflate.result -> Uint8Array|Array|String
  20400. *
  20401. * Uncompressed result, generated by default [[Inflate#onData]]
  20402. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20403. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20404. * push a chunk with explicit flush (call [[Inflate#push]] with
  20405. * `Z_SYNC_FLUSH` param).
  20406. **/
  20407. /**
  20408. * Inflate.err -> Number
  20409. *
  20410. * Error code after inflate finished. 0 (Z_OK) on success.
  20411. * Should be checked if broken data possible.
  20412. **/
  20413. /**
  20414. * Inflate.msg -> String
  20415. *
  20416. * Error message, if [[Inflate.err]] != 0
  20417. **/
  20418. /**
  20419. * new Inflate(options)
  20420. * - options (Object): zlib inflate options.
  20421. *
  20422. * Creates new inflator instance with specified params. Throws exception
  20423. * on bad params. Supported options:
  20424. *
  20425. * - `windowBits`
  20426. *
  20427. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20428. * for more information on these.
  20429. *
  20430. * Additional options, for internal needs:
  20431. *
  20432. * - `chunkSize` - size of generated data chunks (16K by default)
  20433. * - `raw` (Boolean) - do raw inflate
  20434. * - `to` (String) - if equal to 'string', then result will be converted
  20435. * from utf8 to utf16 (javascript) string. When string output requested,
  20436. * chunk length can differ from `chunkSize`, depending on content.
  20437. *
  20438. * By default, when no options set, autodetect deflate/gzip data format via
  20439. * wrapper header.
  20440. *
  20441. * ##### Example:
  20442. *
  20443. * ```javascript
  20444. * var pako = require('pako')
  20445. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20446. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20447. *
  20448. * var inflate = new pako.Inflate({ level: 3});
  20449. *
  20450. * inflate.push(chunk1, false);
  20451. * inflate.push(chunk2, true); // true -> last chunk
  20452. *
  20453. * if (inflate.err) { throw new Error(inflate.err); }
  20454. *
  20455. * console.log(inflate.result);
  20456. * ```
  20457. **/
  20458. var Inflate = function(options) {
  20459. this.options = utils.assign({
  20460. chunkSize: 16384,
  20461. windowBits: 0,
  20462. to: ''
  20463. }, options || {});
  20464. var opt = this.options;
  20465. // Force window size for `raw` data, if not set directly,
  20466. // because we have no header for autodetect.
  20467. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20468. opt.windowBits = -opt.windowBits;
  20469. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20470. }
  20471. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20472. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20473. !(options && options.windowBits)) {
  20474. opt.windowBits += 32;
  20475. }
  20476. // Gzip header has no info about windows size, we can do autodetect only
  20477. // for deflate. So, if window size not set, force it to max when gzip possible
  20478. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20479. // bit 3 (16) -> gzipped data
  20480. // bit 4 (32) -> autodetect gzip/deflate
  20481. if ((opt.windowBits & 15) === 0) {
  20482. opt.windowBits |= 15;
  20483. }
  20484. }
  20485. this.err = 0; // error code, if happens (0 = Z_OK)
  20486. this.msg = ''; // error message
  20487. this.ended = false; // used to avoid multiple onEnd() calls
  20488. this.chunks = []; // chunks of compressed data
  20489. this.strm = new zstream();
  20490. this.strm.avail_out = 0;
  20491. var status = zlib_inflate.inflateInit2(
  20492. this.strm,
  20493. opt.windowBits
  20494. );
  20495. if (status !== c.Z_OK) {
  20496. throw new Error(msg[status]);
  20497. }
  20498. this.header = new gzheader();
  20499. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20500. };
  20501. /**
  20502. * Inflate#push(data[, mode]) -> Boolean
  20503. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20504. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20505. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20506. *
  20507. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20508. * new output chunks. Returns `true` on success. The last data block must have
  20509. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20510. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20511. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20512. *
  20513. * On fail call [[Inflate#onEnd]] with error code and return false.
  20514. *
  20515. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20516. * format is detected automatically). Also, don't skip last param and always
  20517. * use the same type in your code (boolean or number). That will improve JS speed.
  20518. *
  20519. * For regular `Array`-s make sure all elements are [0..255].
  20520. *
  20521. * ##### Example
  20522. *
  20523. * ```javascript
  20524. * push(chunk, false); // push one of data chunks
  20525. * ...
  20526. * push(chunk, true); // push last chunk
  20527. * ```
  20528. **/
  20529. Inflate.prototype.push = function(data, mode) {
  20530. var strm = this.strm;
  20531. var chunkSize = this.options.chunkSize;
  20532. var status, _mode;
  20533. var next_out_utf8, tail, utf8str;
  20534. if (this.ended) { return false; }
  20535. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20536. // Convert data if needed
  20537. if (typeof data === 'string') {
  20538. // Only binary strings can be decompressed on practice
  20539. strm.input = strings.binstring2buf(data);
  20540. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20541. strm.input = new Uint8Array(data);
  20542. } else {
  20543. strm.input = data;
  20544. }
  20545. strm.next_in = 0;
  20546. strm.avail_in = strm.input.length;
  20547. do {
  20548. if (strm.avail_out === 0) {
  20549. strm.output = new utils.Buf8(chunkSize);
  20550. strm.next_out = 0;
  20551. strm.avail_out = chunkSize;
  20552. }
  20553. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20554. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20555. this.onEnd(status);
  20556. this.ended = true;
  20557. return false;
  20558. }
  20559. if (strm.next_out) {
  20560. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20561. if (this.options.to === 'string') {
  20562. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20563. tail = strm.next_out - next_out_utf8;
  20564. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20565. // move tail
  20566. strm.next_out = tail;
  20567. strm.avail_out = chunkSize - tail;
  20568. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20569. this.onData(utf8str);
  20570. } else {
  20571. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20572. }
  20573. }
  20574. }
  20575. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20576. if (status === c.Z_STREAM_END) {
  20577. _mode = c.Z_FINISH;
  20578. }
  20579. // Finalize on the last chunk.
  20580. if (_mode === c.Z_FINISH) {
  20581. status = zlib_inflate.inflateEnd(this.strm);
  20582. this.onEnd(status);
  20583. this.ended = true;
  20584. return status === c.Z_OK;
  20585. }
  20586. // callback interim results if Z_SYNC_FLUSH.
  20587. if (_mode === c.Z_SYNC_FLUSH) {
  20588. this.onEnd(c.Z_OK);
  20589. strm.avail_out = 0;
  20590. return true;
  20591. }
  20592. return true;
  20593. };
  20594. /**
  20595. * Inflate#onData(chunk) -> Void
  20596. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20597. * on js engine support. When string output requested, each chunk
  20598. * will be string.
  20599. *
  20600. * By default, stores data blocks in `chunks[]` property and glue
  20601. * those in `onEnd`. Override this handler, if you need another behaviour.
  20602. **/
  20603. Inflate.prototype.onData = function(chunk) {
  20604. this.chunks.push(chunk);
  20605. };
  20606. /**
  20607. * Inflate#onEnd(status) -> Void
  20608. * - status (Number): inflate status. 0 (Z_OK) on success,
  20609. * other if not.
  20610. *
  20611. * Called either after you tell inflate that the input stream is
  20612. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20613. * or if an error happened. By default - join collected chunks,
  20614. * free memory and fill `results` / `err` properties.
  20615. **/
  20616. Inflate.prototype.onEnd = function(status) {
  20617. // On success - join
  20618. if (status === c.Z_OK) {
  20619. if (this.options.to === 'string') {
  20620. // Glue & convert here, until we teach pako to send
  20621. // utf8 alligned strings to onData
  20622. this.result = this.chunks.join('');
  20623. } else {
  20624. this.result = utils.flattenChunks(this.chunks);
  20625. }
  20626. }
  20627. this.chunks = [];
  20628. this.err = status;
  20629. this.msg = this.strm.msg;
  20630. };
  20631. /**
  20632. * inflate(data[, options]) -> Uint8Array|Array|String
  20633. * - data (Uint8Array|Array|String): input data to decompress.
  20634. * - options (Object): zlib inflate options.
  20635. *
  20636. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20637. * format via wrapper header by default. That's why we don't provide
  20638. * separate `ungzip` method.
  20639. *
  20640. * Supported options are:
  20641. *
  20642. * - windowBits
  20643. *
  20644. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20645. * for more information.
  20646. *
  20647. * Sugar (options):
  20648. *
  20649. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20650. * negative windowBits implicitly.
  20651. * - `to` (String) - if equal to 'string', then result will be converted
  20652. * from utf8 to utf16 (javascript) string. When string output requested,
  20653. * chunk length can differ from `chunkSize`, depending on content.
  20654. *
  20655. *
  20656. * ##### Example:
  20657. *
  20658. * ```javascript
  20659. * var pako = require('pako')
  20660. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20661. * , output;
  20662. *
  20663. * try {
  20664. * output = pako.inflate(input);
  20665. * } catch (err)
  20666. * console.log(err);
  20667. * }
  20668. * ```
  20669. **/
  20670. function inflate(input, options) {
  20671. var inflator = new Inflate(options);
  20672. inflator.push(input, true);
  20673. // That will never happens, if you don't cheat with options :)
  20674. if (inflator.err) { throw inflator.msg; }
  20675. return inflator.result;
  20676. }
  20677. /**
  20678. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20679. * - data (Uint8Array|Array|String): input data to decompress.
  20680. * - options (Object): zlib inflate options.
  20681. *
  20682. * The same as [[inflate]], but creates raw data, without wrapper
  20683. * (header and adler32 crc).
  20684. **/
  20685. function inflateRaw(input, options) {
  20686. options = options || {};
  20687. options.raw = true;
  20688. return inflate(input, options);
  20689. }
  20690. /**
  20691. * ungzip(data[, options]) -> Uint8Array|Array|String
  20692. * - data (Uint8Array|Array|String): input data to decompress.
  20693. * - options (Object): zlib inflate options.
  20694. *
  20695. * Just shortcut to [[inflate]], because it autodetects format
  20696. * by header.content. Done for convenience.
  20697. **/
  20698. exports.Inflate = Inflate;
  20699. exports.inflate = inflate;
  20700. exports.inflateRaw = inflateRaw;
  20701. exports.ungzip = inflate;
  20702. },{"./utils/common":78,"./utils/strings":79,"./zlib/constants":81,"./zlib/gzheader":84,"./zlib/inflate.js":86,"./zlib/messages":88,"./zlib/zstream":90}],78:[function(require,module,exports){
  20703. 'use strict';
  20704. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20705. (typeof Uint16Array !== 'undefined') &&
  20706. (typeof Int32Array !== 'undefined');
  20707. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20708. var sources = Array.prototype.slice.call(arguments, 1);
  20709. while (sources.length) {
  20710. var source = sources.shift();
  20711. if (!source) { continue; }
  20712. if (typeof source !== 'object') {
  20713. throw new TypeError(source + 'must be non-object');
  20714. }
  20715. for (var p in source) {
  20716. if (source.hasOwnProperty(p)) {
  20717. obj[p] = source[p];
  20718. }
  20719. }
  20720. }
  20721. return obj;
  20722. };
  20723. // reduce buffer size, avoiding mem copy
  20724. exports.shrinkBuf = function (buf, size) {
  20725. if (buf.length === size) { return buf; }
  20726. if (buf.subarray) { return buf.subarray(0, size); }
  20727. buf.length = size;
  20728. return buf;
  20729. };
  20730. var fnTyped = {
  20731. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20732. if (src.subarray && dest.subarray) {
  20733. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20734. return;
  20735. }
  20736. // Fallback to ordinary array
  20737. for (var i=0; i<len; i++) {
  20738. dest[dest_offs + i] = src[src_offs + i];
  20739. }
  20740. },
  20741. // Join array of chunks to single array.
  20742. flattenChunks: function(chunks) {
  20743. var i, l, len, pos, chunk, result;
  20744. // calculate data length
  20745. len = 0;
  20746. for (i=0, l=chunks.length; i<l; i++) {
  20747. len += chunks[i].length;
  20748. }
  20749. // join chunks
  20750. result = new Uint8Array(len);
  20751. pos = 0;
  20752. for (i=0, l=chunks.length; i<l; i++) {
  20753. chunk = chunks[i];
  20754. result.set(chunk, pos);
  20755. pos += chunk.length;
  20756. }
  20757. return result;
  20758. }
  20759. };
  20760. var fnUntyped = {
  20761. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20762. for (var i=0; i<len; i++) {
  20763. dest[dest_offs + i] = src[src_offs + i];
  20764. }
  20765. },
  20766. // Join array of chunks to single array.
  20767. flattenChunks: function(chunks) {
  20768. return [].concat.apply([], chunks);
  20769. }
  20770. };
  20771. // Enable/Disable typed arrays use, for testing
  20772. //
  20773. exports.setTyped = function (on) {
  20774. if (on) {
  20775. exports.Buf8 = Uint8Array;
  20776. exports.Buf16 = Uint16Array;
  20777. exports.Buf32 = Int32Array;
  20778. exports.assign(exports, fnTyped);
  20779. } else {
  20780. exports.Buf8 = Array;
  20781. exports.Buf16 = Array;
  20782. exports.Buf32 = Array;
  20783. exports.assign(exports, fnUntyped);
  20784. }
  20785. };
  20786. exports.setTyped(TYPED_OK);
  20787. },{}],79:[function(require,module,exports){
  20788. // String encode/decode helpers
  20789. 'use strict';
  20790. var utils = require('./common');
  20791. // Quick check if we can use fast array to bin string conversion
  20792. //
  20793. // - apply(Array) can fail on Android 2.2
  20794. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20795. //
  20796. var STR_APPLY_OK = true;
  20797. var STR_APPLY_UIA_OK = true;
  20798. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20799. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20800. // Table with utf8 lengths (calculated by first byte of sequence)
  20801. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20802. // because max possible codepoint is 0x10ffff
  20803. var _utf8len = new utils.Buf8(256);
  20804. for (var q=0; q<256; q++) {
  20805. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20806. }
  20807. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20808. // convert string to array (typed, when possible)
  20809. exports.string2buf = function (str) {
  20810. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20811. // count binary size
  20812. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20813. c = str.charCodeAt(m_pos);
  20814. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20815. c2 = str.charCodeAt(m_pos+1);
  20816. if ((c2 & 0xfc00) === 0xdc00) {
  20817. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20818. m_pos++;
  20819. }
  20820. }
  20821. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20822. }
  20823. // allocate buffer
  20824. buf = new utils.Buf8(buf_len);
  20825. // convert
  20826. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20827. c = str.charCodeAt(m_pos);
  20828. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20829. c2 = str.charCodeAt(m_pos+1);
  20830. if ((c2 & 0xfc00) === 0xdc00) {
  20831. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20832. m_pos++;
  20833. }
  20834. }
  20835. if (c < 0x80) {
  20836. /* one byte */
  20837. buf[i++] = c;
  20838. } else if (c < 0x800) {
  20839. /* two bytes */
  20840. buf[i++] = 0xC0 | (c >>> 6);
  20841. buf[i++] = 0x80 | (c & 0x3f);
  20842. } else if (c < 0x10000) {
  20843. /* three bytes */
  20844. buf[i++] = 0xE0 | (c >>> 12);
  20845. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20846. buf[i++] = 0x80 | (c & 0x3f);
  20847. } else {
  20848. /* four bytes */
  20849. buf[i++] = 0xf0 | (c >>> 18);
  20850. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20851. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20852. buf[i++] = 0x80 | (c & 0x3f);
  20853. }
  20854. }
  20855. return buf;
  20856. };
  20857. // Helper (used in 2 places)
  20858. function buf2binstring(buf, len) {
  20859. // use fallback for big arrays to avoid stack overflow
  20860. if (len < 65537) {
  20861. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20862. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20863. }
  20864. }
  20865. var result = '';
  20866. for (var i=0; i < len; i++) {
  20867. result += String.fromCharCode(buf[i]);
  20868. }
  20869. return result;
  20870. }
  20871. // Convert byte array to binary string
  20872. exports.buf2binstring = function(buf) {
  20873. return buf2binstring(buf, buf.length);
  20874. };
  20875. // Convert binary string (typed, when possible)
  20876. exports.binstring2buf = function(str) {
  20877. var buf = new utils.Buf8(str.length);
  20878. for (var i=0, len=buf.length; i < len; i++) {
  20879. buf[i] = str.charCodeAt(i);
  20880. }
  20881. return buf;
  20882. };
  20883. // convert array to string
  20884. exports.buf2string = function (buf, max) {
  20885. var i, out, c, c_len;
  20886. var len = max || buf.length;
  20887. // Reserve max possible length (2 words per char)
  20888. // NB: by unknown reasons, Array is significantly faster for
  20889. // String.fromCharCode.apply than Uint16Array.
  20890. var utf16buf = new Array(len*2);
  20891. for (out=0, i=0; i<len;) {
  20892. c = buf[i++];
  20893. // quick process ascii
  20894. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20895. c_len = _utf8len[c];
  20896. // skip 5 & 6 byte codes
  20897. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20898. // apply mask on first byte
  20899. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20900. // join the rest
  20901. while (c_len > 1 && i < len) {
  20902. c = (c << 6) | (buf[i++] & 0x3f);
  20903. c_len--;
  20904. }
  20905. // terminated by end of string?
  20906. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20907. if (c < 0x10000) {
  20908. utf16buf[out++] = c;
  20909. } else {
  20910. c -= 0x10000;
  20911. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20912. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20913. }
  20914. }
  20915. return buf2binstring(utf16buf, out);
  20916. };
  20917. // Calculate max possible position in utf8 buffer,
  20918. // that will not break sequence. If that's not possible
  20919. // - (very small limits) return max size as is.
  20920. //
  20921. // buf[] - utf8 bytes array
  20922. // max - length limit (mandatory);
  20923. exports.utf8border = function(buf, max) {
  20924. var pos;
  20925. max = max || buf.length;
  20926. if (max > buf.length) { max = buf.length; }
  20927. // go back from last position, until start of sequence found
  20928. pos = max-1;
  20929. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20930. // Fuckup - very small and broken sequence,
  20931. // return max, because we should return something anyway.
  20932. if (pos < 0) { return max; }
  20933. // If we came to start of buffer - that means vuffer is too small,
  20934. // return max too.
  20935. if (pos === 0) { return max; }
  20936. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20937. };
  20938. },{"./common":78}],80:[function(require,module,exports){
  20939. 'use strict';
  20940. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20941. // It doesn't worth to make additional optimizationa as in original.
  20942. // Small size is preferable.
  20943. function adler32(adler, buf, len, pos) {
  20944. var s1 = (adler & 0xffff) |0,
  20945. s2 = ((adler >>> 16) & 0xffff) |0,
  20946. n = 0;
  20947. while (len !== 0) {
  20948. // Set limit ~ twice less than 5552, to keep
  20949. // s2 in 31-bits, because we force signed ints.
  20950. // in other case %= will fail.
  20951. n = len > 2000 ? 2000 : len;
  20952. len -= n;
  20953. do {
  20954. s1 = (s1 + buf[pos++]) |0;
  20955. s2 = (s2 + s1) |0;
  20956. } while (--n);
  20957. s1 %= 65521;
  20958. s2 %= 65521;
  20959. }
  20960. return (s1 | (s2 << 16)) |0;
  20961. }
  20962. module.exports = adler32;
  20963. },{}],81:[function(require,module,exports){
  20964. module.exports = {
  20965. /* Allowed flush values; see deflate() and inflate() below for details */
  20966. Z_NO_FLUSH: 0,
  20967. Z_PARTIAL_FLUSH: 1,
  20968. Z_SYNC_FLUSH: 2,
  20969. Z_FULL_FLUSH: 3,
  20970. Z_FINISH: 4,
  20971. Z_BLOCK: 5,
  20972. Z_TREES: 6,
  20973. /* Return codes for the compression/decompression functions. Negative values
  20974. * are errors, positive values are used for special but normal events.
  20975. */
  20976. Z_OK: 0,
  20977. Z_STREAM_END: 1,
  20978. Z_NEED_DICT: 2,
  20979. Z_ERRNO: -1,
  20980. Z_STREAM_ERROR: -2,
  20981. Z_DATA_ERROR: -3,
  20982. //Z_MEM_ERROR: -4,
  20983. Z_BUF_ERROR: -5,
  20984. //Z_VERSION_ERROR: -6,
  20985. /* compression levels */
  20986. Z_NO_COMPRESSION: 0,
  20987. Z_BEST_SPEED: 1,
  20988. Z_BEST_COMPRESSION: 9,
  20989. Z_DEFAULT_COMPRESSION: -1,
  20990. Z_FILTERED: 1,
  20991. Z_HUFFMAN_ONLY: 2,
  20992. Z_RLE: 3,
  20993. Z_FIXED: 4,
  20994. Z_DEFAULT_STRATEGY: 0,
  20995. /* Possible values of the data_type field (though see inflate()) */
  20996. Z_BINARY: 0,
  20997. Z_TEXT: 1,
  20998. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20999. Z_UNKNOWN: 2,
  21000. /* The deflate compression method */
  21001. Z_DEFLATED: 8
  21002. //Z_NULL: null // Use -1 or null inline, depending on var type
  21003. };
  21004. },{}],82:[function(require,module,exports){
  21005. 'use strict';
  21006. // Note: we can't get significant speed boost here.
  21007. // So write code to minimize size - no pregenerated tables
  21008. // and array tools dependencies.
  21009. // Use ordinary array, since untyped makes no boost here
  21010. function makeTable() {
  21011. var c, table = [];
  21012. for (var n =0; n < 256; n++) {
  21013. c = n;
  21014. for (var k =0; k < 8; k++) {
  21015. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  21016. }
  21017. table[n] = c;
  21018. }
  21019. return table;
  21020. }
  21021. // Create table on load. Just 255 signed longs. Not a problem.
  21022. var crcTable = makeTable();
  21023. function crc32(crc, buf, len, pos) {
  21024. var t = crcTable,
  21025. end = pos + len;
  21026. crc = crc ^ (-1);
  21027. for (var i = pos; i < end; i++) {
  21028. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  21029. }
  21030. return (crc ^ (-1)); // >>> 0;
  21031. }
  21032. module.exports = crc32;
  21033. },{}],83:[function(require,module,exports){
  21034. 'use strict';
  21035. var utils = require('../utils/common');
  21036. var trees = require('./trees');
  21037. var adler32 = require('./adler32');
  21038. var crc32 = require('./crc32');
  21039. var msg = require('./messages');
  21040. /* Public constants ==========================================================*/
  21041. /* ===========================================================================*/
  21042. /* Allowed flush values; see deflate() and inflate() below for details */
  21043. var Z_NO_FLUSH = 0;
  21044. var Z_PARTIAL_FLUSH = 1;
  21045. //var Z_SYNC_FLUSH = 2;
  21046. var Z_FULL_FLUSH = 3;
  21047. var Z_FINISH = 4;
  21048. var Z_BLOCK = 5;
  21049. //var Z_TREES = 6;
  21050. /* Return codes for the compression/decompression functions. Negative values
  21051. * are errors, positive values are used for special but normal events.
  21052. */
  21053. var Z_OK = 0;
  21054. var Z_STREAM_END = 1;
  21055. //var Z_NEED_DICT = 2;
  21056. //var Z_ERRNO = -1;
  21057. var Z_STREAM_ERROR = -2;
  21058. var Z_DATA_ERROR = -3;
  21059. //var Z_MEM_ERROR = -4;
  21060. var Z_BUF_ERROR = -5;
  21061. //var Z_VERSION_ERROR = -6;
  21062. /* compression levels */
  21063. //var Z_NO_COMPRESSION = 0;
  21064. //var Z_BEST_SPEED = 1;
  21065. //var Z_BEST_COMPRESSION = 9;
  21066. var Z_DEFAULT_COMPRESSION = -1;
  21067. var Z_FILTERED = 1;
  21068. var Z_HUFFMAN_ONLY = 2;
  21069. var Z_RLE = 3;
  21070. var Z_FIXED = 4;
  21071. var Z_DEFAULT_STRATEGY = 0;
  21072. /* Possible values of the data_type field (though see inflate()) */
  21073. //var Z_BINARY = 0;
  21074. //var Z_TEXT = 1;
  21075. //var Z_ASCII = 1; // = Z_TEXT
  21076. var Z_UNKNOWN = 2;
  21077. /* The deflate compression method */
  21078. var Z_DEFLATED = 8;
  21079. /*============================================================================*/
  21080. var MAX_MEM_LEVEL = 9;
  21081. /* Maximum value for memLevel in deflateInit2 */
  21082. var MAX_WBITS = 15;
  21083. /* 32K LZ77 window */
  21084. var DEF_MEM_LEVEL = 8;
  21085. var LENGTH_CODES = 29;
  21086. /* number of length codes, not counting the special END_BLOCK code */
  21087. var LITERALS = 256;
  21088. /* number of literal bytes 0..255 */
  21089. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21090. /* number of Literal or Length codes, including the END_BLOCK code */
  21091. var D_CODES = 30;
  21092. /* number of distance codes */
  21093. var BL_CODES = 19;
  21094. /* number of codes used to transfer the bit lengths */
  21095. var HEAP_SIZE = 2*L_CODES + 1;
  21096. /* maximum heap size */
  21097. var MAX_BITS = 15;
  21098. /* All codes must not exceed MAX_BITS bits */
  21099. var MIN_MATCH = 3;
  21100. var MAX_MATCH = 258;
  21101. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  21102. var PRESET_DICT = 0x20;
  21103. var INIT_STATE = 42;
  21104. var EXTRA_STATE = 69;
  21105. var NAME_STATE = 73;
  21106. var COMMENT_STATE = 91;
  21107. var HCRC_STATE = 103;
  21108. var BUSY_STATE = 113;
  21109. var FINISH_STATE = 666;
  21110. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  21111. var BS_BLOCK_DONE = 2; /* block flush performed */
  21112. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  21113. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  21114. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  21115. function err(strm, errorCode) {
  21116. strm.msg = msg[errorCode];
  21117. return errorCode;
  21118. }
  21119. function rank(f) {
  21120. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  21121. }
  21122. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21123. /* =========================================================================
  21124. * Flush as much pending output as possible. All deflate() output goes
  21125. * through this function so some applications may wish to modify it
  21126. * to avoid allocating a large strm->output buffer and copying into it.
  21127. * (See also read_buf()).
  21128. */
  21129. function flush_pending(strm) {
  21130. var s = strm.state;
  21131. //_tr_flush_bits(s);
  21132. var len = s.pending;
  21133. if (len > strm.avail_out) {
  21134. len = strm.avail_out;
  21135. }
  21136. if (len === 0) { return; }
  21137. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  21138. strm.next_out += len;
  21139. s.pending_out += len;
  21140. strm.total_out += len;
  21141. strm.avail_out -= len;
  21142. s.pending -= len;
  21143. if (s.pending === 0) {
  21144. s.pending_out = 0;
  21145. }
  21146. }
  21147. function flush_block_only (s, last) {
  21148. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  21149. s.block_start = s.strstart;
  21150. flush_pending(s.strm);
  21151. }
  21152. function put_byte(s, b) {
  21153. s.pending_buf[s.pending++] = b;
  21154. }
  21155. /* =========================================================================
  21156. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  21157. * IN assertion: the stream state is correct and there is enough room in
  21158. * pending_buf.
  21159. */
  21160. function putShortMSB(s, b) {
  21161. // put_byte(s, (Byte)(b >> 8));
  21162. // put_byte(s, (Byte)(b & 0xff));
  21163. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  21164. s.pending_buf[s.pending++] = b & 0xff;
  21165. }
  21166. /* ===========================================================================
  21167. * Read a new buffer from the current input stream, update the adler32
  21168. * and total number of bytes read. All deflate() input goes through
  21169. * this function so some applications may wish to modify it to avoid
  21170. * allocating a large strm->input buffer and copying from it.
  21171. * (See also flush_pending()).
  21172. */
  21173. function read_buf(strm, buf, start, size) {
  21174. var len = strm.avail_in;
  21175. if (len > size) { len = size; }
  21176. if (len === 0) { return 0; }
  21177. strm.avail_in -= len;
  21178. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  21179. if (strm.state.wrap === 1) {
  21180. strm.adler = adler32(strm.adler, buf, len, start);
  21181. }
  21182. else if (strm.state.wrap === 2) {
  21183. strm.adler = crc32(strm.adler, buf, len, start);
  21184. }
  21185. strm.next_in += len;
  21186. strm.total_in += len;
  21187. return len;
  21188. }
  21189. /* ===========================================================================
  21190. * Set match_start to the longest match starting at the given string and
  21191. * return its length. Matches shorter or equal to prev_length are discarded,
  21192. * in which case the result is equal to prev_length and match_start is
  21193. * garbage.
  21194. * IN assertions: cur_match is the head of the hash chain for the current
  21195. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  21196. * OUT assertion: the match length is not greater than s->lookahead.
  21197. */
  21198. function longest_match(s, cur_match) {
  21199. var chain_length = s.max_chain_length; /* max hash chain length */
  21200. var scan = s.strstart; /* current string */
  21201. var match; /* matched string */
  21202. var len; /* length of current match */
  21203. var best_len = s.prev_length; /* best match length so far */
  21204. var nice_match = s.nice_match; /* stop if match long enough */
  21205. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  21206. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  21207. var _win = s.window; // shortcut
  21208. var wmask = s.w_mask;
  21209. var prev = s.prev;
  21210. /* Stop when cur_match becomes <= limit. To simplify the code,
  21211. * we prevent matches with the string of window index 0.
  21212. */
  21213. var strend = s.strstart + MAX_MATCH;
  21214. var scan_end1 = _win[scan + best_len - 1];
  21215. var scan_end = _win[scan + best_len];
  21216. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  21217. * It is easy to get rid of this optimization if necessary.
  21218. */
  21219. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  21220. /* Do not waste too much time if we already have a good match: */
  21221. if (s.prev_length >= s.good_match) {
  21222. chain_length >>= 2;
  21223. }
  21224. /* Do not look for matches beyond the end of the input. This is necessary
  21225. * to make deflate deterministic.
  21226. */
  21227. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  21228. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  21229. do {
  21230. // Assert(cur_match < s->strstart, "no future");
  21231. match = cur_match;
  21232. /* Skip to next match if the match length cannot increase
  21233. * or if the match length is less than 2. Note that the checks below
  21234. * for insufficient lookahead only occur occasionally for performance
  21235. * reasons. Therefore uninitialized memory will be accessed, and
  21236. * conditional jumps will be made that depend on those values.
  21237. * However the length of the match is limited to the lookahead, so
  21238. * the output of deflate is not affected by the uninitialized values.
  21239. */
  21240. if (_win[match + best_len] !== scan_end ||
  21241. _win[match + best_len - 1] !== scan_end1 ||
  21242. _win[match] !== _win[scan] ||
  21243. _win[++match] !== _win[scan + 1]) {
  21244. continue;
  21245. }
  21246. /* The check at best_len-1 can be removed because it will be made
  21247. * again later. (This heuristic is not always a win.)
  21248. * It is not necessary to compare scan[2] and match[2] since they
  21249. * are always equal when the other bytes match, given that
  21250. * the hash keys are equal and that HASH_BITS >= 8.
  21251. */
  21252. scan += 2;
  21253. match++;
  21254. // Assert(*scan == *match, "match[2]?");
  21255. /* We check for insufficient lookahead only every 8th comparison;
  21256. * the 256th check will be made at strstart+258.
  21257. */
  21258. do {
  21259. /*jshint noempty:false*/
  21260. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21261. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21262. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21263. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21264. scan < strend);
  21265. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  21266. len = MAX_MATCH - (strend - scan);
  21267. scan = strend - MAX_MATCH;
  21268. if (len > best_len) {
  21269. s.match_start = cur_match;
  21270. best_len = len;
  21271. if (len >= nice_match) {
  21272. break;
  21273. }
  21274. scan_end1 = _win[scan + best_len - 1];
  21275. scan_end = _win[scan + best_len];
  21276. }
  21277. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  21278. if (best_len <= s.lookahead) {
  21279. return best_len;
  21280. }
  21281. return s.lookahead;
  21282. }
  21283. /* ===========================================================================
  21284. * Fill the window when the lookahead becomes insufficient.
  21285. * Updates strstart and lookahead.
  21286. *
  21287. * IN assertion: lookahead < MIN_LOOKAHEAD
  21288. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21289. * At least one byte has been read, or avail_in == 0; reads are
  21290. * performed for at least two bytes (required for the zip translate_eol
  21291. * option -- not supported here).
  21292. */
  21293. function fill_window(s) {
  21294. var _w_size = s.w_size;
  21295. var p, n, m, more, str;
  21296. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21297. do {
  21298. more = s.window_size - s.lookahead - s.strstart;
  21299. // JS ints have 32 bit, block below not needed
  21300. /* Deal with !@#$% 64K limit: */
  21301. //if (sizeof(int) <= 2) {
  21302. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21303. // more = wsize;
  21304. //
  21305. // } else if (more == (unsigned)(-1)) {
  21306. // /* Very unlikely, but possible on 16 bit machine if
  21307. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21308. // */
  21309. // more--;
  21310. // }
  21311. //}
  21312. /* If the window is almost full and there is insufficient lookahead,
  21313. * move the upper half to the lower one to make room in the upper half.
  21314. */
  21315. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21316. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21317. s.match_start -= _w_size;
  21318. s.strstart -= _w_size;
  21319. /* we now have strstart >= MAX_DIST */
  21320. s.block_start -= _w_size;
  21321. /* Slide the hash table (could be avoided with 32 bit values
  21322. at the expense of memory usage). We slide even when level == 0
  21323. to keep the hash table consistent if we switch back to level > 0
  21324. later. (Using level 0 permanently is not an optimal usage of
  21325. zlib, so we don't care about this pathological case.)
  21326. */
  21327. n = s.hash_size;
  21328. p = n;
  21329. do {
  21330. m = s.head[--p];
  21331. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21332. } while (--n);
  21333. n = _w_size;
  21334. p = n;
  21335. do {
  21336. m = s.prev[--p];
  21337. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21338. /* If n is not on any hash chain, prev[n] is garbage but
  21339. * its value will never be used.
  21340. */
  21341. } while (--n);
  21342. more += _w_size;
  21343. }
  21344. if (s.strm.avail_in === 0) {
  21345. break;
  21346. }
  21347. /* If there was no sliding:
  21348. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21349. * more == window_size - lookahead - strstart
  21350. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21351. * => more >= window_size - 2*WSIZE + 2
  21352. * In the BIG_MEM or MMAP case (not yet supported),
  21353. * window_size == input_size + MIN_LOOKAHEAD &&
  21354. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21355. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21356. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21357. */
  21358. //Assert(more >= 2, "more < 2");
  21359. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21360. s.lookahead += n;
  21361. /* Initialize the hash value now that we have some input: */
  21362. if (s.lookahead + s.insert >= MIN_MATCH) {
  21363. str = s.strstart - s.insert;
  21364. s.ins_h = s.window[str];
  21365. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21366. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21367. //#if MIN_MATCH != 3
  21368. // Call update_hash() MIN_MATCH-3 more times
  21369. //#endif
  21370. while (s.insert) {
  21371. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21372. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21373. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21374. s.head[s.ins_h] = str;
  21375. str++;
  21376. s.insert--;
  21377. if (s.lookahead + s.insert < MIN_MATCH) {
  21378. break;
  21379. }
  21380. }
  21381. }
  21382. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21383. * but this is not important since only literal bytes will be emitted.
  21384. */
  21385. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21386. /* If the WIN_INIT bytes after the end of the current data have never been
  21387. * written, then zero those bytes in order to avoid memory check reports of
  21388. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21389. * the longest match routines. Update the high water mark for the next
  21390. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21391. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21392. */
  21393. // if (s.high_water < s.window_size) {
  21394. // var curr = s.strstart + s.lookahead;
  21395. // var init = 0;
  21396. //
  21397. // if (s.high_water < curr) {
  21398. // /* Previous high water mark below current data -- zero WIN_INIT
  21399. // * bytes or up to end of window, whichever is less.
  21400. // */
  21401. // init = s.window_size - curr;
  21402. // if (init > WIN_INIT)
  21403. // init = WIN_INIT;
  21404. // zmemzero(s->window + curr, (unsigned)init);
  21405. // s->high_water = curr + init;
  21406. // }
  21407. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21408. // /* High water mark at or above current data, but below current data
  21409. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21410. // * to end of window, whichever is less.
  21411. // */
  21412. // init = (ulg)curr + WIN_INIT - s->high_water;
  21413. // if (init > s->window_size - s->high_water)
  21414. // init = s->window_size - s->high_water;
  21415. // zmemzero(s->window + s->high_water, (unsigned)init);
  21416. // s->high_water += init;
  21417. // }
  21418. // }
  21419. //
  21420. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21421. // "not enough room for search");
  21422. }
  21423. /* ===========================================================================
  21424. * Copy without compression as much as possible from the input stream, return
  21425. * the current block state.
  21426. * This function does not insert new strings in the dictionary since
  21427. * uncompressible data is probably not useful. This function is used
  21428. * only for the level=0 compression option.
  21429. * NOTE: this function should be optimized to avoid extra copying from
  21430. * window to pending_buf.
  21431. */
  21432. function deflate_stored(s, flush) {
  21433. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21434. * to pending_buf_size, and each stored block has a 5 byte header:
  21435. */
  21436. var max_block_size = 0xffff;
  21437. if (max_block_size > s.pending_buf_size - 5) {
  21438. max_block_size = s.pending_buf_size - 5;
  21439. }
  21440. /* Copy as much as possible from input to output: */
  21441. for (;;) {
  21442. /* Fill the window as much as possible: */
  21443. if (s.lookahead <= 1) {
  21444. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21445. // s->block_start >= (long)s->w_size, "slide too late");
  21446. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21447. // s.block_start >= s.w_size)) {
  21448. // throw new Error("slide too late");
  21449. // }
  21450. fill_window(s);
  21451. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21452. return BS_NEED_MORE;
  21453. }
  21454. if (s.lookahead === 0) {
  21455. break;
  21456. }
  21457. /* flush the current block */
  21458. }
  21459. //Assert(s->block_start >= 0L, "block gone");
  21460. // if (s.block_start < 0) throw new Error("block gone");
  21461. s.strstart += s.lookahead;
  21462. s.lookahead = 0;
  21463. /* Emit a stored block if pending_buf will be full: */
  21464. var max_start = s.block_start + max_block_size;
  21465. if (s.strstart === 0 || s.strstart >= max_start) {
  21466. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21467. s.lookahead = s.strstart - max_start;
  21468. s.strstart = max_start;
  21469. /*** FLUSH_BLOCK(s, 0); ***/
  21470. flush_block_only(s, false);
  21471. if (s.strm.avail_out === 0) {
  21472. return BS_NEED_MORE;
  21473. }
  21474. /***/
  21475. }
  21476. /* Flush if we may have to slide, otherwise block_start may become
  21477. * negative and the data will be gone:
  21478. */
  21479. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21480. /*** FLUSH_BLOCK(s, 0); ***/
  21481. flush_block_only(s, false);
  21482. if (s.strm.avail_out === 0) {
  21483. return BS_NEED_MORE;
  21484. }
  21485. /***/
  21486. }
  21487. }
  21488. s.insert = 0;
  21489. if (flush === Z_FINISH) {
  21490. /*** FLUSH_BLOCK(s, 1); ***/
  21491. flush_block_only(s, true);
  21492. if (s.strm.avail_out === 0) {
  21493. return BS_FINISH_STARTED;
  21494. }
  21495. /***/
  21496. return BS_FINISH_DONE;
  21497. }
  21498. if (s.strstart > s.block_start) {
  21499. /*** FLUSH_BLOCK(s, 0); ***/
  21500. flush_block_only(s, false);
  21501. if (s.strm.avail_out === 0) {
  21502. return BS_NEED_MORE;
  21503. }
  21504. /***/
  21505. }
  21506. return BS_NEED_MORE;
  21507. }
  21508. /* ===========================================================================
  21509. * Compress as much as possible from the input stream, return the current
  21510. * block state.
  21511. * This function does not perform lazy evaluation of matches and inserts
  21512. * new strings in the dictionary only for unmatched strings or for short
  21513. * matches. It is used only for the fast compression options.
  21514. */
  21515. function deflate_fast(s, flush) {
  21516. var hash_head; /* head of the hash chain */
  21517. var bflush; /* set if current block must be flushed */
  21518. for (;;) {
  21519. /* Make sure that we always have enough lookahead, except
  21520. * at the end of the input file. We need MAX_MATCH bytes
  21521. * for the next match, plus MIN_MATCH bytes to insert the
  21522. * string following the next match.
  21523. */
  21524. if (s.lookahead < MIN_LOOKAHEAD) {
  21525. fill_window(s);
  21526. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21527. return BS_NEED_MORE;
  21528. }
  21529. if (s.lookahead === 0) {
  21530. break; /* flush the current block */
  21531. }
  21532. }
  21533. /* Insert the string window[strstart .. strstart+2] in the
  21534. * dictionary, and set hash_head to the head of the hash chain:
  21535. */
  21536. hash_head = 0/*NIL*/;
  21537. if (s.lookahead >= MIN_MATCH) {
  21538. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21539. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21540. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21541. s.head[s.ins_h] = s.strstart;
  21542. /***/
  21543. }
  21544. /* Find the longest match, discarding those <= prev_length.
  21545. * At this point we have always match_length < MIN_MATCH
  21546. */
  21547. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21548. /* To simplify the code, we prevent matches with the string
  21549. * of window index 0 (in particular we have to avoid a match
  21550. * of the string with itself at the start of the input file).
  21551. */
  21552. s.match_length = longest_match(s, hash_head);
  21553. /* longest_match() sets match_start */
  21554. }
  21555. if (s.match_length >= MIN_MATCH) {
  21556. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21557. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21558. s.match_length - MIN_MATCH, bflush); ***/
  21559. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21560. s.lookahead -= s.match_length;
  21561. /* Insert new strings in the hash table only if the match length
  21562. * is not too large. This saves time but degrades compression.
  21563. */
  21564. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21565. s.match_length--; /* string at strstart already in table */
  21566. do {
  21567. s.strstart++;
  21568. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21569. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21570. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21571. s.head[s.ins_h] = s.strstart;
  21572. /***/
  21573. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21574. * always MIN_MATCH bytes ahead.
  21575. */
  21576. } while (--s.match_length !== 0);
  21577. s.strstart++;
  21578. } else
  21579. {
  21580. s.strstart += s.match_length;
  21581. s.match_length = 0;
  21582. s.ins_h = s.window[s.strstart];
  21583. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21584. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21585. //#if MIN_MATCH != 3
  21586. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21587. //#endif
  21588. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21589. * matter since it will be recomputed at next deflate call.
  21590. */
  21591. }
  21592. } else {
  21593. /* No match, output a literal byte */
  21594. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21595. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21596. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21597. s.lookahead--;
  21598. s.strstart++;
  21599. }
  21600. if (bflush) {
  21601. /*** FLUSH_BLOCK(s, 0); ***/
  21602. flush_block_only(s, false);
  21603. if (s.strm.avail_out === 0) {
  21604. return BS_NEED_MORE;
  21605. }
  21606. /***/
  21607. }
  21608. }
  21609. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21610. if (flush === Z_FINISH) {
  21611. /*** FLUSH_BLOCK(s, 1); ***/
  21612. flush_block_only(s, true);
  21613. if (s.strm.avail_out === 0) {
  21614. return BS_FINISH_STARTED;
  21615. }
  21616. /***/
  21617. return BS_FINISH_DONE;
  21618. }
  21619. if (s.last_lit) {
  21620. /*** FLUSH_BLOCK(s, 0); ***/
  21621. flush_block_only(s, false);
  21622. if (s.strm.avail_out === 0) {
  21623. return BS_NEED_MORE;
  21624. }
  21625. /***/
  21626. }
  21627. return BS_BLOCK_DONE;
  21628. }
  21629. /* ===========================================================================
  21630. * Same as above, but achieves better compression. We use a lazy
  21631. * evaluation for matches: a match is finally adopted only if there is
  21632. * no better match at the next window position.
  21633. */
  21634. function deflate_slow(s, flush) {
  21635. var hash_head; /* head of hash chain */
  21636. var bflush; /* set if current block must be flushed */
  21637. var max_insert;
  21638. /* Process the input block. */
  21639. for (;;) {
  21640. /* Make sure that we always have enough lookahead, except
  21641. * at the end of the input file. We need MAX_MATCH bytes
  21642. * for the next match, plus MIN_MATCH bytes to insert the
  21643. * string following the next match.
  21644. */
  21645. if (s.lookahead < MIN_LOOKAHEAD) {
  21646. fill_window(s);
  21647. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21648. return BS_NEED_MORE;
  21649. }
  21650. if (s.lookahead === 0) { break; } /* flush the current block */
  21651. }
  21652. /* Insert the string window[strstart .. strstart+2] in the
  21653. * dictionary, and set hash_head to the head of the hash chain:
  21654. */
  21655. hash_head = 0/*NIL*/;
  21656. if (s.lookahead >= MIN_MATCH) {
  21657. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21658. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21659. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21660. s.head[s.ins_h] = s.strstart;
  21661. /***/
  21662. }
  21663. /* Find the longest match, discarding those <= prev_length.
  21664. */
  21665. s.prev_length = s.match_length;
  21666. s.prev_match = s.match_start;
  21667. s.match_length = MIN_MATCH-1;
  21668. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21669. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21670. /* To simplify the code, we prevent matches with the string
  21671. * of window index 0 (in particular we have to avoid a match
  21672. * of the string with itself at the start of the input file).
  21673. */
  21674. s.match_length = longest_match(s, hash_head);
  21675. /* longest_match() sets match_start */
  21676. if (s.match_length <= 5 &&
  21677. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21678. /* If prev_match is also MIN_MATCH, match_start is garbage
  21679. * but we will ignore the current match anyway.
  21680. */
  21681. s.match_length = MIN_MATCH-1;
  21682. }
  21683. }
  21684. /* If there was a match at the previous step and the current
  21685. * match is not better, output the previous match:
  21686. */
  21687. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21688. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21689. /* Do not insert strings in hash table beyond this. */
  21690. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21691. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21692. s.prev_length - MIN_MATCH, bflush);***/
  21693. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21694. /* Insert in hash table all strings up to the end of the match.
  21695. * strstart-1 and strstart are already inserted. If there is not
  21696. * enough lookahead, the last two strings are not inserted in
  21697. * the hash table.
  21698. */
  21699. s.lookahead -= s.prev_length-1;
  21700. s.prev_length -= 2;
  21701. do {
  21702. if (++s.strstart <= max_insert) {
  21703. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21704. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21705. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21706. s.head[s.ins_h] = s.strstart;
  21707. /***/
  21708. }
  21709. } while (--s.prev_length !== 0);
  21710. s.match_available = 0;
  21711. s.match_length = MIN_MATCH-1;
  21712. s.strstart++;
  21713. if (bflush) {
  21714. /*** FLUSH_BLOCK(s, 0); ***/
  21715. flush_block_only(s, false);
  21716. if (s.strm.avail_out === 0) {
  21717. return BS_NEED_MORE;
  21718. }
  21719. /***/
  21720. }
  21721. } else if (s.match_available) {
  21722. /* If there was no match at the previous position, output a
  21723. * single literal. If there was a match but the current match
  21724. * is longer, truncate the previous match to a single literal.
  21725. */
  21726. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21727. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21728. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21729. if (bflush) {
  21730. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21731. flush_block_only(s, false);
  21732. /***/
  21733. }
  21734. s.strstart++;
  21735. s.lookahead--;
  21736. if (s.strm.avail_out === 0) {
  21737. return BS_NEED_MORE;
  21738. }
  21739. } else {
  21740. /* There is no previous match to compare with, wait for
  21741. * the next step to decide.
  21742. */
  21743. s.match_available = 1;
  21744. s.strstart++;
  21745. s.lookahead--;
  21746. }
  21747. }
  21748. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21749. if (s.match_available) {
  21750. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21751. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21752. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21753. s.match_available = 0;
  21754. }
  21755. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21756. if (flush === Z_FINISH) {
  21757. /*** FLUSH_BLOCK(s, 1); ***/
  21758. flush_block_only(s, true);
  21759. if (s.strm.avail_out === 0) {
  21760. return BS_FINISH_STARTED;
  21761. }
  21762. /***/
  21763. return BS_FINISH_DONE;
  21764. }
  21765. if (s.last_lit) {
  21766. /*** FLUSH_BLOCK(s, 0); ***/
  21767. flush_block_only(s, false);
  21768. if (s.strm.avail_out === 0) {
  21769. return BS_NEED_MORE;
  21770. }
  21771. /***/
  21772. }
  21773. return BS_BLOCK_DONE;
  21774. }
  21775. /* ===========================================================================
  21776. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21777. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21778. * deflate switches away from Z_RLE.)
  21779. */
  21780. function deflate_rle(s, flush) {
  21781. var bflush; /* set if current block must be flushed */
  21782. var prev; /* byte at distance one to match */
  21783. var scan, strend; /* scan goes up to strend for length of run */
  21784. var _win = s.window;
  21785. for (;;) {
  21786. /* Make sure that we always have enough lookahead, except
  21787. * at the end of the input file. We need MAX_MATCH bytes
  21788. * for the longest run, plus one for the unrolled loop.
  21789. */
  21790. if (s.lookahead <= MAX_MATCH) {
  21791. fill_window(s);
  21792. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21793. return BS_NEED_MORE;
  21794. }
  21795. if (s.lookahead === 0) { break; } /* flush the current block */
  21796. }
  21797. /* See how many times the previous byte repeats */
  21798. s.match_length = 0;
  21799. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21800. scan = s.strstart - 1;
  21801. prev = _win[scan];
  21802. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21803. strend = s.strstart + MAX_MATCH;
  21804. do {
  21805. /*jshint noempty:false*/
  21806. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21807. prev === _win[++scan] && prev === _win[++scan] &&
  21808. prev === _win[++scan] && prev === _win[++scan] &&
  21809. prev === _win[++scan] && prev === _win[++scan] &&
  21810. scan < strend);
  21811. s.match_length = MAX_MATCH - (strend - scan);
  21812. if (s.match_length > s.lookahead) {
  21813. s.match_length = s.lookahead;
  21814. }
  21815. }
  21816. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21817. }
  21818. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21819. if (s.match_length >= MIN_MATCH) {
  21820. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21821. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21822. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21823. s.lookahead -= s.match_length;
  21824. s.strstart += s.match_length;
  21825. s.match_length = 0;
  21826. } else {
  21827. /* No match, output a literal byte */
  21828. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21829. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21830. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21831. s.lookahead--;
  21832. s.strstart++;
  21833. }
  21834. if (bflush) {
  21835. /*** FLUSH_BLOCK(s, 0); ***/
  21836. flush_block_only(s, false);
  21837. if (s.strm.avail_out === 0) {
  21838. return BS_NEED_MORE;
  21839. }
  21840. /***/
  21841. }
  21842. }
  21843. s.insert = 0;
  21844. if (flush === Z_FINISH) {
  21845. /*** FLUSH_BLOCK(s, 1); ***/
  21846. flush_block_only(s, true);
  21847. if (s.strm.avail_out === 0) {
  21848. return BS_FINISH_STARTED;
  21849. }
  21850. /***/
  21851. return BS_FINISH_DONE;
  21852. }
  21853. if (s.last_lit) {
  21854. /*** FLUSH_BLOCK(s, 0); ***/
  21855. flush_block_only(s, false);
  21856. if (s.strm.avail_out === 0) {
  21857. return BS_NEED_MORE;
  21858. }
  21859. /***/
  21860. }
  21861. return BS_BLOCK_DONE;
  21862. }
  21863. /* ===========================================================================
  21864. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21865. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21866. */
  21867. function deflate_huff(s, flush) {
  21868. var bflush; /* set if current block must be flushed */
  21869. for (;;) {
  21870. /* Make sure that we have a literal to write. */
  21871. if (s.lookahead === 0) {
  21872. fill_window(s);
  21873. if (s.lookahead === 0) {
  21874. if (flush === Z_NO_FLUSH) {
  21875. return BS_NEED_MORE;
  21876. }
  21877. break; /* flush the current block */
  21878. }
  21879. }
  21880. /* Output a literal byte */
  21881. s.match_length = 0;
  21882. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21883. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21884. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21885. s.lookahead--;
  21886. s.strstart++;
  21887. if (bflush) {
  21888. /*** FLUSH_BLOCK(s, 0); ***/
  21889. flush_block_only(s, false);
  21890. if (s.strm.avail_out === 0) {
  21891. return BS_NEED_MORE;
  21892. }
  21893. /***/
  21894. }
  21895. }
  21896. s.insert = 0;
  21897. if (flush === Z_FINISH) {
  21898. /*** FLUSH_BLOCK(s, 1); ***/
  21899. flush_block_only(s, true);
  21900. if (s.strm.avail_out === 0) {
  21901. return BS_FINISH_STARTED;
  21902. }
  21903. /***/
  21904. return BS_FINISH_DONE;
  21905. }
  21906. if (s.last_lit) {
  21907. /*** FLUSH_BLOCK(s, 0); ***/
  21908. flush_block_only(s, false);
  21909. if (s.strm.avail_out === 0) {
  21910. return BS_NEED_MORE;
  21911. }
  21912. /***/
  21913. }
  21914. return BS_BLOCK_DONE;
  21915. }
  21916. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21917. * the desired pack level (0..9). The values given below have been tuned to
  21918. * exclude worst case performance for pathological files. Better values may be
  21919. * found for specific files.
  21920. */
  21921. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21922. this.good_length = good_length;
  21923. this.max_lazy = max_lazy;
  21924. this.nice_length = nice_length;
  21925. this.max_chain = max_chain;
  21926. this.func = func;
  21927. };
  21928. var configuration_table;
  21929. configuration_table = [
  21930. /* good lazy nice chain */
  21931. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21932. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21933. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21934. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21935. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21936. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21937. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21938. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21939. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21940. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21941. ];
  21942. /* ===========================================================================
  21943. * Initialize the "longest match" routines for a new zlib stream
  21944. */
  21945. function lm_init(s) {
  21946. s.window_size = 2 * s.w_size;
  21947. /*** CLEAR_HASH(s); ***/
  21948. zero(s.head); // Fill with NIL (= 0);
  21949. /* Set the default configuration parameters:
  21950. */
  21951. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21952. s.good_match = configuration_table[s.level].good_length;
  21953. s.nice_match = configuration_table[s.level].nice_length;
  21954. s.max_chain_length = configuration_table[s.level].max_chain;
  21955. s.strstart = 0;
  21956. s.block_start = 0;
  21957. s.lookahead = 0;
  21958. s.insert = 0;
  21959. s.match_length = s.prev_length = MIN_MATCH - 1;
  21960. s.match_available = 0;
  21961. s.ins_h = 0;
  21962. }
  21963. function DeflateState() {
  21964. this.strm = null; /* pointer back to this zlib stream */
  21965. this.status = 0; /* as the name implies */
  21966. this.pending_buf = null; /* output still pending */
  21967. this.pending_buf_size = 0; /* size of pending_buf */
  21968. this.pending_out = 0; /* next pending byte to output to the stream */
  21969. this.pending = 0; /* nb of bytes in the pending buffer */
  21970. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21971. this.gzhead = null; /* gzip header information to write */
  21972. this.gzindex = 0; /* where in extra, name, or comment */
  21973. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21974. this.last_flush = -1; /* value of flush param for previous deflate call */
  21975. this.w_size = 0; /* LZ77 window size (32K by default) */
  21976. this.w_bits = 0; /* log2(w_size) (8..16) */
  21977. this.w_mask = 0; /* w_size - 1 */
  21978. this.window = null;
  21979. /* Sliding window. Input bytes are read into the second half of the window,
  21980. * and move to the first half later to keep a dictionary of at least wSize
  21981. * bytes. With this organization, matches are limited to a distance of
  21982. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21983. * performed with a length multiple of the block size.
  21984. */
  21985. this.window_size = 0;
  21986. /* Actual size of window: 2*wSize, except when the user input buffer
  21987. * is directly used as sliding window.
  21988. */
  21989. this.prev = null;
  21990. /* Link to older string with same hash index. To limit the size of this
  21991. * array to 64K, this link is maintained only for the last 32K strings.
  21992. * An index in this array is thus a window index modulo 32K.
  21993. */
  21994. this.head = null; /* Heads of the hash chains or NIL. */
  21995. this.ins_h = 0; /* hash index of string to be inserted */
  21996. this.hash_size = 0; /* number of elements in hash table */
  21997. this.hash_bits = 0; /* log2(hash_size) */
  21998. this.hash_mask = 0; /* hash_size-1 */
  21999. this.hash_shift = 0;
  22000. /* Number of bits by which ins_h must be shifted at each input
  22001. * step. It must be such that after MIN_MATCH steps, the oldest
  22002. * byte no longer takes part in the hash key, that is:
  22003. * hash_shift * MIN_MATCH >= hash_bits
  22004. */
  22005. this.block_start = 0;
  22006. /* Window position at the beginning of the current output block. Gets
  22007. * negative when the window is moved backwards.
  22008. */
  22009. this.match_length = 0; /* length of best match */
  22010. this.prev_match = 0; /* previous match */
  22011. this.match_available = 0; /* set if previous match exists */
  22012. this.strstart = 0; /* start of string to insert */
  22013. this.match_start = 0; /* start of matching string */
  22014. this.lookahead = 0; /* number of valid bytes ahead in window */
  22015. this.prev_length = 0;
  22016. /* Length of the best match at previous step. Matches not greater than this
  22017. * are discarded. This is used in the lazy match evaluation.
  22018. */
  22019. this.max_chain_length = 0;
  22020. /* To speed up deflation, hash chains are never searched beyond this
  22021. * length. A higher limit improves compression ratio but degrades the
  22022. * speed.
  22023. */
  22024. this.max_lazy_match = 0;
  22025. /* Attempt to find a better match only when the current match is strictly
  22026. * smaller than this value. This mechanism is used only for compression
  22027. * levels >= 4.
  22028. */
  22029. // That's alias to max_lazy_match, don't use directly
  22030. //this.max_insert_length = 0;
  22031. /* Insert new strings in the hash table only if the match length is not
  22032. * greater than this length. This saves time but degrades compression.
  22033. * max_insert_length is used only for compression levels <= 3.
  22034. */
  22035. this.level = 0; /* compression level (1..9) */
  22036. this.strategy = 0; /* favor or force Huffman coding*/
  22037. this.good_match = 0;
  22038. /* Use a faster search when the previous match is longer than this */
  22039. this.nice_match = 0; /* Stop searching when current match exceeds this */
  22040. /* used by trees.c: */
  22041. /* Didn't use ct_data typedef below to suppress compiler warning */
  22042. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  22043. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  22044. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  22045. // Use flat array of DOUBLE size, with interleaved fata,
  22046. // because JS does not support effective
  22047. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  22048. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  22049. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  22050. zero(this.dyn_ltree);
  22051. zero(this.dyn_dtree);
  22052. zero(this.bl_tree);
  22053. this.l_desc = null; /* desc. for literal tree */
  22054. this.d_desc = null; /* desc. for distance tree */
  22055. this.bl_desc = null; /* desc. for bit length tree */
  22056. //ush bl_count[MAX_BITS+1];
  22057. this.bl_count = new utils.Buf16(MAX_BITS+1);
  22058. /* number of codes at each bit length for an optimal tree */
  22059. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  22060. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  22061. zero(this.heap);
  22062. this.heap_len = 0; /* number of elements in the heap */
  22063. this.heap_max = 0; /* element of largest frequency */
  22064. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  22065. * The same heap array is used to build all trees.
  22066. */
  22067. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  22068. zero(this.depth);
  22069. /* Depth of each subtree used as tie breaker for trees of equal frequency
  22070. */
  22071. this.l_buf = 0; /* buffer index for literals or lengths */
  22072. this.lit_bufsize = 0;
  22073. /* Size of match buffer for literals/lengths. There are 4 reasons for
  22074. * limiting lit_bufsize to 64K:
  22075. * - frequencies can be kept in 16 bit counters
  22076. * - if compression is not successful for the first block, all input
  22077. * data is still in the window so we can still emit a stored block even
  22078. * when input comes from standard input. (This can also be done for
  22079. * all blocks if lit_bufsize is not greater than 32K.)
  22080. * - if compression is not successful for a file smaller than 64K, we can
  22081. * even emit a stored file instead of a stored block (saving 5 bytes).
  22082. * This is applicable only for zip (not gzip or zlib).
  22083. * - creating new Huffman trees less frequently may not provide fast
  22084. * adaptation to changes in the input data statistics. (Take for
  22085. * example a binary file with poorly compressible code followed by
  22086. * a highly compressible string table.) Smaller buffer sizes give
  22087. * fast adaptation but have of course the overhead of transmitting
  22088. * trees more frequently.
  22089. * - I can't count above 4
  22090. */
  22091. this.last_lit = 0; /* running index in l_buf */
  22092. this.d_buf = 0;
  22093. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  22094. * the same number of elements. To use different lengths, an extra flag
  22095. * array would be necessary.
  22096. */
  22097. this.opt_len = 0; /* bit length of current block with optimal trees */
  22098. this.static_len = 0; /* bit length of current block with static trees */
  22099. this.matches = 0; /* number of string matches in current block */
  22100. this.insert = 0; /* bytes at end of window left to insert */
  22101. this.bi_buf = 0;
  22102. /* Output buffer. bits are inserted starting at the bottom (least
  22103. * significant bits).
  22104. */
  22105. this.bi_valid = 0;
  22106. /* Number of valid bits in bi_buf. All bits above the last valid bit
  22107. * are always zero.
  22108. */
  22109. // Used for window memory init. We safely ignore it for JS. That makes
  22110. // sense only for pointers and memory check tools.
  22111. //this.high_water = 0;
  22112. /* High water mark offset in window for initialized bytes -- bytes above
  22113. * this are set to zero in order to avoid memory check warnings when
  22114. * longest match routines access bytes past the input. This is then
  22115. * updated to the new high water mark.
  22116. */
  22117. }
  22118. function deflateResetKeep(strm) {
  22119. var s;
  22120. if (!strm || !strm.state) {
  22121. return err(strm, Z_STREAM_ERROR);
  22122. }
  22123. strm.total_in = strm.total_out = 0;
  22124. strm.data_type = Z_UNKNOWN;
  22125. s = strm.state;
  22126. s.pending = 0;
  22127. s.pending_out = 0;
  22128. if (s.wrap < 0) {
  22129. s.wrap = -s.wrap;
  22130. /* was made negative by deflate(..., Z_FINISH); */
  22131. }
  22132. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  22133. strm.adler = (s.wrap === 2) ?
  22134. 0 // crc32(0, Z_NULL, 0)
  22135. :
  22136. 1; // adler32(0, Z_NULL, 0)
  22137. s.last_flush = Z_NO_FLUSH;
  22138. trees._tr_init(s);
  22139. return Z_OK;
  22140. }
  22141. function deflateReset(strm) {
  22142. var ret = deflateResetKeep(strm);
  22143. if (ret === Z_OK) {
  22144. lm_init(strm.state);
  22145. }
  22146. return ret;
  22147. }
  22148. function deflateSetHeader(strm, head) {
  22149. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22150. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  22151. strm.state.gzhead = head;
  22152. return Z_OK;
  22153. }
  22154. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  22155. if (!strm) { // === Z_NULL
  22156. return Z_STREAM_ERROR;
  22157. }
  22158. var wrap = 1;
  22159. if (level === Z_DEFAULT_COMPRESSION) {
  22160. level = 6;
  22161. }
  22162. if (windowBits < 0) { /* suppress zlib wrapper */
  22163. wrap = 0;
  22164. windowBits = -windowBits;
  22165. }
  22166. else if (windowBits > 15) {
  22167. wrap = 2; /* write gzip wrapper instead */
  22168. windowBits -= 16;
  22169. }
  22170. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  22171. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  22172. strategy < 0 || strategy > Z_FIXED) {
  22173. return err(strm, Z_STREAM_ERROR);
  22174. }
  22175. if (windowBits === 8) {
  22176. windowBits = 9;
  22177. }
  22178. /* until 256-byte window bug fixed */
  22179. var s = new DeflateState();
  22180. strm.state = s;
  22181. s.strm = strm;
  22182. s.wrap = wrap;
  22183. s.gzhead = null;
  22184. s.w_bits = windowBits;
  22185. s.w_size = 1 << s.w_bits;
  22186. s.w_mask = s.w_size - 1;
  22187. s.hash_bits = memLevel + 7;
  22188. s.hash_size = 1 << s.hash_bits;
  22189. s.hash_mask = s.hash_size - 1;
  22190. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  22191. s.window = new utils.Buf8(s.w_size * 2);
  22192. s.head = new utils.Buf16(s.hash_size);
  22193. s.prev = new utils.Buf16(s.w_size);
  22194. // Don't need mem init magic for JS.
  22195. //s.high_water = 0; /* nothing written to s->window yet */
  22196. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  22197. s.pending_buf_size = s.lit_bufsize * 4;
  22198. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  22199. s.d_buf = s.lit_bufsize >> 1;
  22200. s.l_buf = (1 + 2) * s.lit_bufsize;
  22201. s.level = level;
  22202. s.strategy = strategy;
  22203. s.method = method;
  22204. return deflateReset(strm);
  22205. }
  22206. function deflateInit(strm, level) {
  22207. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  22208. }
  22209. function deflate(strm, flush) {
  22210. var old_flush, s;
  22211. var beg, val; // for gzip header write only
  22212. if (!strm || !strm.state ||
  22213. flush > Z_BLOCK || flush < 0) {
  22214. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  22215. }
  22216. s = strm.state;
  22217. if (!strm.output ||
  22218. (!strm.input && strm.avail_in !== 0) ||
  22219. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  22220. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  22221. }
  22222. s.strm = strm; /* just in case */
  22223. old_flush = s.last_flush;
  22224. s.last_flush = flush;
  22225. /* Write the header */
  22226. if (s.status === INIT_STATE) {
  22227. if (s.wrap === 2) { // GZIP header
  22228. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22229. put_byte(s, 31);
  22230. put_byte(s, 139);
  22231. put_byte(s, 8);
  22232. if (!s.gzhead) { // s->gzhead == Z_NULL
  22233. put_byte(s, 0);
  22234. put_byte(s, 0);
  22235. put_byte(s, 0);
  22236. put_byte(s, 0);
  22237. put_byte(s, 0);
  22238. put_byte(s, s.level === 9 ? 2 :
  22239. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22240. 4 : 0));
  22241. put_byte(s, OS_CODE);
  22242. s.status = BUSY_STATE;
  22243. }
  22244. else {
  22245. put_byte(s, (s.gzhead.text ? 1 : 0) +
  22246. (s.gzhead.hcrc ? 2 : 0) +
  22247. (!s.gzhead.extra ? 0 : 4) +
  22248. (!s.gzhead.name ? 0 : 8) +
  22249. (!s.gzhead.comment ? 0 : 16)
  22250. );
  22251. put_byte(s, s.gzhead.time & 0xff);
  22252. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  22253. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  22254. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  22255. put_byte(s, s.level === 9 ? 2 :
  22256. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22257. 4 : 0));
  22258. put_byte(s, s.gzhead.os & 0xff);
  22259. if (s.gzhead.extra && s.gzhead.extra.length) {
  22260. put_byte(s, s.gzhead.extra.length & 0xff);
  22261. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  22262. }
  22263. if (s.gzhead.hcrc) {
  22264. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  22265. }
  22266. s.gzindex = 0;
  22267. s.status = EXTRA_STATE;
  22268. }
  22269. }
  22270. else // DEFLATE header
  22271. {
  22272. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  22273. var level_flags = -1;
  22274. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  22275. level_flags = 0;
  22276. } else if (s.level < 6) {
  22277. level_flags = 1;
  22278. } else if (s.level === 6) {
  22279. level_flags = 2;
  22280. } else {
  22281. level_flags = 3;
  22282. }
  22283. header |= (level_flags << 6);
  22284. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22285. header += 31 - (header % 31);
  22286. s.status = BUSY_STATE;
  22287. putShortMSB(s, header);
  22288. /* Save the adler32 of the preset dictionary: */
  22289. if (s.strstart !== 0) {
  22290. putShortMSB(s, strm.adler >>> 16);
  22291. putShortMSB(s, strm.adler & 0xffff);
  22292. }
  22293. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22294. }
  22295. }
  22296. //#ifdef GZIP
  22297. if (s.status === EXTRA_STATE) {
  22298. if (s.gzhead.extra/* != Z_NULL*/) {
  22299. beg = s.pending; /* start of bytes to update crc */
  22300. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22301. if (s.pending === s.pending_buf_size) {
  22302. if (s.gzhead.hcrc && s.pending > beg) {
  22303. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22304. }
  22305. flush_pending(strm);
  22306. beg = s.pending;
  22307. if (s.pending === s.pending_buf_size) {
  22308. break;
  22309. }
  22310. }
  22311. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22312. s.gzindex++;
  22313. }
  22314. if (s.gzhead.hcrc && s.pending > beg) {
  22315. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22316. }
  22317. if (s.gzindex === s.gzhead.extra.length) {
  22318. s.gzindex = 0;
  22319. s.status = NAME_STATE;
  22320. }
  22321. }
  22322. else {
  22323. s.status = NAME_STATE;
  22324. }
  22325. }
  22326. if (s.status === NAME_STATE) {
  22327. if (s.gzhead.name/* != Z_NULL*/) {
  22328. beg = s.pending; /* start of bytes to update crc */
  22329. //int val;
  22330. do {
  22331. if (s.pending === s.pending_buf_size) {
  22332. if (s.gzhead.hcrc && s.pending > beg) {
  22333. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22334. }
  22335. flush_pending(strm);
  22336. beg = s.pending;
  22337. if (s.pending === s.pending_buf_size) {
  22338. val = 1;
  22339. break;
  22340. }
  22341. }
  22342. // JS specific: little magic to add zero terminator to end of string
  22343. if (s.gzindex < s.gzhead.name.length) {
  22344. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22345. } else {
  22346. val = 0;
  22347. }
  22348. put_byte(s, val);
  22349. } while (val !== 0);
  22350. if (s.gzhead.hcrc && s.pending > beg) {
  22351. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22352. }
  22353. if (val === 0) {
  22354. s.gzindex = 0;
  22355. s.status = COMMENT_STATE;
  22356. }
  22357. }
  22358. else {
  22359. s.status = COMMENT_STATE;
  22360. }
  22361. }
  22362. if (s.status === COMMENT_STATE) {
  22363. if (s.gzhead.comment/* != Z_NULL*/) {
  22364. beg = s.pending; /* start of bytes to update crc */
  22365. //int val;
  22366. do {
  22367. if (s.pending === s.pending_buf_size) {
  22368. if (s.gzhead.hcrc && s.pending > beg) {
  22369. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22370. }
  22371. flush_pending(strm);
  22372. beg = s.pending;
  22373. if (s.pending === s.pending_buf_size) {
  22374. val = 1;
  22375. break;
  22376. }
  22377. }
  22378. // JS specific: little magic to add zero terminator to end of string
  22379. if (s.gzindex < s.gzhead.comment.length) {
  22380. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22381. } else {
  22382. val = 0;
  22383. }
  22384. put_byte(s, val);
  22385. } while (val !== 0);
  22386. if (s.gzhead.hcrc && s.pending > beg) {
  22387. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22388. }
  22389. if (val === 0) {
  22390. s.status = HCRC_STATE;
  22391. }
  22392. }
  22393. else {
  22394. s.status = HCRC_STATE;
  22395. }
  22396. }
  22397. if (s.status === HCRC_STATE) {
  22398. if (s.gzhead.hcrc) {
  22399. if (s.pending + 2 > s.pending_buf_size) {
  22400. flush_pending(strm);
  22401. }
  22402. if (s.pending + 2 <= s.pending_buf_size) {
  22403. put_byte(s, strm.adler & 0xff);
  22404. put_byte(s, (strm.adler >> 8) & 0xff);
  22405. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22406. s.status = BUSY_STATE;
  22407. }
  22408. }
  22409. else {
  22410. s.status = BUSY_STATE;
  22411. }
  22412. }
  22413. //#endif
  22414. /* Flush as much pending output as possible */
  22415. if (s.pending !== 0) {
  22416. flush_pending(strm);
  22417. if (strm.avail_out === 0) {
  22418. /* Since avail_out is 0, deflate will be called again with
  22419. * more output space, but possibly with both pending and
  22420. * avail_in equal to zero. There won't be anything to do,
  22421. * but this is not an error situation so make sure we
  22422. * return OK instead of BUF_ERROR at next call of deflate:
  22423. */
  22424. s.last_flush = -1;
  22425. return Z_OK;
  22426. }
  22427. /* Make sure there is something to do and avoid duplicate consecutive
  22428. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22429. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22430. */
  22431. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22432. flush !== Z_FINISH) {
  22433. return err(strm, Z_BUF_ERROR);
  22434. }
  22435. /* User must not provide more input after the first FINISH: */
  22436. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22437. return err(strm, Z_BUF_ERROR);
  22438. }
  22439. /* Start a new block or continue the current one.
  22440. */
  22441. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22442. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22443. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22444. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22445. configuration_table[s.level].func(s, flush));
  22446. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22447. s.status = FINISH_STATE;
  22448. }
  22449. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22450. if (strm.avail_out === 0) {
  22451. s.last_flush = -1;
  22452. /* avoid BUF_ERROR next call, see above */
  22453. }
  22454. return Z_OK;
  22455. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22456. * of deflate should use the same flush parameter to make sure
  22457. * that the flush is complete. So we don't have to output an
  22458. * empty block here, this will be done at next call. This also
  22459. * ensures that for a very small output buffer, we emit at most
  22460. * one empty block.
  22461. */
  22462. }
  22463. if (bstate === BS_BLOCK_DONE) {
  22464. if (flush === Z_PARTIAL_FLUSH) {
  22465. trees._tr_align(s);
  22466. }
  22467. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22468. trees._tr_stored_block(s, 0, 0, false);
  22469. /* For a full flush, this empty block will be recognized
  22470. * as a special marker by inflate_sync().
  22471. */
  22472. if (flush === Z_FULL_FLUSH) {
  22473. /*** CLEAR_HASH(s); ***/ /* forget history */
  22474. zero(s.head); // Fill with NIL (= 0);
  22475. if (s.lookahead === 0) {
  22476. s.strstart = 0;
  22477. s.block_start = 0;
  22478. s.insert = 0;
  22479. }
  22480. }
  22481. }
  22482. flush_pending(strm);
  22483. if (strm.avail_out === 0) {
  22484. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22485. return Z_OK;
  22486. }
  22487. }
  22488. }
  22489. //Assert(strm->avail_out > 0, "bug2");
  22490. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22491. if (flush !== Z_FINISH) { return Z_OK; }
  22492. if (s.wrap <= 0) { return Z_STREAM_END; }
  22493. /* Write the trailer */
  22494. if (s.wrap === 2) {
  22495. put_byte(s, strm.adler & 0xff);
  22496. put_byte(s, (strm.adler >> 8) & 0xff);
  22497. put_byte(s, (strm.adler >> 16) & 0xff);
  22498. put_byte(s, (strm.adler >> 24) & 0xff);
  22499. put_byte(s, strm.total_in & 0xff);
  22500. put_byte(s, (strm.total_in >> 8) & 0xff);
  22501. put_byte(s, (strm.total_in >> 16) & 0xff);
  22502. put_byte(s, (strm.total_in >> 24) & 0xff);
  22503. }
  22504. else
  22505. {
  22506. putShortMSB(s, strm.adler >>> 16);
  22507. putShortMSB(s, strm.adler & 0xffff);
  22508. }
  22509. flush_pending(strm);
  22510. /* If avail_out is zero, the application will call deflate again
  22511. * to flush the rest.
  22512. */
  22513. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22514. /* write the trailer only once! */
  22515. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22516. }
  22517. function deflateEnd(strm) {
  22518. var status;
  22519. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22520. return Z_STREAM_ERROR;
  22521. }
  22522. status = strm.state.status;
  22523. if (status !== INIT_STATE &&
  22524. status !== EXTRA_STATE &&
  22525. status !== NAME_STATE &&
  22526. status !== COMMENT_STATE &&
  22527. status !== HCRC_STATE &&
  22528. status !== BUSY_STATE &&
  22529. status !== FINISH_STATE
  22530. ) {
  22531. return err(strm, Z_STREAM_ERROR);
  22532. }
  22533. strm.state = null;
  22534. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22535. }
  22536. /* =========================================================================
  22537. * Copy the source state to the destination state
  22538. */
  22539. //function deflateCopy(dest, source) {
  22540. //
  22541. //}
  22542. exports.deflateInit = deflateInit;
  22543. exports.deflateInit2 = deflateInit2;
  22544. exports.deflateReset = deflateReset;
  22545. exports.deflateResetKeep = deflateResetKeep;
  22546. exports.deflateSetHeader = deflateSetHeader;
  22547. exports.deflate = deflate;
  22548. exports.deflateEnd = deflateEnd;
  22549. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22550. /* Not implemented
  22551. exports.deflateBound = deflateBound;
  22552. exports.deflateCopy = deflateCopy;
  22553. exports.deflateSetDictionary = deflateSetDictionary;
  22554. exports.deflateParams = deflateParams;
  22555. exports.deflatePending = deflatePending;
  22556. exports.deflatePrime = deflatePrime;
  22557. exports.deflateTune = deflateTune;
  22558. */
  22559. },{"../utils/common":78,"./adler32":80,"./crc32":82,"./messages":88,"./trees":89}],84:[function(require,module,exports){
  22560. 'use strict';
  22561. function GZheader() {
  22562. /* true if compressed data believed to be text */
  22563. this.text = 0;
  22564. /* modification time */
  22565. this.time = 0;
  22566. /* extra flags (not used when writing a gzip file) */
  22567. this.xflags = 0;
  22568. /* operating system */
  22569. this.os = 0;
  22570. /* pointer to extra field or Z_NULL if none */
  22571. this.extra = null;
  22572. /* extra field length (valid if extra != Z_NULL) */
  22573. this.extra_len = 0; // Actually, we don't need it in JS,
  22574. // but leave for few code modifications
  22575. //
  22576. // Setup limits is not necessary because in js we should not preallocate memory
  22577. // for inflate use constant limit in 65536 bytes
  22578. //
  22579. /* space at extra (only when reading header) */
  22580. // this.extra_max = 0;
  22581. /* pointer to zero-terminated file name or Z_NULL */
  22582. this.name = '';
  22583. /* space at name (only when reading header) */
  22584. // this.name_max = 0;
  22585. /* pointer to zero-terminated comment or Z_NULL */
  22586. this.comment = '';
  22587. /* space at comment (only when reading header) */
  22588. // this.comm_max = 0;
  22589. /* true if there was or will be a header crc */
  22590. this.hcrc = 0;
  22591. /* true when done reading gzip header (not used when writing a gzip file) */
  22592. this.done = false;
  22593. }
  22594. module.exports = GZheader;
  22595. },{}],85:[function(require,module,exports){
  22596. 'use strict';
  22597. // See state defs from inflate.js
  22598. var BAD = 30; /* got a data error -- remain here until reset */
  22599. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22600. /*
  22601. Decode literal, length, and distance codes and write out the resulting
  22602. literal and match bytes until either not enough input or output is
  22603. available, an end-of-block is encountered, or a data error is encountered.
  22604. When large enough input and output buffers are supplied to inflate(), for
  22605. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22606. inflate execution time is spent in this routine.
  22607. Entry assumptions:
  22608. state.mode === LEN
  22609. strm.avail_in >= 6
  22610. strm.avail_out >= 258
  22611. start >= strm.avail_out
  22612. state.bits < 8
  22613. On return, state.mode is one of:
  22614. LEN -- ran out of enough output space or enough available input
  22615. TYPE -- reached end of block code, inflate() to interpret next block
  22616. BAD -- error in block data
  22617. Notes:
  22618. - The maximum input bits used by a length/distance pair is 15 bits for the
  22619. length code, 5 bits for the length extra, 15 bits for the distance code,
  22620. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22621. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22622. checking for available input while decoding.
  22623. - The maximum bytes that a single length/distance pair can output is 258
  22624. bytes, which is the maximum length that can be coded. inflate_fast()
  22625. requires strm.avail_out >= 258 for each loop to avoid checking for
  22626. output space.
  22627. */
  22628. module.exports = function inflate_fast(strm, start) {
  22629. var state;
  22630. var _in; /* local strm.input */
  22631. var last; /* have enough input while in < last */
  22632. var _out; /* local strm.output */
  22633. var beg; /* inflate()'s initial strm.output */
  22634. var end; /* while out < end, enough space available */
  22635. //#ifdef INFLATE_STRICT
  22636. var dmax; /* maximum distance from zlib header */
  22637. //#endif
  22638. var wsize; /* window size or zero if not using window */
  22639. var whave; /* valid bytes in the window */
  22640. var wnext; /* window write index */
  22641. var window; /* allocated sliding window, if wsize != 0 */
  22642. var hold; /* local strm.hold */
  22643. var bits; /* local strm.bits */
  22644. var lcode; /* local strm.lencode */
  22645. var dcode; /* local strm.distcode */
  22646. var lmask; /* mask for first level of length codes */
  22647. var dmask; /* mask for first level of distance codes */
  22648. var here; /* retrieved table entry */
  22649. var op; /* code bits, operation, extra bits, or */
  22650. /* window position, window bytes to copy */
  22651. var len; /* match length, unused bytes */
  22652. var dist; /* match distance */
  22653. var from; /* where to copy match from */
  22654. var from_source;
  22655. var input, output; // JS specific, because we have no pointers
  22656. /* copy state to local variables */
  22657. state = strm.state;
  22658. //here = state.here;
  22659. _in = strm.next_in;
  22660. input = strm.input;
  22661. last = _in + (strm.avail_in - 5);
  22662. _out = strm.next_out;
  22663. output = strm.output;
  22664. beg = _out - (start - strm.avail_out);
  22665. end = _out + (strm.avail_out - 257);
  22666. //#ifdef INFLATE_STRICT
  22667. dmax = state.dmax;
  22668. //#endif
  22669. wsize = state.wsize;
  22670. whave = state.whave;
  22671. wnext = state.wnext;
  22672. window = state.window;
  22673. hold = state.hold;
  22674. bits = state.bits;
  22675. lcode = state.lencode;
  22676. dcode = state.distcode;
  22677. lmask = (1 << state.lenbits) - 1;
  22678. dmask = (1 << state.distbits) - 1;
  22679. /* decode literals and length/distances until end-of-block or not enough
  22680. input data or output space */
  22681. top:
  22682. do {
  22683. if (bits < 15) {
  22684. hold += input[_in++] << bits;
  22685. bits += 8;
  22686. hold += input[_in++] << bits;
  22687. bits += 8;
  22688. }
  22689. here = lcode[hold & lmask];
  22690. dolen:
  22691. for (;;) { // Goto emulation
  22692. op = here >>> 24/*here.bits*/;
  22693. hold >>>= op;
  22694. bits -= op;
  22695. op = (here >>> 16) & 0xff/*here.op*/;
  22696. if (op === 0) { /* literal */
  22697. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22698. // "inflate: literal '%c'\n" :
  22699. // "inflate: literal 0x%02x\n", here.val));
  22700. output[_out++] = here & 0xffff/*here.val*/;
  22701. }
  22702. else if (op & 16) { /* length base */
  22703. len = here & 0xffff/*here.val*/;
  22704. op &= 15; /* number of extra bits */
  22705. if (op) {
  22706. if (bits < op) {
  22707. hold += input[_in++] << bits;
  22708. bits += 8;
  22709. }
  22710. len += hold & ((1 << op) - 1);
  22711. hold >>>= op;
  22712. bits -= op;
  22713. }
  22714. //Tracevv((stderr, "inflate: length %u\n", len));
  22715. if (bits < 15) {
  22716. hold += input[_in++] << bits;
  22717. bits += 8;
  22718. hold += input[_in++] << bits;
  22719. bits += 8;
  22720. }
  22721. here = dcode[hold & dmask];
  22722. dodist:
  22723. for (;;) { // goto emulation
  22724. op = here >>> 24/*here.bits*/;
  22725. hold >>>= op;
  22726. bits -= op;
  22727. op = (here >>> 16) & 0xff/*here.op*/;
  22728. if (op & 16) { /* distance base */
  22729. dist = here & 0xffff/*here.val*/;
  22730. op &= 15; /* number of extra bits */
  22731. if (bits < op) {
  22732. hold += input[_in++] << bits;
  22733. bits += 8;
  22734. if (bits < op) {
  22735. hold += input[_in++] << bits;
  22736. bits += 8;
  22737. }
  22738. }
  22739. dist += hold & ((1 << op) - 1);
  22740. //#ifdef INFLATE_STRICT
  22741. if (dist > dmax) {
  22742. strm.msg = 'invalid distance too far back';
  22743. state.mode = BAD;
  22744. break top;
  22745. }
  22746. //#endif
  22747. hold >>>= op;
  22748. bits -= op;
  22749. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22750. op = _out - beg; /* max distance in output */
  22751. if (dist > op) { /* see if copy from window */
  22752. op = dist - op; /* distance back in window */
  22753. if (op > whave) {
  22754. if (state.sane) {
  22755. strm.msg = 'invalid distance too far back';
  22756. state.mode = BAD;
  22757. break top;
  22758. }
  22759. // (!) This block is disabled in zlib defailts,
  22760. // don't enable it for binary compatibility
  22761. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22762. // if (len <= op - whave) {
  22763. // do {
  22764. // output[_out++] = 0;
  22765. // } while (--len);
  22766. // continue top;
  22767. // }
  22768. // len -= op - whave;
  22769. // do {
  22770. // output[_out++] = 0;
  22771. // } while (--op > whave);
  22772. // if (op === 0) {
  22773. // from = _out - dist;
  22774. // do {
  22775. // output[_out++] = output[from++];
  22776. // } while (--len);
  22777. // continue top;
  22778. // }
  22779. //#endif
  22780. }
  22781. from = 0; // window index
  22782. from_source = window;
  22783. if (wnext === 0) { /* very common case */
  22784. from += wsize - op;
  22785. if (op < len) { /* some from window */
  22786. len -= op;
  22787. do {
  22788. output[_out++] = window[from++];
  22789. } while (--op);
  22790. from = _out - dist; /* rest from output */
  22791. from_source = output;
  22792. }
  22793. }
  22794. else if (wnext < op) { /* wrap around window */
  22795. from += wsize + wnext - op;
  22796. op -= wnext;
  22797. if (op < len) { /* some from end of window */
  22798. len -= op;
  22799. do {
  22800. output[_out++] = window[from++];
  22801. } while (--op);
  22802. from = 0;
  22803. if (wnext < len) { /* some from start of window */
  22804. op = wnext;
  22805. len -= op;
  22806. do {
  22807. output[_out++] = window[from++];
  22808. } while (--op);
  22809. from = _out - dist; /* rest from output */
  22810. from_source = output;
  22811. }
  22812. }
  22813. }
  22814. else { /* contiguous in window */
  22815. from += wnext - op;
  22816. if (op < len) { /* some from window */
  22817. len -= op;
  22818. do {
  22819. output[_out++] = window[from++];
  22820. } while (--op);
  22821. from = _out - dist; /* rest from output */
  22822. from_source = output;
  22823. }
  22824. }
  22825. while (len > 2) {
  22826. output[_out++] = from_source[from++];
  22827. output[_out++] = from_source[from++];
  22828. output[_out++] = from_source[from++];
  22829. len -= 3;
  22830. }
  22831. if (len) {
  22832. output[_out++] = from_source[from++];
  22833. if (len > 1) {
  22834. output[_out++] = from_source[from++];
  22835. }
  22836. }
  22837. }
  22838. else {
  22839. from = _out - dist; /* copy direct from output */
  22840. do { /* minimum length is three */
  22841. output[_out++] = output[from++];
  22842. output[_out++] = output[from++];
  22843. output[_out++] = output[from++];
  22844. len -= 3;
  22845. } while (len > 2);
  22846. if (len) {
  22847. output[_out++] = output[from++];
  22848. if (len > 1) {
  22849. output[_out++] = output[from++];
  22850. }
  22851. }
  22852. }
  22853. }
  22854. else if ((op & 64) === 0) { /* 2nd level distance code */
  22855. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22856. continue dodist;
  22857. }
  22858. else {
  22859. strm.msg = 'invalid distance code';
  22860. state.mode = BAD;
  22861. break top;
  22862. }
  22863. break; // need to emulate goto via "continue"
  22864. }
  22865. }
  22866. else if ((op & 64) === 0) { /* 2nd level length code */
  22867. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22868. continue dolen;
  22869. }
  22870. else if (op & 32) { /* end-of-block */
  22871. //Tracevv((stderr, "inflate: end of block\n"));
  22872. state.mode = TYPE;
  22873. break top;
  22874. }
  22875. else {
  22876. strm.msg = 'invalid literal/length code';
  22877. state.mode = BAD;
  22878. break top;
  22879. }
  22880. break; // need to emulate goto via "continue"
  22881. }
  22882. } while (_in < last && _out < end);
  22883. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22884. len = bits >> 3;
  22885. _in -= len;
  22886. bits -= len << 3;
  22887. hold &= (1 << bits) - 1;
  22888. /* update state and return */
  22889. strm.next_in = _in;
  22890. strm.next_out = _out;
  22891. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22892. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22893. state.hold = hold;
  22894. state.bits = bits;
  22895. return;
  22896. };
  22897. },{}],86:[function(require,module,exports){
  22898. 'use strict';
  22899. var utils = require('../utils/common');
  22900. var adler32 = require('./adler32');
  22901. var crc32 = require('./crc32');
  22902. var inflate_fast = require('./inffast');
  22903. var inflate_table = require('./inftrees');
  22904. var CODES = 0;
  22905. var LENS = 1;
  22906. var DISTS = 2;
  22907. /* Public constants ==========================================================*/
  22908. /* ===========================================================================*/
  22909. /* Allowed flush values; see deflate() and inflate() below for details */
  22910. //var Z_NO_FLUSH = 0;
  22911. //var Z_PARTIAL_FLUSH = 1;
  22912. //var Z_SYNC_FLUSH = 2;
  22913. //var Z_FULL_FLUSH = 3;
  22914. var Z_FINISH = 4;
  22915. var Z_BLOCK = 5;
  22916. var Z_TREES = 6;
  22917. /* Return codes for the compression/decompression functions. Negative values
  22918. * are errors, positive values are used for special but normal events.
  22919. */
  22920. var Z_OK = 0;
  22921. var Z_STREAM_END = 1;
  22922. var Z_NEED_DICT = 2;
  22923. //var Z_ERRNO = -1;
  22924. var Z_STREAM_ERROR = -2;
  22925. var Z_DATA_ERROR = -3;
  22926. var Z_MEM_ERROR = -4;
  22927. var Z_BUF_ERROR = -5;
  22928. //var Z_VERSION_ERROR = -6;
  22929. /* The deflate compression method */
  22930. var Z_DEFLATED = 8;
  22931. /* STATES ====================================================================*/
  22932. /* ===========================================================================*/
  22933. var HEAD = 1; /* i: waiting for magic header */
  22934. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22935. var TIME = 3; /* i: waiting for modification time (gzip) */
  22936. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22937. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22938. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22939. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22940. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22941. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22942. var DICTID = 10; /* i: waiting for dictionary check value */
  22943. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22944. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22945. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22946. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22947. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22948. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22949. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22950. var LENLENS = 18; /* i: waiting for code length code lengths */
  22951. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22952. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22953. var LEN = 21; /* i: waiting for length/lit/eob code */
  22954. var LENEXT = 22; /* i: waiting for length extra bits */
  22955. var DIST = 23; /* i: waiting for distance code */
  22956. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22957. var MATCH = 25; /* o: waiting for output space to copy string */
  22958. var LIT = 26; /* o: waiting for output space to write literal */
  22959. var CHECK = 27; /* i: waiting for 32-bit check value */
  22960. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22961. var DONE = 29; /* finished check, done -- remain here until reset */
  22962. var BAD = 30; /* got a data error -- remain here until reset */
  22963. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22964. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22965. /* ===========================================================================*/
  22966. var ENOUGH_LENS = 852;
  22967. var ENOUGH_DISTS = 592;
  22968. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22969. var MAX_WBITS = 15;
  22970. /* 32K LZ77 window */
  22971. var DEF_WBITS = MAX_WBITS;
  22972. function ZSWAP32(q) {
  22973. return (((q >>> 24) & 0xff) +
  22974. ((q >>> 8) & 0xff00) +
  22975. ((q & 0xff00) << 8) +
  22976. ((q & 0xff) << 24));
  22977. }
  22978. function InflateState() {
  22979. this.mode = 0; /* current inflate mode */
  22980. this.last = false; /* true if processing last block */
  22981. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22982. this.havedict = false; /* true if dictionary provided */
  22983. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22984. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22985. this.check = 0; /* protected copy of check value */
  22986. this.total = 0; /* protected copy of output count */
  22987. // TODO: may be {}
  22988. this.head = null; /* where to save gzip header information */
  22989. /* sliding window */
  22990. this.wbits = 0; /* log base 2 of requested window size */
  22991. this.wsize = 0; /* window size or zero if not using window */
  22992. this.whave = 0; /* valid bytes in the window */
  22993. this.wnext = 0; /* window write index */
  22994. this.window = null; /* allocated sliding window, if needed */
  22995. /* bit accumulator */
  22996. this.hold = 0; /* input bit accumulator */
  22997. this.bits = 0; /* number of bits in "in" */
  22998. /* for string and stored block copying */
  22999. this.length = 0; /* literal or length of data to copy */
  23000. this.offset = 0; /* distance back to copy string from */
  23001. /* for table and code decoding */
  23002. this.extra = 0; /* extra bits needed */
  23003. /* fixed and dynamic code tables */
  23004. this.lencode = null; /* starting table for length/literal codes */
  23005. this.distcode = null; /* starting table for distance codes */
  23006. this.lenbits = 0; /* index bits for lencode */
  23007. this.distbits = 0; /* index bits for distcode */
  23008. /* dynamic table building */
  23009. this.ncode = 0; /* number of code length code lengths */
  23010. this.nlen = 0; /* number of length code lengths */
  23011. this.ndist = 0; /* number of distance code lengths */
  23012. this.have = 0; /* number of code lengths in lens[] */
  23013. this.next = null; /* next available space in codes[] */
  23014. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  23015. this.work = new utils.Buf16(288); /* work area for code table building */
  23016. /*
  23017. because we don't have pointers in js, we use lencode and distcode directly
  23018. as buffers so we don't need codes
  23019. */
  23020. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  23021. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  23022. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  23023. this.sane = 0; /* if false, allow invalid distance too far */
  23024. this.back = 0; /* bits back of last unprocessed length/lit */
  23025. this.was = 0; /* initial length of match */
  23026. }
  23027. function inflateResetKeep(strm) {
  23028. var state;
  23029. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23030. state = strm.state;
  23031. strm.total_in = strm.total_out = state.total = 0;
  23032. strm.msg = ''; /*Z_NULL*/
  23033. if (state.wrap) { /* to support ill-conceived Java test suite */
  23034. strm.adler = state.wrap & 1;
  23035. }
  23036. state.mode = HEAD;
  23037. state.last = 0;
  23038. state.havedict = 0;
  23039. state.dmax = 32768;
  23040. state.head = null/*Z_NULL*/;
  23041. state.hold = 0;
  23042. state.bits = 0;
  23043. //state.lencode = state.distcode = state.next = state.codes;
  23044. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  23045. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  23046. state.sane = 1;
  23047. state.back = -1;
  23048. //Tracev((stderr, "inflate: reset\n"));
  23049. return Z_OK;
  23050. }
  23051. function inflateReset(strm) {
  23052. var state;
  23053. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23054. state = strm.state;
  23055. state.wsize = 0;
  23056. state.whave = 0;
  23057. state.wnext = 0;
  23058. return inflateResetKeep(strm);
  23059. }
  23060. function inflateReset2(strm, windowBits) {
  23061. var wrap;
  23062. var state;
  23063. /* get the state */
  23064. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23065. state = strm.state;
  23066. /* extract wrap request from windowBits parameter */
  23067. if (windowBits < 0) {
  23068. wrap = 0;
  23069. windowBits = -windowBits;
  23070. }
  23071. else {
  23072. wrap = (windowBits >> 4) + 1;
  23073. if (windowBits < 48) {
  23074. windowBits &= 15;
  23075. }
  23076. }
  23077. /* set number of window bits, free window if different */
  23078. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  23079. return Z_STREAM_ERROR;
  23080. }
  23081. if (state.window !== null && state.wbits !== windowBits) {
  23082. state.window = null;
  23083. }
  23084. /* update state and reset the rest of it */
  23085. state.wrap = wrap;
  23086. state.wbits = windowBits;
  23087. return inflateReset(strm);
  23088. }
  23089. function inflateInit2(strm, windowBits) {
  23090. var ret;
  23091. var state;
  23092. if (!strm) { return Z_STREAM_ERROR; }
  23093. //strm.msg = Z_NULL; /* in case we return an error */
  23094. state = new InflateState();
  23095. //if (state === Z_NULL) return Z_MEM_ERROR;
  23096. //Tracev((stderr, "inflate: allocated\n"));
  23097. strm.state = state;
  23098. state.window = null/*Z_NULL*/;
  23099. ret = inflateReset2(strm, windowBits);
  23100. if (ret !== Z_OK) {
  23101. strm.state = null/*Z_NULL*/;
  23102. }
  23103. return ret;
  23104. }
  23105. function inflateInit(strm) {
  23106. return inflateInit2(strm, DEF_WBITS);
  23107. }
  23108. /*
  23109. Return state with length and distance decoding tables and index sizes set to
  23110. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  23111. If BUILDFIXED is defined, then instead this routine builds the tables the
  23112. first time it's called, and returns those tables the first time and
  23113. thereafter. This reduces the size of the code by about 2K bytes, in
  23114. exchange for a little execution time. However, BUILDFIXED should not be
  23115. used for threaded applications, since the rewriting of the tables and virgin
  23116. may not be thread-safe.
  23117. */
  23118. var virgin = true;
  23119. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  23120. function fixedtables(state) {
  23121. /* build fixed huffman tables if first call (may not be thread safe) */
  23122. if (virgin) {
  23123. var sym;
  23124. lenfix = new utils.Buf32(512);
  23125. distfix = new utils.Buf32(32);
  23126. /* literal/length table */
  23127. sym = 0;
  23128. while (sym < 144) { state.lens[sym++] = 8; }
  23129. while (sym < 256) { state.lens[sym++] = 9; }
  23130. while (sym < 280) { state.lens[sym++] = 7; }
  23131. while (sym < 288) { state.lens[sym++] = 8; }
  23132. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  23133. /* distance table */
  23134. sym = 0;
  23135. while (sym < 32) { state.lens[sym++] = 5; }
  23136. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  23137. /* do this just once */
  23138. virgin = false;
  23139. }
  23140. state.lencode = lenfix;
  23141. state.lenbits = 9;
  23142. state.distcode = distfix;
  23143. state.distbits = 5;
  23144. }
  23145. /*
  23146. Update the window with the last wsize (normally 32K) bytes written before
  23147. returning. If window does not exist yet, create it. This is only called
  23148. when a window is already in use, or when output has been written during this
  23149. inflate call, but the end of the deflate stream has not been reached yet.
  23150. It is also called to create a window for dictionary data when a dictionary
  23151. is loaded.
  23152. Providing output buffers larger than 32K to inflate() should provide a speed
  23153. advantage, since only the last 32K of output is copied to the sliding window
  23154. upon return from inflate(), and since all distances after the first 32K of
  23155. output will fall in the output data, making match copies simpler and faster.
  23156. The advantage may be dependent on the size of the processor's data caches.
  23157. */
  23158. function updatewindow(strm, src, end, copy) {
  23159. var dist;
  23160. var state = strm.state;
  23161. /* if it hasn't been done already, allocate space for the window */
  23162. if (state.window === null) {
  23163. state.wsize = 1 << state.wbits;
  23164. state.wnext = 0;
  23165. state.whave = 0;
  23166. state.window = new utils.Buf8(state.wsize);
  23167. }
  23168. /* copy state->wsize or less output bytes into the circular window */
  23169. if (copy >= state.wsize) {
  23170. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  23171. state.wnext = 0;
  23172. state.whave = state.wsize;
  23173. }
  23174. else {
  23175. dist = state.wsize - state.wnext;
  23176. if (dist > copy) {
  23177. dist = copy;
  23178. }
  23179. //zmemcpy(state->window + state->wnext, end - copy, dist);
  23180. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  23181. copy -= dist;
  23182. if (copy) {
  23183. //zmemcpy(state->window, end - copy, copy);
  23184. utils.arraySet(state.window,src, end - copy, copy, 0);
  23185. state.wnext = copy;
  23186. state.whave = state.wsize;
  23187. }
  23188. else {
  23189. state.wnext += dist;
  23190. if (state.wnext === state.wsize) { state.wnext = 0; }
  23191. if (state.whave < state.wsize) { state.whave += dist; }
  23192. }
  23193. }
  23194. return 0;
  23195. }
  23196. function inflate(strm, flush) {
  23197. var state;
  23198. var input, output; // input/output buffers
  23199. var next; /* next input INDEX */
  23200. var put; /* next output INDEX */
  23201. var have, left; /* available input and output */
  23202. var hold; /* bit buffer */
  23203. var bits; /* bits in bit buffer */
  23204. var _in, _out; /* save starting available input and output */
  23205. var copy; /* number of stored or match bytes to copy */
  23206. var from; /* where to copy match bytes from */
  23207. var from_source;
  23208. var here = 0; /* current decoding table entry */
  23209. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  23210. //var last; /* parent table entry */
  23211. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  23212. var len; /* length to copy for repeats, bits to drop */
  23213. var ret; /* return code */
  23214. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  23215. var opts;
  23216. var n; // temporary var for NEED_BITS
  23217. var order = /* permutation of code lengths */
  23218. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  23219. if (!strm || !strm.state || !strm.output ||
  23220. (!strm.input && strm.avail_in !== 0)) {
  23221. return Z_STREAM_ERROR;
  23222. }
  23223. state = strm.state;
  23224. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  23225. //--- LOAD() ---
  23226. put = strm.next_out;
  23227. output = strm.output;
  23228. left = strm.avail_out;
  23229. next = strm.next_in;
  23230. input = strm.input;
  23231. have = strm.avail_in;
  23232. hold = state.hold;
  23233. bits = state.bits;
  23234. //---
  23235. _in = have;
  23236. _out = left;
  23237. ret = Z_OK;
  23238. inf_leave: // goto emulation
  23239. for (;;) {
  23240. switch (state.mode) {
  23241. case HEAD:
  23242. if (state.wrap === 0) {
  23243. state.mode = TYPEDO;
  23244. break;
  23245. }
  23246. //=== NEEDBITS(16);
  23247. while (bits < 16) {
  23248. if (have === 0) { break inf_leave; }
  23249. have--;
  23250. hold += input[next++] << bits;
  23251. bits += 8;
  23252. }
  23253. //===//
  23254. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  23255. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  23256. //=== CRC2(state.check, hold);
  23257. hbuf[0] = hold & 0xff;
  23258. hbuf[1] = (hold >>> 8) & 0xff;
  23259. state.check = crc32(state.check, hbuf, 2, 0);
  23260. //===//
  23261. //=== INITBITS();
  23262. hold = 0;
  23263. bits = 0;
  23264. //===//
  23265. state.mode = FLAGS;
  23266. break;
  23267. }
  23268. state.flags = 0; /* expect zlib header */
  23269. if (state.head) {
  23270. state.head.done = false;
  23271. }
  23272. if (!(state.wrap & 1) || /* check if zlib header allowed */
  23273. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  23274. strm.msg = 'incorrect header check';
  23275. state.mode = BAD;
  23276. break;
  23277. }
  23278. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  23279. strm.msg = 'unknown compression method';
  23280. state.mode = BAD;
  23281. break;
  23282. }
  23283. //--- DROPBITS(4) ---//
  23284. hold >>>= 4;
  23285. bits -= 4;
  23286. //---//
  23287. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23288. if (state.wbits === 0) {
  23289. state.wbits = len;
  23290. }
  23291. else if (len > state.wbits) {
  23292. strm.msg = 'invalid window size';
  23293. state.mode = BAD;
  23294. break;
  23295. }
  23296. state.dmax = 1 << len;
  23297. //Tracev((stderr, "inflate: zlib header ok\n"));
  23298. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23299. state.mode = hold & 0x200 ? DICTID : TYPE;
  23300. //=== INITBITS();
  23301. hold = 0;
  23302. bits = 0;
  23303. //===//
  23304. break;
  23305. case FLAGS:
  23306. //=== NEEDBITS(16); */
  23307. while (bits < 16) {
  23308. if (have === 0) { break inf_leave; }
  23309. have--;
  23310. hold += input[next++] << bits;
  23311. bits += 8;
  23312. }
  23313. //===//
  23314. state.flags = hold;
  23315. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23316. strm.msg = 'unknown compression method';
  23317. state.mode = BAD;
  23318. break;
  23319. }
  23320. if (state.flags & 0xe000) {
  23321. strm.msg = 'unknown header flags set';
  23322. state.mode = BAD;
  23323. break;
  23324. }
  23325. if (state.head) {
  23326. state.head.text = ((hold >> 8) & 1);
  23327. }
  23328. if (state.flags & 0x0200) {
  23329. //=== CRC2(state.check, hold);
  23330. hbuf[0] = hold & 0xff;
  23331. hbuf[1] = (hold >>> 8) & 0xff;
  23332. state.check = crc32(state.check, hbuf, 2, 0);
  23333. //===//
  23334. }
  23335. //=== INITBITS();
  23336. hold = 0;
  23337. bits = 0;
  23338. //===//
  23339. state.mode = TIME;
  23340. /* falls through */
  23341. case TIME:
  23342. //=== NEEDBITS(32); */
  23343. while (bits < 32) {
  23344. if (have === 0) { break inf_leave; }
  23345. have--;
  23346. hold += input[next++] << bits;
  23347. bits += 8;
  23348. }
  23349. //===//
  23350. if (state.head) {
  23351. state.head.time = hold;
  23352. }
  23353. if (state.flags & 0x0200) {
  23354. //=== CRC4(state.check, hold)
  23355. hbuf[0] = hold & 0xff;
  23356. hbuf[1] = (hold >>> 8) & 0xff;
  23357. hbuf[2] = (hold >>> 16) & 0xff;
  23358. hbuf[3] = (hold >>> 24) & 0xff;
  23359. state.check = crc32(state.check, hbuf, 4, 0);
  23360. //===
  23361. }
  23362. //=== INITBITS();
  23363. hold = 0;
  23364. bits = 0;
  23365. //===//
  23366. state.mode = OS;
  23367. /* falls through */
  23368. case OS:
  23369. //=== NEEDBITS(16); */
  23370. while (bits < 16) {
  23371. if (have === 0) { break inf_leave; }
  23372. have--;
  23373. hold += input[next++] << bits;
  23374. bits += 8;
  23375. }
  23376. //===//
  23377. if (state.head) {
  23378. state.head.xflags = (hold & 0xff);
  23379. state.head.os = (hold >> 8);
  23380. }
  23381. if (state.flags & 0x0200) {
  23382. //=== CRC2(state.check, hold);
  23383. hbuf[0] = hold & 0xff;
  23384. hbuf[1] = (hold >>> 8) & 0xff;
  23385. state.check = crc32(state.check, hbuf, 2, 0);
  23386. //===//
  23387. }
  23388. //=== INITBITS();
  23389. hold = 0;
  23390. bits = 0;
  23391. //===//
  23392. state.mode = EXLEN;
  23393. /* falls through */
  23394. case EXLEN:
  23395. if (state.flags & 0x0400) {
  23396. //=== NEEDBITS(16); */
  23397. while (bits < 16) {
  23398. if (have === 0) { break inf_leave; }
  23399. have--;
  23400. hold += input[next++] << bits;
  23401. bits += 8;
  23402. }
  23403. //===//
  23404. state.length = hold;
  23405. if (state.head) {
  23406. state.head.extra_len = hold;
  23407. }
  23408. if (state.flags & 0x0200) {
  23409. //=== CRC2(state.check, hold);
  23410. hbuf[0] = hold & 0xff;
  23411. hbuf[1] = (hold >>> 8) & 0xff;
  23412. state.check = crc32(state.check, hbuf, 2, 0);
  23413. //===//
  23414. }
  23415. //=== INITBITS();
  23416. hold = 0;
  23417. bits = 0;
  23418. //===//
  23419. }
  23420. else if (state.head) {
  23421. state.head.extra = null/*Z_NULL*/;
  23422. }
  23423. state.mode = EXTRA;
  23424. /* falls through */
  23425. case EXTRA:
  23426. if (state.flags & 0x0400) {
  23427. copy = state.length;
  23428. if (copy > have) { copy = have; }
  23429. if (copy) {
  23430. if (state.head) {
  23431. len = state.head.extra_len - state.length;
  23432. if (!state.head.extra) {
  23433. // Use untyped array for more conveniend processing later
  23434. state.head.extra = new Array(state.head.extra_len);
  23435. }
  23436. utils.arraySet(
  23437. state.head.extra,
  23438. input,
  23439. next,
  23440. // extra field is limited to 65536 bytes
  23441. // - no need for additional size check
  23442. copy,
  23443. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23444. len
  23445. );
  23446. //zmemcpy(state.head.extra + len, next,
  23447. // len + copy > state.head.extra_max ?
  23448. // state.head.extra_max - len : copy);
  23449. }
  23450. if (state.flags & 0x0200) {
  23451. state.check = crc32(state.check, input, copy, next);
  23452. }
  23453. have -= copy;
  23454. next += copy;
  23455. state.length -= copy;
  23456. }
  23457. if (state.length) { break inf_leave; }
  23458. }
  23459. state.length = 0;
  23460. state.mode = NAME;
  23461. /* falls through */
  23462. case NAME:
  23463. if (state.flags & 0x0800) {
  23464. if (have === 0) { break inf_leave; }
  23465. copy = 0;
  23466. do {
  23467. // TODO: 2 or 1 bytes?
  23468. len = input[next + copy++];
  23469. /* use constant limit because in js we should not preallocate memory */
  23470. if (state.head && len &&
  23471. (state.length < 65536 /*state.head.name_max*/)) {
  23472. state.head.name += String.fromCharCode(len);
  23473. }
  23474. } while (len && copy < have);
  23475. if (state.flags & 0x0200) {
  23476. state.check = crc32(state.check, input, copy, next);
  23477. }
  23478. have -= copy;
  23479. next += copy;
  23480. if (len) { break inf_leave; }
  23481. }
  23482. else if (state.head) {
  23483. state.head.name = null;
  23484. }
  23485. state.length = 0;
  23486. state.mode = COMMENT;
  23487. /* falls through */
  23488. case COMMENT:
  23489. if (state.flags & 0x1000) {
  23490. if (have === 0) { break inf_leave; }
  23491. copy = 0;
  23492. do {
  23493. len = input[next + copy++];
  23494. /* use constant limit because in js we should not preallocate memory */
  23495. if (state.head && len &&
  23496. (state.length < 65536 /*state.head.comm_max*/)) {
  23497. state.head.comment += String.fromCharCode(len);
  23498. }
  23499. } while (len && copy < have);
  23500. if (state.flags & 0x0200) {
  23501. state.check = crc32(state.check, input, copy, next);
  23502. }
  23503. have -= copy;
  23504. next += copy;
  23505. if (len) { break inf_leave; }
  23506. }
  23507. else if (state.head) {
  23508. state.head.comment = null;
  23509. }
  23510. state.mode = HCRC;
  23511. /* falls through */
  23512. case HCRC:
  23513. if (state.flags & 0x0200) {
  23514. //=== NEEDBITS(16); */
  23515. while (bits < 16) {
  23516. if (have === 0) { break inf_leave; }
  23517. have--;
  23518. hold += input[next++] << bits;
  23519. bits += 8;
  23520. }
  23521. //===//
  23522. if (hold !== (state.check & 0xffff)) {
  23523. strm.msg = 'header crc mismatch';
  23524. state.mode = BAD;
  23525. break;
  23526. }
  23527. //=== INITBITS();
  23528. hold = 0;
  23529. bits = 0;
  23530. //===//
  23531. }
  23532. if (state.head) {
  23533. state.head.hcrc = ((state.flags >> 9) & 1);
  23534. state.head.done = true;
  23535. }
  23536. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23537. state.mode = TYPE;
  23538. break;
  23539. case DICTID:
  23540. //=== NEEDBITS(32); */
  23541. while (bits < 32) {
  23542. if (have === 0) { break inf_leave; }
  23543. have--;
  23544. hold += input[next++] << bits;
  23545. bits += 8;
  23546. }
  23547. //===//
  23548. strm.adler = state.check = ZSWAP32(hold);
  23549. //=== INITBITS();
  23550. hold = 0;
  23551. bits = 0;
  23552. //===//
  23553. state.mode = DICT;
  23554. /* falls through */
  23555. case DICT:
  23556. if (state.havedict === 0) {
  23557. //--- RESTORE() ---
  23558. strm.next_out = put;
  23559. strm.avail_out = left;
  23560. strm.next_in = next;
  23561. strm.avail_in = have;
  23562. state.hold = hold;
  23563. state.bits = bits;
  23564. //---
  23565. return Z_NEED_DICT;
  23566. }
  23567. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23568. state.mode = TYPE;
  23569. /* falls through */
  23570. case TYPE:
  23571. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23572. /* falls through */
  23573. case TYPEDO:
  23574. if (state.last) {
  23575. //--- BYTEBITS() ---//
  23576. hold >>>= bits & 7;
  23577. bits -= bits & 7;
  23578. //---//
  23579. state.mode = CHECK;
  23580. break;
  23581. }
  23582. //=== NEEDBITS(3); */
  23583. while (bits < 3) {
  23584. if (have === 0) { break inf_leave; }
  23585. have--;
  23586. hold += input[next++] << bits;
  23587. bits += 8;
  23588. }
  23589. //===//
  23590. state.last = (hold & 0x01)/*BITS(1)*/;
  23591. //--- DROPBITS(1) ---//
  23592. hold >>>= 1;
  23593. bits -= 1;
  23594. //---//
  23595. switch ((hold & 0x03)/*BITS(2)*/) {
  23596. case 0: /* stored block */
  23597. //Tracev((stderr, "inflate: stored block%s\n",
  23598. // state.last ? " (last)" : ""));
  23599. state.mode = STORED;
  23600. break;
  23601. case 1: /* fixed block */
  23602. fixedtables(state);
  23603. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23604. // state.last ? " (last)" : ""));
  23605. state.mode = LEN_; /* decode codes */
  23606. if (flush === Z_TREES) {
  23607. //--- DROPBITS(2) ---//
  23608. hold >>>= 2;
  23609. bits -= 2;
  23610. //---//
  23611. break inf_leave;
  23612. }
  23613. break;
  23614. case 2: /* dynamic block */
  23615. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23616. // state.last ? " (last)" : ""));
  23617. state.mode = TABLE;
  23618. break;
  23619. case 3:
  23620. strm.msg = 'invalid block type';
  23621. state.mode = BAD;
  23622. }
  23623. //--- DROPBITS(2) ---//
  23624. hold >>>= 2;
  23625. bits -= 2;
  23626. //---//
  23627. break;
  23628. case STORED:
  23629. //--- BYTEBITS() ---// /* go to byte boundary */
  23630. hold >>>= bits & 7;
  23631. bits -= bits & 7;
  23632. //---//
  23633. //=== NEEDBITS(32); */
  23634. while (bits < 32) {
  23635. if (have === 0) { break inf_leave; }
  23636. have--;
  23637. hold += input[next++] << bits;
  23638. bits += 8;
  23639. }
  23640. //===//
  23641. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23642. strm.msg = 'invalid stored block lengths';
  23643. state.mode = BAD;
  23644. break;
  23645. }
  23646. state.length = hold & 0xffff;
  23647. //Tracev((stderr, "inflate: stored length %u\n",
  23648. // state.length));
  23649. //=== INITBITS();
  23650. hold = 0;
  23651. bits = 0;
  23652. //===//
  23653. state.mode = COPY_;
  23654. if (flush === Z_TREES) { break inf_leave; }
  23655. /* falls through */
  23656. case COPY_:
  23657. state.mode = COPY;
  23658. /* falls through */
  23659. case COPY:
  23660. copy = state.length;
  23661. if (copy) {
  23662. if (copy > have) { copy = have; }
  23663. if (copy > left) { copy = left; }
  23664. if (copy === 0) { break inf_leave; }
  23665. //--- zmemcpy(put, next, copy); ---
  23666. utils.arraySet(output, input, next, copy, put);
  23667. //---//
  23668. have -= copy;
  23669. next += copy;
  23670. left -= copy;
  23671. put += copy;
  23672. state.length -= copy;
  23673. break;
  23674. }
  23675. //Tracev((stderr, "inflate: stored end\n"));
  23676. state.mode = TYPE;
  23677. break;
  23678. case TABLE:
  23679. //=== NEEDBITS(14); */
  23680. while (bits < 14) {
  23681. if (have === 0) { break inf_leave; }
  23682. have--;
  23683. hold += input[next++] << bits;
  23684. bits += 8;
  23685. }
  23686. //===//
  23687. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23688. //--- DROPBITS(5) ---//
  23689. hold >>>= 5;
  23690. bits -= 5;
  23691. //---//
  23692. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23693. //--- DROPBITS(5) ---//
  23694. hold >>>= 5;
  23695. bits -= 5;
  23696. //---//
  23697. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23698. //--- DROPBITS(4) ---//
  23699. hold >>>= 4;
  23700. bits -= 4;
  23701. //---//
  23702. //#ifndef PKZIP_BUG_WORKAROUND
  23703. if (state.nlen > 286 || state.ndist > 30) {
  23704. strm.msg = 'too many length or distance symbols';
  23705. state.mode = BAD;
  23706. break;
  23707. }
  23708. //#endif
  23709. //Tracev((stderr, "inflate: table sizes ok\n"));
  23710. state.have = 0;
  23711. state.mode = LENLENS;
  23712. /* falls through */
  23713. case LENLENS:
  23714. while (state.have < state.ncode) {
  23715. //=== NEEDBITS(3);
  23716. while (bits < 3) {
  23717. if (have === 0) { break inf_leave; }
  23718. have--;
  23719. hold += input[next++] << bits;
  23720. bits += 8;
  23721. }
  23722. //===//
  23723. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23724. //--- DROPBITS(3) ---//
  23725. hold >>>= 3;
  23726. bits -= 3;
  23727. //---//
  23728. }
  23729. while (state.have < 19) {
  23730. state.lens[order[state.have++]] = 0;
  23731. }
  23732. // We have separate tables & no pointers. 2 commented lines below not needed.
  23733. //state.next = state.codes;
  23734. //state.lencode = state.next;
  23735. // Switch to use dynamic table
  23736. state.lencode = state.lendyn;
  23737. state.lenbits = 7;
  23738. opts = {bits: state.lenbits};
  23739. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23740. state.lenbits = opts.bits;
  23741. if (ret) {
  23742. strm.msg = 'invalid code lengths set';
  23743. state.mode = BAD;
  23744. break;
  23745. }
  23746. //Tracev((stderr, "inflate: code lengths ok\n"));
  23747. state.have = 0;
  23748. state.mode = CODELENS;
  23749. /* falls through */
  23750. case CODELENS:
  23751. while (state.have < state.nlen + state.ndist) {
  23752. for (;;) {
  23753. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23754. here_bits = here >>> 24;
  23755. here_op = (here >>> 16) & 0xff;
  23756. here_val = here & 0xffff;
  23757. if ((here_bits) <= bits) { break; }
  23758. //--- PULLBYTE() ---//
  23759. if (have === 0) { break inf_leave; }
  23760. have--;
  23761. hold += input[next++] << bits;
  23762. bits += 8;
  23763. //---//
  23764. }
  23765. if (here_val < 16) {
  23766. //--- DROPBITS(here.bits) ---//
  23767. hold >>>= here_bits;
  23768. bits -= here_bits;
  23769. //---//
  23770. state.lens[state.have++] = here_val;
  23771. }
  23772. else {
  23773. if (here_val === 16) {
  23774. //=== NEEDBITS(here.bits + 2);
  23775. n = here_bits + 2;
  23776. while (bits < n) {
  23777. if (have === 0) { break inf_leave; }
  23778. have--;
  23779. hold += input[next++] << bits;
  23780. bits += 8;
  23781. }
  23782. //===//
  23783. //--- DROPBITS(here.bits) ---//
  23784. hold >>>= here_bits;
  23785. bits -= here_bits;
  23786. //---//
  23787. if (state.have === 0) {
  23788. strm.msg = 'invalid bit length repeat';
  23789. state.mode = BAD;
  23790. break;
  23791. }
  23792. len = state.lens[state.have - 1];
  23793. copy = 3 + (hold & 0x03);//BITS(2);
  23794. //--- DROPBITS(2) ---//
  23795. hold >>>= 2;
  23796. bits -= 2;
  23797. //---//
  23798. }
  23799. else if (here_val === 17) {
  23800. //=== NEEDBITS(here.bits + 3);
  23801. n = here_bits + 3;
  23802. while (bits < n) {
  23803. if (have === 0) { break inf_leave; }
  23804. have--;
  23805. hold += input[next++] << bits;
  23806. bits += 8;
  23807. }
  23808. //===//
  23809. //--- DROPBITS(here.bits) ---//
  23810. hold >>>= here_bits;
  23811. bits -= here_bits;
  23812. //---//
  23813. len = 0;
  23814. copy = 3 + (hold & 0x07);//BITS(3);
  23815. //--- DROPBITS(3) ---//
  23816. hold >>>= 3;
  23817. bits -= 3;
  23818. //---//
  23819. }
  23820. else {
  23821. //=== NEEDBITS(here.bits + 7);
  23822. n = here_bits + 7;
  23823. while (bits < n) {
  23824. if (have === 0) { break inf_leave; }
  23825. have--;
  23826. hold += input[next++] << bits;
  23827. bits += 8;
  23828. }
  23829. //===//
  23830. //--- DROPBITS(here.bits) ---//
  23831. hold >>>= here_bits;
  23832. bits -= here_bits;
  23833. //---//
  23834. len = 0;
  23835. copy = 11 + (hold & 0x7f);//BITS(7);
  23836. //--- DROPBITS(7) ---//
  23837. hold >>>= 7;
  23838. bits -= 7;
  23839. //---//
  23840. }
  23841. if (state.have + copy > state.nlen + state.ndist) {
  23842. strm.msg = 'invalid bit length repeat';
  23843. state.mode = BAD;
  23844. break;
  23845. }
  23846. while (copy--) {
  23847. state.lens[state.have++] = len;
  23848. }
  23849. }
  23850. }
  23851. /* handle error breaks in while */
  23852. if (state.mode === BAD) { break; }
  23853. /* check for end-of-block code (better have one) */
  23854. if (state.lens[256] === 0) {
  23855. strm.msg = 'invalid code -- missing end-of-block';
  23856. state.mode = BAD;
  23857. break;
  23858. }
  23859. /* build code tables -- note: do not change the lenbits or distbits
  23860. values here (9 and 6) without reading the comments in inftrees.h
  23861. concerning the ENOUGH constants, which depend on those values */
  23862. state.lenbits = 9;
  23863. opts = {bits: state.lenbits};
  23864. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23865. // We have separate tables & no pointers. 2 commented lines below not needed.
  23866. // state.next_index = opts.table_index;
  23867. state.lenbits = opts.bits;
  23868. // state.lencode = state.next;
  23869. if (ret) {
  23870. strm.msg = 'invalid literal/lengths set';
  23871. state.mode = BAD;
  23872. break;
  23873. }
  23874. state.distbits = 6;
  23875. //state.distcode.copy(state.codes);
  23876. // Switch to use dynamic table
  23877. state.distcode = state.distdyn;
  23878. opts = {bits: state.distbits};
  23879. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23880. // We have separate tables & no pointers. 2 commented lines below not needed.
  23881. // state.next_index = opts.table_index;
  23882. state.distbits = opts.bits;
  23883. // state.distcode = state.next;
  23884. if (ret) {
  23885. strm.msg = 'invalid distances set';
  23886. state.mode = BAD;
  23887. break;
  23888. }
  23889. //Tracev((stderr, 'inflate: codes ok\n'));
  23890. state.mode = LEN_;
  23891. if (flush === Z_TREES) { break inf_leave; }
  23892. /* falls through */
  23893. case LEN_:
  23894. state.mode = LEN;
  23895. /* falls through */
  23896. case LEN:
  23897. if (have >= 6 && left >= 258) {
  23898. //--- RESTORE() ---
  23899. strm.next_out = put;
  23900. strm.avail_out = left;
  23901. strm.next_in = next;
  23902. strm.avail_in = have;
  23903. state.hold = hold;
  23904. state.bits = bits;
  23905. //---
  23906. inflate_fast(strm, _out);
  23907. //--- LOAD() ---
  23908. put = strm.next_out;
  23909. output = strm.output;
  23910. left = strm.avail_out;
  23911. next = strm.next_in;
  23912. input = strm.input;
  23913. have = strm.avail_in;
  23914. hold = state.hold;
  23915. bits = state.bits;
  23916. //---
  23917. if (state.mode === TYPE) {
  23918. state.back = -1;
  23919. }
  23920. break;
  23921. }
  23922. state.back = 0;
  23923. for (;;) {
  23924. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23925. here_bits = here >>> 24;
  23926. here_op = (here >>> 16) & 0xff;
  23927. here_val = here & 0xffff;
  23928. if (here_bits <= bits) { break; }
  23929. //--- PULLBYTE() ---//
  23930. if (have === 0) { break inf_leave; }
  23931. have--;
  23932. hold += input[next++] << bits;
  23933. bits += 8;
  23934. //---//
  23935. }
  23936. if (here_op && (here_op & 0xf0) === 0) {
  23937. last_bits = here_bits;
  23938. last_op = here_op;
  23939. last_val = here_val;
  23940. for (;;) {
  23941. here = state.lencode[last_val +
  23942. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23943. here_bits = here >>> 24;
  23944. here_op = (here >>> 16) & 0xff;
  23945. here_val = here & 0xffff;
  23946. if ((last_bits + here_bits) <= bits) { break; }
  23947. //--- PULLBYTE() ---//
  23948. if (have === 0) { break inf_leave; }
  23949. have--;
  23950. hold += input[next++] << bits;
  23951. bits += 8;
  23952. //---//
  23953. }
  23954. //--- DROPBITS(last.bits) ---//
  23955. hold >>>= last_bits;
  23956. bits -= last_bits;
  23957. //---//
  23958. state.back += last_bits;
  23959. }
  23960. //--- DROPBITS(here.bits) ---//
  23961. hold >>>= here_bits;
  23962. bits -= here_bits;
  23963. //---//
  23964. state.back += here_bits;
  23965. state.length = here_val;
  23966. if (here_op === 0) {
  23967. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23968. // "inflate: literal '%c'\n" :
  23969. // "inflate: literal 0x%02x\n", here.val));
  23970. state.mode = LIT;
  23971. break;
  23972. }
  23973. if (here_op & 32) {
  23974. //Tracevv((stderr, "inflate: end of block\n"));
  23975. state.back = -1;
  23976. state.mode = TYPE;
  23977. break;
  23978. }
  23979. if (here_op & 64) {
  23980. strm.msg = 'invalid literal/length code';
  23981. state.mode = BAD;
  23982. break;
  23983. }
  23984. state.extra = here_op & 15;
  23985. state.mode = LENEXT;
  23986. /* falls through */
  23987. case LENEXT:
  23988. if (state.extra) {
  23989. //=== NEEDBITS(state.extra);
  23990. n = state.extra;
  23991. while (bits < n) {
  23992. if (have === 0) { break inf_leave; }
  23993. have--;
  23994. hold += input[next++] << bits;
  23995. bits += 8;
  23996. }
  23997. //===//
  23998. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23999. //--- DROPBITS(state.extra) ---//
  24000. hold >>>= state.extra;
  24001. bits -= state.extra;
  24002. //---//
  24003. state.back += state.extra;
  24004. }
  24005. //Tracevv((stderr, "inflate: length %u\n", state.length));
  24006. state.was = state.length;
  24007. state.mode = DIST;
  24008. /* falls through */
  24009. case DIST:
  24010. for (;;) {
  24011. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  24012. here_bits = here >>> 24;
  24013. here_op = (here >>> 16) & 0xff;
  24014. here_val = here & 0xffff;
  24015. if ((here_bits) <= bits) { break; }
  24016. //--- PULLBYTE() ---//
  24017. if (have === 0) { break inf_leave; }
  24018. have--;
  24019. hold += input[next++] << bits;
  24020. bits += 8;
  24021. //---//
  24022. }
  24023. if ((here_op & 0xf0) === 0) {
  24024. last_bits = here_bits;
  24025. last_op = here_op;
  24026. last_val = here_val;
  24027. for (;;) {
  24028. here = state.distcode[last_val +
  24029. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  24030. here_bits = here >>> 24;
  24031. here_op = (here >>> 16) & 0xff;
  24032. here_val = here & 0xffff;
  24033. if ((last_bits + here_bits) <= bits) { break; }
  24034. //--- PULLBYTE() ---//
  24035. if (have === 0) { break inf_leave; }
  24036. have--;
  24037. hold += input[next++] << bits;
  24038. bits += 8;
  24039. //---//
  24040. }
  24041. //--- DROPBITS(last.bits) ---//
  24042. hold >>>= last_bits;
  24043. bits -= last_bits;
  24044. //---//
  24045. state.back += last_bits;
  24046. }
  24047. //--- DROPBITS(here.bits) ---//
  24048. hold >>>= here_bits;
  24049. bits -= here_bits;
  24050. //---//
  24051. state.back += here_bits;
  24052. if (here_op & 64) {
  24053. strm.msg = 'invalid distance code';
  24054. state.mode = BAD;
  24055. break;
  24056. }
  24057. state.offset = here_val;
  24058. state.extra = (here_op) & 15;
  24059. state.mode = DISTEXT;
  24060. /* falls through */
  24061. case DISTEXT:
  24062. if (state.extra) {
  24063. //=== NEEDBITS(state.extra);
  24064. n = state.extra;
  24065. while (bits < n) {
  24066. if (have === 0) { break inf_leave; }
  24067. have--;
  24068. hold += input[next++] << bits;
  24069. bits += 8;
  24070. }
  24071. //===//
  24072. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24073. //--- DROPBITS(state.extra) ---//
  24074. hold >>>= state.extra;
  24075. bits -= state.extra;
  24076. //---//
  24077. state.back += state.extra;
  24078. }
  24079. //#ifdef INFLATE_STRICT
  24080. if (state.offset > state.dmax) {
  24081. strm.msg = 'invalid distance too far back';
  24082. state.mode = BAD;
  24083. break;
  24084. }
  24085. //#endif
  24086. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  24087. state.mode = MATCH;
  24088. /* falls through */
  24089. case MATCH:
  24090. if (left === 0) { break inf_leave; }
  24091. copy = _out - left;
  24092. if (state.offset > copy) { /* copy from window */
  24093. copy = state.offset - copy;
  24094. if (copy > state.whave) {
  24095. if (state.sane) {
  24096. strm.msg = 'invalid distance too far back';
  24097. state.mode = BAD;
  24098. break;
  24099. }
  24100. // (!) This block is disabled in zlib defailts,
  24101. // don't enable it for binary compatibility
  24102. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  24103. // Trace((stderr, "inflate.c too far\n"));
  24104. // copy -= state.whave;
  24105. // if (copy > state.length) { copy = state.length; }
  24106. // if (copy > left) { copy = left; }
  24107. // left -= copy;
  24108. // state.length -= copy;
  24109. // do {
  24110. // output[put++] = 0;
  24111. // } while (--copy);
  24112. // if (state.length === 0) { state.mode = LEN; }
  24113. // break;
  24114. //#endif
  24115. }
  24116. if (copy > state.wnext) {
  24117. copy -= state.wnext;
  24118. from = state.wsize - copy;
  24119. }
  24120. else {
  24121. from = state.wnext - copy;
  24122. }
  24123. if (copy > state.length) { copy = state.length; }
  24124. from_source = state.window;
  24125. }
  24126. else { /* copy from output */
  24127. from_source = output;
  24128. from = put - state.offset;
  24129. copy = state.length;
  24130. }
  24131. if (copy > left) { copy = left; }
  24132. left -= copy;
  24133. state.length -= copy;
  24134. do {
  24135. output[put++] = from_source[from++];
  24136. } while (--copy);
  24137. if (state.length === 0) { state.mode = LEN; }
  24138. break;
  24139. case LIT:
  24140. if (left === 0) { break inf_leave; }
  24141. output[put++] = state.length;
  24142. left--;
  24143. state.mode = LEN;
  24144. break;
  24145. case CHECK:
  24146. if (state.wrap) {
  24147. //=== NEEDBITS(32);
  24148. while (bits < 32) {
  24149. if (have === 0) { break inf_leave; }
  24150. have--;
  24151. // Use '|' insdead of '+' to make sure that result is signed
  24152. hold |= input[next++] << bits;
  24153. bits += 8;
  24154. }
  24155. //===//
  24156. _out -= left;
  24157. strm.total_out += _out;
  24158. state.total += _out;
  24159. if (_out) {
  24160. strm.adler = state.check =
  24161. /*UPDATE(state.check, put - _out, _out);*/
  24162. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  24163. }
  24164. _out = left;
  24165. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  24166. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  24167. strm.msg = 'incorrect data check';
  24168. state.mode = BAD;
  24169. break;
  24170. }
  24171. //=== INITBITS();
  24172. hold = 0;
  24173. bits = 0;
  24174. //===//
  24175. //Tracev((stderr, "inflate: check matches trailer\n"));
  24176. }
  24177. state.mode = LENGTH;
  24178. /* falls through */
  24179. case LENGTH:
  24180. if (state.wrap && state.flags) {
  24181. //=== NEEDBITS(32);
  24182. while (bits < 32) {
  24183. if (have === 0) { break inf_leave; }
  24184. have--;
  24185. hold += input[next++] << bits;
  24186. bits += 8;
  24187. }
  24188. //===//
  24189. if (hold !== (state.total & 0xffffffff)) {
  24190. strm.msg = 'incorrect length check';
  24191. state.mode = BAD;
  24192. break;
  24193. }
  24194. //=== INITBITS();
  24195. hold = 0;
  24196. bits = 0;
  24197. //===//
  24198. //Tracev((stderr, "inflate: length matches trailer\n"));
  24199. }
  24200. state.mode = DONE;
  24201. /* falls through */
  24202. case DONE:
  24203. ret = Z_STREAM_END;
  24204. break inf_leave;
  24205. case BAD:
  24206. ret = Z_DATA_ERROR;
  24207. break inf_leave;
  24208. case MEM:
  24209. return Z_MEM_ERROR;
  24210. case SYNC:
  24211. /* falls through */
  24212. default:
  24213. return Z_STREAM_ERROR;
  24214. }
  24215. }
  24216. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  24217. /*
  24218. Return from inflate(), updating the total counts and the check value.
  24219. If there was no progress during the inflate() call, return a buffer
  24220. error. Call updatewindow() to create and/or update the window state.
  24221. Note: a memory error from inflate() is non-recoverable.
  24222. */
  24223. //--- RESTORE() ---
  24224. strm.next_out = put;
  24225. strm.avail_out = left;
  24226. strm.next_in = next;
  24227. strm.avail_in = have;
  24228. state.hold = hold;
  24229. state.bits = bits;
  24230. //---
  24231. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  24232. (state.mode < CHECK || flush !== Z_FINISH))) {
  24233. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  24234. state.mode = MEM;
  24235. return Z_MEM_ERROR;
  24236. }
  24237. }
  24238. _in -= strm.avail_in;
  24239. _out -= strm.avail_out;
  24240. strm.total_in += _in;
  24241. strm.total_out += _out;
  24242. state.total += _out;
  24243. if (state.wrap && _out) {
  24244. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  24245. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  24246. }
  24247. strm.data_type = state.bits + (state.last ? 64 : 0) +
  24248. (state.mode === TYPE ? 128 : 0) +
  24249. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  24250. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  24251. ret = Z_BUF_ERROR;
  24252. }
  24253. return ret;
  24254. }
  24255. function inflateEnd(strm) {
  24256. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  24257. return Z_STREAM_ERROR;
  24258. }
  24259. var state = strm.state;
  24260. if (state.window) {
  24261. state.window = null;
  24262. }
  24263. strm.state = null;
  24264. return Z_OK;
  24265. }
  24266. function inflateGetHeader(strm, head) {
  24267. var state;
  24268. /* check state */
  24269. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  24270. state = strm.state;
  24271. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  24272. /* save header structure */
  24273. state.head = head;
  24274. head.done = false;
  24275. return Z_OK;
  24276. }
  24277. exports.inflateReset = inflateReset;
  24278. exports.inflateReset2 = inflateReset2;
  24279. exports.inflateResetKeep = inflateResetKeep;
  24280. exports.inflateInit = inflateInit;
  24281. exports.inflateInit2 = inflateInit2;
  24282. exports.inflate = inflate;
  24283. exports.inflateEnd = inflateEnd;
  24284. exports.inflateGetHeader = inflateGetHeader;
  24285. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24286. /* Not implemented
  24287. exports.inflateCopy = inflateCopy;
  24288. exports.inflateGetDictionary = inflateGetDictionary;
  24289. exports.inflateMark = inflateMark;
  24290. exports.inflatePrime = inflatePrime;
  24291. exports.inflateSetDictionary = inflateSetDictionary;
  24292. exports.inflateSync = inflateSync;
  24293. exports.inflateSyncPoint = inflateSyncPoint;
  24294. exports.inflateUndermine = inflateUndermine;
  24295. */
  24296. },{"../utils/common":78,"./adler32":80,"./crc32":82,"./inffast":85,"./inftrees":87}],87:[function(require,module,exports){
  24297. 'use strict';
  24298. var utils = require('../utils/common');
  24299. var MAXBITS = 15;
  24300. var ENOUGH_LENS = 852;
  24301. var ENOUGH_DISTS = 592;
  24302. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24303. var CODES = 0;
  24304. var LENS = 1;
  24305. var DISTS = 2;
  24306. var lbase = [ /* Length codes 257..285 base */
  24307. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24308. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24309. ];
  24310. var lext = [ /* Length codes 257..285 extra */
  24311. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24312. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24313. ];
  24314. var dbase = [ /* Distance codes 0..29 base */
  24315. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24316. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24317. 8193, 12289, 16385, 24577, 0, 0
  24318. ];
  24319. var dext = [ /* Distance codes 0..29 extra */
  24320. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24321. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24322. 28, 28, 29, 29, 64, 64
  24323. ];
  24324. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24325. {
  24326. var bits = opts.bits;
  24327. //here = opts.here; /* table entry for duplication */
  24328. var len = 0; /* a code's length in bits */
  24329. var sym = 0; /* index of code symbols */
  24330. var min = 0, max = 0; /* minimum and maximum code lengths */
  24331. var root = 0; /* number of index bits for root table */
  24332. var curr = 0; /* number of index bits for current table */
  24333. var drop = 0; /* code bits to drop for sub-table */
  24334. var left = 0; /* number of prefix codes available */
  24335. var used = 0; /* code entries in table used */
  24336. var huff = 0; /* Huffman code */
  24337. var incr; /* for incrementing code, index */
  24338. var fill; /* index for replicating entries */
  24339. var low; /* low bits for current root entry */
  24340. var mask; /* mask for low root bits */
  24341. var next; /* next available space in table */
  24342. var base = null; /* base value table to use */
  24343. var base_index = 0;
  24344. // var shoextra; /* extra bits table to use */
  24345. var end; /* use base and extra for symbol > end */
  24346. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24347. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24348. var extra = null;
  24349. var extra_index = 0;
  24350. var here_bits, here_op, here_val;
  24351. /*
  24352. Process a set of code lengths to create a canonical Huffman code. The
  24353. code lengths are lens[0..codes-1]. Each length corresponds to the
  24354. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24355. symbols by length from short to long, and retaining the symbol order
  24356. for codes with equal lengths. Then the code starts with all zero bits
  24357. for the first code of the shortest length, and the codes are integer
  24358. increments for the same length, and zeros are appended as the length
  24359. increases. For the deflate format, these bits are stored backwards
  24360. from their more natural integer increment ordering, and so when the
  24361. decoding tables are built in the large loop below, the integer codes
  24362. are incremented backwards.
  24363. This routine assumes, but does not check, that all of the entries in
  24364. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24365. 1..MAXBITS is interpreted as that code length. zero means that that
  24366. symbol does not occur in this code.
  24367. The codes are sorted by computing a count of codes for each length,
  24368. creating from that a table of starting indices for each length in the
  24369. sorted table, and then entering the symbols in order in the sorted
  24370. table. The sorted table is work[], with that space being provided by
  24371. the caller.
  24372. The length counts are used for other purposes as well, i.e. finding
  24373. the minimum and maximum length codes, determining if there are any
  24374. codes at all, checking for a valid set of lengths, and looking ahead
  24375. at length counts to determine sub-table sizes when building the
  24376. decoding tables.
  24377. */
  24378. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24379. for (len = 0; len <= MAXBITS; len++) {
  24380. count[len] = 0;
  24381. }
  24382. for (sym = 0; sym < codes; sym++) {
  24383. count[lens[lens_index + sym]]++;
  24384. }
  24385. /* bound code lengths, force root to be within code lengths */
  24386. root = bits;
  24387. for (max = MAXBITS; max >= 1; max--) {
  24388. if (count[max] !== 0) { break; }
  24389. }
  24390. if (root > max) {
  24391. root = max;
  24392. }
  24393. if (max === 0) { /* no symbols to code at all */
  24394. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24395. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24396. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24397. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24398. //table.op[opts.table_index] = 64;
  24399. //table.bits[opts.table_index] = 1;
  24400. //table.val[opts.table_index++] = 0;
  24401. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24402. opts.bits = 1;
  24403. return 0; /* no symbols, but wait for decoding to report error */
  24404. }
  24405. for (min = 1; min < max; min++) {
  24406. if (count[min] !== 0) { break; }
  24407. }
  24408. if (root < min) {
  24409. root = min;
  24410. }
  24411. /* check for an over-subscribed or incomplete set of lengths */
  24412. left = 1;
  24413. for (len = 1; len <= MAXBITS; len++) {
  24414. left <<= 1;
  24415. left -= count[len];
  24416. if (left < 0) {
  24417. return -1;
  24418. } /* over-subscribed */
  24419. }
  24420. if (left > 0 && (type === CODES || max !== 1)) {
  24421. return -1; /* incomplete set */
  24422. }
  24423. /* generate offsets into symbol table for each length for sorting */
  24424. offs[1] = 0;
  24425. for (len = 1; len < MAXBITS; len++) {
  24426. offs[len + 1] = offs[len] + count[len];
  24427. }
  24428. /* sort symbols by length, by symbol order within each length */
  24429. for (sym = 0; sym < codes; sym++) {
  24430. if (lens[lens_index + sym] !== 0) {
  24431. work[offs[lens[lens_index + sym]]++] = sym;
  24432. }
  24433. }
  24434. /*
  24435. Create and fill in decoding tables. In this loop, the table being
  24436. filled is at next and has curr index bits. The code being used is huff
  24437. with length len. That code is converted to an index by dropping drop
  24438. bits off of the bottom. For codes where len is less than drop + curr,
  24439. those top drop + curr - len bits are incremented through all values to
  24440. fill the table with replicated entries.
  24441. root is the number of index bits for the root table. When len exceeds
  24442. root, sub-tables are created pointed to by the root entry with an index
  24443. of the low root bits of huff. This is saved in low to check for when a
  24444. new sub-table should be started. drop is zero when the root table is
  24445. being filled, and drop is root when sub-tables are being filled.
  24446. When a new sub-table is needed, it is necessary to look ahead in the
  24447. code lengths to determine what size sub-table is needed. The length
  24448. counts are used for this, and so count[] is decremented as codes are
  24449. entered in the tables.
  24450. used keeps track of how many table entries have been allocated from the
  24451. provided *table space. It is checked for LENS and DIST tables against
  24452. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24453. the initial root table size constants. See the comments in inftrees.h
  24454. for more information.
  24455. sym increments through all symbols, and the loop terminates when
  24456. all codes of length max, i.e. all codes, have been processed. This
  24457. routine permits incomplete codes, so another loop after this one fills
  24458. in the rest of the decoding tables with invalid code markers.
  24459. */
  24460. /* set up for code type */
  24461. // poor man optimization - use if-else instead of switch,
  24462. // to avoid deopts in old v8
  24463. if (type === CODES) {
  24464. base = extra = work; /* dummy value--not used */
  24465. end = 19;
  24466. } else if (type === LENS) {
  24467. base = lbase;
  24468. base_index -= 257;
  24469. extra = lext;
  24470. extra_index -= 257;
  24471. end = 256;
  24472. } else { /* DISTS */
  24473. base = dbase;
  24474. extra = dext;
  24475. end = -1;
  24476. }
  24477. /* initialize opts for loop */
  24478. huff = 0; /* starting code */
  24479. sym = 0; /* starting code symbol */
  24480. len = min; /* starting code length */
  24481. next = table_index; /* current table to fill in */
  24482. curr = root; /* current table index bits */
  24483. drop = 0; /* current bits to drop from code for index */
  24484. low = -1; /* trigger new sub-table when len > root */
  24485. used = 1 << root; /* use root table entries */
  24486. mask = used - 1; /* mask for comparing low */
  24487. /* check available table space */
  24488. if ((type === LENS && used > ENOUGH_LENS) ||
  24489. (type === DISTS && used > ENOUGH_DISTS)) {
  24490. return 1;
  24491. }
  24492. var i=0;
  24493. /* process all codes and make table entries */
  24494. for (;;) {
  24495. i++;
  24496. /* create table entry */
  24497. here_bits = len - drop;
  24498. if (work[sym] < end) {
  24499. here_op = 0;
  24500. here_val = work[sym];
  24501. }
  24502. else if (work[sym] > end) {
  24503. here_op = extra[extra_index + work[sym]];
  24504. here_val = base[base_index + work[sym]];
  24505. }
  24506. else {
  24507. here_op = 32 + 64; /* end of block */
  24508. here_val = 0;
  24509. }
  24510. /* replicate for those indices with low len bits equal to huff */
  24511. incr = 1 << (len - drop);
  24512. fill = 1 << curr;
  24513. min = fill; /* save offset to next table */
  24514. do {
  24515. fill -= incr;
  24516. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24517. } while (fill !== 0);
  24518. /* backwards increment the len-bit code huff */
  24519. incr = 1 << (len - 1);
  24520. while (huff & incr) {
  24521. incr >>= 1;
  24522. }
  24523. if (incr !== 0) {
  24524. huff &= incr - 1;
  24525. huff += incr;
  24526. } else {
  24527. huff = 0;
  24528. }
  24529. /* go to next symbol, update count, len */
  24530. sym++;
  24531. if (--count[len] === 0) {
  24532. if (len === max) { break; }
  24533. len = lens[lens_index + work[sym]];
  24534. }
  24535. /* create new sub-table if needed */
  24536. if (len > root && (huff & mask) !== low) {
  24537. /* if first time, transition to sub-tables */
  24538. if (drop === 0) {
  24539. drop = root;
  24540. }
  24541. /* increment past last table */
  24542. next += min; /* here min is 1 << curr */
  24543. /* determine length of next table */
  24544. curr = len - drop;
  24545. left = 1 << curr;
  24546. while (curr + drop < max) {
  24547. left -= count[curr + drop];
  24548. if (left <= 0) { break; }
  24549. curr++;
  24550. left <<= 1;
  24551. }
  24552. /* check for enough space */
  24553. used += 1 << curr;
  24554. if ((type === LENS && used > ENOUGH_LENS) ||
  24555. (type === DISTS && used > ENOUGH_DISTS)) {
  24556. return 1;
  24557. }
  24558. /* point entry in root table to sub-table */
  24559. low = huff & mask;
  24560. /*table.op[low] = curr;
  24561. table.bits[low] = root;
  24562. table.val[low] = next - opts.table_index;*/
  24563. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24564. }
  24565. }
  24566. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24567. at most one remaining entry, since if the code is incomplete, the
  24568. maximum code length that was allowed to get this far is one bit) */
  24569. if (huff !== 0) {
  24570. //table.op[next + huff] = 64; /* invalid code marker */
  24571. //table.bits[next + huff] = len - drop;
  24572. //table.val[next + huff] = 0;
  24573. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24574. }
  24575. /* set return parameters */
  24576. //opts.table_index += used;
  24577. opts.bits = root;
  24578. return 0;
  24579. };
  24580. },{"../utils/common":78}],88:[function(require,module,exports){
  24581. 'use strict';
  24582. module.exports = {
  24583. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24584. '1': 'stream end', /* Z_STREAM_END 1 */
  24585. '0': '', /* Z_OK 0 */
  24586. '-1': 'file error', /* Z_ERRNO (-1) */
  24587. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24588. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24589. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24590. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24591. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24592. };
  24593. },{}],89:[function(require,module,exports){
  24594. 'use strict';
  24595. var utils = require('../utils/common');
  24596. /* Public constants ==========================================================*/
  24597. /* ===========================================================================*/
  24598. //var Z_FILTERED = 1;
  24599. //var Z_HUFFMAN_ONLY = 2;
  24600. //var Z_RLE = 3;
  24601. var Z_FIXED = 4;
  24602. //var Z_DEFAULT_STRATEGY = 0;
  24603. /* Possible values of the data_type field (though see inflate()) */
  24604. var Z_BINARY = 0;
  24605. var Z_TEXT = 1;
  24606. //var Z_ASCII = 1; // = Z_TEXT
  24607. var Z_UNKNOWN = 2;
  24608. /*============================================================================*/
  24609. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24610. // From zutil.h
  24611. var STORED_BLOCK = 0;
  24612. var STATIC_TREES = 1;
  24613. var DYN_TREES = 2;
  24614. /* The three kinds of block type */
  24615. var MIN_MATCH = 3;
  24616. var MAX_MATCH = 258;
  24617. /* The minimum and maximum match lengths */
  24618. // From deflate.h
  24619. /* ===========================================================================
  24620. * Internal compression state.
  24621. */
  24622. var LENGTH_CODES = 29;
  24623. /* number of length codes, not counting the special END_BLOCK code */
  24624. var LITERALS = 256;
  24625. /* number of literal bytes 0..255 */
  24626. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24627. /* number of Literal or Length codes, including the END_BLOCK code */
  24628. var D_CODES = 30;
  24629. /* number of distance codes */
  24630. var BL_CODES = 19;
  24631. /* number of codes used to transfer the bit lengths */
  24632. var HEAP_SIZE = 2*L_CODES + 1;
  24633. /* maximum heap size */
  24634. var MAX_BITS = 15;
  24635. /* All codes must not exceed MAX_BITS bits */
  24636. var Buf_size = 16;
  24637. /* size of bit buffer in bi_buf */
  24638. /* ===========================================================================
  24639. * Constants
  24640. */
  24641. var MAX_BL_BITS = 7;
  24642. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24643. var END_BLOCK = 256;
  24644. /* end of block literal code */
  24645. var REP_3_6 = 16;
  24646. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24647. var REPZ_3_10 = 17;
  24648. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24649. var REPZ_11_138 = 18;
  24650. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24651. var extra_lbits = /* extra bits for each length code */
  24652. [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];
  24653. var extra_dbits = /* extra bits for each distance code */
  24654. [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];
  24655. var extra_blbits = /* extra bits for each bit length code */
  24656. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24657. var bl_order =
  24658. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24659. /* The lengths of the bit length codes are sent in order of decreasing
  24660. * probability, to avoid transmitting the lengths for unused bit length codes.
  24661. */
  24662. /* ===========================================================================
  24663. * Local data. These are initialized only once.
  24664. */
  24665. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24666. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24667. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24668. var static_ltree = new Array((L_CODES+2) * 2);
  24669. zero(static_ltree);
  24670. /* The static literal tree. Since the bit lengths are imposed, there is no
  24671. * need for the L_CODES extra codes used during heap construction. However
  24672. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24673. * below).
  24674. */
  24675. var static_dtree = new Array(D_CODES * 2);
  24676. zero(static_dtree);
  24677. /* The static distance tree. (Actually a trivial tree since all codes use
  24678. * 5 bits.)
  24679. */
  24680. var _dist_code = new Array(DIST_CODE_LEN);
  24681. zero(_dist_code);
  24682. /* Distance codes. The first 256 values correspond to the distances
  24683. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24684. * the 15 bit distances.
  24685. */
  24686. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24687. zero(_length_code);
  24688. /* length code for each normalized match length (0 == MIN_MATCH) */
  24689. var base_length = new Array(LENGTH_CODES);
  24690. zero(base_length);
  24691. /* First normalized length for each code (0 = MIN_MATCH) */
  24692. var base_dist = new Array(D_CODES);
  24693. zero(base_dist);
  24694. /* First normalized distance for each code (0 = distance of 1) */
  24695. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24696. this.static_tree = static_tree; /* static tree or NULL */
  24697. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24698. this.extra_base = extra_base; /* base index for extra_bits */
  24699. this.elems = elems; /* max number of elements in the tree */
  24700. this.max_length = max_length; /* max bit length for the codes */
  24701. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24702. this.has_stree = static_tree && static_tree.length;
  24703. };
  24704. var static_l_desc;
  24705. var static_d_desc;
  24706. var static_bl_desc;
  24707. var TreeDesc = function(dyn_tree, stat_desc) {
  24708. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24709. this.max_code = 0; /* largest code with non zero frequency */
  24710. this.stat_desc = stat_desc; /* the corresponding static tree */
  24711. };
  24712. function d_code(dist) {
  24713. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24714. }
  24715. /* ===========================================================================
  24716. * Output a short LSB first on the stream.
  24717. * IN assertion: there is enough room in pendingBuf.
  24718. */
  24719. function put_short (s, w) {
  24720. // put_byte(s, (uch)((w) & 0xff));
  24721. // put_byte(s, (uch)((ush)(w) >> 8));
  24722. s.pending_buf[s.pending++] = (w) & 0xff;
  24723. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24724. }
  24725. /* ===========================================================================
  24726. * Send a value on a given number of bits.
  24727. * IN assertion: length <= 16 and value fits in length bits.
  24728. */
  24729. function send_bits(s, value, length) {
  24730. if (s.bi_valid > (Buf_size - length)) {
  24731. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24732. put_short(s, s.bi_buf);
  24733. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24734. s.bi_valid += length - Buf_size;
  24735. } else {
  24736. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24737. s.bi_valid += length;
  24738. }
  24739. }
  24740. function send_code(s, c, tree) {
  24741. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24742. }
  24743. /* ===========================================================================
  24744. * Reverse the first len bits of a code, using straightforward code (a faster
  24745. * method would use a table)
  24746. * IN assertion: 1 <= len <= 15
  24747. */
  24748. function bi_reverse(code, len) {
  24749. var res = 0;
  24750. do {
  24751. res |= code & 1;
  24752. code >>>= 1;
  24753. res <<= 1;
  24754. } while (--len > 0);
  24755. return res >>> 1;
  24756. }
  24757. /* ===========================================================================
  24758. * Flush the bit buffer, keeping at most 7 bits in it.
  24759. */
  24760. function bi_flush(s) {
  24761. if (s.bi_valid === 16) {
  24762. put_short(s, s.bi_buf);
  24763. s.bi_buf = 0;
  24764. s.bi_valid = 0;
  24765. } else if (s.bi_valid >= 8) {
  24766. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24767. s.bi_buf >>= 8;
  24768. s.bi_valid -= 8;
  24769. }
  24770. }
  24771. /* ===========================================================================
  24772. * Compute the optimal bit lengths for a tree and update the total bit length
  24773. * for the current block.
  24774. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24775. * above are the tree nodes sorted by increasing frequency.
  24776. * OUT assertions: the field len is set to the optimal bit length, the
  24777. * array bl_count contains the frequencies for each bit length.
  24778. * The length opt_len is updated; static_len is also updated if stree is
  24779. * not null.
  24780. */
  24781. function gen_bitlen(s, desc)
  24782. // deflate_state *s;
  24783. // tree_desc *desc; /* the tree descriptor */
  24784. {
  24785. var tree = desc.dyn_tree;
  24786. var max_code = desc.max_code;
  24787. var stree = desc.stat_desc.static_tree;
  24788. var has_stree = desc.stat_desc.has_stree;
  24789. var extra = desc.stat_desc.extra_bits;
  24790. var base = desc.stat_desc.extra_base;
  24791. var max_length = desc.stat_desc.max_length;
  24792. var h; /* heap index */
  24793. var n, m; /* iterate over the tree elements */
  24794. var bits; /* bit length */
  24795. var xbits; /* extra bits */
  24796. var f; /* frequency */
  24797. var overflow = 0; /* number of elements with bit length too large */
  24798. for (bits = 0; bits <= MAX_BITS; bits++) {
  24799. s.bl_count[bits] = 0;
  24800. }
  24801. /* In a first pass, compute the optimal bit lengths (which may
  24802. * overflow in the case of the bit length tree).
  24803. */
  24804. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24805. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24806. n = s.heap[h];
  24807. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24808. if (bits > max_length) {
  24809. bits = max_length;
  24810. overflow++;
  24811. }
  24812. tree[n*2 + 1]/*.Len*/ = bits;
  24813. /* We overwrite tree[n].Dad which is no longer needed */
  24814. if (n > max_code) { continue; } /* not a leaf node */
  24815. s.bl_count[bits]++;
  24816. xbits = 0;
  24817. if (n >= base) {
  24818. xbits = extra[n-base];
  24819. }
  24820. f = tree[n * 2]/*.Freq*/;
  24821. s.opt_len += f * (bits + xbits);
  24822. if (has_stree) {
  24823. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24824. }
  24825. }
  24826. if (overflow === 0) { return; }
  24827. // Trace((stderr,"\nbit length overflow\n"));
  24828. /* This happens for example on obj2 and pic of the Calgary corpus */
  24829. /* Find the first bit length which could increase: */
  24830. do {
  24831. bits = max_length-1;
  24832. while (s.bl_count[bits] === 0) { bits--; }
  24833. s.bl_count[bits]--; /* move one leaf down the tree */
  24834. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24835. s.bl_count[max_length]--;
  24836. /* The brother of the overflow item also moves one step up,
  24837. * but this does not affect bl_count[max_length]
  24838. */
  24839. overflow -= 2;
  24840. } while (overflow > 0);
  24841. /* Now recompute all bit lengths, scanning in increasing frequency.
  24842. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24843. * lengths instead of fixing only the wrong ones. This idea is taken
  24844. * from 'ar' written by Haruhiko Okumura.)
  24845. */
  24846. for (bits = max_length; bits !== 0; bits--) {
  24847. n = s.bl_count[bits];
  24848. while (n !== 0) {
  24849. m = s.heap[--h];
  24850. if (m > max_code) { continue; }
  24851. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24852. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24853. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24854. tree[m*2 + 1]/*.Len*/ = bits;
  24855. }
  24856. n--;
  24857. }
  24858. }
  24859. }
  24860. /* ===========================================================================
  24861. * Generate the codes for a given tree and bit counts (which need not be
  24862. * optimal).
  24863. * IN assertion: the array bl_count contains the bit length statistics for
  24864. * the given tree and the field len is set for all tree elements.
  24865. * OUT assertion: the field code is set for all tree elements of non
  24866. * zero code length.
  24867. */
  24868. function gen_codes(tree, max_code, bl_count)
  24869. // ct_data *tree; /* the tree to decorate */
  24870. // int max_code; /* largest code with non zero frequency */
  24871. // ushf *bl_count; /* number of codes at each bit length */
  24872. {
  24873. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24874. var code = 0; /* running code value */
  24875. var bits; /* bit index */
  24876. var n; /* code index */
  24877. /* The distribution counts are first used to generate the code values
  24878. * without bit reversal.
  24879. */
  24880. for (bits = 1; bits <= MAX_BITS; bits++) {
  24881. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24882. }
  24883. /* Check that the bit counts in bl_count are consistent. The last code
  24884. * must be all ones.
  24885. */
  24886. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24887. // "inconsistent bit counts");
  24888. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24889. for (n = 0; n <= max_code; n++) {
  24890. var len = tree[n*2 + 1]/*.Len*/;
  24891. if (len === 0) { continue; }
  24892. /* Now reverse the bits */
  24893. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24894. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24895. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24896. }
  24897. }
  24898. /* ===========================================================================
  24899. * Initialize the various 'constant' tables.
  24900. */
  24901. function tr_static_init() {
  24902. var n; /* iterates over tree elements */
  24903. var bits; /* bit counter */
  24904. var length; /* length value */
  24905. var code; /* code value */
  24906. var dist; /* distance index */
  24907. var bl_count = new Array(MAX_BITS+1);
  24908. /* number of codes at each bit length for an optimal tree */
  24909. // do check in _tr_init()
  24910. //if (static_init_done) return;
  24911. /* For some embedded targets, global variables are not initialized: */
  24912. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24913. static_l_desc.static_tree = static_ltree;
  24914. static_l_desc.extra_bits = extra_lbits;
  24915. static_d_desc.static_tree = static_dtree;
  24916. static_d_desc.extra_bits = extra_dbits;
  24917. static_bl_desc.extra_bits = extra_blbits;
  24918. #endif*/
  24919. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24920. length = 0;
  24921. for (code = 0; code < LENGTH_CODES-1; code++) {
  24922. base_length[code] = length;
  24923. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24924. _length_code[length++] = code;
  24925. }
  24926. }
  24927. //Assert (length == 256, "tr_static_init: length != 256");
  24928. /* Note that the length 255 (match length 258) can be represented
  24929. * in two different ways: code 284 + 5 bits or code 285, so we
  24930. * overwrite length_code[255] to use the best encoding:
  24931. */
  24932. _length_code[length-1] = code;
  24933. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24934. dist = 0;
  24935. for (code = 0 ; code < 16; code++) {
  24936. base_dist[code] = dist;
  24937. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24938. _dist_code[dist++] = code;
  24939. }
  24940. }
  24941. //Assert (dist == 256, "tr_static_init: dist != 256");
  24942. dist >>= 7; /* from now on, all distances are divided by 128 */
  24943. for (; code < D_CODES; code++) {
  24944. base_dist[code] = dist << 7;
  24945. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24946. _dist_code[256 + dist++] = code;
  24947. }
  24948. }
  24949. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24950. /* Construct the codes of the static literal tree */
  24951. for (bits = 0; bits <= MAX_BITS; bits++) {
  24952. bl_count[bits] = 0;
  24953. }
  24954. n = 0;
  24955. while (n <= 143) {
  24956. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24957. n++;
  24958. bl_count[8]++;
  24959. }
  24960. while (n <= 255) {
  24961. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24962. n++;
  24963. bl_count[9]++;
  24964. }
  24965. while (n <= 279) {
  24966. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24967. n++;
  24968. bl_count[7]++;
  24969. }
  24970. while (n <= 287) {
  24971. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24972. n++;
  24973. bl_count[8]++;
  24974. }
  24975. /* Codes 286 and 287 do not exist, but we must include them in the
  24976. * tree construction to get a canonical Huffman tree (longest code
  24977. * all ones)
  24978. */
  24979. gen_codes(static_ltree, L_CODES+1, bl_count);
  24980. /* The static distance tree is trivial: */
  24981. for (n = 0; n < D_CODES; n++) {
  24982. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24983. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24984. }
  24985. // Now data ready and we can init static trees
  24986. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24987. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24988. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24989. //static_init_done = true;
  24990. }
  24991. /* ===========================================================================
  24992. * Initialize a new block.
  24993. */
  24994. function init_block(s) {
  24995. var n; /* iterates over tree elements */
  24996. /* Initialize the trees. */
  24997. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24998. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24999. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  25000. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  25001. s.opt_len = s.static_len = 0;
  25002. s.last_lit = s.matches = 0;
  25003. }
  25004. /* ===========================================================================
  25005. * Flush the bit buffer and align the output on a byte boundary
  25006. */
  25007. function bi_windup(s)
  25008. {
  25009. if (s.bi_valid > 8) {
  25010. put_short(s, s.bi_buf);
  25011. } else if (s.bi_valid > 0) {
  25012. //put_byte(s, (Byte)s->bi_buf);
  25013. s.pending_buf[s.pending++] = s.bi_buf;
  25014. }
  25015. s.bi_buf = 0;
  25016. s.bi_valid = 0;
  25017. }
  25018. /* ===========================================================================
  25019. * Copy a stored block, storing first the length and its
  25020. * one's complement if requested.
  25021. */
  25022. function copy_block(s, buf, len, header)
  25023. //DeflateState *s;
  25024. //charf *buf; /* the input data */
  25025. //unsigned len; /* its length */
  25026. //int header; /* true if block header must be written */
  25027. {
  25028. bi_windup(s); /* align on byte boundary */
  25029. if (header) {
  25030. put_short(s, len);
  25031. put_short(s, ~len);
  25032. }
  25033. // while (len--) {
  25034. // put_byte(s, *buf++);
  25035. // }
  25036. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  25037. s.pending += len;
  25038. }
  25039. /* ===========================================================================
  25040. * Compares to subtrees, using the tree depth as tie breaker when
  25041. * the subtrees have equal frequency. This minimizes the worst case length.
  25042. */
  25043. function smaller(tree, n, m, depth) {
  25044. var _n2 = n*2;
  25045. var _m2 = m*2;
  25046. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  25047. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  25048. }
  25049. /* ===========================================================================
  25050. * Restore the heap property by moving down the tree starting at node k,
  25051. * exchanging a node with the smallest of its two sons if necessary, stopping
  25052. * when the heap property is re-established (each father smaller than its
  25053. * two sons).
  25054. */
  25055. function pqdownheap(s, tree, k)
  25056. // deflate_state *s;
  25057. // ct_data *tree; /* the tree to restore */
  25058. // int k; /* node to move down */
  25059. {
  25060. var v = s.heap[k];
  25061. var j = k << 1; /* left son of k */
  25062. while (j <= s.heap_len) {
  25063. /* Set j to the smallest of the two sons: */
  25064. if (j < s.heap_len &&
  25065. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  25066. j++;
  25067. }
  25068. /* Exit if v is smaller than both sons */
  25069. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  25070. /* Exchange v with the smallest son */
  25071. s.heap[k] = s.heap[j];
  25072. k = j;
  25073. /* And continue down the tree, setting j to the left son of k */
  25074. j <<= 1;
  25075. }
  25076. s.heap[k] = v;
  25077. }
  25078. // inlined manually
  25079. // var SMALLEST = 1;
  25080. /* ===========================================================================
  25081. * Send the block data compressed using the given Huffman trees
  25082. */
  25083. function compress_block(s, ltree, dtree)
  25084. // deflate_state *s;
  25085. // const ct_data *ltree; /* literal tree */
  25086. // const ct_data *dtree; /* distance tree */
  25087. {
  25088. var dist; /* distance of matched string */
  25089. var lc; /* match length or unmatched char (if dist == 0) */
  25090. var lx = 0; /* running index in l_buf */
  25091. var code; /* the code to send */
  25092. var extra; /* number of extra bits to send */
  25093. if (s.last_lit !== 0) {
  25094. do {
  25095. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  25096. lc = s.pending_buf[s.l_buf + lx];
  25097. lx++;
  25098. if (dist === 0) {
  25099. send_code(s, lc, ltree); /* send a literal byte */
  25100. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  25101. } else {
  25102. /* Here, lc is the match length - MIN_MATCH */
  25103. code = _length_code[lc];
  25104. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  25105. extra = extra_lbits[code];
  25106. if (extra !== 0) {
  25107. lc -= base_length[code];
  25108. send_bits(s, lc, extra); /* send the extra length bits */
  25109. }
  25110. dist--; /* dist is now the match distance - 1 */
  25111. code = d_code(dist);
  25112. //Assert (code < D_CODES, "bad d_code");
  25113. send_code(s, code, dtree); /* send the distance code */
  25114. extra = extra_dbits[code];
  25115. if (extra !== 0) {
  25116. dist -= base_dist[code];
  25117. send_bits(s, dist, extra); /* send the extra distance bits */
  25118. }
  25119. } /* literal or match pair ? */
  25120. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  25121. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  25122. // "pendingBuf overflow");
  25123. } while (lx < s.last_lit);
  25124. }
  25125. send_code(s, END_BLOCK, ltree);
  25126. }
  25127. /* ===========================================================================
  25128. * Construct one Huffman tree and assigns the code bit strings and lengths.
  25129. * Update the total bit length for the current block.
  25130. * IN assertion: the field freq is set for all tree elements.
  25131. * OUT assertions: the fields len and code are set to the optimal bit length
  25132. * and corresponding code. The length opt_len is updated; static_len is
  25133. * also updated if stree is not null. The field max_code is set.
  25134. */
  25135. function build_tree(s, desc)
  25136. // deflate_state *s;
  25137. // tree_desc *desc; /* the tree descriptor */
  25138. {
  25139. var tree = desc.dyn_tree;
  25140. var stree = desc.stat_desc.static_tree;
  25141. var has_stree = desc.stat_desc.has_stree;
  25142. var elems = desc.stat_desc.elems;
  25143. var n, m; /* iterate over heap elements */
  25144. var max_code = -1; /* largest code with non zero frequency */
  25145. var node; /* new node being created */
  25146. /* Construct the initial heap, with least frequent element in
  25147. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  25148. * heap[0] is not used.
  25149. */
  25150. s.heap_len = 0;
  25151. s.heap_max = HEAP_SIZE;
  25152. for (n = 0; n < elems; n++) {
  25153. if (tree[n * 2]/*.Freq*/ !== 0) {
  25154. s.heap[++s.heap_len] = max_code = n;
  25155. s.depth[n] = 0;
  25156. } else {
  25157. tree[n*2 + 1]/*.Len*/ = 0;
  25158. }
  25159. }
  25160. /* The pkzip format requires that at least one distance code exists,
  25161. * and that at least one bit should be sent even if there is only one
  25162. * possible code. So to avoid special checks later on we force at least
  25163. * two codes of non zero frequency.
  25164. */
  25165. while (s.heap_len < 2) {
  25166. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  25167. tree[node * 2]/*.Freq*/ = 1;
  25168. s.depth[node] = 0;
  25169. s.opt_len--;
  25170. if (has_stree) {
  25171. s.static_len -= stree[node*2 + 1]/*.Len*/;
  25172. }
  25173. /* node is 0 or 1 so it does not have extra bits */
  25174. }
  25175. desc.max_code = max_code;
  25176. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  25177. * establish sub-heaps of increasing lengths:
  25178. */
  25179. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  25180. /* Construct the Huffman tree by repeatedly combining the least two
  25181. * frequent nodes.
  25182. */
  25183. node = elems; /* next internal node of the tree */
  25184. do {
  25185. //pqremove(s, tree, n); /* n = node of least frequency */
  25186. /*** pqremove ***/
  25187. n = s.heap[1/*SMALLEST*/];
  25188. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  25189. pqdownheap(s, tree, 1/*SMALLEST*/);
  25190. /***/
  25191. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  25192. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  25193. s.heap[--s.heap_max] = m;
  25194. /* Create a new node father of n and m */
  25195. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  25196. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  25197. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  25198. /* and insert the new node in the heap */
  25199. s.heap[1/*SMALLEST*/] = node++;
  25200. pqdownheap(s, tree, 1/*SMALLEST*/);
  25201. } while (s.heap_len >= 2);
  25202. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  25203. /* At this point, the fields freq and dad are set. We can now
  25204. * generate the bit lengths.
  25205. */
  25206. gen_bitlen(s, desc);
  25207. /* The field len is now set, we can generate the bit codes */
  25208. gen_codes(tree, max_code, s.bl_count);
  25209. }
  25210. /* ===========================================================================
  25211. * Scan a literal or distance tree to determine the frequencies of the codes
  25212. * in the bit length tree.
  25213. */
  25214. function scan_tree(s, tree, max_code)
  25215. // deflate_state *s;
  25216. // ct_data *tree; /* the tree to be scanned */
  25217. // int max_code; /* and its largest code of non zero frequency */
  25218. {
  25219. var n; /* iterates over all tree elements */
  25220. var prevlen = -1; /* last emitted length */
  25221. var curlen; /* length of current code */
  25222. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25223. var count = 0; /* repeat count of the current code */
  25224. var max_count = 7; /* max repeat count */
  25225. var min_count = 4; /* min repeat count */
  25226. if (nextlen === 0) {
  25227. max_count = 138;
  25228. min_count = 3;
  25229. }
  25230. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  25231. for (n = 0; n <= max_code; n++) {
  25232. curlen = nextlen;
  25233. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25234. if (++count < max_count && curlen === nextlen) {
  25235. continue;
  25236. } else if (count < min_count) {
  25237. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  25238. } else if (curlen !== 0) {
  25239. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  25240. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  25241. } else if (count <= 10) {
  25242. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  25243. } else {
  25244. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  25245. }
  25246. count = 0;
  25247. prevlen = curlen;
  25248. if (nextlen === 0) {
  25249. max_count = 138;
  25250. min_count = 3;
  25251. } else if (curlen === nextlen) {
  25252. max_count = 6;
  25253. min_count = 3;
  25254. } else {
  25255. max_count = 7;
  25256. min_count = 4;
  25257. }
  25258. }
  25259. }
  25260. /* ===========================================================================
  25261. * Send a literal or distance tree in compressed form, using the codes in
  25262. * bl_tree.
  25263. */
  25264. function send_tree(s, tree, max_code)
  25265. // deflate_state *s;
  25266. // ct_data *tree; /* the tree to be scanned */
  25267. // int max_code; /* and its largest code of non zero frequency */
  25268. {
  25269. var n; /* iterates over all tree elements */
  25270. var prevlen = -1; /* last emitted length */
  25271. var curlen; /* length of current code */
  25272. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25273. var count = 0; /* repeat count of the current code */
  25274. var max_count = 7; /* max repeat count */
  25275. var min_count = 4; /* min repeat count */
  25276. /* tree[max_code+1].Len = -1; */ /* guard already set */
  25277. if (nextlen === 0) {
  25278. max_count = 138;
  25279. min_count = 3;
  25280. }
  25281. for (n = 0; n <= max_code; n++) {
  25282. curlen = nextlen;
  25283. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25284. if (++count < max_count && curlen === nextlen) {
  25285. continue;
  25286. } else if (count < min_count) {
  25287. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25288. } else if (curlen !== 0) {
  25289. if (curlen !== prevlen) {
  25290. send_code(s, curlen, s.bl_tree);
  25291. count--;
  25292. }
  25293. //Assert(count >= 3 && count <= 6, " 3_6?");
  25294. send_code(s, REP_3_6, s.bl_tree);
  25295. send_bits(s, count-3, 2);
  25296. } else if (count <= 10) {
  25297. send_code(s, REPZ_3_10, s.bl_tree);
  25298. send_bits(s, count-3, 3);
  25299. } else {
  25300. send_code(s, REPZ_11_138, s.bl_tree);
  25301. send_bits(s, count-11, 7);
  25302. }
  25303. count = 0;
  25304. prevlen = curlen;
  25305. if (nextlen === 0) {
  25306. max_count = 138;
  25307. min_count = 3;
  25308. } else if (curlen === nextlen) {
  25309. max_count = 6;
  25310. min_count = 3;
  25311. } else {
  25312. max_count = 7;
  25313. min_count = 4;
  25314. }
  25315. }
  25316. }
  25317. /* ===========================================================================
  25318. * Construct the Huffman tree for the bit lengths and return the index in
  25319. * bl_order of the last bit length code to send.
  25320. */
  25321. function build_bl_tree(s) {
  25322. var max_blindex; /* index of last bit length code of non zero freq */
  25323. /* Determine the bit length frequencies for literal and distance trees */
  25324. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25325. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25326. /* Build the bit length tree: */
  25327. build_tree(s, s.bl_desc);
  25328. /* opt_len now includes the length of the tree representations, except
  25329. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25330. */
  25331. /* Determine the number of bit length codes to send. The pkzip format
  25332. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25333. * 3 but the actual value used is 4.)
  25334. */
  25335. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25336. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25337. break;
  25338. }
  25339. }
  25340. /* Update opt_len to include the bit length tree and counts */
  25341. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25342. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25343. // s->opt_len, s->static_len));
  25344. return max_blindex;
  25345. }
  25346. /* ===========================================================================
  25347. * Send the header for a block using dynamic Huffman trees: the counts, the
  25348. * lengths of the bit length codes, the literal tree and the distance tree.
  25349. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25350. */
  25351. function send_all_trees(s, lcodes, dcodes, blcodes)
  25352. // deflate_state *s;
  25353. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25354. {
  25355. var rank; /* index in bl_order */
  25356. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25357. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25358. // "too many codes");
  25359. //Tracev((stderr, "\nbl counts: "));
  25360. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25361. send_bits(s, dcodes-1, 5);
  25362. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25363. for (rank = 0; rank < blcodes; rank++) {
  25364. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25365. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25366. }
  25367. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25368. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25369. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25370. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25371. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25372. }
  25373. /* ===========================================================================
  25374. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25375. * - TEXT if the two conditions below are satisfied:
  25376. * a) There are no non-portable control characters belonging to the
  25377. * "black list" (0..6, 14..25, 28..31).
  25378. * b) There is at least one printable character belonging to the
  25379. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25380. * - BINARY otherwise.
  25381. * - The following partially-portable control characters form a
  25382. * "gray list" that is ignored in this detection algorithm:
  25383. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25384. * IN assertion: the fields Freq of dyn_ltree are set.
  25385. */
  25386. function detect_data_type(s) {
  25387. /* black_mask is the bit mask of black-listed bytes
  25388. * set bits 0..6, 14..25, and 28..31
  25389. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25390. */
  25391. var black_mask = 0xf3ffc07f;
  25392. var n;
  25393. /* Check for non-textual ("black-listed") bytes. */
  25394. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25395. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25396. return Z_BINARY;
  25397. }
  25398. }
  25399. /* Check for textual ("white-listed") bytes. */
  25400. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25401. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25402. return Z_TEXT;
  25403. }
  25404. for (n = 32; n < LITERALS; n++) {
  25405. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25406. return Z_TEXT;
  25407. }
  25408. }
  25409. /* There are no "black-listed" or "white-listed" bytes:
  25410. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25411. */
  25412. return Z_BINARY;
  25413. }
  25414. var static_init_done = false;
  25415. /* ===========================================================================
  25416. * Initialize the tree data structures for a new zlib stream.
  25417. */
  25418. function _tr_init(s)
  25419. {
  25420. if (!static_init_done) {
  25421. tr_static_init();
  25422. static_init_done = true;
  25423. }
  25424. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25425. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25426. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25427. s.bi_buf = 0;
  25428. s.bi_valid = 0;
  25429. /* Initialize the first block of the first file: */
  25430. init_block(s);
  25431. }
  25432. /* ===========================================================================
  25433. * Send a stored block
  25434. */
  25435. function _tr_stored_block(s, buf, stored_len, last)
  25436. //DeflateState *s;
  25437. //charf *buf; /* input block */
  25438. //ulg stored_len; /* length of input block */
  25439. //int last; /* one if this is the last block for a file */
  25440. {
  25441. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25442. copy_block(s, buf, stored_len, true); /* with header */
  25443. }
  25444. /* ===========================================================================
  25445. * Send one empty static block to give enough lookahead for inflate.
  25446. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25447. */
  25448. function _tr_align(s) {
  25449. send_bits(s, STATIC_TREES<<1, 3);
  25450. send_code(s, END_BLOCK, static_ltree);
  25451. bi_flush(s);
  25452. }
  25453. /* ===========================================================================
  25454. * Determine the best encoding for the current block: dynamic trees, static
  25455. * trees or store, and output the encoded block to the zip file.
  25456. */
  25457. function _tr_flush_block(s, buf, stored_len, last)
  25458. //DeflateState *s;
  25459. //charf *buf; /* input block, or NULL if too old */
  25460. //ulg stored_len; /* length of input block */
  25461. //int last; /* one if this is the last block for a file */
  25462. {
  25463. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25464. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25465. /* Build the Huffman trees unless a stored block is forced */
  25466. if (s.level > 0) {
  25467. /* Check if the file is binary or text */
  25468. if (s.strm.data_type === Z_UNKNOWN) {
  25469. s.strm.data_type = detect_data_type(s);
  25470. }
  25471. /* Construct the literal and distance trees */
  25472. build_tree(s, s.l_desc);
  25473. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25474. // s->static_len));
  25475. build_tree(s, s.d_desc);
  25476. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25477. // s->static_len));
  25478. /* At this point, opt_len and static_len are the total bit lengths of
  25479. * the compressed block data, excluding the tree representations.
  25480. */
  25481. /* Build the bit length tree for the above two trees, and get the index
  25482. * in bl_order of the last bit length code to send.
  25483. */
  25484. max_blindex = build_bl_tree(s);
  25485. /* Determine the best encoding. Compute the block lengths in bytes. */
  25486. opt_lenb = (s.opt_len+3+7) >>> 3;
  25487. static_lenb = (s.static_len+3+7) >>> 3;
  25488. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25489. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25490. // s->last_lit));
  25491. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25492. } else {
  25493. // Assert(buf != (char*)0, "lost buf");
  25494. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25495. }
  25496. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25497. /* 4: two words for the lengths */
  25498. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25499. * Otherwise we can't have processed more than WSIZE input bytes since
  25500. * the last block flush, because compression would have been
  25501. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25502. * transform a block into a stored block.
  25503. */
  25504. _tr_stored_block(s, buf, stored_len, last);
  25505. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25506. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25507. compress_block(s, static_ltree, static_dtree);
  25508. } else {
  25509. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25510. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25511. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25512. }
  25513. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25514. /* The above check is made mod 2^32, for files larger than 512 MB
  25515. * and uLong implemented on 32 bits.
  25516. */
  25517. init_block(s);
  25518. if (last) {
  25519. bi_windup(s);
  25520. }
  25521. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25522. // s->compressed_len-7*last));
  25523. }
  25524. /* ===========================================================================
  25525. * Save the match info and tally the frequency counts. Return true if
  25526. * the current block must be flushed.
  25527. */
  25528. function _tr_tally(s, dist, lc)
  25529. // deflate_state *s;
  25530. // unsigned dist; /* distance of matched string */
  25531. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25532. {
  25533. //var out_length, in_length, dcode;
  25534. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25535. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25536. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25537. s.last_lit++;
  25538. if (dist === 0) {
  25539. /* lc is the unmatched char */
  25540. s.dyn_ltree[lc*2]/*.Freq*/++;
  25541. } else {
  25542. s.matches++;
  25543. /* Here, lc is the match length - MIN_MATCH */
  25544. dist--; /* dist = match distance - 1 */
  25545. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25546. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25547. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25548. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25549. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25550. }
  25551. // (!) This block is disabled in zlib defailts,
  25552. // don't enable it for binary compatibility
  25553. //#ifdef TRUNCATE_BLOCK
  25554. // /* Try to guess if it is profitable to stop the current block here */
  25555. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25556. // /* Compute an upper bound for the compressed length */
  25557. // out_length = s.last_lit*8;
  25558. // in_length = s.strstart - s.block_start;
  25559. //
  25560. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25561. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25562. // }
  25563. // out_length >>>= 3;
  25564. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25565. // // s->last_lit, in_length, out_length,
  25566. // // 100L - out_length*100L/in_length));
  25567. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25568. // return true;
  25569. // }
  25570. // }
  25571. //#endif
  25572. return (s.last_lit === s.lit_bufsize-1);
  25573. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25574. * on 16 bit machines and because stored blocks are restricted to
  25575. * 64K-1 bytes.
  25576. */
  25577. }
  25578. exports._tr_init = _tr_init;
  25579. exports._tr_stored_block = _tr_stored_block;
  25580. exports._tr_flush_block = _tr_flush_block;
  25581. exports._tr_tally = _tr_tally;
  25582. exports._tr_align = _tr_align;
  25583. },{"../utils/common":78}],90:[function(require,module,exports){
  25584. 'use strict';
  25585. function ZStream() {
  25586. /* next input byte */
  25587. this.input = null; // JS specific, because we have no pointers
  25588. this.next_in = 0;
  25589. /* number of bytes available at input */
  25590. this.avail_in = 0;
  25591. /* total number of input bytes read so far */
  25592. this.total_in = 0;
  25593. /* next output byte should be put there */
  25594. this.output = null; // JS specific, because we have no pointers
  25595. this.next_out = 0;
  25596. /* remaining free space at output */
  25597. this.avail_out = 0;
  25598. /* total number of bytes output so far */
  25599. this.total_out = 0;
  25600. /* last error message, NULL if no error */
  25601. this.msg = ''/*Z_NULL*/;
  25602. /* not visible by applications */
  25603. this.state = null;
  25604. /* best guess about the data type: binary or text */
  25605. this.data_type = 2/*Z_UNKNOWN*/;
  25606. /* adler32 value of the uncompressed data */
  25607. this.adler = 0;
  25608. }
  25609. module.exports = ZStream;
  25610. },{}],91:[function(require,module,exports){
  25611. module.exports = require('./lib/retry');
  25612. },{"./lib/retry":92}],92:[function(require,module,exports){
  25613. var RetryOperation = require('./retry_operation');
  25614. exports.operation = function(options) {
  25615. var timeouts = exports.timeouts(options);
  25616. return new RetryOperation(timeouts);
  25617. };
  25618. exports.timeouts = function(options) {
  25619. if (options instanceof Array) {
  25620. return [].concat(options);
  25621. }
  25622. var opts = {
  25623. retries: 10,
  25624. factor: 2,
  25625. minTimeout: 1 * 1000,
  25626. maxTimeout: Infinity,
  25627. randomize: false
  25628. };
  25629. for (var key in options) {
  25630. opts[key] = options[key];
  25631. }
  25632. if (opts.minTimeout > opts.maxTimeout) {
  25633. throw new Error('minTimeout is greater than maxTimeout');
  25634. }
  25635. var timeouts = [];
  25636. for (var i = 0; i < opts.retries; i++) {
  25637. timeouts.push(this._createTimeout(i, opts));
  25638. }
  25639. // sort the array numerically ascending
  25640. timeouts.sort(function(a,b) {
  25641. return a - b;
  25642. });
  25643. return timeouts;
  25644. };
  25645. exports._createTimeout = function(attempt, opts) {
  25646. var random = (opts.randomize)
  25647. ? (Math.random() + 1)
  25648. : 1;
  25649. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25650. timeout = Math.min(timeout, opts.maxTimeout);
  25651. return timeout;
  25652. };
  25653. },{"./retry_operation":93}],93:[function(require,module,exports){
  25654. function RetryOperation(timeouts) {
  25655. this._timeouts = timeouts;
  25656. this._fn = null;
  25657. this._errors = [];
  25658. this._attempts = 1;
  25659. this._operationTimeout = null;
  25660. this._operationTimeoutCb = null;
  25661. this._timeout = null;
  25662. }
  25663. module.exports = RetryOperation;
  25664. RetryOperation.prototype.retry = function(err) {
  25665. if (this._timeout) {
  25666. clearTimeout(this._timeout);
  25667. }
  25668. if (!err) {
  25669. return false;
  25670. }
  25671. this._errors.push(err);
  25672. var timeout = this._timeouts.shift();
  25673. if (timeout === undefined) {
  25674. return false;
  25675. }
  25676. this._attempts++;
  25677. var self = this;
  25678. setTimeout(function() {
  25679. self._fn(self._attempts);
  25680. if (self._operationTimeoutCb) {
  25681. self._timeout = setTimeout(function() {
  25682. self._operationTimeoutCb(self._attempts);
  25683. }, self._operationTimeout);
  25684. }
  25685. }, timeout);
  25686. return true;
  25687. };
  25688. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25689. this._fn = fn;
  25690. if (timeoutOps) {
  25691. if (timeoutOps.timeout) {
  25692. this._operationTimeout = timeoutOps.timeout;
  25693. }
  25694. if (timeoutOps.cb) {
  25695. this._operationTimeoutCb = timeoutOps.cb;
  25696. }
  25697. }
  25698. this._fn(this._attempts);
  25699. var self = this;
  25700. if (this._operationTimeoutCb) {
  25701. this._timeout = setTimeout(function() {
  25702. self._operationTimeoutCb();
  25703. }, self._operationTimeout);
  25704. }
  25705. };
  25706. RetryOperation.prototype.try = function(fn) {
  25707. console.log('Using RetryOperation.try() is deprecated');
  25708. this.attempt(fn);
  25709. };
  25710. RetryOperation.prototype.start = function(fn) {
  25711. console.log('Using RetryOperation.start() is deprecated');
  25712. this.attempt(fn);
  25713. };
  25714. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25715. RetryOperation.prototype.errors = function() {
  25716. return this._errors;
  25717. };
  25718. RetryOperation.prototype.attempts = function() {
  25719. return this._attempts;
  25720. };
  25721. RetryOperation.prototype.mainError = function() {
  25722. if (this._errors.length === 0) {
  25723. return null;
  25724. }
  25725. var counts = {};
  25726. var mainError = null;
  25727. var mainErrorCount = 0;
  25728. for (var i = 0; i < this._errors.length; i++) {
  25729. var error = this._errors[i];
  25730. var message = error.message;
  25731. var count = (counts[message] || 0) + 1;
  25732. counts[message] = count;
  25733. if (count >= mainErrorCount) {
  25734. mainError = error;
  25735. mainErrorCount = count;
  25736. }
  25737. }
  25738. return mainError;
  25739. };
  25740. },{}],94:[function(require,module,exports){
  25741. module.exports = function arrayEquals(array) {
  25742. // if the other array is a falsy value, return
  25743. if (!array)
  25744. return false;
  25745. // compare lengths - can save a lot of time
  25746. if (this.length != array.length)
  25747. return false;
  25748. for (var i = 0, l = this.length; i < l; i++) {
  25749. // Check if we have nested arrays
  25750. if (this[i] instanceof Array && array[i] instanceof Array) {
  25751. // recurse into the nested arrays
  25752. if (!arrayEquals.apply(this[i], [array[i]]))
  25753. return false;
  25754. } else if (this[i] != array[i]) {
  25755. // Warning - two different object instances will never be equal:
  25756. // {x:20} != {x:20}
  25757. return false;
  25758. }
  25759. }
  25760. return true;
  25761. }
  25762. },{}],95:[function(require,module,exports){
  25763. exports.Interop = require('./interop');
  25764. },{"./interop":96}],96:[function(require,module,exports){
  25765. "use strict";
  25766. var transform = require('./transform');
  25767. var arrayEquals = require('./array-equals');
  25768. function Interop() {
  25769. /**
  25770. * This map holds the most recent Unified Plan offer/answer SDP that was
  25771. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25772. * the SDP string as values.
  25773. *
  25774. * @type {{}}
  25775. */
  25776. this.cache = {};
  25777. }
  25778. module.exports = Interop;
  25779. /**
  25780. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25781. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25782. * application.
  25783. *
  25784. * @param desc
  25785. * @returns {*}
  25786. */
  25787. Interop.prototype.toPlanB = function(desc) {
  25788. //#region Preliminary input validation.
  25789. if (typeof desc !== 'object' || desc === null ||
  25790. typeof desc.sdp !== 'string') {
  25791. console.warn('An empty description was passed as an argument.');
  25792. return desc;
  25793. }
  25794. // Objectify the SDP for easier manipulation.
  25795. var session = transform.parse(desc.sdp);
  25796. // If the SDP contains no media, there's nothing to transform.
  25797. if (typeof session.media === 'undefined' ||
  25798. !Array.isArray(session.media) || session.media.length === 0) {
  25799. console.warn('The description has no media.');
  25800. return desc;
  25801. }
  25802. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25803. // SDP has a video, an audio and a data "channel" at most.
  25804. if (session.media.length <= 3 && session.media.every(function(m) {
  25805. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25806. })) {
  25807. console.warn('This description does not look like Unified Plan.');
  25808. return desc;
  25809. }
  25810. //#endregion
  25811. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25812. // -> Unified Plan transformation.
  25813. this.cache[desc.type] = desc.sdp;
  25814. //#region Convert from Unified Plan to Plan B.
  25815. // We rebuild the session.media array.
  25816. var media = session.media;
  25817. session.media = [];
  25818. // Associative array that maps channel types to channel objects for fast
  25819. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25820. // obj.
  25821. var type2bl = {};
  25822. // Used to build the group:BUNDLE value after the channels construction
  25823. // loop.
  25824. var types = [];
  25825. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25826. media.forEach(function(unifiedLine) {
  25827. // rtcp-mux is required in the Plan B SDP.
  25828. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25829. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25830. unifiedLine.direction !== 'inactive') {
  25831. throw new Error('Cannot convert to Plan B because m-lines ' +
  25832. 'without the rtcp-mux attribute were found.');
  25833. }
  25834. if (unifiedLine.type === 'application') {
  25835. session.media.push(unifiedLine);
  25836. types.push(unifiedLine.mid);
  25837. return;
  25838. }
  25839. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25840. // as the channel basis.
  25841. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25842. type2bl[unifiedLine.type] = unifiedLine;
  25843. }
  25844. // Add sources to the channel and handle a=msid.
  25845. if (typeof unifiedLine.sources === 'object') {
  25846. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25847. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25848. type2bl[unifiedLine.type].sources = {};
  25849. // Assign the sources to the channel.
  25850. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25851. if (typeof unifiedLine.msid !== 'undefined') {
  25852. // In Plan B the msid is an SSRC attribute. Also, we don't
  25853. // care about the obsolete label and mslabel attributes.
  25854. //
  25855. // Note that it is not guaranteed that the unifiedLine will have
  25856. // an msid. recvonly channels in particular don't have one.
  25857. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25858. }
  25859. // NOTE ssrcs in ssrc groups will share msids, as
  25860. // draft-uberti-rtcweb-plan-00 mandates.
  25861. });
  25862. }
  25863. // Add ssrc groups to the channel.
  25864. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25865. Array.isArray(unifiedLine.ssrcGroups)) {
  25866. // Create the ssrcGroups array, if it's not defined.
  25867. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25868. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25869. type2bl[unifiedLine.type].ssrcGroups = [];
  25870. }
  25871. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25872. }
  25873. if (type2bl[unifiedLine.type] === unifiedLine) {
  25874. // Copy ICE related stuff from the principal media line.
  25875. unifiedLine.candidates = media[0].candidates;
  25876. unifiedLine.iceUfrag = media[0].iceUfrag;
  25877. unifiedLine.icePwd = media[0].icePwd;
  25878. unifiedLine.fingerprint = media[0].fingerprint;
  25879. // Plan B mids are in ['audio', 'video', 'data']
  25880. unifiedLine.mid = unifiedLine.type;
  25881. // Plan B doesn't support/need the bundle-only attribute.
  25882. delete unifiedLine.bundleOnly;
  25883. // In Plan B the msid is an SSRC attribute.
  25884. delete unifiedLine.msid;
  25885. // Used to build the group:BUNDLE value after this loop.
  25886. types.push(unifiedLine.type);
  25887. // Add the channel to the new media array.
  25888. session.media.push(unifiedLine);
  25889. }
  25890. });
  25891. // We regenerate the BUNDLE group with the new mids.
  25892. session.groups.some(function(group) {
  25893. if (group.type === 'BUNDLE') {
  25894. group.mids = types.join(' ');
  25895. return true;
  25896. }
  25897. });
  25898. // msid semantic
  25899. session.msidSemantic = {
  25900. semantic: 'WMS',
  25901. token: '*'
  25902. };
  25903. var resStr = transform.write(session);
  25904. return new RTCSessionDescription({
  25905. type: desc.type,
  25906. sdp: resStr
  25907. });
  25908. //#endregion
  25909. };
  25910. /**
  25911. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25912. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25913. * to FF.
  25914. *
  25915. * @param desc
  25916. * @returns {*}
  25917. */
  25918. Interop.prototype.toUnifiedPlan = function(desc) {
  25919. //#region Preliminary input validation.
  25920. if (typeof desc !== 'object' || desc === null ||
  25921. typeof desc.sdp !== 'string') {
  25922. console.warn('An empty description was passed as an argument.');
  25923. return desc;
  25924. }
  25925. var session = transform.parse(desc.sdp);
  25926. // If the SDP contains no media, there's nothing to transform.
  25927. if (typeof session.media === 'undefined' ||
  25928. !Array.isArray(session.media) || session.media.length === 0) {
  25929. console.warn('The description has no media.');
  25930. return desc;
  25931. }
  25932. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25933. // a video, an audio and a data "channel" at most.
  25934. if (session.media.length > 3 || !session.media.every(function(m) {
  25935. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25936. })) {
  25937. console.warn('This description does not look like Plan B.');
  25938. return desc;
  25939. }
  25940. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25941. var mids = [];
  25942. session.media.forEach(function(m) {
  25943. mids.push(m.mid);
  25944. });
  25945. var hasBundle = false;
  25946. if (typeof session.groups !== 'undefined' &&
  25947. Array.isArray(session.groups)) {
  25948. hasBundle = session.groups.every(function(g) {
  25949. return g.type !== 'BUNDLE' ||
  25950. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25951. });
  25952. }
  25953. if (!hasBundle) {
  25954. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25955. " are not bundled were found.");
  25956. }
  25957. //#endregion
  25958. //#region Convert from Plan B to Unified Plan.
  25959. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25960. // rebuild an equivalent Unified Plan offer/answer.
  25961. //
  25962. // For example, if this is a local answer (in Unified Plan style) that we
  25963. // convert to Plan B prior to handing it over to the application (the
  25964. // PeerConnection wrapper called us, for instance, after a successful
  25965. // createAnswer), we want to remember the m-line at which we've seen the
  25966. // (local) SSRC. That's because when the application wants to do call the
  25967. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25968. // Unified Plan), we need to know to which m-line to assign the (local)
  25969. // SSRC. We also need to know all the other m-lines that the original
  25970. // answer had and include them in the transformed answer as well.
  25971. //
  25972. // Another example is if this is a remote offer that we convert to Plan B
  25973. // prior to giving it to the application, we want to remember the mid at
  25974. // which we've seen the (remote) SSRC.
  25975. //
  25976. // In the iteration that follows, we use the cached Unified Plan (if it
  25977. // exists) to assign mids to ssrcs.
  25978. var cached;
  25979. if (typeof this.cache[desc.type] !== 'undefined') {
  25980. cached = transform.parse(this.cache[desc.type]);
  25981. }
  25982. // A helper map that sends mids to m-line objects. We use it later to
  25983. // rebuild the Unified Plan style session.media array.
  25984. var mid2ul = {};
  25985. session.media.forEach(function(bLine) {
  25986. if ((typeof bLine.rtcpMux !== 'string' ||
  25987. bLine.rtcpMux !== 'rtcp-mux') &&
  25988. bLine.direction !== 'inactive') {
  25989. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25990. "without the rtcp-mux attribute were found.");
  25991. }
  25992. if (bLine.type === 'application') {
  25993. mid2ul[bLine.mid] = bLine;
  25994. return;
  25995. }
  25996. // With rtcp-mux and bundle all the channels should have the same ICE
  25997. // stuff.
  25998. var sources = bLine.sources;
  25999. var ssrcGroups = bLine.ssrcGroups;
  26000. var candidates = bLine.candidates;
  26001. var iceUfrag = bLine.iceUfrag;
  26002. var icePwd = bLine.icePwd;
  26003. var fingerprint = bLine.fingerprint;
  26004. var port = bLine.port;
  26005. // We'll use the "bLine" object as a prototype for each new "mLine"
  26006. // that we create, but first we need to clean it up a bit.
  26007. delete bLine.sources;
  26008. delete bLine.ssrcGroups;
  26009. delete bLine.candidates;
  26010. delete bLine.iceUfrag;
  26011. delete bLine.icePwd;
  26012. delete bLine.fingerprint;
  26013. delete bLine.port;
  26014. delete bLine.mid;
  26015. // inverted ssrc group map
  26016. var ssrc2group = {};
  26017. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  26018. ssrcGroups.forEach(function (ssrcGroup) {
  26019. // TODO(gp) find out how to receive simulcast with FF. For the
  26020. // time being, hide it.
  26021. if (ssrcGroup.semantics === 'SIM') {
  26022. return;
  26023. }
  26024. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26025. Array.isArray(ssrcGroup.ssrcs)) {
  26026. ssrcGroup.ssrcs.forEach(function (ssrc) {
  26027. if (typeof ssrc2group[ssrc] === 'undefined') {
  26028. ssrc2group[ssrc] = [];
  26029. }
  26030. ssrc2group[ssrc].push(ssrcGroup);
  26031. });
  26032. }
  26033. });
  26034. }
  26035. // ssrc to m-line index.
  26036. var ssrc2ml = {};
  26037. if (typeof sources === 'object') {
  26038. // Explode the Plan B channel sources with one m-line per source.
  26039. Object.keys(sources).forEach(function(ssrc) {
  26040. // The (unified) m-line for this SSRC. We either create it from
  26041. // scratch or, if it's a grouped SSRC, we re-use a related
  26042. // mline. In other words, if the source is grouped with another
  26043. // source, put the two together in the same m-line.
  26044. var unifiedLine;
  26045. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  26046. Array.isArray(ssrc2group[ssrc])) {
  26047. ssrc2group[ssrc].some(function (ssrcGroup) {
  26048. // ssrcGroup.ssrcs *is* an Array, no need to check
  26049. // again here.
  26050. return ssrcGroup.ssrcs.some(function (related) {
  26051. if (typeof ssrc2ml[related] === 'object') {
  26052. unifiedLine = ssrc2ml[related];
  26053. return true;
  26054. }
  26055. });
  26056. });
  26057. }
  26058. if (typeof unifiedLine === 'object') {
  26059. // the m-line already exists. Just add the source.
  26060. unifiedLine.sources[ssrc] = sources[ssrc];
  26061. delete sources[ssrc].msid;
  26062. } else {
  26063. // Use the "bLine" as a prototype for the "unifiedLine".
  26064. unifiedLine = Object.create(bLine);
  26065. ssrc2ml[ssrc] = unifiedLine;
  26066. if (typeof sources[ssrc].msid !== 'undefined') {
  26067. // Assign the msid of the source to the m-line. Note
  26068. // that it is not guaranteed that the source will have
  26069. // msid. In particular "recvonly" sources don't have an
  26070. // msid. Note that "recvonly" is a term only defined
  26071. // for m-lines.
  26072. unifiedLine.msid = sources[ssrc].msid;
  26073. delete sources[ssrc].msid;
  26074. }
  26075. // We assign one SSRC per media line.
  26076. unifiedLine.sources = {};
  26077. unifiedLine.sources[ssrc] = sources[ssrc];
  26078. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  26079. // Use the cached Unified Plan SDP (if it exists) to assign
  26080. // SSRCs to mids.
  26081. if (typeof cached !== 'undefined' &&
  26082. typeof cached.media !== 'undefined' &&
  26083. Array.isArray(cached.media)) {
  26084. cached.media.forEach(function (m) {
  26085. if (typeof m.sources === 'object') {
  26086. Object.keys(m.sources).forEach(function (s) {
  26087. if (s === ssrc) {
  26088. unifiedLine.mid = m.mid;
  26089. }
  26090. });
  26091. }
  26092. });
  26093. }
  26094. if (typeof unifiedLine.mid === 'undefined') {
  26095. // If this is an SSRC that we see for the first time
  26096. // assign it a new mid. This is typically the case when
  26097. // this method is called to transform a remote
  26098. // description for the first time or when there is a
  26099. // new SSRC in the remote description because a new
  26100. // peer has joined the conference. Local SSRCs should
  26101. // have already been added to the map in the toPlanB
  26102. // method.
  26103. //
  26104. // Because FF generates answers in Unified Plan style,
  26105. // we MUST already have a cached answer with all the
  26106. // local SSRCs mapped to some m-line/mid.
  26107. if (desc.type === 'answer') {
  26108. throw new Error("An unmapped SSRC was found.");
  26109. }
  26110. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  26111. }
  26112. // Include the candidates in the 1st media line.
  26113. unifiedLine.candidates = candidates;
  26114. unifiedLine.iceUfrag = iceUfrag;
  26115. unifiedLine.icePwd = icePwd;
  26116. unifiedLine.fingerprint = fingerprint;
  26117. unifiedLine.port = port;
  26118. mid2ul[unifiedLine.mid] = unifiedLine;
  26119. }
  26120. });
  26121. }
  26122. });
  26123. // Rebuild the media array in the right order and add the missing mLines
  26124. // (missing from the Plan B SDP).
  26125. session.media = [];
  26126. mids = []; // reuse
  26127. if (desc.type === 'answer') {
  26128. // The media lines in the answer must match the media lines in the
  26129. // offer. The order is important too. Here we assume that Firefox is the
  26130. // answerer, so we merely have to use the reconstructed (unified) answer
  26131. // to update the cached (unified) answer accordingly.
  26132. //
  26133. // In the general case, one would have to use the cached (unified) offer
  26134. // to find the m-lines that are missing from the reconstructed answer,
  26135. // potentially grabbing them from the cached (unified) answer. One has
  26136. // to be carefull with this approach because inactive m-lines do not
  26137. // always have an mid, making it tricky (impossible?) to find where
  26138. // exactly and which m-lines are missing from the reconstructed answer.
  26139. for (var i = 0; i < cached.media.length; i++) {
  26140. var unifiedLine = cached.media[i];
  26141. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  26142. // The mid isn't in the reconstructed (unified) answer.
  26143. // This is either a (unified) m-line containing a remote
  26144. // track only, or a (unified) m-line containing a remote
  26145. // track and a local track that has been removed.
  26146. // In either case, it MUST exist in the cached
  26147. // (unified) answer.
  26148. //
  26149. // In case this is a removed local track, clean-up
  26150. // the (unified) m-line and make sure it's 'recvonly' or
  26151. // 'inactive'.
  26152. delete unifiedLine.msid;
  26153. delete unifiedLine.sources;
  26154. delete unifiedLine.ssrcGroups;
  26155. if (!unifiedLine.direction
  26156. || unifiedLine.direction === 'sendrecv')
  26157. unifiedLine.direction = 'recvonly';
  26158. if (!unifiedLine.direction
  26159. || unifiedLine.direction === 'sendonly')
  26160. unifiedLine.direction = 'inactive';
  26161. } else {
  26162. // This is an (unified) m-line/channel that contains a local
  26163. // track (sendrecv or sendonly channel) or it's a unified
  26164. // recvonly m-line/channel. In either case, since we're
  26165. // going from PlanB -> Unified Plan this m-line MUST
  26166. // exist in the cached answer.
  26167. }
  26168. session.media.push(unifiedLine);
  26169. if (typeof unifiedLine.mid === 'string') {
  26170. // inactive lines don't/may not have an mid.
  26171. mids.push(unifiedLine.mid);
  26172. }
  26173. }
  26174. } else {
  26175. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  26176. // under any circumstances. If we are no longer interested in sending a
  26177. // track, we just remove the msid and ssrc attributes and set it to
  26178. // either a=recvonly (as the reofferer, we must use recvonly if the
  26179. // other side was previously sending on the m-section, but we can also
  26180. // leave the possibility open if it wasn't previously in use), or
  26181. // a=inacive.
  26182. if (typeof cached !== 'undefined' &&
  26183. typeof cached.media !== 'undefined' &&
  26184. Array.isArray(cached.media)) {
  26185. cached.media.forEach(function(unifiedLine) {
  26186. mids.push(unifiedLine.mid);
  26187. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  26188. session.media.push(mid2ul[unifiedLine.mid]);
  26189. } else {
  26190. delete unifiedLine.msid;
  26191. delete unifiedLine.sources;
  26192. delete unifiedLine.ssrcGroups;
  26193. if (!unifiedLine.direction
  26194. || unifiedLine.direction === 'sendrecv')
  26195. unifiedLine.direction = 'recvonly';
  26196. if (!unifiedLine.direction
  26197. || unifiedLine.direction === 'sendonly')
  26198. unifiedLine.direction = 'inactive';
  26199. session.media.push(unifiedLine);
  26200. }
  26201. });
  26202. }
  26203. // Add all the remaining (new) m-lines of the transformed SDP.
  26204. Object.keys(mid2ul).forEach(function(mid) {
  26205. if (mids.indexOf(mid) === -1) {
  26206. mids.push(mid);
  26207. if (typeof mid2ul[mid].direction === 'recvonly') {
  26208. // This is a remote recvonly channel. Add its SSRC to the
  26209. // appropriate sendrecv or sendonly channel.
  26210. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  26211. session.media.some(function (unifiedLine) {
  26212. if ((unifiedLine.direction === 'sendrecv' ||
  26213. unifiedLine.direction === 'sendonly') &&
  26214. unifiedLine.type === mid2ul[mid].type) {
  26215. // mid2ul[mid] shouldn't have any ssrc-groups
  26216. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  26217. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  26218. });
  26219. return true;
  26220. }
  26221. });
  26222. } else {
  26223. session.media.push(mid2ul[mid]);
  26224. }
  26225. }
  26226. });
  26227. }
  26228. // We regenerate the BUNDLE group (since we regenerated the mids)
  26229. session.groups.some(function(group) {
  26230. if (group.type === 'BUNDLE') {
  26231. group.mids = mids.join(' ');
  26232. return true;
  26233. }
  26234. });
  26235. // msid semantic
  26236. session.msidSemantic = {
  26237. semantic: 'WMS',
  26238. token: '*'
  26239. };
  26240. var resStr = transform.write(session);
  26241. // Cache the transformed SDP (Unified Plan) for later re-use in this
  26242. // function.
  26243. this.cache[desc.type] = resStr;
  26244. return new RTCSessionDescription({
  26245. type: desc.type,
  26246. sdp: resStr
  26247. });
  26248. //#endregion
  26249. };
  26250. },{"./array-equals":94,"./transform":97}],97:[function(require,module,exports){
  26251. var transform = require('sdp-transform');
  26252. exports.write = function(session, opts) {
  26253. if (typeof session !== 'undefined' &&
  26254. typeof session.media !== 'undefined' &&
  26255. Array.isArray(session.media)) {
  26256. session.media.forEach(function (mLine) {
  26257. // expand sources to ssrcs
  26258. if (typeof mLine.sources !== 'undefined' &&
  26259. Object.keys(mLine.sources).length !== 0) {
  26260. mLine.ssrcs = [];
  26261. Object.keys(mLine.sources).forEach(function (ssrc) {
  26262. var source = mLine.sources[ssrc];
  26263. Object.keys(source).forEach(function (attribute) {
  26264. mLine.ssrcs.push({
  26265. id: ssrc,
  26266. attribute: attribute,
  26267. value: source[attribute]
  26268. });
  26269. });
  26270. });
  26271. delete mLine.sources;
  26272. }
  26273. // join ssrcs in ssrc groups
  26274. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26275. Array.isArray(mLine.ssrcGroups)) {
  26276. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26277. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26278. Array.isArray(ssrcGroup.ssrcs)) {
  26279. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  26280. }
  26281. });
  26282. }
  26283. });
  26284. }
  26285. // join group mids
  26286. if (typeof session !== 'undefined' &&
  26287. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26288. session.groups.forEach(function (g) {
  26289. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26290. g.mids = g.mids.join(' ');
  26291. }
  26292. });
  26293. }
  26294. return transform.write(session, opts);
  26295. };
  26296. exports.parse = function(sdp) {
  26297. var session = transform.parse(sdp);
  26298. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26299. Array.isArray(session.media)) {
  26300. session.media.forEach(function (mLine) {
  26301. // group sources attributes by ssrc
  26302. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26303. mLine.sources = {};
  26304. mLine.ssrcs.forEach(function (ssrc) {
  26305. if (!mLine.sources[ssrc.id])
  26306. mLine.sources[ssrc.id] = {};
  26307. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26308. });
  26309. delete mLine.ssrcs;
  26310. }
  26311. // split ssrcs in ssrc groups
  26312. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26313. Array.isArray(mLine.ssrcGroups)) {
  26314. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26315. if (typeof ssrcGroup.ssrcs === 'string') {
  26316. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26317. }
  26318. });
  26319. }
  26320. });
  26321. }
  26322. // split group mids
  26323. if (typeof session !== 'undefined' &&
  26324. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26325. session.groups.forEach(function (g) {
  26326. if (typeof g.mids === 'string') {
  26327. g.mids = g.mids.split(' ');
  26328. }
  26329. });
  26330. }
  26331. return session;
  26332. };
  26333. },{"sdp-transform":99}],98:[function(require,module,exports){
  26334. var grammar = module.exports = {
  26335. v: [{
  26336. name: 'version',
  26337. reg: /^(\d*)$/
  26338. }],
  26339. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26340. // NB: sessionId will be a String in most cases because it is huge
  26341. name: 'origin',
  26342. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26343. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26344. format: "%s %s %d %s IP%d %s"
  26345. }],
  26346. // default parsing of these only (though some of these feel outdated)
  26347. s: [{ name: 'name' }],
  26348. i: [{ name: 'description' }],
  26349. u: [{ name: 'uri' }],
  26350. e: [{ name: 'email' }],
  26351. p: [{ name: 'phone' }],
  26352. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26353. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26354. //k: [{}], // outdated thing ignored
  26355. t: [{ //t=0 0
  26356. name: 'timing',
  26357. reg: /^(\d*) (\d*)/,
  26358. names: ['start', 'stop'],
  26359. format: "%d %d"
  26360. }],
  26361. c: [{ //c=IN IP4 10.47.197.26
  26362. name: 'connection',
  26363. reg: /^IN IP(\d) (\S*)/,
  26364. names: ['version', 'ip'],
  26365. format: "IN IP%d %s"
  26366. }],
  26367. b: [{ //b=AS:4000
  26368. push: 'bandwidth',
  26369. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26370. names: ['type', 'limit'],
  26371. format: "%s:%s"
  26372. }],
  26373. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26374. // NB: special - pushes to session
  26375. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26376. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26377. names: ['type', 'port', 'protocol', 'payloads'],
  26378. format: "%s %d %s %s"
  26379. }],
  26380. a: [
  26381. { //a=rtpmap:110 opus/48000/2
  26382. push: 'rtp',
  26383. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26384. names: ['payload', 'codec', 'rate', 'encoding'],
  26385. format: function (o) {
  26386. return (o.encoding) ?
  26387. "rtpmap:%d %s/%s/%s":
  26388. "rtpmap:%d %s/%s";
  26389. }
  26390. },
  26391. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26392. push: 'fmtp',
  26393. reg: /^fmtp:(\d*) (\S*)/,
  26394. names: ['payload', 'config'],
  26395. format: "fmtp:%d %s"
  26396. },
  26397. { //a=control:streamid=0
  26398. name: 'control',
  26399. reg: /^control:(.*)/,
  26400. format: "control:%s"
  26401. },
  26402. { //a=rtcp:65179 IN IP4 193.84.77.194
  26403. name: 'rtcp',
  26404. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26405. names: ['port', 'netType', 'ipVer', 'address'],
  26406. format: function (o) {
  26407. return (o.address != null) ?
  26408. "rtcp:%d %s IP%d %s":
  26409. "rtcp:%d";
  26410. }
  26411. },
  26412. { //a=rtcp-fb:98 trr-int 100
  26413. push: 'rtcpFbTrrInt',
  26414. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26415. names: ['payload', 'value'],
  26416. format: "rtcp-fb:%d trr-int %d"
  26417. },
  26418. { //a=rtcp-fb:98 nack rpsi
  26419. push: 'rtcpFb',
  26420. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26421. names: ['payload', 'type', 'subtype'],
  26422. format: function (o) {
  26423. return (o.subtype != null) ?
  26424. "rtcp-fb:%s %s %s":
  26425. "rtcp-fb:%s %s";
  26426. }
  26427. },
  26428. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26429. //a=extmap:1/recvonly URI-gps-string
  26430. push: 'ext',
  26431. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26432. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26433. format: function (o) {
  26434. return (o.config != null) ?
  26435. "extmap:%s %s %s":
  26436. "extmap:%s %s";
  26437. }
  26438. },
  26439. {
  26440. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26441. push: 'crypto',
  26442. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26443. names: ['id', 'suite', 'config', 'sessionConfig'],
  26444. format: function (o) {
  26445. return (o.sessionConfig != null) ?
  26446. "crypto:%d %s %s %s":
  26447. "crypto:%d %s %s";
  26448. }
  26449. },
  26450. { //a=setup:actpass
  26451. name: 'setup',
  26452. reg: /^setup:(\w*)/,
  26453. format: "setup:%s"
  26454. },
  26455. { //a=mid:1
  26456. name: 'mid',
  26457. reg: /^mid:([^\s]*)/,
  26458. format: "mid:%s"
  26459. },
  26460. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26461. name: 'msid',
  26462. reg: /^msid:(.*)/,
  26463. format: "msid:%s"
  26464. },
  26465. { //a=ptime:20
  26466. name: 'ptime',
  26467. reg: /^ptime:(\d*)/,
  26468. format: "ptime:%d"
  26469. },
  26470. { //a=maxptime:60
  26471. name: 'maxptime',
  26472. reg: /^maxptime:(\d*)/,
  26473. format: "maxptime:%d"
  26474. },
  26475. { //a=sendrecv
  26476. name: 'direction',
  26477. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26478. },
  26479. { //a=ice-lite
  26480. name: 'icelite',
  26481. reg: /^(ice-lite)/
  26482. },
  26483. { //a=ice-ufrag:F7gI
  26484. name: 'iceUfrag',
  26485. reg: /^ice-ufrag:(\S*)/,
  26486. format: "ice-ufrag:%s"
  26487. },
  26488. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26489. name: 'icePwd',
  26490. reg: /^ice-pwd:(\S*)/,
  26491. format: "ice-pwd:%s"
  26492. },
  26493. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26494. name: 'fingerprint',
  26495. reg: /^fingerprint:(\S*) (\S*)/,
  26496. names: ['type', 'hash'],
  26497. format: "fingerprint:%s %s"
  26498. },
  26499. {
  26500. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26501. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26502. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26503. push:'candidates',
  26504. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26505. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26506. format: function (o) {
  26507. var str = "candidate:%s %d %s %d %s %d typ %s";
  26508. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26509. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26510. if (o.generation != null) {
  26511. str += " generation %d";
  26512. }
  26513. return str;
  26514. }
  26515. },
  26516. { //a=end-of-candidates (keep after the candidates line for readability)
  26517. name: 'endOfCandidates',
  26518. reg: /^(end-of-candidates)/
  26519. },
  26520. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26521. name: 'remoteCandidates',
  26522. reg: /^remote-candidates:(.*)/,
  26523. format: "remote-candidates:%s"
  26524. },
  26525. { //a=ice-options:google-ice
  26526. name: 'iceOptions',
  26527. reg: /^ice-options:(\S*)/,
  26528. format: "ice-options:%s"
  26529. },
  26530. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26531. push: "ssrcs",
  26532. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26533. names: ['id', 'attribute', 'value'],
  26534. format: "ssrc:%d %s:%s"
  26535. },
  26536. { //a=ssrc-group:FEC 1 2
  26537. push: "ssrcGroups",
  26538. reg: /^ssrc-group:(\w*) (.*)/,
  26539. names: ['semantics', 'ssrcs'],
  26540. format: "ssrc-group:%s %s"
  26541. },
  26542. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26543. name: "msidSemantic",
  26544. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26545. names: ['semantic', 'token'],
  26546. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26547. },
  26548. { //a=group:BUNDLE audio video
  26549. push: 'groups',
  26550. reg: /^group:(\w*) (.*)/,
  26551. names: ['type', 'mids'],
  26552. format: "group:%s %s"
  26553. },
  26554. { //a=rtcp-mux
  26555. name: 'rtcpMux',
  26556. reg: /^(rtcp-mux)/
  26557. },
  26558. { //a=rtcp-rsize
  26559. name: 'rtcpRsize',
  26560. reg: /^(rtcp-rsize)/
  26561. },
  26562. { // any a= that we don't understand is kepts verbatim on media.invalid
  26563. push: 'invalid',
  26564. names: ["value"]
  26565. }
  26566. ]
  26567. };
  26568. // set sensible defaults to avoid polluting the grammar with boring details
  26569. Object.keys(grammar).forEach(function (key) {
  26570. var objs = grammar[key];
  26571. objs.forEach(function (obj) {
  26572. if (!obj.reg) {
  26573. obj.reg = /(.*)/;
  26574. }
  26575. if (!obj.format) {
  26576. obj.format = "%s";
  26577. }
  26578. });
  26579. });
  26580. },{}],99:[function(require,module,exports){
  26581. var parser = require('./parser');
  26582. var writer = require('./writer');
  26583. exports.write = writer;
  26584. exports.parse = parser.parse;
  26585. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26586. exports.parsePayloads = parser.parsePayloads;
  26587. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26588. },{"./parser":100,"./writer":101}],100:[function(require,module,exports){
  26589. var toIntIfInt = function (v) {
  26590. return String(Number(v)) === v ? Number(v) : v;
  26591. };
  26592. var attachProperties = function (match, location, names, rawName) {
  26593. if (rawName && !names) {
  26594. location[rawName] = toIntIfInt(match[1]);
  26595. }
  26596. else {
  26597. for (var i = 0; i < names.length; i += 1) {
  26598. if (match[i+1] != null) {
  26599. location[names[i]] = toIntIfInt(match[i+1]);
  26600. }
  26601. }
  26602. }
  26603. };
  26604. var parseReg = function (obj, location, content) {
  26605. var needsBlank = obj.name && obj.names;
  26606. if (obj.push && !location[obj.push]) {
  26607. location[obj.push] = [];
  26608. }
  26609. else if (needsBlank && !location[obj.name]) {
  26610. location[obj.name] = {};
  26611. }
  26612. var keyLocation = obj.push ?
  26613. {} : // blank object that will be pushed
  26614. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26615. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26616. if (obj.push) {
  26617. location[obj.push].push(keyLocation);
  26618. }
  26619. };
  26620. var grammar = require('./grammar');
  26621. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26622. exports.parse = function (sdp) {
  26623. var session = {}
  26624. , media = []
  26625. , location = session; // points at where properties go under (one of the above)
  26626. // parse lines we understand
  26627. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26628. var type = l[0];
  26629. var content = l.slice(2);
  26630. if (type === 'm') {
  26631. media.push({rtp: [], fmtp: []});
  26632. location = media[media.length-1]; // point at latest media line
  26633. }
  26634. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26635. var obj = grammar[type][j];
  26636. if (obj.reg.test(content)) {
  26637. return parseReg(obj, location, content);
  26638. }
  26639. }
  26640. });
  26641. session.media = media; // link it up
  26642. return session;
  26643. };
  26644. var fmtpReducer = function (acc, expr) {
  26645. var s = expr.split('=');
  26646. if (s.length === 2) {
  26647. acc[s[0]] = toIntIfInt(s[1]);
  26648. }
  26649. return acc;
  26650. };
  26651. exports.parseFmtpConfig = function (str) {
  26652. return str.split(';').reduce(fmtpReducer, {});
  26653. };
  26654. exports.parsePayloads = function (str) {
  26655. return str.split(' ').map(Number);
  26656. };
  26657. exports.parseRemoteCandidates = function (str) {
  26658. var candidates = [];
  26659. var parts = str.split(' ').map(toIntIfInt);
  26660. for (var i = 0; i < parts.length; i += 3) {
  26661. candidates.push({
  26662. component: parts[i],
  26663. ip: parts[i + 1],
  26664. port: parts[i + 2]
  26665. });
  26666. }
  26667. return candidates;
  26668. };
  26669. },{"./grammar":98}],101:[function(require,module,exports){
  26670. var grammar = require('./grammar');
  26671. // customized util.format - discards excess arguments and can void middle ones
  26672. var formatRegExp = /%[sdv%]/g;
  26673. var format = function (formatStr) {
  26674. var i = 1;
  26675. var args = arguments;
  26676. var len = args.length;
  26677. return formatStr.replace(formatRegExp, function (x) {
  26678. if (i >= len) {
  26679. return x; // missing argument
  26680. }
  26681. var arg = args[i];
  26682. i += 1;
  26683. switch (x) {
  26684. case '%%':
  26685. return '%';
  26686. case '%s':
  26687. return String(arg);
  26688. case '%d':
  26689. return Number(arg);
  26690. case '%v':
  26691. return '';
  26692. }
  26693. });
  26694. // NB: we discard excess arguments - they are typically undefined from makeLine
  26695. };
  26696. var makeLine = function (type, obj, location) {
  26697. var str = obj.format instanceof Function ?
  26698. (obj.format(obj.push ? location : location[obj.name])) :
  26699. obj.format;
  26700. var args = [type + '=' + str];
  26701. if (obj.names) {
  26702. for (var i = 0; i < obj.names.length; i += 1) {
  26703. var n = obj.names[i];
  26704. if (obj.name) {
  26705. args.push(location[obj.name][n]);
  26706. }
  26707. else { // for mLine and push attributes
  26708. args.push(location[obj.names[i]]);
  26709. }
  26710. }
  26711. }
  26712. else {
  26713. args.push(location[obj.name]);
  26714. }
  26715. return format.apply(null, args);
  26716. };
  26717. // RFC specified order
  26718. // TODO: extend this with all the rest
  26719. var defaultOuterOrder = [
  26720. 'v', 'o', 's', 'i',
  26721. 'u', 'e', 'p', 'c',
  26722. 'b', 't', 'r', 'z', 'a'
  26723. ];
  26724. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26725. module.exports = function (session, opts) {
  26726. opts = opts || {};
  26727. // ensure certain properties exist
  26728. if (session.version == null) {
  26729. session.version = 0; // "v=0" must be there (only defined version atm)
  26730. }
  26731. if (session.name == null) {
  26732. session.name = " "; // "s= " must be there if no meaningful name set
  26733. }
  26734. session.media.forEach(function (mLine) {
  26735. if (mLine.payloads == null) {
  26736. mLine.payloads = "";
  26737. }
  26738. });
  26739. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26740. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26741. var sdp = [];
  26742. // loop through outerOrder for matching properties on session
  26743. outerOrder.forEach(function (type) {
  26744. grammar[type].forEach(function (obj) {
  26745. if (obj.name in session && session[obj.name] != null) {
  26746. sdp.push(makeLine(type, obj, session));
  26747. }
  26748. else if (obj.push in session && session[obj.push] != null) {
  26749. session[obj.push].forEach(function (el) {
  26750. sdp.push(makeLine(type, obj, el));
  26751. });
  26752. }
  26753. });
  26754. });
  26755. // then for each media line, follow the innerOrder
  26756. session.media.forEach(function (mLine) {
  26757. sdp.push(makeLine('m', grammar.m[0], mLine));
  26758. innerOrder.forEach(function (type) {
  26759. grammar[type].forEach(function (obj) {
  26760. if (obj.name in mLine && mLine[obj.name] != null) {
  26761. sdp.push(makeLine(type, obj, mLine));
  26762. }
  26763. else if (obj.push in mLine && mLine[obj.push] != null) {
  26764. mLine[obj.push].forEach(function (el) {
  26765. sdp.push(makeLine(type, obj, el));
  26766. });
  26767. }
  26768. });
  26769. });
  26770. });
  26771. return sdp.join('\r\n') + '\r\n';
  26772. };
  26773. },{"./grammar":98}],102:[function(require,module,exports){
  26774. var transform = require('sdp-transform');
  26775. var transformUtils = require('./transform-utils');
  26776. var parseSsrcs = transformUtils.parseSsrcs;
  26777. var writeSsrcs = transformUtils.writeSsrcs;
  26778. //region Constants
  26779. var DEFAULT_NUM_OF_LAYERS = 3;
  26780. //endregion
  26781. //region Ctor
  26782. function Simulcast(options) {
  26783. this.options = options ? options : {};
  26784. if (!this.options.numOfLayers) {
  26785. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26786. }
  26787. this.layers = [];
  26788. }
  26789. //endregion
  26790. //region Stateless private utility functions
  26791. /**
  26792. * Returns a random integer between min (included) and max (excluded)
  26793. * Using Math.round() gives a non-uniform distribution!
  26794. * @returns {number}
  26795. */
  26796. function generateSSRC() {
  26797. var min = 0, max = 0xffffffff;
  26798. return Math.floor(Math.random() * (max - min)) + min;
  26799. };
  26800. function processVideo(session, action) {
  26801. if (session == null || !Array.isArray(session.media)) {
  26802. return;
  26803. }
  26804. session.media.forEach(function (mLine) {
  26805. if (mLine.type === 'video') {
  26806. action(mLine);
  26807. }
  26808. });
  26809. }
  26810. function validateDescription(desc)
  26811. {
  26812. return desc && desc != null
  26813. && desc.type && desc.type != ''
  26814. && desc.sdp && desc.sdp != '';
  26815. }
  26816. function explodeRemoteSimulcast(mLine) {
  26817. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26818. return;
  26819. }
  26820. var sources = parseSsrcs(mLine);
  26821. var order = [];
  26822. // Find the SIM group and explode its sources.
  26823. var j = mLine.ssrcGroups.length;
  26824. while (j--) {
  26825. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26826. continue;
  26827. }
  26828. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26829. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26830. var ssrc = simulcastSsrcs[i];
  26831. order.push(ssrc);
  26832. var parts = sources[ssrc].msid.split(' ');
  26833. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26834. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26835. // Remove all the groups that this SSRC participates in.
  26836. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26837. if (relatedGroup.semantics === 'SIM') {
  26838. return;
  26839. }
  26840. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26841. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26842. return;
  26843. }
  26844. // Nuke all the related SSRCs.
  26845. relatedSsrcs.forEach(function (relatedSSRC) {
  26846. sources[relatedSSRC].msid = sources[ssrc].msid;
  26847. sources[relatedSSRC].cname = sources[ssrc].cname;
  26848. if (relatedSSRC !== ssrc) {
  26849. order.push(relatedSSRC);
  26850. }
  26851. });
  26852. // Schedule the related group for nuking.
  26853. })
  26854. }
  26855. mLine.ssrcs = writeSsrcs(sources, order);
  26856. mLine.ssrcGroups.splice(j, 1);
  26857. };
  26858. }
  26859. function squeezeRemoteSimulcast(mLine) {
  26860. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26861. return;
  26862. }
  26863. var sources = parseSsrcs(mLine);
  26864. // Find the SIM group and nuke it.
  26865. mLine.ssrcGroups.some(function (simulcastGroup) {
  26866. if (simulcastGroup.semantics !== 'SIM') {
  26867. return false;
  26868. }
  26869. // Schedule the SIM group for nuking.
  26870. simulcastGroup.nuke = true;
  26871. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26872. // Nuke all the higher layer SSRCs.
  26873. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26874. var ssrc = simulcastSsrcs[i];
  26875. delete sources[ssrc];
  26876. // Remove all the groups that this SSRC participates in.
  26877. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26878. if (relatedGroup.semantics === 'SIM') {
  26879. return;
  26880. }
  26881. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26882. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26883. return;
  26884. }
  26885. // Nuke all the related SSRCs.
  26886. relatedSsrcs.forEach(function (relatedSSRC) {
  26887. delete sources[relatedSSRC];
  26888. });
  26889. // Schedule the related group for nuking.
  26890. relatedGroup.nuke = true;
  26891. })
  26892. }
  26893. return true;
  26894. });
  26895. mLine.ssrcs = writeSsrcs(sources);
  26896. // Nuke all the scheduled groups.
  26897. var i = mLine.ssrcGroups.length;
  26898. while (i--) {
  26899. if (mLine.ssrcGroups[i].nuke) {
  26900. mLine.ssrcGroups.splice(i, 1);
  26901. }
  26902. }
  26903. }
  26904. function removeGoogConference(mLine) {
  26905. if (!mLine || !Array.isArray(mLine.invalid)) {
  26906. return;
  26907. }
  26908. var i = mLine.invalid.length;
  26909. while (i--) {
  26910. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26911. mLine.invalid.splice(i, 1);
  26912. }
  26913. }
  26914. }
  26915. function assertGoogConference(mLine) {
  26916. if (!mLine) {
  26917. return;
  26918. }
  26919. if (!Array.isArray(mLine.invalid)) {
  26920. mLine.invalid = [];
  26921. }
  26922. if (!mLine.invalid.some(
  26923. function (i) { return i.value === 'x-google-flag:conference' })) {
  26924. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26925. }
  26926. }
  26927. //endregion
  26928. //region "Private" functions
  26929. /**
  26930. *
  26931. * @param mLine
  26932. * @private
  26933. */
  26934. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26935. if (!mLine || mLine.type !== 'video') {
  26936. return;
  26937. }
  26938. var sources = parseSsrcs(mLine);
  26939. if (Object.keys(sources).length === 0) {
  26940. // no sources, disable simulcast.
  26941. if (this.layers.length !== 0) {
  26942. this.layers = [];
  26943. }
  26944. return;
  26945. }
  26946. // find the base layer (we'll reuse its msid and cname).
  26947. var baseLayerSSRC = Object.keys(sources)[0];
  26948. var baseLayer = sources[baseLayerSSRC];
  26949. // todo(gp) handle screen sharing.
  26950. // check if base CNAME has changed and reinitialise layers.
  26951. if (this.layers.length > 0
  26952. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26953. this.layers = [];
  26954. }
  26955. // (re)initialise layers
  26956. if (this.layers.length < 1) {
  26957. // first push the base layer.
  26958. this.layers.push({
  26959. ssrc: baseLayerSSRC,
  26960. msid: baseLayer.msid,
  26961. cname: baseLayer.cname
  26962. });
  26963. var rtx = false; // RFC 4588
  26964. if (Array.isArray(mLine.rtp)) {
  26965. rtx = mLine.rtp.some(
  26966. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26967. }
  26968. if (rtx) {
  26969. this.layers[0].rtx = generateSSRC();
  26970. }
  26971. // now push additional layers.
  26972. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26973. var layer = { ssrc: generateSSRC() };
  26974. if (rtx) {
  26975. layer.rtx = generateSSRC();
  26976. }
  26977. this.layers.push(layer);
  26978. }
  26979. }
  26980. };
  26981. /**
  26982. *
  26983. * @param mLine
  26984. * @private
  26985. */
  26986. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26987. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26988. var sources = {};
  26989. var msid = this.layers[0].msid;
  26990. var cname = this.layers[0].cname;
  26991. var simulcastSsrcs = [];
  26992. var ssrcGroups = [];
  26993. for (var i = 0; i < this.layers.length; i++) {
  26994. var layer = this.layers[i];
  26995. sources[layer.ssrc] = { msid: msid, cname: cname };
  26996. simulcastSsrcs.push(layer.ssrc);
  26997. if (layer.rtx) {
  26998. sources[layer.rtx] = {
  26999. msid: msid,
  27000. cname: cname
  27001. }
  27002. ssrcGroups.push({
  27003. semantics: 'FID',
  27004. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  27005. });
  27006. }
  27007. }
  27008. ssrcGroups.push({
  27009. semantics: 'SIM',
  27010. ssrcs: simulcastSsrcs.join(' ')
  27011. });
  27012. mLine.ssrcGroups = ssrcGroups;
  27013. mLine.ssrcs = writeSsrcs(sources);
  27014. }
  27015. }
  27016. //endregion
  27017. //region "Public" functions
  27018. Simulcast.prototype.isSupported = function () {
  27019. return window.chrome;
  27020. // TODO this needs improvements. For example I doubt that Chrome in Android
  27021. // has simulcast support. Also, only recent versions of Chromium have native
  27022. // simulcast support.
  27023. }
  27024. /**
  27025. *
  27026. * @param desc
  27027. * @returns {RTCSessionDescription}
  27028. */
  27029. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  27030. if (!validateDescription(desc)) {
  27031. return desc;
  27032. }
  27033. var session = transform.parse(desc.sdp);
  27034. var self = this;
  27035. processVideo(session, function (mLine) {
  27036. // Handle simulcast reception.
  27037. if (self.options.explodeRemoteSimulcast) {
  27038. explodeRemoteSimulcast(mLine);
  27039. } else {
  27040. squeezeRemoteSimulcast(mLine);
  27041. }
  27042. // If native simulcast is enabled, we must append the x-goog-conference
  27043. // attribute to the SDP.
  27044. if (self.layers.length < 1) {
  27045. removeGoogConference(mLine);
  27046. } else {
  27047. assertGoogConference(mLine);
  27048. }
  27049. });
  27050. return new RTCSessionDescription({
  27051. type: desc.type,
  27052. sdp: transform.write(session)
  27053. });
  27054. };
  27055. /**
  27056. *
  27057. * @param desc
  27058. * @returns {RTCSessionDescription}
  27059. */
  27060. Simulcast.prototype.mungeLocalDescription = function (desc) {
  27061. if (!validateDescription(desc) || !this.isSupported()) {
  27062. return desc;
  27063. }
  27064. var session = transform.parse(desc.sdp);
  27065. var self = this;
  27066. processVideo(session, function (mLine) {
  27067. // Initialize native simulcast layers, if not already done.
  27068. self._maybeInitializeLayers(mLine);
  27069. // Update the SDP with the simulcast layers.
  27070. self._restoreSimulcastView(mLine);
  27071. });
  27072. return new RTCSessionDescription({
  27073. type: desc.type,
  27074. sdp: transform.write(session)
  27075. });
  27076. };
  27077. //endregion
  27078. module.exports = Simulcast;
  27079. },{"./transform-utils":103,"sdp-transform":105}],103:[function(require,module,exports){
  27080. exports.writeSsrcs = function(sources, order) {
  27081. var ssrcs = [];
  27082. // expand sources to ssrcs
  27083. if (typeof sources !== 'undefined' &&
  27084. Object.keys(sources).length !== 0) {
  27085. if (Array.isArray(order)) {
  27086. for (var i = 0; i < order.length; i++) {
  27087. var ssrc = order[i];
  27088. var source = sources[ssrc];
  27089. Object.keys(source).forEach(function (attribute) {
  27090. ssrcs.push({
  27091. id: ssrc,
  27092. attribute: attribute,
  27093. value: source[attribute]
  27094. });
  27095. });
  27096. }
  27097. } else {
  27098. Object.keys(sources).forEach(function (ssrc) {
  27099. var source = sources[ssrc];
  27100. Object.keys(source).forEach(function (attribute) {
  27101. ssrcs.push({
  27102. id: ssrc,
  27103. attribute: attribute,
  27104. value: source[attribute]
  27105. });
  27106. });
  27107. });
  27108. }
  27109. }
  27110. return ssrcs;
  27111. };
  27112. exports.parseSsrcs = function (mLine) {
  27113. var sources = {};
  27114. // group sources attributes by ssrc.
  27115. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  27116. mLine.ssrcs.forEach(function (ssrc) {
  27117. if (!sources[ssrc.id])
  27118. sources[ssrc.id] = {};
  27119. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  27120. });
  27121. }
  27122. return sources;
  27123. };
  27124. },{}],104:[function(require,module,exports){
  27125. arguments[4][98][0].apply(exports,arguments)
  27126. },{"dup":98}],105:[function(require,module,exports){
  27127. arguments[4][99][0].apply(exports,arguments)
  27128. },{"./parser":106,"./writer":107,"dup":99}],106:[function(require,module,exports){
  27129. arguments[4][100][0].apply(exports,arguments)
  27130. },{"./grammar":104,"dup":100}],107:[function(require,module,exports){
  27131. arguments[4][101][0].apply(exports,arguments)
  27132. },{"./grammar":104,"dup":101}],108:[function(require,module,exports){
  27133. var grammar = module.exports = {
  27134. v: [{
  27135. name: 'version',
  27136. reg: /^(\d*)$/
  27137. }],
  27138. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  27139. // NB: sessionId will be a String in most cases because it is huge
  27140. name: 'origin',
  27141. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  27142. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  27143. format: "%s %s %d %s IP%d %s"
  27144. }],
  27145. // default parsing of these only (though some of these feel outdated)
  27146. s: [{ name: 'name' }],
  27147. i: [{ name: 'description' }],
  27148. u: [{ name: 'uri' }],
  27149. e: [{ name: 'email' }],
  27150. p: [{ name: 'phone' }],
  27151. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  27152. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  27153. //k: [{}], // outdated thing ignored
  27154. t: [{ //t=0 0
  27155. name: 'timing',
  27156. reg: /^(\d*) (\d*)/,
  27157. names: ['start', 'stop'],
  27158. format: "%d %d"
  27159. }],
  27160. c: [{ //c=IN IP4 10.47.197.26
  27161. name: 'connection',
  27162. reg: /^IN IP(\d) (\S*)/,
  27163. names: ['version', 'ip'],
  27164. format: "IN IP%d %s"
  27165. }],
  27166. b: [{ //b=AS:4000
  27167. push: 'bandwidth',
  27168. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  27169. names: ['type', 'limit'],
  27170. format: "%s:%s"
  27171. }],
  27172. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  27173. // NB: special - pushes to session
  27174. // TODO: rtp/fmtp should be filtered by the payloads found here?
  27175. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  27176. names: ['type', 'port', 'protocol', 'payloads'],
  27177. format: "%s %d %s %s"
  27178. }],
  27179. a: [
  27180. { //a=rtpmap:110 opus/48000/2
  27181. push: 'rtp',
  27182. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  27183. names: ['payload', 'codec', 'rate', 'encoding'],
  27184. format: function (o) {
  27185. return (o.encoding) ?
  27186. "rtpmap:%d %s/%s/%s":
  27187. "rtpmap:%d %s/%s";
  27188. }
  27189. },
  27190. {
  27191. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  27192. //a=fmtp:111 minptime=10; useinbandfec=1
  27193. push: 'fmtp',
  27194. reg: /^fmtp:(\d*) ([\S| ]*)/,
  27195. names: ['payload', 'config'],
  27196. format: "fmtp:%d %s"
  27197. },
  27198. { //a=control:streamid=0
  27199. name: 'control',
  27200. reg: /^control:(.*)/,
  27201. format: "control:%s"
  27202. },
  27203. { //a=rtcp:65179 IN IP4 193.84.77.194
  27204. name: 'rtcp',
  27205. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  27206. names: ['port', 'netType', 'ipVer', 'address'],
  27207. format: function (o) {
  27208. return (o.address != null) ?
  27209. "rtcp:%d %s IP%d %s":
  27210. "rtcp:%d";
  27211. }
  27212. },
  27213. { //a=rtcp-fb:98 trr-int 100
  27214. push: 'rtcpFbTrrInt',
  27215. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  27216. names: ['payload', 'value'],
  27217. format: "rtcp-fb:%d trr-int %d"
  27218. },
  27219. { //a=rtcp-fb:98 nack rpsi
  27220. push: 'rtcpFb',
  27221. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  27222. names: ['payload', 'type', 'subtype'],
  27223. format: function (o) {
  27224. return (o.subtype != null) ?
  27225. "rtcp-fb:%s %s %s":
  27226. "rtcp-fb:%s %s";
  27227. }
  27228. },
  27229. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  27230. //a=extmap:1/recvonly URI-gps-string
  27231. push: 'ext',
  27232. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  27233. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  27234. format: function (o) {
  27235. return (o.config != null) ?
  27236. "extmap:%s %s %s":
  27237. "extmap:%s %s";
  27238. }
  27239. },
  27240. {
  27241. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  27242. push: 'crypto',
  27243. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  27244. names: ['id', 'suite', 'config', 'sessionConfig'],
  27245. format: function (o) {
  27246. return (o.sessionConfig != null) ?
  27247. "crypto:%d %s %s %s":
  27248. "crypto:%d %s %s";
  27249. }
  27250. },
  27251. { //a=setup:actpass
  27252. name: 'setup',
  27253. reg: /^setup:(\w*)/,
  27254. format: "setup:%s"
  27255. },
  27256. { //a=mid:1
  27257. name: 'mid',
  27258. reg: /^mid:([^\s]*)/,
  27259. format: "mid:%s"
  27260. },
  27261. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  27262. name: 'msid',
  27263. reg: /^msid:(.*)/,
  27264. format: "msid:%s"
  27265. },
  27266. { //a=ptime:20
  27267. name: 'ptime',
  27268. reg: /^ptime:(\d*)/,
  27269. format: "ptime:%d"
  27270. },
  27271. { //a=maxptime:60
  27272. name: 'maxptime',
  27273. reg: /^maxptime:(\d*)/,
  27274. format: "maxptime:%d"
  27275. },
  27276. { //a=sendrecv
  27277. name: 'direction',
  27278. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  27279. },
  27280. { //a=ice-lite
  27281. name: 'icelite',
  27282. reg: /^(ice-lite)/
  27283. },
  27284. { //a=ice-ufrag:F7gI
  27285. name: 'iceUfrag',
  27286. reg: /^ice-ufrag:(\S*)/,
  27287. format: "ice-ufrag:%s"
  27288. },
  27289. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  27290. name: 'icePwd',
  27291. reg: /^ice-pwd:(\S*)/,
  27292. format: "ice-pwd:%s"
  27293. },
  27294. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  27295. name: 'fingerprint',
  27296. reg: /^fingerprint:(\S*) (\S*)/,
  27297. names: ['type', 'hash'],
  27298. format: "fingerprint:%s %s"
  27299. },
  27300. {
  27301. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  27302. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  27303. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  27304. push:'candidates',
  27305. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  27306. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  27307. format: function (o) {
  27308. var str = "candidate:%s %d %s %d %s %d typ %s";
  27309. // NB: candidate has two optional chunks, so %void middle one if it's missing
  27310. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  27311. if (o.generation != null) {
  27312. str += " generation %d";
  27313. }
  27314. return str;
  27315. }
  27316. },
  27317. { //a=end-of-candidates (keep after the candidates line for readability)
  27318. name: 'endOfCandidates',
  27319. reg: /^(end-of-candidates)/
  27320. },
  27321. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  27322. name: 'remoteCandidates',
  27323. reg: /^remote-candidates:(.*)/,
  27324. format: "remote-candidates:%s"
  27325. },
  27326. { //a=ice-options:google-ice
  27327. name: 'iceOptions',
  27328. reg: /^ice-options:(\S*)/,
  27329. format: "ice-options:%s"
  27330. },
  27331. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  27332. push: "ssrcs",
  27333. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  27334. names: ['id', 'attribute', 'value'],
  27335. format: "ssrc:%d %s:%s"
  27336. },
  27337. { //a=ssrc-group:FEC 1 2
  27338. push: "ssrcGroups",
  27339. reg: /^ssrc-group:(\w*) (.*)/,
  27340. names: ['semantics', 'ssrcs'],
  27341. format: "ssrc-group:%s %s"
  27342. },
  27343. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  27344. name: "msidSemantic",
  27345. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  27346. names: ['semantic', 'token'],
  27347. format: "msid-semantic: %s %s" // space after ":" is not accidental
  27348. },
  27349. { //a=group:BUNDLE audio video
  27350. push: 'groups',
  27351. reg: /^group:(\w*) (.*)/,
  27352. names: ['type', 'mids'],
  27353. format: "group:%s %s"
  27354. },
  27355. { //a=rtcp-mux
  27356. name: 'rtcpMux',
  27357. reg: /^(rtcp-mux)/
  27358. },
  27359. { //a=rtcp-rsize
  27360. name: 'rtcpRsize',
  27361. reg: /^(rtcp-rsize)/
  27362. },
  27363. { // any a= that we don't understand is kepts verbatim on media.invalid
  27364. push: 'invalid',
  27365. names: ["value"]
  27366. }
  27367. ]
  27368. };
  27369. // set sensible defaults to avoid polluting the grammar with boring details
  27370. Object.keys(grammar).forEach(function (key) {
  27371. var objs = grammar[key];
  27372. objs.forEach(function (obj) {
  27373. if (!obj.reg) {
  27374. obj.reg = /(.*)/;
  27375. }
  27376. if (!obj.format) {
  27377. obj.format = "%s";
  27378. }
  27379. });
  27380. });
  27381. },{}],109:[function(require,module,exports){
  27382. arguments[4][99][0].apply(exports,arguments)
  27383. },{"./parser":110,"./writer":111,"dup":99}],110:[function(require,module,exports){
  27384. var toIntIfInt = function (v) {
  27385. return String(Number(v)) === v ? Number(v) : v;
  27386. };
  27387. var attachProperties = function (match, location, names, rawName) {
  27388. if (rawName && !names) {
  27389. location[rawName] = toIntIfInt(match[1]);
  27390. }
  27391. else {
  27392. for (var i = 0; i < names.length; i += 1) {
  27393. if (match[i+1] != null) {
  27394. location[names[i]] = toIntIfInt(match[i+1]);
  27395. }
  27396. }
  27397. }
  27398. };
  27399. var parseReg = function (obj, location, content) {
  27400. var needsBlank = obj.name && obj.names;
  27401. if (obj.push && !location[obj.push]) {
  27402. location[obj.push] = [];
  27403. }
  27404. else if (needsBlank && !location[obj.name]) {
  27405. location[obj.name] = {};
  27406. }
  27407. var keyLocation = obj.push ?
  27408. {} : // blank object that will be pushed
  27409. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  27410. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  27411. if (obj.push) {
  27412. location[obj.push].push(keyLocation);
  27413. }
  27414. };
  27415. var grammar = require('./grammar');
  27416. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  27417. exports.parse = function (sdp) {
  27418. var session = {}
  27419. , media = []
  27420. , location = session; // points at where properties go under (one of the above)
  27421. // parse lines we understand
  27422. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  27423. var type = l[0];
  27424. var content = l.slice(2);
  27425. if (type === 'm') {
  27426. media.push({rtp: [], fmtp: []});
  27427. location = media[media.length-1]; // point at latest media line
  27428. }
  27429. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  27430. var obj = grammar[type][j];
  27431. if (obj.reg.test(content)) {
  27432. return parseReg(obj, location, content);
  27433. }
  27434. }
  27435. });
  27436. session.media = media; // link it up
  27437. return session;
  27438. };
  27439. var fmtpReducer = function (acc, expr) {
  27440. var s = expr.split('=');
  27441. if (s.length === 2) {
  27442. acc[s[0]] = toIntIfInt(s[1]);
  27443. }
  27444. return acc;
  27445. };
  27446. exports.parseFmtpConfig = function (str) {
  27447. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  27448. };
  27449. exports.parsePayloads = function (str) {
  27450. return str.split(' ').map(Number);
  27451. };
  27452. exports.parseRemoteCandidates = function (str) {
  27453. var candidates = [];
  27454. var parts = str.split(' ').map(toIntIfInt);
  27455. for (var i = 0; i < parts.length; i += 3) {
  27456. candidates.push({
  27457. component: parts[i],
  27458. ip: parts[i + 1],
  27459. port: parts[i + 2]
  27460. });
  27461. }
  27462. return candidates;
  27463. };
  27464. },{"./grammar":108}],111:[function(require,module,exports){
  27465. arguments[4][101][0].apply(exports,arguments)
  27466. },{"./grammar":108,"dup":101}],112:[function(require,module,exports){
  27467. module.exports = require('./lib/');
  27468. },{"./lib/":113}],113:[function(require,module,exports){
  27469. /**
  27470. * Module dependencies.
  27471. */
  27472. var url = require('./url');
  27473. var parser = require('socket.io-parser');
  27474. var Manager = require('./manager');
  27475. var debug = require('debug')('socket.io-client');
  27476. /**
  27477. * Module exports.
  27478. */
  27479. module.exports = exports = lookup;
  27480. /**
  27481. * Managers cache.
  27482. */
  27483. var cache = exports.managers = {};
  27484. /**
  27485. * Looks up an existing `Manager` for multiplexing.
  27486. * If the user summons:
  27487. *
  27488. * `io('http://localhost/a');`
  27489. * `io('http://localhost/b');`
  27490. *
  27491. * We reuse the existing instance based on same scheme/port/host,
  27492. * and we initialize sockets for each namespace.
  27493. *
  27494. * @api public
  27495. */
  27496. function lookup(uri, opts) {
  27497. if (typeof uri == 'object') {
  27498. opts = uri;
  27499. uri = undefined;
  27500. }
  27501. opts = opts || {};
  27502. var parsed = url(uri);
  27503. var source = parsed.source;
  27504. var id = parsed.id;
  27505. var io;
  27506. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  27507. debug('ignoring socket cache for %s', source);
  27508. io = Manager(source, opts);
  27509. } else {
  27510. if (!cache[id]) {
  27511. debug('new io instance for %s', source);
  27512. cache[id] = Manager(source, opts);
  27513. }
  27514. io = cache[id];
  27515. }
  27516. return io.socket(parsed.path);
  27517. }
  27518. /**
  27519. * Protocol version.
  27520. *
  27521. * @api public
  27522. */
  27523. exports.protocol = parser.protocol;
  27524. /**
  27525. * `connect`.
  27526. *
  27527. * @param {String} uri
  27528. * @api public
  27529. */
  27530. exports.connect = lookup;
  27531. /**
  27532. * Expose constructors for standalone build.
  27533. *
  27534. * @api public
  27535. */
  27536. exports.Manager = require('./manager');
  27537. exports.Socket = require('./socket');
  27538. },{"./manager":114,"./socket":116,"./url":117,"debug":121,"socket.io-parser":157}],114:[function(require,module,exports){
  27539. /**
  27540. * Module dependencies.
  27541. */
  27542. var url = require('./url');
  27543. var eio = require('engine.io-client');
  27544. var Socket = require('./socket');
  27545. var Emitter = require('component-emitter');
  27546. var parser = require('socket.io-parser');
  27547. var on = require('./on');
  27548. var bind = require('component-bind');
  27549. var object = require('object-component');
  27550. var debug = require('debug')('socket.io-client:manager');
  27551. var indexOf = require('indexof');
  27552. var Backoff = require('backo2');
  27553. /**
  27554. * Module exports
  27555. */
  27556. module.exports = Manager;
  27557. /**
  27558. * `Manager` constructor.
  27559. *
  27560. * @param {String} engine instance or engine uri/opts
  27561. * @param {Object} options
  27562. * @api public
  27563. */
  27564. function Manager(uri, opts){
  27565. if (!(this instanceof Manager)) return new Manager(uri, opts);
  27566. if (uri && ('object' == typeof uri)) {
  27567. opts = uri;
  27568. uri = undefined;
  27569. }
  27570. opts = opts || {};
  27571. opts.path = opts.path || '/socket.io';
  27572. this.nsps = {};
  27573. this.subs = [];
  27574. this.opts = opts;
  27575. this.reconnection(opts.reconnection !== false);
  27576. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  27577. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  27578. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  27579. this.randomizationFactor(opts.randomizationFactor || 0.5);
  27580. this.backoff = new Backoff({
  27581. min: this.reconnectionDelay(),
  27582. max: this.reconnectionDelayMax(),
  27583. jitter: this.randomizationFactor()
  27584. });
  27585. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  27586. this.readyState = 'closed';
  27587. this.uri = uri;
  27588. this.connected = [];
  27589. this.encoding = false;
  27590. this.packetBuffer = [];
  27591. this.encoder = new parser.Encoder();
  27592. this.decoder = new parser.Decoder();
  27593. this.autoConnect = opts.autoConnect !== false;
  27594. if (this.autoConnect) this.open();
  27595. }
  27596. /**
  27597. * Propagate given event to sockets and emit on `this`
  27598. *
  27599. * @api private
  27600. */
  27601. Manager.prototype.emitAll = function() {
  27602. this.emit.apply(this, arguments);
  27603. for (var nsp in this.nsps) {
  27604. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  27605. }
  27606. };
  27607. /**
  27608. * Update `socket.id` of all sockets
  27609. *
  27610. * @api private
  27611. */
  27612. Manager.prototype.updateSocketIds = function(){
  27613. for (var nsp in this.nsps) {
  27614. this.nsps[nsp].id = this.engine.id;
  27615. }
  27616. };
  27617. /**
  27618. * Mix in `Emitter`.
  27619. */
  27620. Emitter(Manager.prototype);
  27621. /**
  27622. * Sets the `reconnection` config.
  27623. *
  27624. * @param {Boolean} true/false if it should automatically reconnect
  27625. * @return {Manager} self or value
  27626. * @api public
  27627. */
  27628. Manager.prototype.reconnection = function(v){
  27629. if (!arguments.length) return this._reconnection;
  27630. this._reconnection = !!v;
  27631. return this;
  27632. };
  27633. /**
  27634. * Sets the reconnection attempts config.
  27635. *
  27636. * @param {Number} max reconnection attempts before giving up
  27637. * @return {Manager} self or value
  27638. * @api public
  27639. */
  27640. Manager.prototype.reconnectionAttempts = function(v){
  27641. if (!arguments.length) return this._reconnectionAttempts;
  27642. this._reconnectionAttempts = v;
  27643. return this;
  27644. };
  27645. /**
  27646. * Sets the delay between reconnections.
  27647. *
  27648. * @param {Number} delay
  27649. * @return {Manager} self or value
  27650. * @api public
  27651. */
  27652. Manager.prototype.reconnectionDelay = function(v){
  27653. if (!arguments.length) return this._reconnectionDelay;
  27654. this._reconnectionDelay = v;
  27655. this.backoff && this.backoff.setMin(v);
  27656. return this;
  27657. };
  27658. Manager.prototype.randomizationFactor = function(v){
  27659. if (!arguments.length) return this._randomizationFactor;
  27660. this._randomizationFactor = v;
  27661. this.backoff && this.backoff.setJitter(v);
  27662. return this;
  27663. };
  27664. /**
  27665. * Sets the maximum delay between reconnections.
  27666. *
  27667. * @param {Number} delay
  27668. * @return {Manager} self or value
  27669. * @api public
  27670. */
  27671. Manager.prototype.reconnectionDelayMax = function(v){
  27672. if (!arguments.length) return this._reconnectionDelayMax;
  27673. this._reconnectionDelayMax = v;
  27674. this.backoff && this.backoff.setMax(v);
  27675. return this;
  27676. };
  27677. /**
  27678. * Sets the connection timeout. `false` to disable
  27679. *
  27680. * @return {Manager} self or value
  27681. * @api public
  27682. */
  27683. Manager.prototype.timeout = function(v){
  27684. if (!arguments.length) return this._timeout;
  27685. this._timeout = v;
  27686. return this;
  27687. };
  27688. /**
  27689. * Starts trying to reconnect if reconnection is enabled and we have not
  27690. * started reconnecting yet
  27691. *
  27692. * @api private
  27693. */
  27694. Manager.prototype.maybeReconnectOnOpen = function() {
  27695. // Only try to reconnect if it's the first time we're connecting
  27696. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  27697. // keeps reconnection from firing twice for the same reconnection loop
  27698. this.reconnect();
  27699. }
  27700. };
  27701. /**
  27702. * Sets the current transport `socket`.
  27703. *
  27704. * @param {Function} optional, callback
  27705. * @return {Manager} self
  27706. * @api public
  27707. */
  27708. Manager.prototype.open =
  27709. Manager.prototype.connect = function(fn){
  27710. debug('readyState %s', this.readyState);
  27711. if (~this.readyState.indexOf('open')) return this;
  27712. debug('opening %s', this.uri);
  27713. this.engine = eio(this.uri, this.opts);
  27714. var socket = this.engine;
  27715. var self = this;
  27716. this.readyState = 'opening';
  27717. this.skipReconnect = false;
  27718. // emit `open`
  27719. var openSub = on(socket, 'open', function() {
  27720. self.onopen();
  27721. fn && fn();
  27722. });
  27723. // emit `connect_error`
  27724. var errorSub = on(socket, 'error', function(data){
  27725. debug('connect_error');
  27726. self.cleanup();
  27727. self.readyState = 'closed';
  27728. self.emitAll('connect_error', data);
  27729. if (fn) {
  27730. var err = new Error('Connection error');
  27731. err.data = data;
  27732. fn(err);
  27733. } else {
  27734. // Only do this if there is no fn to handle the error
  27735. self.maybeReconnectOnOpen();
  27736. }
  27737. });
  27738. // emit `connect_timeout`
  27739. if (false !== this._timeout) {
  27740. var timeout = this._timeout;
  27741. debug('connect attempt will timeout after %d', timeout);
  27742. // set timer
  27743. var timer = setTimeout(function(){
  27744. debug('connect attempt timed out after %d', timeout);
  27745. openSub.destroy();
  27746. socket.close();
  27747. socket.emit('error', 'timeout');
  27748. self.emitAll('connect_timeout', timeout);
  27749. }, timeout);
  27750. this.subs.push({
  27751. destroy: function(){
  27752. clearTimeout(timer);
  27753. }
  27754. });
  27755. }
  27756. this.subs.push(openSub);
  27757. this.subs.push(errorSub);
  27758. return this;
  27759. };
  27760. /**
  27761. * Called upon transport open.
  27762. *
  27763. * @api private
  27764. */
  27765. Manager.prototype.onopen = function(){
  27766. debug('open');
  27767. // clear old subs
  27768. this.cleanup();
  27769. // mark as open
  27770. this.readyState = 'open';
  27771. this.emit('open');
  27772. // add new subs
  27773. var socket = this.engine;
  27774. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  27775. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  27776. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  27777. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  27778. };
  27779. /**
  27780. * Called with data.
  27781. *
  27782. * @api private
  27783. */
  27784. Manager.prototype.ondata = function(data){
  27785. this.decoder.add(data);
  27786. };
  27787. /**
  27788. * Called when parser fully decodes a packet.
  27789. *
  27790. * @api private
  27791. */
  27792. Manager.prototype.ondecoded = function(packet) {
  27793. this.emit('packet', packet);
  27794. };
  27795. /**
  27796. * Called upon socket error.
  27797. *
  27798. * @api private
  27799. */
  27800. Manager.prototype.onerror = function(err){
  27801. debug('error', err);
  27802. this.emitAll('error', err);
  27803. };
  27804. /**
  27805. * Creates a new socket for the given `nsp`.
  27806. *
  27807. * @return {Socket}
  27808. * @api public
  27809. */
  27810. Manager.prototype.socket = function(nsp){
  27811. var socket = this.nsps[nsp];
  27812. if (!socket) {
  27813. socket = new Socket(this, nsp);
  27814. this.nsps[nsp] = socket;
  27815. var self = this;
  27816. socket.on('connect', function(){
  27817. socket.id = self.engine.id;
  27818. if (!~indexOf(self.connected, socket)) {
  27819. self.connected.push(socket);
  27820. }
  27821. });
  27822. }
  27823. return socket;
  27824. };
  27825. /**
  27826. * Called upon a socket close.
  27827. *
  27828. * @param {Socket} socket
  27829. */
  27830. Manager.prototype.destroy = function(socket){
  27831. var index = indexOf(this.connected, socket);
  27832. if (~index) this.connected.splice(index, 1);
  27833. if (this.connected.length) return;
  27834. this.close();
  27835. };
  27836. /**
  27837. * Writes a packet.
  27838. *
  27839. * @param {Object} packet
  27840. * @api private
  27841. */
  27842. Manager.prototype.packet = function(packet){
  27843. debug('writing packet %j', packet);
  27844. var self = this;
  27845. if (!self.encoding) {
  27846. // encode, then write to engine with result
  27847. self.encoding = true;
  27848. this.encoder.encode(packet, function(encodedPackets) {
  27849. for (var i = 0; i < encodedPackets.length; i++) {
  27850. self.engine.write(encodedPackets[i]);
  27851. }
  27852. self.encoding = false;
  27853. self.processPacketQueue();
  27854. });
  27855. } else { // add packet to the queue
  27856. self.packetBuffer.push(packet);
  27857. }
  27858. };
  27859. /**
  27860. * If packet buffer is non-empty, begins encoding the
  27861. * next packet in line.
  27862. *
  27863. * @api private
  27864. */
  27865. Manager.prototype.processPacketQueue = function() {
  27866. if (this.packetBuffer.length > 0 && !this.encoding) {
  27867. var pack = this.packetBuffer.shift();
  27868. this.packet(pack);
  27869. }
  27870. };
  27871. /**
  27872. * Clean up transport subscriptions and packet buffer.
  27873. *
  27874. * @api private
  27875. */
  27876. Manager.prototype.cleanup = function(){
  27877. var sub;
  27878. while (sub = this.subs.shift()) sub.destroy();
  27879. this.packetBuffer = [];
  27880. this.encoding = false;
  27881. this.decoder.destroy();
  27882. };
  27883. /**
  27884. * Close the current socket.
  27885. *
  27886. * @api private
  27887. */
  27888. Manager.prototype.close =
  27889. Manager.prototype.disconnect = function(){
  27890. this.skipReconnect = true;
  27891. this.backoff.reset();
  27892. this.readyState = 'closed';
  27893. this.engine && this.engine.close();
  27894. };
  27895. /**
  27896. * Called upon engine close.
  27897. *
  27898. * @api private
  27899. */
  27900. Manager.prototype.onclose = function(reason){
  27901. debug('close');
  27902. this.cleanup();
  27903. this.backoff.reset();
  27904. this.readyState = 'closed';
  27905. this.emit('close', reason);
  27906. if (this._reconnection && !this.skipReconnect) {
  27907. this.reconnect();
  27908. }
  27909. };
  27910. /**
  27911. * Attempt a reconnection.
  27912. *
  27913. * @api private
  27914. */
  27915. Manager.prototype.reconnect = function(){
  27916. if (this.reconnecting || this.skipReconnect) return this;
  27917. var self = this;
  27918. if (this.backoff.attempts >= this._reconnectionAttempts) {
  27919. debug('reconnect failed');
  27920. this.backoff.reset();
  27921. this.emitAll('reconnect_failed');
  27922. this.reconnecting = false;
  27923. } else {
  27924. var delay = this.backoff.duration();
  27925. debug('will wait %dms before reconnect attempt', delay);
  27926. this.reconnecting = true;
  27927. var timer = setTimeout(function(){
  27928. if (self.skipReconnect) return;
  27929. debug('attempting reconnect');
  27930. self.emitAll('reconnect_attempt', self.backoff.attempts);
  27931. self.emitAll('reconnecting', self.backoff.attempts);
  27932. // check again for the case socket closed in above events
  27933. if (self.skipReconnect) return;
  27934. self.open(function(err){
  27935. if (err) {
  27936. debug('reconnect attempt error');
  27937. self.reconnecting = false;
  27938. self.reconnect();
  27939. self.emitAll('reconnect_error', err.data);
  27940. } else {
  27941. debug('reconnect success');
  27942. self.onreconnect();
  27943. }
  27944. });
  27945. }, delay);
  27946. this.subs.push({
  27947. destroy: function(){
  27948. clearTimeout(timer);
  27949. }
  27950. });
  27951. }
  27952. };
  27953. /**
  27954. * Called upon successful reconnect.
  27955. *
  27956. * @api private
  27957. */
  27958. Manager.prototype.onreconnect = function(){
  27959. var attempt = this.backoff.attempts;
  27960. this.reconnecting = false;
  27961. this.backoff.reset();
  27962. this.updateSocketIds();
  27963. this.emitAll('reconnect', attempt);
  27964. };
  27965. },{"./on":115,"./socket":116,"./url":117,"backo2":118,"component-bind":119,"component-emitter":120,"debug":121,"engine.io-client":122,"indexof":153,"object-component":154,"socket.io-parser":157}],115:[function(require,module,exports){
  27966. /**
  27967. * Module exports.
  27968. */
  27969. module.exports = on;
  27970. /**
  27971. * Helper for subscriptions.
  27972. *
  27973. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  27974. * @param {String} event name
  27975. * @param {Function} callback
  27976. * @api public
  27977. */
  27978. function on(obj, ev, fn) {
  27979. obj.on(ev, fn);
  27980. return {
  27981. destroy: function(){
  27982. obj.removeListener(ev, fn);
  27983. }
  27984. };
  27985. }
  27986. },{}],116:[function(require,module,exports){
  27987. /**
  27988. * Module dependencies.
  27989. */
  27990. var parser = require('socket.io-parser');
  27991. var Emitter = require('component-emitter');
  27992. var toArray = require('to-array');
  27993. var on = require('./on');
  27994. var bind = require('component-bind');
  27995. var debug = require('debug')('socket.io-client:socket');
  27996. var hasBin = require('has-binary');
  27997. /**
  27998. * Module exports.
  27999. */
  28000. module.exports = exports = Socket;
  28001. /**
  28002. * Internal events (blacklisted).
  28003. * These events can't be emitted by the user.
  28004. *
  28005. * @api private
  28006. */
  28007. var events = {
  28008. connect: 1,
  28009. connect_error: 1,
  28010. connect_timeout: 1,
  28011. disconnect: 1,
  28012. error: 1,
  28013. reconnect: 1,
  28014. reconnect_attempt: 1,
  28015. reconnect_failed: 1,
  28016. reconnect_error: 1,
  28017. reconnecting: 1
  28018. };
  28019. /**
  28020. * Shortcut to `Emitter#emit`.
  28021. */
  28022. var emit = Emitter.prototype.emit;
  28023. /**
  28024. * `Socket` constructor.
  28025. *
  28026. * @api public
  28027. */
  28028. function Socket(io, nsp){
  28029. this.io = io;
  28030. this.nsp = nsp;
  28031. this.json = this; // compat
  28032. this.ids = 0;
  28033. this.acks = {};
  28034. if (this.io.autoConnect) this.open();
  28035. this.receiveBuffer = [];
  28036. this.sendBuffer = [];
  28037. this.connected = false;
  28038. this.disconnected = true;
  28039. }
  28040. /**
  28041. * Mix in `Emitter`.
  28042. */
  28043. Emitter(Socket.prototype);
  28044. /**
  28045. * Subscribe to open, close and packet events
  28046. *
  28047. * @api private
  28048. */
  28049. Socket.prototype.subEvents = function() {
  28050. if (this.subs) return;
  28051. var io = this.io;
  28052. this.subs = [
  28053. on(io, 'open', bind(this, 'onopen')),
  28054. on(io, 'packet', bind(this, 'onpacket')),
  28055. on(io, 'close', bind(this, 'onclose'))
  28056. ];
  28057. };
  28058. /**
  28059. * "Opens" the socket.
  28060. *
  28061. * @api public
  28062. */
  28063. Socket.prototype.open =
  28064. Socket.prototype.connect = function(){
  28065. if (this.connected) return this;
  28066. this.subEvents();
  28067. this.io.open(); // ensure open
  28068. if ('open' == this.io.readyState) this.onopen();
  28069. return this;
  28070. };
  28071. /**
  28072. * Sends a `message` event.
  28073. *
  28074. * @return {Socket} self
  28075. * @api public
  28076. */
  28077. Socket.prototype.send = function(){
  28078. var args = toArray(arguments);
  28079. args.unshift('message');
  28080. this.emit.apply(this, args);
  28081. return this;
  28082. };
  28083. /**
  28084. * Override `emit`.
  28085. * If the event is in `events`, it's emitted normally.
  28086. *
  28087. * @param {String} event name
  28088. * @return {Socket} self
  28089. * @api public
  28090. */
  28091. Socket.prototype.emit = function(ev){
  28092. if (events.hasOwnProperty(ev)) {
  28093. emit.apply(this, arguments);
  28094. return this;
  28095. }
  28096. var args = toArray(arguments);
  28097. var parserType = parser.EVENT; // default
  28098. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  28099. var packet = { type: parserType, data: args };
  28100. // event ack callback
  28101. if ('function' == typeof args[args.length - 1]) {
  28102. debug('emitting packet with ack id %d', this.ids);
  28103. this.acks[this.ids] = args.pop();
  28104. packet.id = this.ids++;
  28105. }
  28106. if (this.connected) {
  28107. this.packet(packet);
  28108. } else {
  28109. this.sendBuffer.push(packet);
  28110. }
  28111. return this;
  28112. };
  28113. /**
  28114. * Sends a packet.
  28115. *
  28116. * @param {Object} packet
  28117. * @api private
  28118. */
  28119. Socket.prototype.packet = function(packet){
  28120. packet.nsp = this.nsp;
  28121. this.io.packet(packet);
  28122. };
  28123. /**
  28124. * Called upon engine `open`.
  28125. *
  28126. * @api private
  28127. */
  28128. Socket.prototype.onopen = function(){
  28129. debug('transport is open - connecting');
  28130. // write connect packet if necessary
  28131. if ('/' != this.nsp) {
  28132. this.packet({ type: parser.CONNECT });
  28133. }
  28134. };
  28135. /**
  28136. * Called upon engine `close`.
  28137. *
  28138. * @param {String} reason
  28139. * @api private
  28140. */
  28141. Socket.prototype.onclose = function(reason){
  28142. debug('close (%s)', reason);
  28143. this.connected = false;
  28144. this.disconnected = true;
  28145. delete this.id;
  28146. this.emit('disconnect', reason);
  28147. };
  28148. /**
  28149. * Called with socket packet.
  28150. *
  28151. * @param {Object} packet
  28152. * @api private
  28153. */
  28154. Socket.prototype.onpacket = function(packet){
  28155. if (packet.nsp != this.nsp) return;
  28156. switch (packet.type) {
  28157. case parser.CONNECT:
  28158. this.onconnect();
  28159. break;
  28160. case parser.EVENT:
  28161. this.onevent(packet);
  28162. break;
  28163. case parser.BINARY_EVENT:
  28164. this.onevent(packet);
  28165. break;
  28166. case parser.ACK:
  28167. this.onack(packet);
  28168. break;
  28169. case parser.BINARY_ACK:
  28170. this.onack(packet);
  28171. break;
  28172. case parser.DISCONNECT:
  28173. this.ondisconnect();
  28174. break;
  28175. case parser.ERROR:
  28176. this.emit('error', packet.data);
  28177. break;
  28178. }
  28179. };
  28180. /**
  28181. * Called upon a server event.
  28182. *
  28183. * @param {Object} packet
  28184. * @api private
  28185. */
  28186. Socket.prototype.onevent = function(packet){
  28187. var args = packet.data || [];
  28188. debug('emitting event %j', args);
  28189. if (null != packet.id) {
  28190. debug('attaching ack callback to event');
  28191. args.push(this.ack(packet.id));
  28192. }
  28193. if (this.connected) {
  28194. emit.apply(this, args);
  28195. } else {
  28196. this.receiveBuffer.push(args);
  28197. }
  28198. };
  28199. /**
  28200. * Produces an ack callback to emit with an event.
  28201. *
  28202. * @api private
  28203. */
  28204. Socket.prototype.ack = function(id){
  28205. var self = this;
  28206. var sent = false;
  28207. return function(){
  28208. // prevent double callbacks
  28209. if (sent) return;
  28210. sent = true;
  28211. var args = toArray(arguments);
  28212. debug('sending ack %j', args);
  28213. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  28214. self.packet({
  28215. type: type,
  28216. id: id,
  28217. data: args
  28218. });
  28219. };
  28220. };
  28221. /**
  28222. * Called upon a server acknowlegement.
  28223. *
  28224. * @param {Object} packet
  28225. * @api private
  28226. */
  28227. Socket.prototype.onack = function(packet){
  28228. debug('calling ack %s with %j', packet.id, packet.data);
  28229. var fn = this.acks[packet.id];
  28230. fn.apply(this, packet.data);
  28231. delete this.acks[packet.id];
  28232. };
  28233. /**
  28234. * Called upon server connect.
  28235. *
  28236. * @api private
  28237. */
  28238. Socket.prototype.onconnect = function(){
  28239. this.connected = true;
  28240. this.disconnected = false;
  28241. this.emit('connect');
  28242. this.emitBuffered();
  28243. };
  28244. /**
  28245. * Emit buffered events (received and emitted).
  28246. *
  28247. * @api private
  28248. */
  28249. Socket.prototype.emitBuffered = function(){
  28250. var i;
  28251. for (i = 0; i < this.receiveBuffer.length; i++) {
  28252. emit.apply(this, this.receiveBuffer[i]);
  28253. }
  28254. this.receiveBuffer = [];
  28255. for (i = 0; i < this.sendBuffer.length; i++) {
  28256. this.packet(this.sendBuffer[i]);
  28257. }
  28258. this.sendBuffer = [];
  28259. };
  28260. /**
  28261. * Called upon server disconnect.
  28262. *
  28263. * @api private
  28264. */
  28265. Socket.prototype.ondisconnect = function(){
  28266. debug('server disconnect (%s)', this.nsp);
  28267. this.destroy();
  28268. this.onclose('io server disconnect');
  28269. };
  28270. /**
  28271. * Called upon forced client/server side disconnections,
  28272. * this method ensures the manager stops tracking us and
  28273. * that reconnections don't get triggered for this.
  28274. *
  28275. * @api private.
  28276. */
  28277. Socket.prototype.destroy = function(){
  28278. if (this.subs) {
  28279. // clean subscriptions to avoid reconnections
  28280. for (var i = 0; i < this.subs.length; i++) {
  28281. this.subs[i].destroy();
  28282. }
  28283. this.subs = null;
  28284. }
  28285. this.io.destroy(this);
  28286. };
  28287. /**
  28288. * Disconnects the socket manually.
  28289. *
  28290. * @return {Socket} self
  28291. * @api public
  28292. */
  28293. Socket.prototype.close =
  28294. Socket.prototype.disconnect = function(){
  28295. if (this.connected) {
  28296. debug('performing disconnect (%s)', this.nsp);
  28297. this.packet({ type: parser.DISCONNECT });
  28298. }
  28299. // remove socket from pool
  28300. this.destroy();
  28301. if (this.connected) {
  28302. // fire events
  28303. this.onclose('io client disconnect');
  28304. }
  28305. return this;
  28306. };
  28307. },{"./on":115,"component-bind":119,"component-emitter":120,"debug":121,"has-binary":151,"socket.io-parser":157,"to-array":161}],117:[function(require,module,exports){
  28308. (function (global){
  28309. /**
  28310. * Module dependencies.
  28311. */
  28312. var parseuri = require('parseuri');
  28313. var debug = require('debug')('socket.io-client:url');
  28314. /**
  28315. * Module exports.
  28316. */
  28317. module.exports = url;
  28318. /**
  28319. * URL parser.
  28320. *
  28321. * @param {String} url
  28322. * @param {Object} An object meant to mimic window.location.
  28323. * Defaults to window.location.
  28324. * @api public
  28325. */
  28326. function url(uri, loc){
  28327. var obj = uri;
  28328. // default to window.location
  28329. var loc = loc || global.location;
  28330. if (null == uri) uri = loc.protocol + '//' + loc.host;
  28331. // relative path support
  28332. if ('string' == typeof uri) {
  28333. if ('/' == uri.charAt(0)) {
  28334. if ('/' == uri.charAt(1)) {
  28335. uri = loc.protocol + uri;
  28336. } else {
  28337. uri = loc.hostname + uri;
  28338. }
  28339. }
  28340. if (!/^(https?|wss?):\/\//.test(uri)) {
  28341. debug('protocol-less url %s', uri);
  28342. if ('undefined' != typeof loc) {
  28343. uri = loc.protocol + '//' + uri;
  28344. } else {
  28345. uri = 'https://' + uri;
  28346. }
  28347. }
  28348. // parse
  28349. debug('parse %s', uri);
  28350. obj = parseuri(uri);
  28351. }
  28352. // make sure we treat `localhost:80` and `localhost` equally
  28353. if (!obj.port) {
  28354. if (/^(http|ws)$/.test(obj.protocol)) {
  28355. obj.port = '80';
  28356. }
  28357. else if (/^(http|ws)s$/.test(obj.protocol)) {
  28358. obj.port = '443';
  28359. }
  28360. }
  28361. obj.path = obj.path || '/';
  28362. // define unique id
  28363. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  28364. // define href
  28365. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  28366. return obj;
  28367. }
  28368. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  28369. },{"debug":121,"parseuri":155}],118:[function(require,module,exports){
  28370. /**
  28371. * Expose `Backoff`.
  28372. */
  28373. module.exports = Backoff;
  28374. /**
  28375. * Initialize backoff timer with `opts`.
  28376. *
  28377. * - `min` initial timeout in milliseconds [100]
  28378. * - `max` max timeout [10000]
  28379. * - `jitter` [0]
  28380. * - `factor` [2]
  28381. *
  28382. * @param {Object} opts
  28383. * @api public
  28384. */
  28385. function Backoff(opts) {
  28386. opts = opts || {};
  28387. this.ms = opts.min || 100;
  28388. this.max = opts.max || 10000;
  28389. this.factor = opts.factor || 2;
  28390. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  28391. this.attempts = 0;
  28392. }
  28393. /**
  28394. * Return the backoff duration.
  28395. *
  28396. * @return {Number}
  28397. * @api public
  28398. */
  28399. Backoff.prototype.duration = function(){
  28400. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  28401. if (this.jitter) {
  28402. var rand = Math.random();
  28403. var deviation = Math.floor(rand * this.jitter * ms);
  28404. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  28405. }
  28406. return Math.min(ms, this.max) | 0;
  28407. };
  28408. /**
  28409. * Reset the number of attempts.
  28410. *
  28411. * @api public
  28412. */
  28413. Backoff.prototype.reset = function(){
  28414. this.attempts = 0;
  28415. };
  28416. /**
  28417. * Set the minimum duration
  28418. *
  28419. * @api public
  28420. */
  28421. Backoff.prototype.setMin = function(min){
  28422. this.ms = min;
  28423. };
  28424. /**
  28425. * Set the maximum duration
  28426. *
  28427. * @api public
  28428. */
  28429. Backoff.prototype.setMax = function(max){
  28430. this.max = max;
  28431. };
  28432. /**
  28433. * Set the jitter
  28434. *
  28435. * @api public
  28436. */
  28437. Backoff.prototype.setJitter = function(jitter){
  28438. this.jitter = jitter;
  28439. };
  28440. },{}],119:[function(require,module,exports){
  28441. /**
  28442. * Slice reference.
  28443. */
  28444. var slice = [].slice;
  28445. /**
  28446. * Bind `obj` to `fn`.
  28447. *
  28448. * @param {Object} obj
  28449. * @param {Function|String} fn or string
  28450. * @return {Function}
  28451. * @api public
  28452. */
  28453. module.exports = function(obj, fn){
  28454. if ('string' == typeof fn) fn = obj[fn];
  28455. if ('function' != typeof fn) throw new Error('bind() requires a function');
  28456. var args = slice.call(arguments, 2);
  28457. return function(){
  28458. return fn.apply(obj, args.concat(slice.call(arguments)));
  28459. }
  28460. };
  28461. },{}],120:[function(require,module,exports){
  28462. /**
  28463. * Expose `Emitter`.
  28464. */
  28465. module.exports = Emitter;
  28466. /**
  28467. * Initialize a new `Emitter`.
  28468. *
  28469. * @api public
  28470. */
  28471. function Emitter(obj) {
  28472. if (obj) return mixin(obj);
  28473. };
  28474. /**
  28475. * Mixin the emitter properties.
  28476. *
  28477. * @param {Object} obj
  28478. * @return {Object}
  28479. * @api private
  28480. */
  28481. function mixin(obj) {
  28482. for (var key in Emitter.prototype) {
  28483. obj[key] = Emitter.prototype[key];
  28484. }
  28485. return obj;
  28486. }
  28487. /**
  28488. * Listen on the given `event` with `fn`.
  28489. *
  28490. * @param {String} event
  28491. * @param {Function} fn
  28492. * @return {Emitter}
  28493. * @api public
  28494. */
  28495. Emitter.prototype.on =
  28496. Emitter.prototype.addEventListener = function(event, fn){
  28497. this._callbacks = this._callbacks || {};
  28498. (this._callbacks[event] = this._callbacks[event] || [])
  28499. .push(fn);
  28500. return this;
  28501. };
  28502. /**
  28503. * Adds an `event` listener that will be invoked a single
  28504. * time then automatically removed.
  28505. *
  28506. * @param {String} event
  28507. * @param {Function} fn
  28508. * @return {Emitter}
  28509. * @api public
  28510. */
  28511. Emitter.prototype.once = function(event, fn){
  28512. var self = this;
  28513. this._callbacks = this._callbacks || {};
  28514. function on() {
  28515. self.off(event, on);
  28516. fn.apply(this, arguments);
  28517. }
  28518. on.fn = fn;
  28519. this.on(event, on);
  28520. return this;
  28521. };
  28522. /**
  28523. * Remove the given callback for `event` or all
  28524. * registered callbacks.
  28525. *
  28526. * @param {String} event
  28527. * @param {Function} fn
  28528. * @return {Emitter}
  28529. * @api public
  28530. */
  28531. Emitter.prototype.off =
  28532. Emitter.prototype.removeListener =
  28533. Emitter.prototype.removeAllListeners =
  28534. Emitter.prototype.removeEventListener = function(event, fn){
  28535. this._callbacks = this._callbacks || {};
  28536. // all
  28537. if (0 == arguments.length) {
  28538. this._callbacks = {};
  28539. return this;
  28540. }
  28541. // specific event
  28542. var callbacks = this._callbacks[event];
  28543. if (!callbacks) return this;
  28544. // remove all handlers
  28545. if (1 == arguments.length) {
  28546. delete this._callbacks[event];
  28547. return this;
  28548. }
  28549. // remove specific handler
  28550. var cb;
  28551. for (var i = 0; i < callbacks.length; i++) {
  28552. cb = callbacks[i];
  28553. if (cb === fn || cb.fn === fn) {
  28554. callbacks.splice(i, 1);
  28555. break;
  28556. }
  28557. }
  28558. return this;
  28559. };
  28560. /**
  28561. * Emit `event` with the given args.
  28562. *
  28563. * @param {String} event
  28564. * @param {Mixed} ...
  28565. * @return {Emitter}
  28566. */
  28567. Emitter.prototype.emit = function(event){
  28568. this._callbacks = this._callbacks || {};
  28569. var args = [].slice.call(arguments, 1)
  28570. , callbacks = this._callbacks[event];
  28571. if (callbacks) {
  28572. callbacks = callbacks.slice(0);
  28573. for (var i = 0, len = callbacks.length; i < len; ++i) {
  28574. callbacks[i].apply(this, args);
  28575. }
  28576. }
  28577. return this;
  28578. };
  28579. /**
  28580. * Return array of callbacks for `event`.
  28581. *
  28582. * @param {String} event
  28583. * @return {Array}
  28584. * @api public
  28585. */
  28586. Emitter.prototype.listeners = function(event){
  28587. this._callbacks = this._callbacks || {};
  28588. return this._callbacks[event] || [];
  28589. };
  28590. /**
  28591. * Check if this emitter has `event` handlers.
  28592. *
  28593. * @param {String} event
  28594. * @return {Boolean}
  28595. * @api public
  28596. */
  28597. Emitter.prototype.hasListeners = function(event){
  28598. return !! this.listeners(event).length;
  28599. };
  28600. },{}],121:[function(require,module,exports){
  28601. /**
  28602. * Expose `debug()` as the module.
  28603. */
  28604. module.exports = debug;
  28605. /**
  28606. * Create a debugger with the given `name`.
  28607. *
  28608. * @param {String} name
  28609. * @return {Type}
  28610. * @api public
  28611. */
  28612. function debug(name) {
  28613. if (!debug.enabled(name)) return function(){};
  28614. return function(fmt){
  28615. fmt = coerce(fmt);
  28616. var curr = new Date;
  28617. var ms = curr - (debug[name] || curr);
  28618. debug[name] = curr;
  28619. fmt = name
  28620. + ' '
  28621. + fmt
  28622. + ' +' + debug.humanize(ms);
  28623. // This hackery is required for IE8
  28624. // where `console.log` doesn't have 'apply'
  28625. window.console
  28626. && console.log
  28627. && Function.prototype.apply.call(console.log, console, arguments);
  28628. }
  28629. }
  28630. /**
  28631. * The currently active debug mode names.
  28632. */
  28633. debug.names = [];
  28634. debug.skips = [];
  28635. /**
  28636. * Enables a debug mode by name. This can include modes
  28637. * separated by a colon and wildcards.
  28638. *
  28639. * @param {String} name
  28640. * @api public
  28641. */
  28642. debug.enable = function(name) {
  28643. try {
  28644. localStorage.debug = name;
  28645. } catch(e){}
  28646. var split = (name || '').split(/[\s,]+/)
  28647. , len = split.length;
  28648. for (var i = 0; i < len; i++) {
  28649. name = split[i].replace('*', '.*?');
  28650. if (name[0] === '-') {
  28651. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  28652. }
  28653. else {
  28654. debug.names.push(new RegExp('^' + name + '$'));
  28655. }
  28656. }
  28657. };
  28658. /**
  28659. * Disable debug output.
  28660. *
  28661. * @api public
  28662. */
  28663. debug.disable = function(){
  28664. debug.enable('');
  28665. };
  28666. /**
  28667. * Humanize the given `ms`.
  28668. *
  28669. * @param {Number} m
  28670. * @return {String}
  28671. * @api private
  28672. */
  28673. debug.humanize = function(ms) {
  28674. var sec = 1000
  28675. , min = 60 * 1000
  28676. , hour = 60 * min;
  28677. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  28678. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  28679. if (ms >= sec) return (ms / sec | 0) + 's';
  28680. return ms + 'ms';
  28681. };
  28682. /**
  28683. * Returns true if the given mode name is enabled, false otherwise.
  28684. *
  28685. * @param {String} name
  28686. * @return {Boolean}
  28687. * @api public
  28688. */
  28689. debug.enabled = function(name) {
  28690. for (var i = 0, len = debug.skips.length; i < len; i++) {
  28691. if (debug.skips[i].test(name)) {
  28692. return false;
  28693. }
  28694. }
  28695. for (var i = 0, len = debug.names.length; i < len; i++) {
  28696. if (debug.names[i].test(name)) {
  28697. return true;
  28698. }
  28699. }
  28700. return false;
  28701. };
  28702. /**
  28703. * Coerce `val`.
  28704. */
  28705. function coerce(val) {
  28706. if (val instanceof Error) return val.stack || val.message;
  28707. return val;
  28708. }
  28709. // persist
  28710. try {
  28711. if (window.localStorage) debug.enable(localStorage.debug);
  28712. } catch(e){}
  28713. },{}],122:[function(require,module,exports){
  28714. module.exports = require('./lib/');
  28715. },{"./lib/":123}],123:[function(require,module,exports){
  28716. module.exports = require('./socket');
  28717. /**
  28718. * Exports parser
  28719. *
  28720. * @api public
  28721. *
  28722. */
  28723. module.exports.parser = require('engine.io-parser');
  28724. },{"./socket":124,"engine.io-parser":136}],124:[function(require,module,exports){
  28725. (function (global){
  28726. /**
  28727. * Module dependencies.
  28728. */
  28729. var transports = require('./transports');
  28730. var Emitter = require('component-emitter');
  28731. var debug = require('debug')('engine.io-client:socket');
  28732. var index = require('indexof');
  28733. var parser = require('engine.io-parser');
  28734. var parseuri = require('parseuri');
  28735. var parsejson = require('parsejson');
  28736. var parseqs = require('parseqs');
  28737. /**
  28738. * Module exports.
  28739. */
  28740. module.exports = Socket;
  28741. /**
  28742. * Noop function.
  28743. *
  28744. * @api private
  28745. */
  28746. function noop(){}
  28747. /**
  28748. * Socket constructor.
  28749. *
  28750. * @param {String|Object} uri or options
  28751. * @param {Object} options
  28752. * @api public
  28753. */
  28754. function Socket(uri, opts){
  28755. if (!(this instanceof Socket)) return new Socket(uri, opts);
  28756. opts = opts || {};
  28757. if (uri && 'object' == typeof uri) {
  28758. opts = uri;
  28759. uri = null;
  28760. }
  28761. if (uri) {
  28762. uri = parseuri(uri);
  28763. opts.host = uri.host;
  28764. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  28765. opts.port = uri.port;
  28766. if (uri.query) opts.query = uri.query;
  28767. }
  28768. this.secure = null != opts.secure ? opts.secure :
  28769. (global.location && 'https:' == location.protocol);
  28770. if (opts.host) {
  28771. var pieces = opts.host.split(':');
  28772. opts.hostname = pieces.shift();
  28773. if (pieces.length) {
  28774. opts.port = pieces.pop();
  28775. } else if (!opts.port) {
  28776. // if no port is specified manually, use the protocol default
  28777. opts.port = this.secure ? '443' : '80';
  28778. }
  28779. }
  28780. this.agent = opts.agent || false;
  28781. this.hostname = opts.hostname ||
  28782. (global.location ? location.hostname : 'localhost');
  28783. this.port = opts.port || (global.location && location.port ?
  28784. location.port :
  28785. (this.secure ? 443 : 80));
  28786. this.query = opts.query || {};
  28787. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  28788. this.upgrade = false !== opts.upgrade;
  28789. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  28790. this.forceJSONP = !!opts.forceJSONP;
  28791. this.jsonp = false !== opts.jsonp;
  28792. this.forceBase64 = !!opts.forceBase64;
  28793. this.enablesXDR = !!opts.enablesXDR;
  28794. this.timestampParam = opts.timestampParam || 't';
  28795. this.timestampRequests = opts.timestampRequests;
  28796. this.transports = opts.transports || ['polling', 'websocket'];
  28797. this.readyState = '';
  28798. this.writeBuffer = [];
  28799. this.callbackBuffer = [];
  28800. this.policyPort = opts.policyPort || 843;
  28801. this.rememberUpgrade = opts.rememberUpgrade || false;
  28802. this.binaryType = null;
  28803. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  28804. // SSL options for Node.js client
  28805. this.pfx = opts.pfx || null;
  28806. this.key = opts.key || null;
  28807. this.passphrase = opts.passphrase || null;
  28808. this.cert = opts.cert || null;
  28809. this.ca = opts.ca || null;
  28810. this.ciphers = opts.ciphers || null;
  28811. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  28812. this.open();
  28813. }
  28814. Socket.priorWebsocketSuccess = false;
  28815. /**
  28816. * Mix in `Emitter`.
  28817. */
  28818. Emitter(Socket.prototype);
  28819. /**
  28820. * Protocol version.
  28821. *
  28822. * @api public
  28823. */
  28824. Socket.protocol = parser.protocol; // this is an int
  28825. /**
  28826. * Expose deps for legacy compatibility
  28827. * and standalone browser access.
  28828. */
  28829. Socket.Socket = Socket;
  28830. Socket.Transport = require('./transport');
  28831. Socket.transports = require('./transports');
  28832. Socket.parser = require('engine.io-parser');
  28833. /**
  28834. * Creates transport of the given type.
  28835. *
  28836. * @param {String} transport name
  28837. * @return {Transport}
  28838. * @api private
  28839. */
  28840. Socket.prototype.createTransport = function (name) {
  28841. debug('creating transport "%s"', name);
  28842. var query = clone(this.query);
  28843. // append engine.io protocol identifier
  28844. query.EIO = parser.protocol;
  28845. // transport name
  28846. query.transport = name;
  28847. // session id if we already have one
  28848. if (this.id) query.sid = this.id;
  28849. var transport = new transports[name]({
  28850. agent: this.agent,
  28851. hostname: this.hostname,
  28852. port: this.port,
  28853. secure: this.secure,
  28854. path: this.path,
  28855. query: query,
  28856. forceJSONP: this.forceJSONP,
  28857. jsonp: this.jsonp,
  28858. forceBase64: this.forceBase64,
  28859. enablesXDR: this.enablesXDR,
  28860. timestampRequests: this.timestampRequests,
  28861. timestampParam: this.timestampParam,
  28862. policyPort: this.policyPort,
  28863. socket: this,
  28864. pfx: this.pfx,
  28865. key: this.key,
  28866. passphrase: this.passphrase,
  28867. cert: this.cert,
  28868. ca: this.ca,
  28869. ciphers: this.ciphers,
  28870. rejectUnauthorized: this.rejectUnauthorized
  28871. });
  28872. return transport;
  28873. };
  28874. function clone (obj) {
  28875. var o = {};
  28876. for (var i in obj) {
  28877. if (obj.hasOwnProperty(i)) {
  28878. o[i] = obj[i];
  28879. }
  28880. }
  28881. return o;
  28882. }
  28883. /**
  28884. * Initializes transport to use and starts probe.
  28885. *
  28886. * @api private
  28887. */
  28888. Socket.prototype.open = function () {
  28889. var transport;
  28890. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  28891. transport = 'websocket';
  28892. } else if (0 == this.transports.length) {
  28893. // Emit error on next tick so it can be listened to
  28894. var self = this;
  28895. setTimeout(function() {
  28896. self.emit('error', 'No transports available');
  28897. }, 0);
  28898. return;
  28899. } else {
  28900. transport = this.transports[0];
  28901. }
  28902. this.readyState = 'opening';
  28903. // Retry with the next transport if the transport is disabled (jsonp: false)
  28904. var transport;
  28905. try {
  28906. transport = this.createTransport(transport);
  28907. } catch (e) {
  28908. this.transports.shift();
  28909. this.open();
  28910. return;
  28911. }
  28912. transport.open();
  28913. this.setTransport(transport);
  28914. };
  28915. /**
  28916. * Sets the current transport. Disables the existing one (if any).
  28917. *
  28918. * @api private
  28919. */
  28920. Socket.prototype.setTransport = function(transport){
  28921. debug('setting transport %s', transport.name);
  28922. var self = this;
  28923. if (this.transport) {
  28924. debug('clearing existing transport %s', this.transport.name);
  28925. this.transport.removeAllListeners();
  28926. }
  28927. // set up transport
  28928. this.transport = transport;
  28929. // set up transport listeners
  28930. transport
  28931. .on('drain', function(){
  28932. self.onDrain();
  28933. })
  28934. .on('packet', function(packet){
  28935. self.onPacket(packet);
  28936. })
  28937. .on('error', function(e){
  28938. self.onError(e);
  28939. })
  28940. .on('close', function(){
  28941. self.onClose('transport close');
  28942. });
  28943. };
  28944. /**
  28945. * Probes a transport.
  28946. *
  28947. * @param {String} transport name
  28948. * @api private
  28949. */
  28950. Socket.prototype.probe = function (name) {
  28951. debug('probing transport "%s"', name);
  28952. var transport = this.createTransport(name, { probe: 1 })
  28953. , failed = false
  28954. , self = this;
  28955. Socket.priorWebsocketSuccess = false;
  28956. function onTransportOpen(){
  28957. if (self.onlyBinaryUpgrades) {
  28958. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  28959. failed = failed || upgradeLosesBinary;
  28960. }
  28961. if (failed) return;
  28962. debug('probe transport "%s" opened', name);
  28963. transport.send([{ type: 'ping', data: 'probe' }]);
  28964. transport.once('packet', function (msg) {
  28965. if (failed) return;
  28966. if ('pong' == msg.type && 'probe' == msg.data) {
  28967. debug('probe transport "%s" pong', name);
  28968. self.upgrading = true;
  28969. self.emit('upgrading', transport);
  28970. if (!transport) return;
  28971. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  28972. debug('pausing current transport "%s"', self.transport.name);
  28973. self.transport.pause(function () {
  28974. if (failed) return;
  28975. if ('closed' == self.readyState) return;
  28976. debug('changing transport and sending upgrade packet');
  28977. cleanup();
  28978. self.setTransport(transport);
  28979. transport.send([{ type: 'upgrade' }]);
  28980. self.emit('upgrade', transport);
  28981. transport = null;
  28982. self.upgrading = false;
  28983. self.flush();
  28984. });
  28985. } else {
  28986. debug('probe transport "%s" failed', name);
  28987. var err = new Error('probe error');
  28988. err.transport = transport.name;
  28989. self.emit('upgradeError', err);
  28990. }
  28991. });
  28992. }
  28993. function freezeTransport() {
  28994. if (failed) return;
  28995. // Any callback called by transport should be ignored since now
  28996. failed = true;
  28997. cleanup();
  28998. transport.close();
  28999. transport = null;
  29000. }
  29001. //Handle any error that happens while probing
  29002. function onerror(err) {
  29003. var error = new Error('probe error: ' + err);
  29004. error.transport = transport.name;
  29005. freezeTransport();
  29006. debug('probe transport "%s" failed because of error: %s', name, err);
  29007. self.emit('upgradeError', error);
  29008. }
  29009. function onTransportClose(){
  29010. onerror("transport closed");
  29011. }
  29012. //When the socket is closed while we're probing
  29013. function onclose(){
  29014. onerror("socket closed");
  29015. }
  29016. //When the socket is upgraded while we're probing
  29017. function onupgrade(to){
  29018. if (transport && to.name != transport.name) {
  29019. debug('"%s" works - aborting "%s"', to.name, transport.name);
  29020. freezeTransport();
  29021. }
  29022. }
  29023. //Remove all listeners on the transport and on self
  29024. function cleanup(){
  29025. transport.removeListener('open', onTransportOpen);
  29026. transport.removeListener('error', onerror);
  29027. transport.removeListener('close', onTransportClose);
  29028. self.removeListener('close', onclose);
  29029. self.removeListener('upgrading', onupgrade);
  29030. }
  29031. transport.once('open', onTransportOpen);
  29032. transport.once('error', onerror);
  29033. transport.once('close', onTransportClose);
  29034. this.once('close', onclose);
  29035. this.once('upgrading', onupgrade);
  29036. transport.open();
  29037. };
  29038. /**
  29039. * Called when connection is deemed open.
  29040. *
  29041. * @api public
  29042. */
  29043. Socket.prototype.onOpen = function () {
  29044. debug('socket open');
  29045. this.readyState = 'open';
  29046. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  29047. this.emit('open');
  29048. this.flush();
  29049. // we check for `readyState` in case an `open`
  29050. // listener already closed the socket
  29051. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  29052. debug('starting upgrade probes');
  29053. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  29054. this.probe(this.upgrades[i]);
  29055. }
  29056. }
  29057. };
  29058. /**
  29059. * Handles a packet.
  29060. *
  29061. * @api private
  29062. */
  29063. Socket.prototype.onPacket = function (packet) {
  29064. if ('opening' == this.readyState || 'open' == this.readyState) {
  29065. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  29066. this.emit('packet', packet);
  29067. // Socket is live - any packet counts
  29068. this.emit('heartbeat');
  29069. switch (packet.type) {
  29070. case 'open':
  29071. this.onHandshake(parsejson(packet.data));
  29072. break;
  29073. case 'pong':
  29074. this.setPing();
  29075. break;
  29076. case 'error':
  29077. var err = new Error('server error');
  29078. err.code = packet.data;
  29079. this.emit('error', err);
  29080. break;
  29081. case 'message':
  29082. this.emit('data', packet.data);
  29083. this.emit('message', packet.data);
  29084. break;
  29085. }
  29086. } else {
  29087. debug('packet received with socket readyState "%s"', this.readyState);
  29088. }
  29089. };
  29090. /**
  29091. * Called upon handshake completion.
  29092. *
  29093. * @param {Object} handshake obj
  29094. * @api private
  29095. */
  29096. Socket.prototype.onHandshake = function (data) {
  29097. this.emit('handshake', data);
  29098. this.id = data.sid;
  29099. this.transport.query.sid = data.sid;
  29100. this.upgrades = this.filterUpgrades(data.upgrades);
  29101. this.pingInterval = data.pingInterval;
  29102. this.pingTimeout = data.pingTimeout;
  29103. this.onOpen();
  29104. // In case open handler closes socket
  29105. if ('closed' == this.readyState) return;
  29106. this.setPing();
  29107. // Prolong liveness of socket on heartbeat
  29108. this.removeListener('heartbeat', this.onHeartbeat);
  29109. this.on('heartbeat', this.onHeartbeat);
  29110. };
  29111. /**
  29112. * Resets ping timeout.
  29113. *
  29114. * @api private
  29115. */
  29116. Socket.prototype.onHeartbeat = function (timeout) {
  29117. clearTimeout(this.pingTimeoutTimer);
  29118. var self = this;
  29119. self.pingTimeoutTimer = setTimeout(function () {
  29120. if ('closed' == self.readyState) return;
  29121. self.onClose('ping timeout');
  29122. }, timeout || (self.pingInterval + self.pingTimeout));
  29123. };
  29124. /**
  29125. * Pings server every `this.pingInterval` and expects response
  29126. * within `this.pingTimeout` or closes connection.
  29127. *
  29128. * @api private
  29129. */
  29130. Socket.prototype.setPing = function () {
  29131. var self = this;
  29132. clearTimeout(self.pingIntervalTimer);
  29133. self.pingIntervalTimer = setTimeout(function () {
  29134. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  29135. self.ping();
  29136. self.onHeartbeat(self.pingTimeout);
  29137. }, self.pingInterval);
  29138. };
  29139. /**
  29140. * Sends a ping packet.
  29141. *
  29142. * @api public
  29143. */
  29144. Socket.prototype.ping = function () {
  29145. this.sendPacket('ping');
  29146. };
  29147. /**
  29148. * Called on `drain` event
  29149. *
  29150. * @api private
  29151. */
  29152. Socket.prototype.onDrain = function() {
  29153. for (var i = 0; i < this.prevBufferLen; i++) {
  29154. if (this.callbackBuffer[i]) {
  29155. this.callbackBuffer[i]();
  29156. }
  29157. }
  29158. this.writeBuffer.splice(0, this.prevBufferLen);
  29159. this.callbackBuffer.splice(0, this.prevBufferLen);
  29160. // setting prevBufferLen = 0 is very important
  29161. // for example, when upgrading, upgrade packet is sent over,
  29162. // and a nonzero prevBufferLen could cause problems on `drain`
  29163. this.prevBufferLen = 0;
  29164. if (this.writeBuffer.length == 0) {
  29165. this.emit('drain');
  29166. } else {
  29167. this.flush();
  29168. }
  29169. };
  29170. /**
  29171. * Flush write buffers.
  29172. *
  29173. * @api private
  29174. */
  29175. Socket.prototype.flush = function () {
  29176. if ('closed' != this.readyState && this.transport.writable &&
  29177. !this.upgrading && this.writeBuffer.length) {
  29178. debug('flushing %d packets in socket', this.writeBuffer.length);
  29179. this.transport.send(this.writeBuffer);
  29180. // keep track of current length of writeBuffer
  29181. // splice writeBuffer and callbackBuffer on `drain`
  29182. this.prevBufferLen = this.writeBuffer.length;
  29183. this.emit('flush');
  29184. }
  29185. };
  29186. /**
  29187. * Sends a message.
  29188. *
  29189. * @param {String} message.
  29190. * @param {Function} callback function.
  29191. * @return {Socket} for chaining.
  29192. * @api public
  29193. */
  29194. Socket.prototype.write =
  29195. Socket.prototype.send = function (msg, fn) {
  29196. this.sendPacket('message', msg, fn);
  29197. return this;
  29198. };
  29199. /**
  29200. * Sends a packet.
  29201. *
  29202. * @param {String} packet type.
  29203. * @param {String} data.
  29204. * @param {Function} callback function.
  29205. * @api private
  29206. */
  29207. Socket.prototype.sendPacket = function (type, data, fn) {
  29208. if ('closing' == this.readyState || 'closed' == this.readyState) {
  29209. return;
  29210. }
  29211. var packet = { type: type, data: data };
  29212. this.emit('packetCreate', packet);
  29213. this.writeBuffer.push(packet);
  29214. this.callbackBuffer.push(fn);
  29215. this.flush();
  29216. };
  29217. /**
  29218. * Closes the connection.
  29219. *
  29220. * @api private
  29221. */
  29222. Socket.prototype.close = function () {
  29223. if ('opening' == this.readyState || 'open' == this.readyState) {
  29224. this.readyState = 'closing';
  29225. var self = this;
  29226. function close() {
  29227. self.onClose('forced close');
  29228. debug('socket closing - telling transport to close');
  29229. self.transport.close();
  29230. }
  29231. function cleanupAndClose() {
  29232. self.removeListener('upgrade', cleanupAndClose);
  29233. self.removeListener('upgradeError', cleanupAndClose);
  29234. close();
  29235. }
  29236. function waitForUpgrade() {
  29237. // wait for upgrade to finish since we can't send packets while pausing a transport
  29238. self.once('upgrade', cleanupAndClose);
  29239. self.once('upgradeError', cleanupAndClose);
  29240. }
  29241. if (this.writeBuffer.length) {
  29242. this.once('drain', function() {
  29243. if (this.upgrading) {
  29244. waitForUpgrade();
  29245. } else {
  29246. close();
  29247. }
  29248. });
  29249. } else if (this.upgrading) {
  29250. waitForUpgrade();
  29251. } else {
  29252. close();
  29253. }
  29254. }
  29255. return this;
  29256. };
  29257. /**
  29258. * Called upon transport error
  29259. *
  29260. * @api private
  29261. */
  29262. Socket.prototype.onError = function (err) {
  29263. debug('socket error %j', err);
  29264. Socket.priorWebsocketSuccess = false;
  29265. this.emit('error', err);
  29266. this.onClose('transport error', err);
  29267. };
  29268. /**
  29269. * Called upon transport close.
  29270. *
  29271. * @api private
  29272. */
  29273. Socket.prototype.onClose = function (reason, desc) {
  29274. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  29275. debug('socket close with reason: "%s"', reason);
  29276. var self = this;
  29277. // clear timers
  29278. clearTimeout(this.pingIntervalTimer);
  29279. clearTimeout(this.pingTimeoutTimer);
  29280. // clean buffers in next tick, so developers can still
  29281. // grab the buffers on `close` event
  29282. setTimeout(function() {
  29283. self.writeBuffer = [];
  29284. self.callbackBuffer = [];
  29285. self.prevBufferLen = 0;
  29286. }, 0);
  29287. // stop event from firing again for transport
  29288. this.transport.removeAllListeners('close');
  29289. // ensure transport won't stay open
  29290. this.transport.close();
  29291. // ignore further transport communication
  29292. this.transport.removeAllListeners();
  29293. // set ready state
  29294. this.readyState = 'closed';
  29295. // clear session id
  29296. this.id = null;
  29297. // emit close event
  29298. this.emit('close', reason, desc);
  29299. }
  29300. };
  29301. /**
  29302. * Filters upgrades, returning only those matching client transports.
  29303. *
  29304. * @param {Array} server upgrades
  29305. * @api private
  29306. *
  29307. */
  29308. Socket.prototype.filterUpgrades = function (upgrades) {
  29309. var filteredUpgrades = [];
  29310. for (var i = 0, j = upgrades.length; i<j; i++) {
  29311. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  29312. }
  29313. return filteredUpgrades;
  29314. };
  29315. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29316. },{"./transport":125,"./transports":126,"component-emitter":120,"debug":133,"engine.io-parser":136,"indexof":153,"parsejson":147,"parseqs":148,"parseuri":149}],125:[function(require,module,exports){
  29317. /**
  29318. * Module dependencies.
  29319. */
  29320. var parser = require('engine.io-parser');
  29321. var Emitter = require('component-emitter');
  29322. /**
  29323. * Module exports.
  29324. */
  29325. module.exports = Transport;
  29326. /**
  29327. * Transport abstract constructor.
  29328. *
  29329. * @param {Object} options.
  29330. * @api private
  29331. */
  29332. function Transport (opts) {
  29333. this.path = opts.path;
  29334. this.hostname = opts.hostname;
  29335. this.port = opts.port;
  29336. this.secure = opts.secure;
  29337. this.query = opts.query;
  29338. this.timestampParam = opts.timestampParam;
  29339. this.timestampRequests = opts.timestampRequests;
  29340. this.readyState = '';
  29341. this.agent = opts.agent || false;
  29342. this.socket = opts.socket;
  29343. this.enablesXDR = opts.enablesXDR;
  29344. // SSL options for Node.js client
  29345. this.pfx = opts.pfx;
  29346. this.key = opts.key;
  29347. this.passphrase = opts.passphrase;
  29348. this.cert = opts.cert;
  29349. this.ca = opts.ca;
  29350. this.ciphers = opts.ciphers;
  29351. this.rejectUnauthorized = opts.rejectUnauthorized;
  29352. }
  29353. /**
  29354. * Mix in `Emitter`.
  29355. */
  29356. Emitter(Transport.prototype);
  29357. /**
  29358. * A counter used to prevent collisions in the timestamps used
  29359. * for cache busting.
  29360. */
  29361. Transport.timestamps = 0;
  29362. /**
  29363. * Emits an error.
  29364. *
  29365. * @param {String} str
  29366. * @return {Transport} for chaining
  29367. * @api public
  29368. */
  29369. Transport.prototype.onError = function (msg, desc) {
  29370. var err = new Error(msg);
  29371. err.type = 'TransportError';
  29372. err.description = desc;
  29373. this.emit('error', err);
  29374. return this;
  29375. };
  29376. /**
  29377. * Opens the transport.
  29378. *
  29379. * @api public
  29380. */
  29381. Transport.prototype.open = function () {
  29382. if ('closed' == this.readyState || '' == this.readyState) {
  29383. this.readyState = 'opening';
  29384. this.doOpen();
  29385. }
  29386. return this;
  29387. };
  29388. /**
  29389. * Closes the transport.
  29390. *
  29391. * @api private
  29392. */
  29393. Transport.prototype.close = function () {
  29394. if ('opening' == this.readyState || 'open' == this.readyState) {
  29395. this.doClose();
  29396. this.onClose();
  29397. }
  29398. return this;
  29399. };
  29400. /**
  29401. * Sends multiple packets.
  29402. *
  29403. * @param {Array} packets
  29404. * @api private
  29405. */
  29406. Transport.prototype.send = function(packets){
  29407. if ('open' == this.readyState) {
  29408. this.write(packets);
  29409. } else {
  29410. throw new Error('Transport not open');
  29411. }
  29412. };
  29413. /**
  29414. * Called upon open
  29415. *
  29416. * @api private
  29417. */
  29418. Transport.prototype.onOpen = function () {
  29419. this.readyState = 'open';
  29420. this.writable = true;
  29421. this.emit('open');
  29422. };
  29423. /**
  29424. * Called with data.
  29425. *
  29426. * @param {String} data
  29427. * @api private
  29428. */
  29429. Transport.prototype.onData = function(data){
  29430. var packet = parser.decodePacket(data, this.socket.binaryType);
  29431. this.onPacket(packet);
  29432. };
  29433. /**
  29434. * Called with a decoded packet.
  29435. */
  29436. Transport.prototype.onPacket = function (packet) {
  29437. this.emit('packet', packet);
  29438. };
  29439. /**
  29440. * Called upon close.
  29441. *
  29442. * @api private
  29443. */
  29444. Transport.prototype.onClose = function () {
  29445. this.readyState = 'closed';
  29446. this.emit('close');
  29447. };
  29448. },{"component-emitter":120,"engine.io-parser":136}],126:[function(require,module,exports){
  29449. (function (global){
  29450. /**
  29451. * Module dependencies
  29452. */
  29453. var XMLHttpRequest = require('xmlhttprequest');
  29454. var XHR = require('./polling-xhr');
  29455. var JSONP = require('./polling-jsonp');
  29456. var websocket = require('./websocket');
  29457. /**
  29458. * Export transports.
  29459. */
  29460. exports.polling = polling;
  29461. exports.websocket = websocket;
  29462. /**
  29463. * Polling transport polymorphic constructor.
  29464. * Decides on xhr vs jsonp based on feature detection.
  29465. *
  29466. * @api private
  29467. */
  29468. function polling(opts){
  29469. var xhr;
  29470. var xd = false;
  29471. var xs = false;
  29472. var jsonp = false !== opts.jsonp;
  29473. if (global.location) {
  29474. var isSSL = 'https:' == location.protocol;
  29475. var port = location.port;
  29476. // some user agents have empty `location.port`
  29477. if (!port) {
  29478. port = isSSL ? 443 : 80;
  29479. }
  29480. xd = opts.hostname != location.hostname || port != opts.port;
  29481. xs = opts.secure != isSSL;
  29482. }
  29483. opts.xdomain = xd;
  29484. opts.xscheme = xs;
  29485. xhr = new XMLHttpRequest(opts);
  29486. if ('open' in xhr && !opts.forceJSONP) {
  29487. return new XHR(opts);
  29488. } else {
  29489. if (!jsonp) throw new Error('JSONP disabled');
  29490. return new JSONP(opts);
  29491. }
  29492. }
  29493. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29494. },{"./polling-jsonp":127,"./polling-xhr":128,"./websocket":130,"xmlhttprequest":131}],127:[function(require,module,exports){
  29495. (function (global){
  29496. /**
  29497. * Module requirements.
  29498. */
  29499. var Polling = require('./polling');
  29500. var inherit = require('component-inherit');
  29501. /**
  29502. * Module exports.
  29503. */
  29504. module.exports = JSONPPolling;
  29505. /**
  29506. * Cached regular expressions.
  29507. */
  29508. var rNewline = /\n/g;
  29509. var rEscapedNewline = /\\n/g;
  29510. /**
  29511. * Global JSONP callbacks.
  29512. */
  29513. var callbacks;
  29514. /**
  29515. * Callbacks count.
  29516. */
  29517. var index = 0;
  29518. /**
  29519. * Noop.
  29520. */
  29521. function empty () { }
  29522. /**
  29523. * JSONP Polling constructor.
  29524. *
  29525. * @param {Object} opts.
  29526. * @api public
  29527. */
  29528. function JSONPPolling (opts) {
  29529. Polling.call(this, opts);
  29530. this.query = this.query || {};
  29531. // define global callbacks array if not present
  29532. // we do this here (lazily) to avoid unneeded global pollution
  29533. if (!callbacks) {
  29534. // we need to consider multiple engines in the same page
  29535. if (!global.___eio) global.___eio = [];
  29536. callbacks = global.___eio;
  29537. }
  29538. // callback identifier
  29539. this.index = callbacks.length;
  29540. // add callback to jsonp global
  29541. var self = this;
  29542. callbacks.push(function (msg) {
  29543. self.onData(msg);
  29544. });
  29545. // append to query string
  29546. this.query.j = this.index;
  29547. // prevent spurious errors from being emitted when the window is unloaded
  29548. if (global.document && global.addEventListener) {
  29549. global.addEventListener('beforeunload', function () {
  29550. if (self.script) self.script.onerror = empty;
  29551. }, false);
  29552. }
  29553. }
  29554. /**
  29555. * Inherits from Polling.
  29556. */
  29557. inherit(JSONPPolling, Polling);
  29558. /*
  29559. * JSONP only supports binary as base64 encoded strings
  29560. */
  29561. JSONPPolling.prototype.supportsBinary = false;
  29562. /**
  29563. * Closes the socket.
  29564. *
  29565. * @api private
  29566. */
  29567. JSONPPolling.prototype.doClose = function () {
  29568. if (this.script) {
  29569. this.script.parentNode.removeChild(this.script);
  29570. this.script = null;
  29571. }
  29572. if (this.form) {
  29573. this.form.parentNode.removeChild(this.form);
  29574. this.form = null;
  29575. this.iframe = null;
  29576. }
  29577. Polling.prototype.doClose.call(this);
  29578. };
  29579. /**
  29580. * Starts a poll cycle.
  29581. *
  29582. * @api private
  29583. */
  29584. JSONPPolling.prototype.doPoll = function () {
  29585. var self = this;
  29586. var script = document.createElement('script');
  29587. if (this.script) {
  29588. this.script.parentNode.removeChild(this.script);
  29589. this.script = null;
  29590. }
  29591. script.async = true;
  29592. script.src = this.uri();
  29593. script.onerror = function(e){
  29594. self.onError('jsonp poll error',e);
  29595. };
  29596. var insertAt = document.getElementsByTagName('script')[0];
  29597. insertAt.parentNode.insertBefore(script, insertAt);
  29598. this.script = script;
  29599. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  29600. if (isUAgecko) {
  29601. setTimeout(function () {
  29602. var iframe = document.createElement('iframe');
  29603. document.body.appendChild(iframe);
  29604. document.body.removeChild(iframe);
  29605. }, 100);
  29606. }
  29607. };
  29608. /**
  29609. * Writes with a hidden iframe.
  29610. *
  29611. * @param {String} data to send
  29612. * @param {Function} called upon flush.
  29613. * @api private
  29614. */
  29615. JSONPPolling.prototype.doWrite = function (data, fn) {
  29616. var self = this;
  29617. if (!this.form) {
  29618. var form = document.createElement('form');
  29619. var area = document.createElement('textarea');
  29620. var id = this.iframeId = 'eio_iframe_' + this.index;
  29621. var iframe;
  29622. form.className = 'socketio';
  29623. form.style.position = 'absolute';
  29624. form.style.top = '-1000px';
  29625. form.style.left = '-1000px';
  29626. form.target = id;
  29627. form.method = 'POST';
  29628. form.setAttribute('accept-charset', 'utf-8');
  29629. area.name = 'd';
  29630. form.appendChild(area);
  29631. document.body.appendChild(form);
  29632. this.form = form;
  29633. this.area = area;
  29634. }
  29635. this.form.action = this.uri();
  29636. function complete () {
  29637. initIframe();
  29638. fn();
  29639. }
  29640. function initIframe () {
  29641. if (self.iframe) {
  29642. try {
  29643. self.form.removeChild(self.iframe);
  29644. } catch (e) {
  29645. self.onError('jsonp polling iframe removal error', e);
  29646. }
  29647. }
  29648. try {
  29649. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  29650. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  29651. iframe = document.createElement(html);
  29652. } catch (e) {
  29653. iframe = document.createElement('iframe');
  29654. iframe.name = self.iframeId;
  29655. iframe.src = 'javascript:0';
  29656. }
  29657. iframe.id = self.iframeId;
  29658. self.form.appendChild(iframe);
  29659. self.iframe = iframe;
  29660. }
  29661. initIframe();
  29662. // escape \n to prevent it from being converted into \r\n by some UAs
  29663. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  29664. data = data.replace(rEscapedNewline, '\\\n');
  29665. this.area.value = data.replace(rNewline, '\\n');
  29666. try {
  29667. this.form.submit();
  29668. } catch(e) {}
  29669. if (this.iframe.attachEvent) {
  29670. this.iframe.onreadystatechange = function(){
  29671. if (self.iframe.readyState == 'complete') {
  29672. complete();
  29673. }
  29674. };
  29675. } else {
  29676. this.iframe.onload = complete;
  29677. }
  29678. };
  29679. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  29680. },{"./polling":129,"component-inherit":132}],128:[function(require,module,exports){
  29681. (function (global){
  29682. /**
  29683. * Module requirements.
  29684. */
  29685. var XMLHttpRequest = require('xmlhttprequest');
  29686. var Polling = require('./polling');
  29687. var Emitter = require('component-emitter');
  29688. var inherit = require('component-inherit');
  29689. var debug = require('debug')('engine.io-client:polling-xhr');
  29690. /**
  29691. * Module exports.
  29692. */
  29693. module.exports = XHR;
  29694. module.exports.Request = Request;
  29695. /**
  29696. * Empty function
  29697. */
  29698. function empty(){}
  29699. /**
  29700. * XHR Polling constructor.
  29701. *
  29702. * @param {Object} opts
  29703. * @api public
  29704. */
  29705. function XHR(opts){
  29706. Polling.call(this, opts);
  29707. if (global.location) {
  29708. var isSSL = 'https:' == location.protocol;
  29709. var port = location.port;
  29710. // some user agents have empty `location.port`
  29711. if (!port) {
  29712. port = isSSL ? 443 : 80;
  29713. }
  29714. this.xd = opts.hostname != global.location.hostname ||
  29715. port != opts.port;
  29716. this.xs = opts.secure != isSSL;
  29717. }
  29718. }
  29719. /**
  29720. * Inherits from Polling.
  29721. */
  29722. inherit(XHR, Polling);
  29723. /**
  29724. * XHR supports binary
  29725. */
  29726. XHR.prototype.supportsBinary = true;
  29727. /**
  29728. * Creates a request.
  29729. *
  29730. * @param {String} method
  29731. * @api private
  29732. */
  29733. XHR.prototype.request = function(opts){
  29734. opts = opts || {};
  29735. opts.uri = this.uri();
  29736. opts.xd = this.xd;
  29737. opts.xs = this.xs;
  29738. opts.agent = this.agent || false;
  29739. opts.supportsBinary = this.supportsBinary;
  29740. opts.enablesXDR = this.enablesXDR;
  29741. // SSL options for Node.js client
  29742. opts.pfx = this.pfx;
  29743. opts.key = this.key;
  29744. opts.passphrase = this.passphrase;
  29745. opts.cert = this.cert;
  29746. opts.ca = this.ca;
  29747. opts.ciphers = this.ciphers;
  29748. opts.rejectUnauthorized = this.rejectUnauthorized;
  29749. return new Request(opts);
  29750. };
  29751. /**
  29752. * Sends data.
  29753. *
  29754. * @param {String} data to send.
  29755. * @param {Function} called upon flush.
  29756. * @api private
  29757. */
  29758. XHR.prototype.doWrite = function(data, fn){
  29759. var isBinary = typeof data !== 'string' && data !== undefined;
  29760. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  29761. var self = this;
  29762. req.on('success', fn);
  29763. req.on('error', function(err){
  29764. self.onError('xhr post error', err);
  29765. });
  29766. this.sendXhr = req;
  29767. };
  29768. /**
  29769. * Starts a poll cycle.
  29770. *
  29771. * @api private
  29772. */
  29773. XHR.prototype.doPoll = function(){
  29774. debug('xhr poll');
  29775. var req = this.request();
  29776. var self = this;
  29777. req.on('data', function(data){
  29778. self.onData(data);
  29779. });
  29780. req.on('error', function(err){
  29781. self.onError('xhr poll error', err);
  29782. });
  29783. this.pollXhr = req;
  29784. };
  29785. /**
  29786. * Request constructor
  29787. *
  29788. * @param {Object} options
  29789. * @api public
  29790. */
  29791. function Request(opts){
  29792. this.method = opts.method || 'GET';
  29793. this.uri = opts.uri;
  29794. this.xd = !!opts.xd;
  29795. this.xs = !!opts.xs;
  29796. this.async = false !== opts.async;
  29797. this.data = undefined != opts.data ? opts.data : null;
  29798. this.agent = opts.agent;
  29799. this.isBinary = opts.isBinary;
  29800. this.supportsBinary = opts.supportsBinary;
  29801. this.enablesXDR = opts.enablesXDR;
  29802. // SSL options for Node.js client
  29803. this.pfx = opts.pfx;
  29804. this.key = opts.key;
  29805. this.passphrase = opts.passphrase;
  29806. this.cert = opts.cert;
  29807. this.ca = opts.ca;
  29808. this.ciphers = opts.ciphers;
  29809. this.rejectUnauthorized = opts.rejectUnauthorized;
  29810. this.create();
  29811. }
  29812. /**
  29813. * Mix in `Emitter`.
  29814. */
  29815. Emitter(Request.prototype);
  29816. /**
  29817. * Creates the XHR object and sends the request.
  29818. *
  29819. * @api private
  29820. */
  29821. Request.prototype.create = function(){
  29822. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  29823. // SSL options for Node.js client
  29824. opts.pfx = this.pfx;
  29825. opts.key = this.key;
  29826. opts.passphrase = this.passphrase;
  29827. opts.cert = this.cert;
  29828. opts.ca = this.ca;
  29829. opts.ciphers = this.ciphers;
  29830. opts.rejectUnauthorized = this.rejectUnauthorized;
  29831. var xhr = this.xhr = new XMLHttpRequest(opts);
  29832. var self = this;
  29833. try {
  29834. debug('xhr open %s: %s', this.method, this.uri);
  29835. xhr.open(this.method, this.uri, this.async);
  29836. if (this.supportsBinary) {
  29837. // This has to be done after open because Firefox is stupid
  29838. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  29839. xhr.responseType = 'arraybuffer';
  29840. }
  29841. if ('POST' == this.method) {
  29842. try {
  29843. if (this.isBinary) {
  29844. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  29845. } else {
  29846. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  29847. }
  29848. } catch (e) {}
  29849. }
  29850. // ie6 check
  29851. if ('withCredentials' in xhr) {
  29852. xhr.withCredentials = true;
  29853. }
  29854. if (this.hasXDR()) {
  29855. xhr.onload = function(){
  29856. self.onLoad();
  29857. };
  29858. xhr.onerror = function(){
  29859. self.onError(xhr.responseText);
  29860. };
  29861. } else {
  29862. xhr.onreadystatechange = function(){
  29863. if (4 != xhr.readyState) return;
  29864. if (200 == xhr.status || 1223 == xhr.status) {
  29865. self.onLoad();
  29866. } else {
  29867. // make sure the `error` event handler that's user-set
  29868. // does not throw in the same tick and gets caught here
  29869. setTimeout(function(){
  29870. self.onError(xhr.status);
  29871. }, 0);
  29872. }
  29873. };
  29874. }
  29875. debug('xhr data %s', this.data);
  29876. xhr.send(this.data);
  29877. } catch (e) {
  29878. // Need to defer since .create() is called directly fhrom the constructor
  29879. // and thus the 'error' event can only be only bound *after* this exception
  29880. // occurs. Therefore, also, we cannot throw here at all.
  29881. setTimeout(function() {
  29882. self.onError(e);
  29883. }, 0);
  29884. return;
  29885. }
  29886. if (global.document) {
  29887. this.index = Request.requestsCount++;
  29888. Request.requests[this.index] = this;
  29889. }
  29890. };
  29891. /**
  29892. * Called upon successful response.
  29893. *
  29894. * @api private
  29895. */
  29896. Request.prototype.onSuccess = function(){
  29897. this.emit('success');
  29898. this.cleanup();
  29899. };
  29900. /**
  29901. * Called if we have data.
  29902. *
  29903. * @api private
  29904. */
  29905. Request.prototype.onData = function(data){
  29906. this.emit('data', data);
  29907. this.onSuccess();
  29908. };
  29909. /**
  29910. * Called upon error.
  29911. *
  29912. * @api private
  29913. */
  29914. Request.prototype.onError = function(err){
  29915. this.emit('error', err);
  29916. this.cleanup(true);
  29917. };
  29918. /**
  29919. * Cleans up house.
  29920. *
  29921. * @api private
  29922. */
  29923. Request.prototype.cleanup = function(fromError){
  29924. if ('undefined' == typeof this.xhr || null === this.xhr) {
  29925. return;
  29926. }
  29927. // xmlhttprequest
  29928. if (this.hasXDR()) {
  29929. this.xhr.onload = this.xhr.onerror = empty;
  29930. } else {
  29931. this.xhr.onreadystatechange = empty;
  29932. }
  29933. if (fromError) {
  29934. try {
  29935. this.xhr.abort();
  29936. } catch(e) {}
  29937. }
  29938. if (global.document) {
  29939. delete Request.requests[this.index];
  29940. }
  29941. this.xhr = null;
  29942. };
  29943. /**
  29944. * Called upon load.
  29945. *
  29946. * @api private
  29947. */
  29948. Request.prototype.onLoad = function(){
  29949. var data;
  29950. try {
  29951. var contentType;
  29952. try {
  29953. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  29954. } catch (e) {}
  29955. if (contentType === 'application/octet-stream') {
  29956. data = this.xhr.response;
  29957. } else {
  29958. if (!this.supportsBinary) {
  29959. data = this.xhr.responseText;
  29960. } else {
  29961. data = 'ok';
  29962. }
  29963. }
  29964. } catch (e) {
  29965. this.onError(e);
  29966. }
  29967. if (null != data) {
  29968. this.onData(data);
  29969. }
  29970. };
  29971. /**
  29972. * Check if it has XDomainRequest.
  29973. *
  29974. * @api private
  29975. */
  29976. Request.prototype.hasXDR = function(){
  29977. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  29978. };
  29979. /**
  29980. * Aborts the request.
  29981. *
  29982. * @api public
  29983. */
  29984. Request.prototype.abort = function(){
  29985. this.cleanup();
  29986. };
  29987. /**
  29988. * Aborts pending requests when unloading the window. This is needed to prevent
  29989. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  29990. * emitted.
  29991. */
  29992. if (global.document) {
  29993. Request.requestsCount = 0;
  29994. Request.requests = {};
  29995. if (global.attachEvent) {
  29996. global.attachEvent('onunload', unloadHandler);
  29997. } else if (global.addEventListener) {
  29998. global.addEventListener('beforeunload', unloadHandler, false);
  29999. }
  30000. }
  30001. function unloadHandler() {
  30002. for (var i in Request.requests) {
  30003. if (Request.requests.hasOwnProperty(i)) {
  30004. Request.requests[i].abort();
  30005. }
  30006. }
  30007. }
  30008. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  30009. },{"./polling":129,"component-emitter":120,"component-inherit":132,"debug":133,"xmlhttprequest":131}],129:[function(require,module,exports){
  30010. /**
  30011. * Module dependencies.
  30012. */
  30013. var Transport = require('../transport');
  30014. var parseqs = require('parseqs');
  30015. var parser = require('engine.io-parser');
  30016. var inherit = require('component-inherit');
  30017. var debug = require('debug')('engine.io-client:polling');
  30018. /**
  30019. * Module exports.
  30020. */
  30021. module.exports = Polling;
  30022. /**
  30023. * Is XHR2 supported?
  30024. */
  30025. var hasXHR2 = (function() {
  30026. var XMLHttpRequest = require('xmlhttprequest');
  30027. var xhr = new XMLHttpRequest({ xdomain: false });
  30028. return null != xhr.responseType;
  30029. })();
  30030. /**
  30031. * Polling interface.
  30032. *
  30033. * @param {Object} opts
  30034. * @api private
  30035. */
  30036. function Polling(opts){
  30037. var forceBase64 = (opts && opts.forceBase64);
  30038. if (!hasXHR2 || forceBase64) {
  30039. this.supportsBinary = false;
  30040. }
  30041. Transport.call(this, opts);
  30042. }
  30043. /**
  30044. * Inherits from Transport.
  30045. */
  30046. inherit(Polling, Transport);
  30047. /**
  30048. * Transport name.
  30049. */
  30050. Polling.prototype.name = 'polling';
  30051. /**
  30052. * Opens the socket (triggers polling). We write a PING message to determine
  30053. * when the transport is open.
  30054. *
  30055. * @api private
  30056. */
  30057. Polling.prototype.doOpen = function(){
  30058. this.poll();
  30059. };
  30060. /**
  30061. * Pauses polling.
  30062. *
  30063. * @param {Function} callback upon buffers are flushed and transport is paused
  30064. * @api private
  30065. */
  30066. Polling.prototype.pause = function(onPause){
  30067. var pending = 0;
  30068. var self = this;
  30069. this.readyState = 'pausing';
  30070. function pause(){
  30071. debug('paused');
  30072. self.readyState = 'paused';
  30073. onPause();
  30074. }
  30075. if (this.polling || !this.writable) {
  30076. var total = 0;
  30077. if (this.polling) {
  30078. debug('we are currently polling - waiting to pause');
  30079. total++;
  30080. this.once('pollComplete', function(){
  30081. debug('pre-pause polling complete');
  30082. --total || pause();
  30083. });
  30084. }
  30085. if (!this.writable) {
  30086. debug('we are currently writing - waiting to pause');
  30087. total++;
  30088. this.once('drain', function(){
  30089. debug('pre-pause writing complete');
  30090. --total || pause();
  30091. });
  30092. }
  30093. } else {
  30094. pause();
  30095. }
  30096. };
  30097. /**
  30098. * Starts polling cycle.
  30099. *
  30100. * @api public
  30101. */
  30102. Polling.prototype.poll = function(){
  30103. debug('polling');
  30104. this.polling = true;
  30105. this.doPoll();
  30106. this.emit('poll');
  30107. };
  30108. /**
  30109. * Overloads onData to detect payloads.
  30110. *
  30111. * @api private
  30112. */
  30113. Polling.prototype.onData = function(data){
  30114. var self = this;
  30115. debug('polling got data %s', data);
  30116. var callback = function(packet, index, total) {
  30117. // if its the first message we consider the transport open
  30118. if ('opening' == self.readyState) {
  30119. self.onOpen();
  30120. }
  30121. // if its a close packet, we close the ongoing requests
  30122. if ('close' == packet.type) {
  30123. self.onClose();
  30124. return false;
  30125. }
  30126. // otherwise bypass onData and handle the message
  30127. self.onPacket(packet);
  30128. };
  30129. // decode payload
  30130. parser.decodePayload(data, this.socket.binaryType, callback);
  30131. // if an event did not trigger closing
  30132. if ('closed' != this.readyState) {
  30133. // if we got data we're not polling
  30134. this.polling = false;
  30135. this.emit('pollComplete');
  30136. if ('open' == this.readyState) {
  30137. this.poll();
  30138. } else {
  30139. debug('ignoring poll - transport state "%s"', this.readyState);
  30140. }
  30141. }
  30142. };
  30143. /**
  30144. * For polling, send a close packet.
  30145. *
  30146. * @api private
  30147. */
  30148. Polling.prototype.doClose = function(){
  30149. var self = this;
  30150. function close(){
  30151. debug('writing close packet');
  30152. self.write([{ type: 'close' }]);
  30153. }
  30154. if ('open' == this.readyState) {
  30155. debug('transport open - closing');
  30156. close();
  30157. } else {
  30158. // in case we're trying to close while
  30159. // handshaking is in progress (GH-164)
  30160. debug('transport not open - deferring close');
  30161. this.once('open', close);
  30162. }
  30163. };
  30164. /**
  30165. * Writes a packets payload.
  30166. *
  30167. * @param {Array} data packets
  30168. * @param {Function} drain callback
  30169. * @api private
  30170. */
  30171. Polling.prototype.write = function(packets){
  30172. var self = this;
  30173. this.writable = false;
  30174. var callbackfn = function() {
  30175. self.writable = true;
  30176. self.emit('drain');
  30177. };
  30178. var self = this;
  30179. parser.encodePayload(packets, this.supportsBinary, function(data) {
  30180. self.doWrite(data, callbackfn);
  30181. });
  30182. };
  30183. /**
  30184. * Generates uri for connection.
  30185. *
  30186. * @api private
  30187. */
  30188. Polling.prototype.uri = function(){
  30189. var query = this.query || {};
  30190. var schema = this.secure ? 'https' : 'http';
  30191. var port = '';
  30192. // cache busting is forced
  30193. if (false !== this.timestampRequests) {
  30194. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  30195. }
  30196. if (!this.supportsBinary && !query.sid) {
  30197. query.b64 = 1;
  30198. }
  30199. query = parseqs.encode(query);
  30200. // avoid port if default for schema
  30201. if (this.port && (('https' == schema && this.port != 443) ||
  30202. ('http' == schema && this.port != 80))) {
  30203. port = ':' + this.port;
  30204. }
  30205. // prepend ? to query
  30206. if (query.length) {
  30207. query = '?' + query;
  30208. }
  30209. return schema + '://' + this.hostname + port + this.path + query;
  30210. };
  30211. },{"../transport":125,"component-inherit":132,"debug":133,"engine.io-parser":136,"parseqs":148,"xmlhttprequest":131}],130:[function(require,module,exports){
  30212. /**
  30213. * Module dependencies.
  30214. */
  30215. var Transport = require('../transport');
  30216. var parser = require('engine.io-parser');
  30217. var parseqs = require('parseqs');
  30218. var inherit = require('component-inherit');
  30219. var debug = require('debug')('engine.io-client:websocket');
  30220. /**
  30221. * `ws` exposes a WebSocket-compatible interface in
  30222. * Node, or the `WebSocket` or `MozWebSocket` globals
  30223. * in the browser.
  30224. */
  30225. var WebSocket = require('ws');
  30226. /**
  30227. * Module exports.
  30228. */
  30229. module.exports = WS;
  30230. /**
  30231. * WebSocket transport constructor.
  30232. *
  30233. * @api {Object} connection options
  30234. * @api public
  30235. */
  30236. function WS(opts){
  30237. var forceBase64 = (opts && opts.forceBase64);
  30238. if (forceBase64) {
  30239. this.supportsBinary = false;
  30240. }
  30241. Transport.call(this, opts);
  30242. }
  30243. /**
  30244. * Inherits from Transport.
  30245. */
  30246. inherit(WS, Transport);
  30247. /**
  30248. * Transport name.
  30249. *
  30250. * @api public
  30251. */
  30252. WS.prototype.name = 'websocket';
  30253. /*
  30254. * WebSockets support binary
  30255. */
  30256. WS.prototype.supportsBinary = true;
  30257. /**
  30258. * Opens socket.
  30259. *
  30260. * @api private
  30261. */
  30262. WS.prototype.doOpen = function(){
  30263. if (!this.check()) {
  30264. // let probe timeout
  30265. return;
  30266. }
  30267. var self = this;
  30268. var uri = this.uri();
  30269. var protocols = void(0);
  30270. var opts = { agent: this.agent };
  30271. // SSL options for Node.js client
  30272. opts.pfx = this.pfx;
  30273. opts.key = this.key;
  30274. opts.passphrase = this.passphrase;
  30275. opts.cert = this.cert;
  30276. opts.ca = this.ca;
  30277. opts.ciphers = this.ciphers;
  30278. opts.rejectUnauthorized = this.rejectUnauthorized;
  30279. this.ws = new WebSocket(uri, protocols, opts);
  30280. if (this.ws.binaryType === undefined) {
  30281. this.supportsBinary = false;
  30282. }
  30283. this.ws.binaryType = 'arraybuffer';
  30284. this.addEventListeners();
  30285. };
  30286. /**
  30287. * Adds event listeners to the socket
  30288. *
  30289. * @api private
  30290. */
  30291. WS.prototype.addEventListeners = function(){
  30292. var self = this;
  30293. this.ws.onopen = function(){
  30294. self.onOpen();
  30295. };
  30296. this.ws.onclose = function(){
  30297. self.onClose();
  30298. };
  30299. this.ws.onmessage = function(ev){
  30300. self.onData(ev.data);
  30301. };
  30302. this.ws.onerror = function(e){
  30303. self.onError('websocket error', e);
  30304. };
  30305. };
  30306. /**
  30307. * Override `onData` to use a timer on iOS.
  30308. * See: https://gist.github.com/mloughran/2052006
  30309. *
  30310. * @api private
  30311. */
  30312. if ('undefined' != typeof navigator
  30313. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  30314. WS.prototype.onData = function(data){
  30315. var self = this;
  30316. setTimeout(function(){
  30317. Transport.prototype.onData.call(self, data);
  30318. }, 0);
  30319. };
  30320. }
  30321. /**
  30322. * Writes data to socket.
  30323. *
  30324. * @param {Array} array of packets.
  30325. * @api private
  30326. */
  30327. WS.prototype.write = function(packets){
  30328. var self = this;
  30329. this.writable = false;
  30330. // encodePacket efficient as it uses WS framing
  30331. // no need for encodePayload
  30332. for (var i = 0, l = packets.length; i < l; i++) {
  30333. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  30334. //Sometimes the websocket has already been closed but the browser didn't
  30335. //have a chance of informing us about it yet, in that case send will
  30336. //throw an error
  30337. try {
  30338. self.ws.send(data);
  30339. } catch (e){
  30340. debug('websocket closed before onclose event');
  30341. }
  30342. });
  30343. }
  30344. function ondrain() {
  30345. self.writable = true;
  30346. self.emit('drain');
  30347. }
  30348. // fake drain
  30349. // defer to next tick to allow Socket to clear writeBuffer
  30350. setTimeout(ondrain, 0);
  30351. };
  30352. /**
  30353. * Called upon close
  30354. *
  30355. * @api private
  30356. */
  30357. WS.prototype.onClose = function(){
  30358. Transport.prototype.onClose.call(this);
  30359. };
  30360. /**
  30361. * Closes socket.
  30362. *
  30363. * @api private
  30364. */
  30365. WS.prototype.doClose = function(){
  30366. if (typeof this.ws !== 'undefined') {
  30367. this.ws.close();
  30368. }
  30369. };
  30370. /**
  30371. * Generates uri for connection.
  30372. *
  30373. * @api private
  30374. */
  30375. WS.prototype.uri = function(){
  30376. var query = this.query || {};
  30377. var schema = this.secure ? 'wss' : 'ws';
  30378. var port = '';
  30379. // avoid port if default for schema
  30380. if (this.port && (('wss' == schema && this.port != 443)
  30381. || ('ws' == schema && this.port != 80))) {
  30382. port = ':' + this.port;
  30383. }
  30384. // append timestamp to URI
  30385. if (this.timestampRequests) {
  30386. query[this.timestampParam] = +new Date;
  30387. }
  30388. // communicate binary support capabilities
  30389. if (!this.supportsBinary) {
  30390. query.b64 = 1;
  30391. }
  30392. query = parseqs.encode(query);
  30393. // prepend ? to query
  30394. if (query.length) {
  30395. query = '?' + query;
  30396. }
  30397. return schema + '://' + this.hostname + port + this.path + query;
  30398. };
  30399. /**
  30400. * Feature detection for WebSocket.
  30401. *
  30402. * @return {Boolean} whether this transport is available.
  30403. * @api public
  30404. */
  30405. WS.prototype.check = function(){
  30406. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  30407. };
  30408. },{"../transport":125,"component-inherit":132,"debug":133,"engine.io-parser":136,"parseqs":148,"ws":150}],131:[function(require,module,exports){
  30409. // browser shim for xmlhttprequest module
  30410. var hasCORS = require('has-cors');
  30411. module.exports = function(opts) {
  30412. var xdomain = opts.xdomain;
  30413. // scheme must be same when usign XDomainRequest
  30414. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  30415. var xscheme = opts.xscheme;
  30416. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  30417. // https://github.com/Automattic/engine.io-client/pull/217
  30418. var enablesXDR = opts.enablesXDR;
  30419. // XMLHttpRequest can be disabled on IE
  30420. try {
  30421. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  30422. return new XMLHttpRequest();
  30423. }
  30424. } catch (e) { }
  30425. // Use XDomainRequest for IE8 if enablesXDR is true
  30426. // because loading bar keeps flashing when using jsonp-polling
  30427. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  30428. try {
  30429. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  30430. return new XDomainRequest();
  30431. }
  30432. } catch (e) { }
  30433. if (!xdomain) {
  30434. try {
  30435. return new ActiveXObject('Microsoft.XMLHTTP');
  30436. } catch(e) { }
  30437. }
  30438. }
  30439. },{"has-cors":145}],132:[function(require,module,exports){
  30440. module.exports = function(a, b){
  30441. var fn = function(){};
  30442. fn.prototype = b.prototype;
  30443. a.prototype = new fn;
  30444. a.prototype.constructor = a;
  30445. };
  30446. },{}],133:[function(require,module,exports){
  30447. /**
  30448. * This is the web browser implementation of `debug()`.
  30449. *
  30450. * Expose `debug()` as the module.
  30451. */
  30452. exports = module.exports = require('./debug');
  30453. exports.log = log;
  30454. exports.formatArgs = formatArgs;
  30455. exports.save = save;
  30456. exports.load = load;
  30457. exports.useColors = useColors;
  30458. /**
  30459. * Colors.
  30460. */
  30461. exports.colors = [
  30462. 'lightseagreen',
  30463. 'forestgreen',
  30464. 'goldenrod',
  30465. 'dodgerblue',
  30466. 'darkorchid',
  30467. 'crimson'
  30468. ];
  30469. /**
  30470. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  30471. * and the Firebug extension (any Firefox version) are known
  30472. * to support "%c" CSS customizations.
  30473. *
  30474. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  30475. */
  30476. function useColors() {
  30477. // is webkit? http://stackoverflow.com/a/16459606/376773
  30478. return ('WebkitAppearance' in document.documentElement.style) ||
  30479. // is firebug? http://stackoverflow.com/a/398120/376773
  30480. (window.console && (console.firebug || (console.exception && console.table))) ||
  30481. // is firefox >= v31?
  30482. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  30483. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  30484. }
  30485. /**
  30486. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  30487. */
  30488. exports.formatters.j = function(v) {
  30489. return JSON.stringify(v);
  30490. };
  30491. /**
  30492. * Colorize log arguments if enabled.
  30493. *
  30494. * @api public
  30495. */
  30496. function formatArgs() {
  30497. var args = arguments;
  30498. var useColors = this.useColors;
  30499. args[0] = (useColors ? '%c' : '')
  30500. + this.namespace
  30501. + (useColors ? ' %c' : ' ')
  30502. + args[0]
  30503. + (useColors ? '%c ' : ' ')
  30504. + '+' + exports.humanize(this.diff);
  30505. if (!useColors) return args;
  30506. var c = 'color: ' + this.color;
  30507. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  30508. // the final "%c" is somewhat tricky, because there could be other
  30509. // arguments passed either before or after the %c, so we need to
  30510. // figure out the correct index to insert the CSS into
  30511. var index = 0;
  30512. var lastC = 0;
  30513. args[0].replace(/%[a-z%]/g, function(match) {
  30514. if ('%%' === match) return;
  30515. index++;
  30516. if ('%c' === match) {
  30517. // we only are interested in the *last* %c
  30518. // (the user may have provided their own)
  30519. lastC = index;
  30520. }
  30521. });
  30522. args.splice(lastC, 0, c);
  30523. return args;
  30524. }
  30525. /**
  30526. * Invokes `console.log()` when available.
  30527. * No-op when `console.log` is not a "function".
  30528. *
  30529. * @api public
  30530. */
  30531. function log() {
  30532. // This hackery is required for IE8,
  30533. // where the `console.log` function doesn't have 'apply'
  30534. return 'object' == typeof console
  30535. && 'function' == typeof console.log
  30536. && Function.prototype.apply.call(console.log, console, arguments);
  30537. }
  30538. /**
  30539. * Save `namespaces`.
  30540. *
  30541. * @param {String} namespaces
  30542. * @api private
  30543. */
  30544. function save(namespaces) {
  30545. try {
  30546. if (null == namespaces) {
  30547. localStorage.removeItem('debug');
  30548. } else {
  30549. localStorage.debug = namespaces;
  30550. }
  30551. } catch(e) {}
  30552. }
  30553. /**
  30554. * Load `namespaces`.
  30555. *
  30556. * @return {String} returns the previously persisted debug modes
  30557. * @api private
  30558. */
  30559. function load() {
  30560. var r;
  30561. try {
  30562. r = localStorage.debug;
  30563. } catch(e) {}
  30564. return r;
  30565. }
  30566. /**
  30567. * Enable namespaces listed in `localStorage.debug` initially.
  30568. */
  30569. exports.enable(load());
  30570. },{"./debug":134}],134:[function(require,module,exports){
  30571. /**
  30572. * This is the common logic for both the Node.js and web browser
  30573. * implementations of `debug()`.
  30574. *
  30575. * Expose `debug()` as the module.
  30576. */
  30577. exports = module.exports = debug;
  30578. exports.coerce = coerce;
  30579. exports.disable = disable;
  30580. exports.enable = enable;
  30581. exports.enabled = enabled;
  30582. exports.humanize = require('ms');
  30583. /**
  30584. * The currently active debug mode names, and names to skip.
  30585. */
  30586. exports.names = [];
  30587. exports.skips = [];
  30588. /**
  30589. * Map of special "%n" handling functions, for the debug "format" argument.
  30590. *
  30591. * Valid key names are a single, lowercased letter, i.e. "n".
  30592. */
  30593. exports.formatters = {};
  30594. /**
  30595. * Previously assigned color.
  30596. */
  30597. var prevColor = 0;
  30598. /**
  30599. * Previous log timestamp.
  30600. */
  30601. var prevTime;
  30602. /**
  30603. * Select a color.
  30604. *
  30605. * @return {Number}
  30606. * @api private
  30607. */
  30608. function selectColor() {
  30609. return exports.colors[prevColor++ % exports.colors.length];
  30610. }
  30611. /**
  30612. * Create a debugger with the given `namespace`.
  30613. *
  30614. * @param {String} namespace
  30615. * @return {Function}
  30616. * @api public
  30617. */
  30618. function debug(namespace) {
  30619. // define the `disabled` version
  30620. function disabled() {
  30621. }
  30622. disabled.enabled = false;
  30623. // define the `enabled` version
  30624. function enabled() {
  30625. var self = enabled;
  30626. // set `diff` timestamp
  30627. var curr = +new Date();
  30628. var ms = curr - (prevTime || curr);
  30629. self.diff = ms;
  30630. self.prev = prevTime;
  30631. self.curr = curr;
  30632. prevTime = curr;
  30633. // add the `color` if not set
  30634. if (null == self.useColors) self.useColors = exports.useColors();
  30635. if (null == self.color && self.useColors) self.color = selectColor();
  30636. var args = Array.prototype.slice.call(arguments);
  30637. args[0] = exports.coerce(args[0]);
  30638. if ('string' !== typeof args[0]) {
  30639. // anything else let's inspect with %o
  30640. args = ['%o'].concat(args);
  30641. }
  30642. // apply any `formatters` transformations
  30643. var index = 0;
  30644. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  30645. // if we encounter an escaped % then don't increase the array index
  30646. if (match === '%%') return match;
  30647. index++;
  30648. var formatter = exports.formatters[format];
  30649. if ('function' === typeof formatter) {
  30650. var val = args[index];
  30651. match = formatter.call(self, val);
  30652. // now we need to remove `args[index]` since it's inlined in the `format`
  30653. args.splice(index, 1);
  30654. index--;
  30655. }
  30656. return match;
  30657. });
  30658. if ('function' === typeof exports.formatArgs) {
  30659. args = exports.formatArgs.apply(self, args);
  30660. }
  30661. var logFn = enabled.log || exports.log || console.log.bind(console);
  30662. logFn.apply(self, args);
  30663. }
  30664. enabled.enabled = true;
  30665. var fn = exports.enabled(namespace) ? enabled : disabled;
  30666. fn.namespace = namespace;
  30667. return fn;
  30668. }
  30669. /**
  30670. * Enables a debug mode by namespaces. This can include modes
  30671. * separated by a colon and wildcards.
  30672. *
  30673. * @param {String} namespaces
  30674. * @api public
  30675. */
  30676. function enable(namespaces) {
  30677. exports.save(namespaces);
  30678. var split = (namespaces || '').split(/[\s,]+/);
  30679. var len = split.length;
  30680. for (var i = 0; i < len; i++) {
  30681. if (!split[i]) continue; // ignore empty strings
  30682. namespaces = split[i].replace(/\*/g, '.*?');
  30683. if (namespaces[0] === '-') {
  30684. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  30685. } else {
  30686. exports.names.push(new RegExp('^' + namespaces + '$'));
  30687. }
  30688. }
  30689. }
  30690. /**
  30691. * Disable debug output.
  30692. *
  30693. * @api public
  30694. */
  30695. function disable() {
  30696. exports.enable('');
  30697. }
  30698. /**
  30699. * Returns true if the given mode name is enabled, false otherwise.
  30700. *
  30701. * @param {String} name
  30702. * @return {Boolean}
  30703. * @api public
  30704. */
  30705. function enabled(name) {
  30706. var i, len;
  30707. for (i = 0, len = exports.skips.length; i < len; i++) {
  30708. if (exports.skips[i].test(name)) {
  30709. return false;
  30710. }
  30711. }
  30712. for (i = 0, len = exports.names.length; i < len; i++) {
  30713. if (exports.names[i].test(name)) {
  30714. return true;
  30715. }
  30716. }
  30717. return false;
  30718. }
  30719. /**
  30720. * Coerce `val`.
  30721. *
  30722. * @param {Mixed} val
  30723. * @return {Mixed}
  30724. * @api private
  30725. */
  30726. function coerce(val) {
  30727. if (val instanceof Error) return val.stack || val.message;
  30728. return val;
  30729. }
  30730. },{"ms":135}],135:[function(require,module,exports){
  30731. /**
  30732. * Helpers.
  30733. */
  30734. var s = 1000;
  30735. var m = s * 60;
  30736. var h = m * 60;
  30737. var d = h * 24;
  30738. var y = d * 365.25;
  30739. /**
  30740. * Parse or format the given `val`.
  30741. *
  30742. * Options:
  30743. *
  30744. * - `long` verbose formatting [false]
  30745. *
  30746. * @param {String|Number} val
  30747. * @param {Object} options
  30748. * @return {String|Number}
  30749. * @api public
  30750. */
  30751. module.exports = function(val, options){
  30752. options = options || {};
  30753. if ('string' == typeof val) return parse(val);
  30754. return options.long
  30755. ? long(val)
  30756. : short(val);
  30757. };
  30758. /**
  30759. * Parse the given `str` and return milliseconds.
  30760. *
  30761. * @param {String} str
  30762. * @return {Number}
  30763. * @api private
  30764. */
  30765. function parse(str) {
  30766. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  30767. if (!match) return;
  30768. var n = parseFloat(match[1]);
  30769. var type = (match[2] || 'ms').toLowerCase();
  30770. switch (type) {
  30771. case 'years':
  30772. case 'year':
  30773. case 'y':
  30774. return n * y;
  30775. case 'days':
  30776. case 'day':
  30777. case 'd':
  30778. return n * d;
  30779. case 'hours':
  30780. case 'hour':
  30781. case 'h':
  30782. return n * h;
  30783. case 'minutes':
  30784. case 'minute':
  30785. case 'm':
  30786. return n * m;
  30787. case 'seconds':
  30788. case 'second':
  30789. case 's':
  30790. return n * s;
  30791. case 'ms':
  30792. return n;
  30793. }
  30794. }
  30795. /**
  30796. * Short format for `ms`.
  30797. *
  30798. * @param {Number} ms
  30799. * @return {String}
  30800. * @api private
  30801. */
  30802. function short(ms) {
  30803. if (ms >= d) return Math.round(ms / d) + 'd';
  30804. if (ms >= h) return Math.round(ms / h) + 'h';
  30805. if (ms >= m) return Math.round(ms / m) + 'm';
  30806. if (ms >= s) return Math.round(ms / s) + 's';
  30807. return ms + 'ms';
  30808. }
  30809. /**
  30810. * Long format for `ms`.
  30811. *
  30812. * @param {Number} ms
  30813. * @return {String}
  30814. * @api private
  30815. */
  30816. function long(ms) {
  30817. return plural(ms, d, 'day')
  30818. || plural(ms, h, 'hour')
  30819. || plural(ms, m, 'minute')
  30820. || plural(ms, s, 'second')
  30821. || ms + ' ms';
  30822. }
  30823. /**
  30824. * Pluralization helper.
  30825. */
  30826. function plural(ms, n, name) {
  30827. if (ms < n) return;
  30828. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  30829. return Math.ceil(ms / n) + ' ' + name + 's';
  30830. }
  30831. },{}],136:[function(require,module,exports){
  30832. (function (global){
  30833. /**
  30834. * Module dependencies.
  30835. */
  30836. var keys = require('./keys');
  30837. var hasBinary = require('has-binary');
  30838. var sliceBuffer = require('arraybuffer.slice');
  30839. var base64encoder = require('base64-arraybuffer');
  30840. var after = require('after');
  30841. var utf8 = require('utf8');
  30842. /**
  30843. * Check if we are running an android browser. That requires us to use
  30844. * ArrayBuffer with polling transports...
  30845. *
  30846. * http://ghinda.net/jpeg-blob-ajax-android/
  30847. */
  30848. var isAndroid = navigator.userAgent.match(/Android/i);
  30849. /**
  30850. * Check if we are running in PhantomJS.
  30851. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  30852. * https://github.com/ariya/phantomjs/issues/11395
  30853. * @type boolean
  30854. */
  30855. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  30856. /**
  30857. * When true, avoids using Blobs to encode payloads.
  30858. * @type boolean
  30859. */
  30860. var dontSendBlobs = isAndroid || isPhantomJS;
  30861. /**
  30862. * Current protocol version.
  30863. */
  30864. exports.protocol = 3;
  30865. /**
  30866. * Packet types.
  30867. */
  30868. var packets = exports.packets = {
  30869. open: 0 // non-ws
  30870. , close: 1 // non-ws
  30871. , ping: 2
  30872. , pong: 3
  30873. , message: 4
  30874. , upgrade: 5
  30875. , noop: 6
  30876. };
  30877. var packetslist = keys(packets);
  30878. /**
  30879. * Premade error packet.
  30880. */
  30881. var err = { type: 'error', data: 'parser error' };
  30882. /**
  30883. * Create a blob api even for blob builder when vendor prefixes exist
  30884. */
  30885. var Blob = require('blob');
  30886. /**
  30887. * Encodes a packet.
  30888. *
  30889. * <packet type id> [ <data> ]
  30890. *
  30891. * Example:
  30892. *
  30893. * 5hello world
  30894. * 3
  30895. * 4
  30896. *
  30897. * Binary is encoded in an identical principle
  30898. *
  30899. * @api private
  30900. */
  30901. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  30902. if ('function' == typeof supportsBinary) {
  30903. callback = supportsBinary;
  30904. supportsBinary = false;
  30905. }
  30906. if ('function' == typeof utf8encode) {
  30907. callback = utf8encode;
  30908. utf8encode = null;
  30909. }
  30910. var data = (packet.data === undefined)
  30911. ? undefined
  30912. : packet.data.buffer || packet.data;
  30913. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  30914. return encodeArrayBuffer(packet, supportsBinary, callback);
  30915. } else if (Blob && data instanceof global.Blob) {
  30916. return encodeBlob(packet, supportsBinary, callback);
  30917. }
  30918. // might be an object with { base64: true, data: dataAsBase64String }
  30919. if (data && data.base64) {
  30920. return encodeBase64Object(packet, callback);
  30921. }
  30922. // Sending data as a utf-8 string
  30923. var encoded = packets[packet.type];
  30924. // data fragment is optional
  30925. if (undefined !== packet.data) {
  30926. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  30927. }
  30928. return callback('' + encoded);
  30929. };
  30930. function encodeBase64Object(packet, callback) {
  30931. // packet data is an object { base64: true, data: dataAsBase64String }
  30932. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  30933. return callback(message);
  30934. }
  30935. /**
  30936. * Encode packet helpers for binary types
  30937. */
  30938. function encodeArrayBuffer(packet, supportsBinary, callback) {
  30939. if (!supportsBinary) {
  30940. return exports.encodeBase64Packet(packet, callback);
  30941. }
  30942. var data = packet.data;
  30943. var contentArray = new Uint8Array(data);
  30944. var resultBuffer = new Uint8Array(1 + data.byteLength);
  30945. resultBuffer[0] = packets[packet.type];
  30946. for (var i = 0; i < contentArray.length; i++) {
  30947. resultBuffer[i+1] = contentArray[i];
  30948. }
  30949. return callback(resultBuffer.buffer);
  30950. }
  30951. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  30952. if (!supportsBinary) {
  30953. return exports.encodeBase64Packet(packet, callback);
  30954. }
  30955. var fr = new FileReader();
  30956. fr.onload = function() {
  30957. packet.data = fr.result;
  30958. exports.encodePacket(packet, supportsBinary, true, callback);
  30959. };
  30960. return fr.readAsArrayBuffer(packet.data);
  30961. }
  30962. function encodeBlob(packet, supportsBinary, callback) {
  30963. if (!supportsBinary) {
  30964. return exports.encodeBase64Packet(packet, callback);
  30965. }
  30966. if (dontSendBlobs) {
  30967. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  30968. }
  30969. var length = new Uint8Array(1);
  30970. length[0] = packets[packet.type];
  30971. var blob = new Blob([length.buffer, packet.data]);
  30972. return callback(blob);
  30973. }
  30974. /**
  30975. * Encodes a packet with binary data in a base64 string
  30976. *
  30977. * @param {Object} packet, has `type` and `data`
  30978. * @return {String} base64 encoded message
  30979. */
  30980. exports.encodeBase64Packet = function(packet, callback) {
  30981. var message = 'b' + exports.packets[packet.type];
  30982. if (Blob && packet.data instanceof Blob) {
  30983. var fr = new FileReader();
  30984. fr.onload = function() {
  30985. var b64 = fr.result.split(',')[1];
  30986. callback(message + b64);
  30987. };
  30988. return fr.readAsDataURL(packet.data);
  30989. }
  30990. var b64data;
  30991. try {
  30992. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  30993. } catch (e) {
  30994. // iPhone Safari doesn't let you apply with typed arrays
  30995. var typed = new Uint8Array(packet.data);
  30996. var basic = new Array(typed.length);
  30997. for (var i = 0; i < typed.length; i++) {
  30998. basic[i] = typed[i];
  30999. }
  31000. b64data = String.fromCharCode.apply(null, basic);
  31001. }
  31002. message += global.btoa(b64data);
  31003. return callback(message);
  31004. };
  31005. /**
  31006. * Decodes a packet. Changes format to Blob if requested.
  31007. *
  31008. * @return {Object} with `type` and `data` (if any)
  31009. * @api private
  31010. */
  31011. exports.decodePacket = function (data, binaryType, utf8decode) {
  31012. // String data
  31013. if (typeof data == 'string' || data === undefined) {
  31014. if (data.charAt(0) == 'b') {
  31015. return exports.decodeBase64Packet(data.substr(1), binaryType);
  31016. }
  31017. if (utf8decode) {
  31018. try {
  31019. data = utf8.decode(data);
  31020. } catch (e) {
  31021. return err;
  31022. }
  31023. }
  31024. var type = data.charAt(0);
  31025. if (Number(type) != type || !packetslist[type]) {
  31026. return err;
  31027. }
  31028. if (data.length > 1) {
  31029. return { type: packetslist[type], data: data.substring(1) };
  31030. } else {
  31031. return { type: packetslist[type] };
  31032. }
  31033. }
  31034. var asArray = new Uint8Array(data);
  31035. var type = asArray[0];
  31036. var rest = sliceBuffer(data, 1);
  31037. if (Blob && binaryType === 'blob') {
  31038. rest = new Blob([rest]);
  31039. }
  31040. return { type: packetslist[type], data: rest };
  31041. };
  31042. /**
  31043. * Decodes a packet encoded in a base64 string
  31044. *
  31045. * @param {String} base64 encoded message
  31046. * @return {Object} with `type` and `data` (if any)
  31047. */
  31048. exports.decodeBase64Packet = function(msg, binaryType) {
  31049. var type = packetslist[msg.charAt(0)];
  31050. if (!global.ArrayBuffer) {
  31051. return { type: type, data: { base64: true, data: msg.substr(1) } };
  31052. }
  31053. var data = base64encoder.decode(msg.substr(1));
  31054. if (binaryType === 'blob' && Blob) {
  31055. data = new Blob([data]);
  31056. }
  31057. return { type: type, data: data };
  31058. };
  31059. /**
  31060. * Encodes multiple messages (payload).
  31061. *
  31062. * <length>:data
  31063. *
  31064. * Example:
  31065. *
  31066. * 11:hello world2:hi
  31067. *
  31068. * If any contents are binary, they will be encoded as base64 strings. Base64
  31069. * encoded strings are marked with a b before the length specifier
  31070. *
  31071. * @param {Array} packets
  31072. * @api private
  31073. */
  31074. exports.encodePayload = function (packets, supportsBinary, callback) {
  31075. if (typeof supportsBinary == 'function') {
  31076. callback = supportsBinary;
  31077. supportsBinary = null;
  31078. }
  31079. var isBinary = hasBinary(packets);
  31080. if (supportsBinary && isBinary) {
  31081. if (Blob && !dontSendBlobs) {
  31082. return exports.encodePayloadAsBlob(packets, callback);
  31083. }
  31084. return exports.encodePayloadAsArrayBuffer(packets, callback);
  31085. }
  31086. if (!packets.length) {
  31087. return callback('0:');
  31088. }
  31089. function setLengthHeader(message) {
  31090. return message.length + ':' + message;
  31091. }
  31092. function encodeOne(packet, doneCallback) {
  31093. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  31094. doneCallback(null, setLengthHeader(message));
  31095. });
  31096. }
  31097. map(packets, encodeOne, function(err, results) {
  31098. return callback(results.join(''));
  31099. });
  31100. };
  31101. /**
  31102. * Async array map using after
  31103. */
  31104. function map(ary, each, done) {
  31105. var result = new Array(ary.length);
  31106. var next = after(ary.length, done);
  31107. var eachWithIndex = function(i, el, cb) {
  31108. each(el, function(error, msg) {
  31109. result[i] = msg;
  31110. cb(error, result);
  31111. });
  31112. };
  31113. for (var i = 0; i < ary.length; i++) {
  31114. eachWithIndex(i, ary[i], next);
  31115. }
  31116. }
  31117. /*
  31118. * Decodes data when a payload is maybe expected. Possible binary contents are
  31119. * decoded from their base64 representation
  31120. *
  31121. * @param {String} data, callback method
  31122. * @api public
  31123. */
  31124. exports.decodePayload = function (data, binaryType, callback) {
  31125. if (typeof data != 'string') {
  31126. return exports.decodePayloadAsBinary(data, binaryType, callback);
  31127. }
  31128. if (typeof binaryType === 'function') {
  31129. callback = binaryType;
  31130. binaryType = null;
  31131. }
  31132. var packet;
  31133. if (data == '') {
  31134. // parser error - ignoring payload
  31135. return callback(err, 0, 1);
  31136. }
  31137. var length = ''
  31138. , n, msg;
  31139. for (var i = 0, l = data.length; i < l; i++) {
  31140. var chr = data.charAt(i);
  31141. if (':' != chr) {
  31142. length += chr;
  31143. } else {
  31144. if ('' == length || (length != (n = Number(length)))) {
  31145. // parser error - ignoring payload
  31146. return callback(err, 0, 1);
  31147. }
  31148. msg = data.substr(i + 1, n);
  31149. if (length != msg.length) {
  31150. // parser error - ignoring payload
  31151. return callback(err, 0, 1);
  31152. }
  31153. if (msg.length) {
  31154. packet = exports.decodePacket(msg, binaryType, true);
  31155. if (err.type == packet.type && err.data == packet.data) {
  31156. // parser error in individual packet - ignoring payload
  31157. return callback(err, 0, 1);
  31158. }
  31159. var ret = callback(packet, i + n, l);
  31160. if (false === ret) return;
  31161. }
  31162. // advance cursor
  31163. i += n;
  31164. length = '';
  31165. }
  31166. }
  31167. if (length != '') {
  31168. // parser error - ignoring payload
  31169. return callback(err, 0, 1);
  31170. }
  31171. };
  31172. /**
  31173. * Encodes multiple messages (payload) as binary.
  31174. *
  31175. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  31176. * 255><data>
  31177. *
  31178. * Example:
  31179. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  31180. *
  31181. * @param {Array} packets
  31182. * @return {ArrayBuffer} encoded payload
  31183. * @api private
  31184. */
  31185. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  31186. if (!packets.length) {
  31187. return callback(new ArrayBuffer(0));
  31188. }
  31189. function encodeOne(packet, doneCallback) {
  31190. exports.encodePacket(packet, true, true, function(data) {
  31191. return doneCallback(null, data);
  31192. });
  31193. }
  31194. map(packets, encodeOne, function(err, encodedPackets) {
  31195. var totalLength = encodedPackets.reduce(function(acc, p) {
  31196. var len;
  31197. if (typeof p === 'string'){
  31198. len = p.length;
  31199. } else {
  31200. len = p.byteLength;
  31201. }
  31202. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  31203. }, 0);
  31204. var resultArray = new Uint8Array(totalLength);
  31205. var bufferIndex = 0;
  31206. encodedPackets.forEach(function(p) {
  31207. var isString = typeof p === 'string';
  31208. var ab = p;
  31209. if (isString) {
  31210. var view = new Uint8Array(p.length);
  31211. for (var i = 0; i < p.length; i++) {
  31212. view[i] = p.charCodeAt(i);
  31213. }
  31214. ab = view.buffer;
  31215. }
  31216. if (isString) { // not true binary
  31217. resultArray[bufferIndex++] = 0;
  31218. } else { // true binary
  31219. resultArray[bufferIndex++] = 1;
  31220. }
  31221. var lenStr = ab.byteLength.toString();
  31222. for (var i = 0; i < lenStr.length; i++) {
  31223. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  31224. }
  31225. resultArray[bufferIndex++] = 255;
  31226. var view = new Uint8Array(ab);
  31227. for (var i = 0; i < view.length; i++) {
  31228. resultArray[bufferIndex++] = view[i];
  31229. }
  31230. });
  31231. return callback(resultArray.buffer);
  31232. });
  31233. };
  31234. /**
  31235. * Encode as Blob
  31236. */
  31237. exports.encodePayloadAsBlob = function(packets, callback) {
  31238. function encodeOne(packet, doneCallback) {
  31239. exports.encodePacket(packet, true, true, function(encoded) {
  31240. var binaryIdentifier = new Uint8Array(1);
  31241. binaryIdentifier[0] = 1;
  31242. if (typeof encoded === 'string') {
  31243. var view = new Uint8Array(encoded.length);
  31244. for (var i = 0; i < encoded.length; i++) {
  31245. view[i] = encoded.charCodeAt(i);
  31246. }
  31247. encoded = view.buffer;
  31248. binaryIdentifier[0] = 0;
  31249. }
  31250. var len = (encoded instanceof ArrayBuffer)
  31251. ? encoded.byteLength
  31252. : encoded.size;
  31253. var lenStr = len.toString();
  31254. var lengthAry = new Uint8Array(lenStr.length + 1);
  31255. for (var i = 0; i < lenStr.length; i++) {
  31256. lengthAry[i] = parseInt(lenStr[i]);
  31257. }
  31258. lengthAry[lenStr.length] = 255;
  31259. if (Blob) {
  31260. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  31261. doneCallback(null, blob);
  31262. }
  31263. });
  31264. }
  31265. map(packets, encodeOne, function(err, results) {
  31266. return callback(new Blob(results));
  31267. });
  31268. };
  31269. /*
  31270. * Decodes data when a payload is maybe expected. Strings are decoded by
  31271. * interpreting each byte as a key code for entries marked to start with 0. See
  31272. * description of encodePayloadAsBinary
  31273. *
  31274. * @param {ArrayBuffer} data, callback method
  31275. * @api public
  31276. */
  31277. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  31278. if (typeof binaryType === 'function') {
  31279. callback = binaryType;
  31280. binaryType = null;
  31281. }
  31282. var bufferTail = data;
  31283. var buffers = [];
  31284. var numberTooLong = false;
  31285. while (bufferTail.byteLength > 0) {
  31286. var tailArray = new Uint8Array(bufferTail);
  31287. var isString = tailArray[0] === 0;
  31288. var msgLength = '';
  31289. for (var i = 1; ; i++) {
  31290. if (tailArray[i] == 255) break;
  31291. if (msgLength.length > 310) {
  31292. numberTooLong = true;
  31293. break;
  31294. }
  31295. msgLength += tailArray[i];
  31296. }
  31297. if(numberTooLong) return callback(err, 0, 1);
  31298. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  31299. msgLength = parseInt(msgLength);
  31300. var msg = sliceBuffer(bufferTail, 0, msgLength);
  31301. if (isString) {
  31302. try {
  31303. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  31304. } catch (e) {
  31305. // iPhone Safari doesn't let you apply to typed arrays
  31306. var typed = new Uint8Array(msg);
  31307. msg = '';
  31308. for (var i = 0; i < typed.length; i++) {
  31309. msg += String.fromCharCode(typed[i]);
  31310. }
  31311. }
  31312. }
  31313. buffers.push(msg);
  31314. bufferTail = sliceBuffer(bufferTail, msgLength);
  31315. }
  31316. var total = buffers.length;
  31317. buffers.forEach(function(buffer, i) {
  31318. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  31319. });
  31320. };
  31321. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31322. },{"./keys":137,"after":138,"arraybuffer.slice":139,"base64-arraybuffer":140,"blob":141,"has-binary":142,"utf8":144}],137:[function(require,module,exports){
  31323. /**
  31324. * Gets the keys for an object.
  31325. *
  31326. * @return {Array} keys
  31327. * @api private
  31328. */
  31329. module.exports = Object.keys || function keys (obj){
  31330. var arr = [];
  31331. var has = Object.prototype.hasOwnProperty;
  31332. for (var i in obj) {
  31333. if (has.call(obj, i)) {
  31334. arr.push(i);
  31335. }
  31336. }
  31337. return arr;
  31338. };
  31339. },{}],138:[function(require,module,exports){
  31340. module.exports = after
  31341. function after(count, callback, err_cb) {
  31342. var bail = false
  31343. err_cb = err_cb || noop
  31344. proxy.count = count
  31345. return (count === 0) ? callback() : proxy
  31346. function proxy(err, result) {
  31347. if (proxy.count <= 0) {
  31348. throw new Error('after called too many times')
  31349. }
  31350. --proxy.count
  31351. // after first error, rest are passed to err_cb
  31352. if (err) {
  31353. bail = true
  31354. callback(err)
  31355. // future error callbacks will go to error handler
  31356. callback = err_cb
  31357. } else if (proxy.count === 0 && !bail) {
  31358. callback(null, result)
  31359. }
  31360. }
  31361. }
  31362. function noop() {}
  31363. },{}],139:[function(require,module,exports){
  31364. /**
  31365. * An abstraction for slicing an arraybuffer even when
  31366. * ArrayBuffer.prototype.slice is not supported
  31367. *
  31368. * @api public
  31369. */
  31370. module.exports = function(arraybuffer, start, end) {
  31371. var bytes = arraybuffer.byteLength;
  31372. start = start || 0;
  31373. end = end || bytes;
  31374. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  31375. if (start < 0) { start += bytes; }
  31376. if (end < 0) { end += bytes; }
  31377. if (end > bytes) { end = bytes; }
  31378. if (start >= bytes || start >= end || bytes === 0) {
  31379. return new ArrayBuffer(0);
  31380. }
  31381. var abv = new Uint8Array(arraybuffer);
  31382. var result = new Uint8Array(end - start);
  31383. for (var i = start, ii = 0; i < end; i++, ii++) {
  31384. result[ii] = abv[i];
  31385. }
  31386. return result.buffer;
  31387. };
  31388. },{}],140:[function(require,module,exports){
  31389. /*
  31390. * base64-arraybuffer
  31391. * https://github.com/niklasvh/base64-arraybuffer
  31392. *
  31393. * Copyright (c) 2012 Niklas von Hertzen
  31394. * Licensed under the MIT license.
  31395. */
  31396. (function(chars){
  31397. "use strict";
  31398. exports.encode = function(arraybuffer) {
  31399. var bytes = new Uint8Array(arraybuffer),
  31400. i, len = bytes.length, base64 = "";
  31401. for (i = 0; i < len; i+=3) {
  31402. base64 += chars[bytes[i] >> 2];
  31403. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  31404. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  31405. base64 += chars[bytes[i + 2] & 63];
  31406. }
  31407. if ((len % 3) === 2) {
  31408. base64 = base64.substring(0, base64.length - 1) + "=";
  31409. } else if (len % 3 === 1) {
  31410. base64 = base64.substring(0, base64.length - 2) + "==";
  31411. }
  31412. return base64;
  31413. };
  31414. exports.decode = function(base64) {
  31415. var bufferLength = base64.length * 0.75,
  31416. len = base64.length, i, p = 0,
  31417. encoded1, encoded2, encoded3, encoded4;
  31418. if (base64[base64.length - 1] === "=") {
  31419. bufferLength--;
  31420. if (base64[base64.length - 2] === "=") {
  31421. bufferLength--;
  31422. }
  31423. }
  31424. var arraybuffer = new ArrayBuffer(bufferLength),
  31425. bytes = new Uint8Array(arraybuffer);
  31426. for (i = 0; i < len; i+=4) {
  31427. encoded1 = chars.indexOf(base64[i]);
  31428. encoded2 = chars.indexOf(base64[i+1]);
  31429. encoded3 = chars.indexOf(base64[i+2]);
  31430. encoded4 = chars.indexOf(base64[i+3]);
  31431. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  31432. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  31433. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  31434. }
  31435. return arraybuffer;
  31436. };
  31437. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  31438. },{}],141:[function(require,module,exports){
  31439. (function (global){
  31440. /**
  31441. * Create a blob builder even when vendor prefixes exist
  31442. */
  31443. var BlobBuilder = global.BlobBuilder
  31444. || global.WebKitBlobBuilder
  31445. || global.MSBlobBuilder
  31446. || global.MozBlobBuilder;
  31447. /**
  31448. * Check if Blob constructor is supported
  31449. */
  31450. var blobSupported = (function() {
  31451. try {
  31452. var b = new Blob(['hi']);
  31453. return b.size == 2;
  31454. } catch(e) {
  31455. return false;
  31456. }
  31457. })();
  31458. /**
  31459. * Check if BlobBuilder is supported
  31460. */
  31461. var blobBuilderSupported = BlobBuilder
  31462. && BlobBuilder.prototype.append
  31463. && BlobBuilder.prototype.getBlob;
  31464. function BlobBuilderConstructor(ary, options) {
  31465. options = options || {};
  31466. var bb = new BlobBuilder();
  31467. for (var i = 0; i < ary.length; i++) {
  31468. bb.append(ary[i]);
  31469. }
  31470. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  31471. };
  31472. module.exports = (function() {
  31473. if (blobSupported) {
  31474. return global.Blob;
  31475. } else if (blobBuilderSupported) {
  31476. return BlobBuilderConstructor;
  31477. } else {
  31478. return undefined;
  31479. }
  31480. })();
  31481. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31482. },{}],142:[function(require,module,exports){
  31483. (function (global){
  31484. /*
  31485. * Module requirements.
  31486. */
  31487. var isArray = require('isarray');
  31488. /**
  31489. * Module exports.
  31490. */
  31491. module.exports = hasBinary;
  31492. /**
  31493. * Checks for binary data.
  31494. *
  31495. * Right now only Buffer and ArrayBuffer are supported..
  31496. *
  31497. * @param {Object} anything
  31498. * @api public
  31499. */
  31500. function hasBinary(data) {
  31501. function _hasBinary(obj) {
  31502. if (!obj) return false;
  31503. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31504. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31505. (global.Blob && obj instanceof Blob) ||
  31506. (global.File && obj instanceof File)
  31507. ) {
  31508. return true;
  31509. }
  31510. if (isArray(obj)) {
  31511. for (var i = 0; i < obj.length; i++) {
  31512. if (_hasBinary(obj[i])) {
  31513. return true;
  31514. }
  31515. }
  31516. } else if (obj && 'object' == typeof obj) {
  31517. if (obj.toJSON) {
  31518. obj = obj.toJSON();
  31519. }
  31520. for (var key in obj) {
  31521. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  31522. return true;
  31523. }
  31524. }
  31525. }
  31526. return false;
  31527. }
  31528. return _hasBinary(data);
  31529. }
  31530. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31531. },{"isarray":143}],143:[function(require,module,exports){
  31532. module.exports = Array.isArray || function (arr) {
  31533. return Object.prototype.toString.call(arr) == '[object Array]';
  31534. };
  31535. },{}],144:[function(require,module,exports){
  31536. (function (global){
  31537. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  31538. ;(function(root) {
  31539. // Detect free variables `exports`
  31540. var freeExports = typeof exports == 'object' && exports;
  31541. // Detect free variable `module`
  31542. var freeModule = typeof module == 'object' && module &&
  31543. module.exports == freeExports && module;
  31544. // Detect free variable `global`, from Node.js or Browserified code,
  31545. // and use it as `root`
  31546. var freeGlobal = typeof global == 'object' && global;
  31547. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  31548. root = freeGlobal;
  31549. }
  31550. /*--------------------------------------------------------------------------*/
  31551. var stringFromCharCode = String.fromCharCode;
  31552. // Taken from http://mths.be/punycode
  31553. function ucs2decode(string) {
  31554. var output = [];
  31555. var counter = 0;
  31556. var length = string.length;
  31557. var value;
  31558. var extra;
  31559. while (counter < length) {
  31560. value = string.charCodeAt(counter++);
  31561. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  31562. // high surrogate, and there is a next character
  31563. extra = string.charCodeAt(counter++);
  31564. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  31565. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  31566. } else {
  31567. // unmatched surrogate; only append this code unit, in case the next
  31568. // code unit is the high surrogate of a surrogate pair
  31569. output.push(value);
  31570. counter--;
  31571. }
  31572. } else {
  31573. output.push(value);
  31574. }
  31575. }
  31576. return output;
  31577. }
  31578. // Taken from http://mths.be/punycode
  31579. function ucs2encode(array) {
  31580. var length = array.length;
  31581. var index = -1;
  31582. var value;
  31583. var output = '';
  31584. while (++index < length) {
  31585. value = array[index];
  31586. if (value > 0xFFFF) {
  31587. value -= 0x10000;
  31588. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  31589. value = 0xDC00 | value & 0x3FF;
  31590. }
  31591. output += stringFromCharCode(value);
  31592. }
  31593. return output;
  31594. }
  31595. /*--------------------------------------------------------------------------*/
  31596. function createByte(codePoint, shift) {
  31597. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  31598. }
  31599. function encodeCodePoint(codePoint) {
  31600. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  31601. return stringFromCharCode(codePoint);
  31602. }
  31603. var symbol = '';
  31604. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  31605. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  31606. }
  31607. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  31608. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  31609. symbol += createByte(codePoint, 6);
  31610. }
  31611. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  31612. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  31613. symbol += createByte(codePoint, 12);
  31614. symbol += createByte(codePoint, 6);
  31615. }
  31616. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  31617. return symbol;
  31618. }
  31619. function utf8encode(string) {
  31620. var codePoints = ucs2decode(string);
  31621. // console.log(JSON.stringify(codePoints.map(function(x) {
  31622. // return 'U+' + x.toString(16).toUpperCase();
  31623. // })));
  31624. var length = codePoints.length;
  31625. var index = -1;
  31626. var codePoint;
  31627. var byteString = '';
  31628. while (++index < length) {
  31629. codePoint = codePoints[index];
  31630. byteString += encodeCodePoint(codePoint);
  31631. }
  31632. return byteString;
  31633. }
  31634. /*--------------------------------------------------------------------------*/
  31635. function readContinuationByte() {
  31636. if (byteIndex >= byteCount) {
  31637. throw Error('Invalid byte index');
  31638. }
  31639. var continuationByte = byteArray[byteIndex] & 0xFF;
  31640. byteIndex++;
  31641. if ((continuationByte & 0xC0) == 0x80) {
  31642. return continuationByte & 0x3F;
  31643. }
  31644. // If we end up here, it’s not a continuation byte
  31645. throw Error('Invalid continuation byte');
  31646. }
  31647. function decodeSymbol() {
  31648. var byte1;
  31649. var byte2;
  31650. var byte3;
  31651. var byte4;
  31652. var codePoint;
  31653. if (byteIndex > byteCount) {
  31654. throw Error('Invalid byte index');
  31655. }
  31656. if (byteIndex == byteCount) {
  31657. return false;
  31658. }
  31659. // Read first byte
  31660. byte1 = byteArray[byteIndex] & 0xFF;
  31661. byteIndex++;
  31662. // 1-byte sequence (no continuation bytes)
  31663. if ((byte1 & 0x80) == 0) {
  31664. return byte1;
  31665. }
  31666. // 2-byte sequence
  31667. if ((byte1 & 0xE0) == 0xC0) {
  31668. var byte2 = readContinuationByte();
  31669. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  31670. if (codePoint >= 0x80) {
  31671. return codePoint;
  31672. } else {
  31673. throw Error('Invalid continuation byte');
  31674. }
  31675. }
  31676. // 3-byte sequence (may include unpaired surrogates)
  31677. if ((byte1 & 0xF0) == 0xE0) {
  31678. byte2 = readContinuationByte();
  31679. byte3 = readContinuationByte();
  31680. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  31681. if (codePoint >= 0x0800) {
  31682. return codePoint;
  31683. } else {
  31684. throw Error('Invalid continuation byte');
  31685. }
  31686. }
  31687. // 4-byte sequence
  31688. if ((byte1 & 0xF8) == 0xF0) {
  31689. byte2 = readContinuationByte();
  31690. byte3 = readContinuationByte();
  31691. byte4 = readContinuationByte();
  31692. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  31693. (byte3 << 0x06) | byte4;
  31694. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  31695. return codePoint;
  31696. }
  31697. }
  31698. throw Error('Invalid UTF-8 detected');
  31699. }
  31700. var byteArray;
  31701. var byteCount;
  31702. var byteIndex;
  31703. function utf8decode(byteString) {
  31704. byteArray = ucs2decode(byteString);
  31705. byteCount = byteArray.length;
  31706. byteIndex = 0;
  31707. var codePoints = [];
  31708. var tmp;
  31709. while ((tmp = decodeSymbol()) !== false) {
  31710. codePoints.push(tmp);
  31711. }
  31712. return ucs2encode(codePoints);
  31713. }
  31714. /*--------------------------------------------------------------------------*/
  31715. var utf8 = {
  31716. 'version': '2.0.0',
  31717. 'encode': utf8encode,
  31718. 'decode': utf8decode
  31719. };
  31720. // Some AMD build optimizers, like r.js, check for specific condition patterns
  31721. // like the following:
  31722. if (
  31723. typeof define == 'function' &&
  31724. typeof define.amd == 'object' &&
  31725. define.amd
  31726. ) {
  31727. define(function() {
  31728. return utf8;
  31729. });
  31730. } else if (freeExports && !freeExports.nodeType) {
  31731. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  31732. freeModule.exports = utf8;
  31733. } else { // in Narwhal or RingoJS v0.7.0-
  31734. var object = {};
  31735. var hasOwnProperty = object.hasOwnProperty;
  31736. for (var key in utf8) {
  31737. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  31738. }
  31739. }
  31740. } else { // in Rhino or a web browser
  31741. root.utf8 = utf8;
  31742. }
  31743. }(this));
  31744. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31745. },{}],145:[function(require,module,exports){
  31746. /**
  31747. * Module dependencies.
  31748. */
  31749. var global = require('global');
  31750. /**
  31751. * Module exports.
  31752. *
  31753. * Logic borrowed from Modernizr:
  31754. *
  31755. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  31756. */
  31757. try {
  31758. module.exports = 'XMLHttpRequest' in global &&
  31759. 'withCredentials' in new global.XMLHttpRequest();
  31760. } catch (err) {
  31761. // if XMLHttp support is disabled in IE then it will throw
  31762. // when trying to create
  31763. module.exports = false;
  31764. }
  31765. },{"global":146}],146:[function(require,module,exports){
  31766. /**
  31767. * Returns `this`. Execute this without a "context" (i.e. without it being
  31768. * attached to an object of the left-hand side), and `this` points to the
  31769. * "global" scope of the current JS execution.
  31770. */
  31771. module.exports = (function () { return this; })();
  31772. },{}],147:[function(require,module,exports){
  31773. (function (global){
  31774. /**
  31775. * JSON parse.
  31776. *
  31777. * @see Based on jQuery#parseJSON (MIT) and JSON2
  31778. * @api private
  31779. */
  31780. var rvalidchars = /^[\],:{}\s]*$/;
  31781. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  31782. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  31783. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  31784. var rtrimLeft = /^\s+/;
  31785. var rtrimRight = /\s+$/;
  31786. module.exports = function parsejson(data) {
  31787. if ('string' != typeof data || !data) {
  31788. return null;
  31789. }
  31790. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  31791. // Attempt to parse using the native JSON parser first
  31792. if (global.JSON && JSON.parse) {
  31793. return JSON.parse(data);
  31794. }
  31795. if (rvalidchars.test(data.replace(rvalidescape, '@')
  31796. .replace(rvalidtokens, ']')
  31797. .replace(rvalidbraces, ''))) {
  31798. return (new Function('return ' + data))();
  31799. }
  31800. };
  31801. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31802. },{}],148:[function(require,module,exports){
  31803. /**
  31804. * Compiles a querystring
  31805. * Returns string representation of the object
  31806. *
  31807. * @param {Object}
  31808. * @api private
  31809. */
  31810. exports.encode = function (obj) {
  31811. var str = '';
  31812. for (var i in obj) {
  31813. if (obj.hasOwnProperty(i)) {
  31814. if (str.length) str += '&';
  31815. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  31816. }
  31817. }
  31818. return str;
  31819. };
  31820. /**
  31821. * Parses a simple querystring into an object
  31822. *
  31823. * @param {String} qs
  31824. * @api private
  31825. */
  31826. exports.decode = function(qs){
  31827. var qry = {};
  31828. var pairs = qs.split('&');
  31829. for (var i = 0, l = pairs.length; i < l; i++) {
  31830. var pair = pairs[i].split('=');
  31831. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  31832. }
  31833. return qry;
  31834. };
  31835. },{}],149:[function(require,module,exports){
  31836. /**
  31837. * Parses an URI
  31838. *
  31839. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  31840. * @api private
  31841. */
  31842. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  31843. var parts = [
  31844. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  31845. ];
  31846. module.exports = function parseuri(str) {
  31847. var src = str,
  31848. b = str.indexOf('['),
  31849. e = str.indexOf(']');
  31850. if (b != -1 && e != -1) {
  31851. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  31852. }
  31853. var m = re.exec(str || ''),
  31854. uri = {},
  31855. i = 14;
  31856. while (i--) {
  31857. uri[parts[i]] = m[i] || '';
  31858. }
  31859. if (b != -1 && e != -1) {
  31860. uri.source = src;
  31861. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  31862. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  31863. uri.ipv6uri = true;
  31864. }
  31865. return uri;
  31866. };
  31867. },{}],150:[function(require,module,exports){
  31868. /**
  31869. * Module dependencies.
  31870. */
  31871. var global = (function() { return this; })();
  31872. /**
  31873. * WebSocket constructor.
  31874. */
  31875. var WebSocket = global.WebSocket || global.MozWebSocket;
  31876. /**
  31877. * Module exports.
  31878. */
  31879. module.exports = WebSocket ? ws : null;
  31880. /**
  31881. * WebSocket constructor.
  31882. *
  31883. * The third `opts` options object gets ignored in web browsers, since it's
  31884. * non-standard, and throws a TypeError if passed to the constructor.
  31885. * See: https://github.com/einaros/ws/issues/227
  31886. *
  31887. * @param {String} uri
  31888. * @param {Array} protocols (optional)
  31889. * @param {Object) opts (optional)
  31890. * @api public
  31891. */
  31892. function ws(uri, protocols, opts) {
  31893. var instance;
  31894. if (protocols) {
  31895. instance = new WebSocket(uri, protocols);
  31896. } else {
  31897. instance = new WebSocket(uri);
  31898. }
  31899. return instance;
  31900. }
  31901. if (WebSocket) ws.prototype = WebSocket.prototype;
  31902. },{}],151:[function(require,module,exports){
  31903. (function (global){
  31904. /*
  31905. * Module requirements.
  31906. */
  31907. var isArray = require('isarray');
  31908. /**
  31909. * Module exports.
  31910. */
  31911. module.exports = hasBinary;
  31912. /**
  31913. * Checks for binary data.
  31914. *
  31915. * Right now only Buffer and ArrayBuffer are supported..
  31916. *
  31917. * @param {Object} anything
  31918. * @api public
  31919. */
  31920. function hasBinary(data) {
  31921. function _hasBinary(obj) {
  31922. if (!obj) return false;
  31923. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  31924. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  31925. (global.Blob && obj instanceof Blob) ||
  31926. (global.File && obj instanceof File)
  31927. ) {
  31928. return true;
  31929. }
  31930. if (isArray(obj)) {
  31931. for (var i = 0; i < obj.length; i++) {
  31932. if (_hasBinary(obj[i])) {
  31933. return true;
  31934. }
  31935. }
  31936. } else if (obj && 'object' == typeof obj) {
  31937. if (obj.toJSON) {
  31938. obj = obj.toJSON();
  31939. }
  31940. for (var key in obj) {
  31941. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  31942. return true;
  31943. }
  31944. }
  31945. }
  31946. return false;
  31947. }
  31948. return _hasBinary(data);
  31949. }
  31950. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  31951. },{"isarray":152}],152:[function(require,module,exports){
  31952. arguments[4][143][0].apply(exports,arguments)
  31953. },{"dup":143}],153:[function(require,module,exports){
  31954. var indexOf = [].indexOf;
  31955. module.exports = function(arr, obj){
  31956. if (indexOf) return arr.indexOf(obj);
  31957. for (var i = 0; i < arr.length; ++i) {
  31958. if (arr[i] === obj) return i;
  31959. }
  31960. return -1;
  31961. };
  31962. },{}],154:[function(require,module,exports){
  31963. /**
  31964. * HOP ref.
  31965. */
  31966. var has = Object.prototype.hasOwnProperty;
  31967. /**
  31968. * Return own keys in `obj`.
  31969. *
  31970. * @param {Object} obj
  31971. * @return {Array}
  31972. * @api public
  31973. */
  31974. exports.keys = Object.keys || function(obj){
  31975. var keys = [];
  31976. for (var key in obj) {
  31977. if (has.call(obj, key)) {
  31978. keys.push(key);
  31979. }
  31980. }
  31981. return keys;
  31982. };
  31983. /**
  31984. * Return own values in `obj`.
  31985. *
  31986. * @param {Object} obj
  31987. * @return {Array}
  31988. * @api public
  31989. */
  31990. exports.values = function(obj){
  31991. var vals = [];
  31992. for (var key in obj) {
  31993. if (has.call(obj, key)) {
  31994. vals.push(obj[key]);
  31995. }
  31996. }
  31997. return vals;
  31998. };
  31999. /**
  32000. * Merge `b` into `a`.
  32001. *
  32002. * @param {Object} a
  32003. * @param {Object} b
  32004. * @return {Object} a
  32005. * @api public
  32006. */
  32007. exports.merge = function(a, b){
  32008. for (var key in b) {
  32009. if (has.call(b, key)) {
  32010. a[key] = b[key];
  32011. }
  32012. }
  32013. return a;
  32014. };
  32015. /**
  32016. * Return length of `obj`.
  32017. *
  32018. * @param {Object} obj
  32019. * @return {Number}
  32020. * @api public
  32021. */
  32022. exports.length = function(obj){
  32023. return exports.keys(obj).length;
  32024. };
  32025. /**
  32026. * Check if `obj` is empty.
  32027. *
  32028. * @param {Object} obj
  32029. * @return {Boolean}
  32030. * @api public
  32031. */
  32032. exports.isEmpty = function(obj){
  32033. return 0 == exports.length(obj);
  32034. };
  32035. },{}],155:[function(require,module,exports){
  32036. /**
  32037. * Parses an URI
  32038. *
  32039. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  32040. * @api private
  32041. */
  32042. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  32043. var parts = [
  32044. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  32045. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  32046. ];
  32047. module.exports = function parseuri(str) {
  32048. var m = re.exec(str || '')
  32049. , uri = {}
  32050. , i = 14;
  32051. while (i--) {
  32052. uri[parts[i]] = m[i] || '';
  32053. }
  32054. return uri;
  32055. };
  32056. },{}],156:[function(require,module,exports){
  32057. (function (global){
  32058. /*global Blob,File*/
  32059. /**
  32060. * Module requirements
  32061. */
  32062. var isArray = require('isarray');
  32063. var isBuf = require('./is-buffer');
  32064. /**
  32065. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  32066. * Anything with blobs or files should be fed through removeBlobs before coming
  32067. * here.
  32068. *
  32069. * @param {Object} packet - socket.io event packet
  32070. * @return {Object} with deconstructed packet and list of buffers
  32071. * @api public
  32072. */
  32073. exports.deconstructPacket = function(packet){
  32074. var buffers = [];
  32075. var packetData = packet.data;
  32076. function _deconstructPacket(data) {
  32077. if (!data) return data;
  32078. if (isBuf(data)) {
  32079. var placeholder = { _placeholder: true, num: buffers.length };
  32080. buffers.push(data);
  32081. return placeholder;
  32082. } else if (isArray(data)) {
  32083. var newData = new Array(data.length);
  32084. for (var i = 0; i < data.length; i++) {
  32085. newData[i] = _deconstructPacket(data[i]);
  32086. }
  32087. return newData;
  32088. } else if ('object' == typeof data && !(data instanceof Date)) {
  32089. var newData = {};
  32090. for (var key in data) {
  32091. newData[key] = _deconstructPacket(data[key]);
  32092. }
  32093. return newData;
  32094. }
  32095. return data;
  32096. }
  32097. var pack = packet;
  32098. pack.data = _deconstructPacket(packetData);
  32099. pack.attachments = buffers.length; // number of binary 'attachments'
  32100. return {packet: pack, buffers: buffers};
  32101. };
  32102. /**
  32103. * Reconstructs a binary packet from its placeholder packet and buffers
  32104. *
  32105. * @param {Object} packet - event packet with placeholders
  32106. * @param {Array} buffers - binary buffers to put in placeholder positions
  32107. * @return {Object} reconstructed packet
  32108. * @api public
  32109. */
  32110. exports.reconstructPacket = function(packet, buffers) {
  32111. var curPlaceHolder = 0;
  32112. function _reconstructPacket(data) {
  32113. if (data && data._placeholder) {
  32114. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  32115. return buf;
  32116. } else if (isArray(data)) {
  32117. for (var i = 0; i < data.length; i++) {
  32118. data[i] = _reconstructPacket(data[i]);
  32119. }
  32120. return data;
  32121. } else if (data && 'object' == typeof data) {
  32122. for (var key in data) {
  32123. data[key] = _reconstructPacket(data[key]);
  32124. }
  32125. return data;
  32126. }
  32127. return data;
  32128. }
  32129. packet.data = _reconstructPacket(packet.data);
  32130. packet.attachments = undefined; // no longer useful
  32131. return packet;
  32132. };
  32133. /**
  32134. * Asynchronously removes Blobs or Files from data via
  32135. * FileReader's readAsArrayBuffer method. Used before encoding
  32136. * data as msgpack. Calls callback with the blobless data.
  32137. *
  32138. * @param {Object} data
  32139. * @param {Function} callback
  32140. * @api private
  32141. */
  32142. exports.removeBlobs = function(data, callback) {
  32143. function _removeBlobs(obj, curKey, containingObject) {
  32144. if (!obj) return obj;
  32145. // convert any blob
  32146. if ((global.Blob && obj instanceof Blob) ||
  32147. (global.File && obj instanceof File)) {
  32148. pendingBlobs++;
  32149. // async filereader
  32150. var fileReader = new FileReader();
  32151. fileReader.onload = function() { // this.result == arraybuffer
  32152. if (containingObject) {
  32153. containingObject[curKey] = this.result;
  32154. }
  32155. else {
  32156. bloblessData = this.result;
  32157. }
  32158. // if nothing pending its callback time
  32159. if(! --pendingBlobs) {
  32160. callback(bloblessData);
  32161. }
  32162. };
  32163. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  32164. } else if (isArray(obj)) { // handle array
  32165. for (var i = 0; i < obj.length; i++) {
  32166. _removeBlobs(obj[i], i, obj);
  32167. }
  32168. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  32169. for (var key in obj) {
  32170. _removeBlobs(obj[key], key, obj);
  32171. }
  32172. }
  32173. }
  32174. var pendingBlobs = 0;
  32175. var bloblessData = data;
  32176. _removeBlobs(bloblessData);
  32177. if (!pendingBlobs) {
  32178. callback(bloblessData);
  32179. }
  32180. };
  32181. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32182. },{"./is-buffer":158,"isarray":159}],157:[function(require,module,exports){
  32183. /**
  32184. * Module dependencies.
  32185. */
  32186. var debug = require('debug')('socket.io-parser');
  32187. var json = require('json3');
  32188. var isArray = require('isarray');
  32189. var Emitter = require('component-emitter');
  32190. var binary = require('./binary');
  32191. var isBuf = require('./is-buffer');
  32192. /**
  32193. * Protocol version.
  32194. *
  32195. * @api public
  32196. */
  32197. exports.protocol = 4;
  32198. /**
  32199. * Packet types.
  32200. *
  32201. * @api public
  32202. */
  32203. exports.types = [
  32204. 'CONNECT',
  32205. 'DISCONNECT',
  32206. 'EVENT',
  32207. 'BINARY_EVENT',
  32208. 'ACK',
  32209. 'BINARY_ACK',
  32210. 'ERROR'
  32211. ];
  32212. /**
  32213. * Packet type `connect`.
  32214. *
  32215. * @api public
  32216. */
  32217. exports.CONNECT = 0;
  32218. /**
  32219. * Packet type `disconnect`.
  32220. *
  32221. * @api public
  32222. */
  32223. exports.DISCONNECT = 1;
  32224. /**
  32225. * Packet type `event`.
  32226. *
  32227. * @api public
  32228. */
  32229. exports.EVENT = 2;
  32230. /**
  32231. * Packet type `ack`.
  32232. *
  32233. * @api public
  32234. */
  32235. exports.ACK = 3;
  32236. /**
  32237. * Packet type `error`.
  32238. *
  32239. * @api public
  32240. */
  32241. exports.ERROR = 4;
  32242. /**
  32243. * Packet type 'binary event'
  32244. *
  32245. * @api public
  32246. */
  32247. exports.BINARY_EVENT = 5;
  32248. /**
  32249. * Packet type `binary ack`. For acks with binary arguments.
  32250. *
  32251. * @api public
  32252. */
  32253. exports.BINARY_ACK = 6;
  32254. /**
  32255. * Encoder constructor.
  32256. *
  32257. * @api public
  32258. */
  32259. exports.Encoder = Encoder;
  32260. /**
  32261. * Decoder constructor.
  32262. *
  32263. * @api public
  32264. */
  32265. exports.Decoder = Decoder;
  32266. /**
  32267. * A socket.io Encoder instance
  32268. *
  32269. * @api public
  32270. */
  32271. function Encoder() {}
  32272. /**
  32273. * Encode a packet as a single string if non-binary, or as a
  32274. * buffer sequence, depending on packet type.
  32275. *
  32276. * @param {Object} obj - packet object
  32277. * @param {Function} callback - function to handle encodings (likely engine.write)
  32278. * @return Calls callback with Array of encodings
  32279. * @api public
  32280. */
  32281. Encoder.prototype.encode = function(obj, callback){
  32282. debug('encoding packet %j', obj);
  32283. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  32284. encodeAsBinary(obj, callback);
  32285. }
  32286. else {
  32287. var encoding = encodeAsString(obj);
  32288. callback([encoding]);
  32289. }
  32290. };
  32291. /**
  32292. * Encode packet as string.
  32293. *
  32294. * @param {Object} packet
  32295. * @return {String} encoded
  32296. * @api private
  32297. */
  32298. function encodeAsString(obj) {
  32299. var str = '';
  32300. var nsp = false;
  32301. // first is type
  32302. str += obj.type;
  32303. // attachments if we have them
  32304. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  32305. str += obj.attachments;
  32306. str += '-';
  32307. }
  32308. // if we have a namespace other than `/`
  32309. // we append it followed by a comma `,`
  32310. if (obj.nsp && '/' != obj.nsp) {
  32311. nsp = true;
  32312. str += obj.nsp;
  32313. }
  32314. // immediately followed by the id
  32315. if (null != obj.id) {
  32316. if (nsp) {
  32317. str += ',';
  32318. nsp = false;
  32319. }
  32320. str += obj.id;
  32321. }
  32322. // json data
  32323. if (null != obj.data) {
  32324. if (nsp) str += ',';
  32325. str += json.stringify(obj.data);
  32326. }
  32327. debug('encoded %j as %s', obj, str);
  32328. return str;
  32329. }
  32330. /**
  32331. * Encode packet as 'buffer sequence' by removing blobs, and
  32332. * deconstructing packet into object with placeholders and
  32333. * a list of buffers.
  32334. *
  32335. * @param {Object} packet
  32336. * @return {Buffer} encoded
  32337. * @api private
  32338. */
  32339. function encodeAsBinary(obj, callback) {
  32340. function writeEncoding(bloblessData) {
  32341. var deconstruction = binary.deconstructPacket(bloblessData);
  32342. var pack = encodeAsString(deconstruction.packet);
  32343. var buffers = deconstruction.buffers;
  32344. buffers.unshift(pack); // add packet info to beginning of data list
  32345. callback(buffers); // write all the buffers
  32346. }
  32347. binary.removeBlobs(obj, writeEncoding);
  32348. }
  32349. /**
  32350. * A socket.io Decoder instance
  32351. *
  32352. * @return {Object} decoder
  32353. * @api public
  32354. */
  32355. function Decoder() {
  32356. this.reconstructor = null;
  32357. }
  32358. /**
  32359. * Mix in `Emitter` with Decoder.
  32360. */
  32361. Emitter(Decoder.prototype);
  32362. /**
  32363. * Decodes an ecoded packet string into packet JSON.
  32364. *
  32365. * @param {String} obj - encoded packet
  32366. * @return {Object} packet
  32367. * @api public
  32368. */
  32369. Decoder.prototype.add = function(obj) {
  32370. var packet;
  32371. if ('string' == typeof obj) {
  32372. packet = decodeString(obj);
  32373. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  32374. this.reconstructor = new BinaryReconstructor(packet);
  32375. // no attachments, labeled binary but no binary data to follow
  32376. if (this.reconstructor.reconPack.attachments === 0) {
  32377. this.emit('decoded', packet);
  32378. }
  32379. } else { // non-binary full packet
  32380. this.emit('decoded', packet);
  32381. }
  32382. }
  32383. else if (isBuf(obj) || obj.base64) { // raw binary data
  32384. if (!this.reconstructor) {
  32385. throw new Error('got binary data when not reconstructing a packet');
  32386. } else {
  32387. packet = this.reconstructor.takeBinaryData(obj);
  32388. if (packet) { // received final buffer
  32389. this.reconstructor = null;
  32390. this.emit('decoded', packet);
  32391. }
  32392. }
  32393. }
  32394. else {
  32395. throw new Error('Unknown type: ' + obj);
  32396. }
  32397. };
  32398. /**
  32399. * Decode a packet String (JSON data)
  32400. *
  32401. * @param {String} str
  32402. * @return {Object} packet
  32403. * @api private
  32404. */
  32405. function decodeString(str) {
  32406. var p = {};
  32407. var i = 0;
  32408. // look up type
  32409. p.type = Number(str.charAt(0));
  32410. if (null == exports.types[p.type]) return error();
  32411. // look up attachments if type binary
  32412. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  32413. var buf = '';
  32414. while (str.charAt(++i) != '-') {
  32415. buf += str.charAt(i);
  32416. if (i == str.length) break;
  32417. }
  32418. if (buf != Number(buf) || str.charAt(i) != '-') {
  32419. throw new Error('Illegal attachments');
  32420. }
  32421. p.attachments = Number(buf);
  32422. }
  32423. // look up namespace (if any)
  32424. if ('/' == str.charAt(i + 1)) {
  32425. p.nsp = '';
  32426. while (++i) {
  32427. var c = str.charAt(i);
  32428. if (',' == c) break;
  32429. p.nsp += c;
  32430. if (i == str.length) break;
  32431. }
  32432. } else {
  32433. p.nsp = '/';
  32434. }
  32435. // look up id
  32436. var next = str.charAt(i + 1);
  32437. if ('' !== next && Number(next) == next) {
  32438. p.id = '';
  32439. while (++i) {
  32440. var c = str.charAt(i);
  32441. if (null == c || Number(c) != c) {
  32442. --i;
  32443. break;
  32444. }
  32445. p.id += str.charAt(i);
  32446. if (i == str.length) break;
  32447. }
  32448. p.id = Number(p.id);
  32449. }
  32450. // look up json data
  32451. if (str.charAt(++i)) {
  32452. try {
  32453. p.data = json.parse(str.substr(i));
  32454. } catch(e){
  32455. return error();
  32456. }
  32457. }
  32458. debug('decoded %s as %j', str, p);
  32459. return p;
  32460. }
  32461. /**
  32462. * Deallocates a parser's resources
  32463. *
  32464. * @api public
  32465. */
  32466. Decoder.prototype.destroy = function() {
  32467. if (this.reconstructor) {
  32468. this.reconstructor.finishedReconstruction();
  32469. }
  32470. };
  32471. /**
  32472. * A manager of a binary event's 'buffer sequence'. Should
  32473. * be constructed whenever a packet of type BINARY_EVENT is
  32474. * decoded.
  32475. *
  32476. * @param {Object} packet
  32477. * @return {BinaryReconstructor} initialized reconstructor
  32478. * @api private
  32479. */
  32480. function BinaryReconstructor(packet) {
  32481. this.reconPack = packet;
  32482. this.buffers = [];
  32483. }
  32484. /**
  32485. * Method to be called when binary data received from connection
  32486. * after a BINARY_EVENT packet.
  32487. *
  32488. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  32489. * @return {null | Object} returns null if more binary data is expected or
  32490. * a reconstructed packet object if all buffers have been received.
  32491. * @api private
  32492. */
  32493. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  32494. this.buffers.push(binData);
  32495. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  32496. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  32497. this.finishedReconstruction();
  32498. return packet;
  32499. }
  32500. return null;
  32501. };
  32502. /**
  32503. * Cleans up binary packet reconstruction variables.
  32504. *
  32505. * @api private
  32506. */
  32507. BinaryReconstructor.prototype.finishedReconstruction = function() {
  32508. this.reconPack = null;
  32509. this.buffers = [];
  32510. };
  32511. function error(data){
  32512. return {
  32513. type: exports.ERROR,
  32514. data: 'parser error'
  32515. };
  32516. }
  32517. },{"./binary":156,"./is-buffer":158,"component-emitter":120,"debug":121,"isarray":159,"json3":160}],158:[function(require,module,exports){
  32518. (function (global){
  32519. module.exports = isBuf;
  32520. /**
  32521. * Returns true if obj is a buffer or an arraybuffer.
  32522. *
  32523. * @api private
  32524. */
  32525. function isBuf(obj) {
  32526. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  32527. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  32528. }
  32529. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  32530. },{}],159:[function(require,module,exports){
  32531. arguments[4][143][0].apply(exports,arguments)
  32532. },{"dup":143}],160:[function(require,module,exports){
  32533. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  32534. ;(function (window) {
  32535. // Convenience aliases.
  32536. var getClass = {}.toString, isProperty, forEach, undef;
  32537. // Detect the `define` function exposed by asynchronous module loaders. The
  32538. // strict `define` check is necessary for compatibility with `r.js`.
  32539. var isLoader = typeof define === "function" && define.amd;
  32540. // Detect native implementations.
  32541. var nativeJSON = typeof JSON == "object" && JSON;
  32542. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  32543. // available.
  32544. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  32545. if (JSON3 && nativeJSON) {
  32546. // Explicitly delegate to the native `stringify` and `parse`
  32547. // implementations in CommonJS environments.
  32548. JSON3.stringify = nativeJSON.stringify;
  32549. JSON3.parse = nativeJSON.parse;
  32550. } else {
  32551. // Export for web browsers, JavaScript engines, and asynchronous module
  32552. // loaders, using the global `JSON` object if available.
  32553. JSON3 = window.JSON = nativeJSON || {};
  32554. }
  32555. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  32556. var isExtended = new Date(-3509827334573292);
  32557. try {
  32558. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  32559. // results for certain dates in Opera >= 10.53.
  32560. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  32561. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  32562. // but clips the values returned by the date methods to the range of
  32563. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  32564. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  32565. } catch (exception) {}
  32566. // Internal: Determines whether the native `JSON.stringify` and `parse`
  32567. // implementations are spec-compliant. Based on work by Ken Snyder.
  32568. function has(name) {
  32569. if (has[name] !== undef) {
  32570. // Return cached feature test result.
  32571. return has[name];
  32572. }
  32573. var isSupported;
  32574. if (name == "bug-string-char-index") {
  32575. // IE <= 7 doesn't support accessing string characters using square
  32576. // bracket notation. IE 8 only supports this for primitives.
  32577. isSupported = "a"[0] != "a";
  32578. } else if (name == "json") {
  32579. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  32580. // supported.
  32581. isSupported = has("json-stringify") && has("json-parse");
  32582. } else {
  32583. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  32584. // Test `JSON.stringify`.
  32585. if (name == "json-stringify") {
  32586. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  32587. if (stringifySupported) {
  32588. // A test function object with a custom `toJSON` method.
  32589. (value = function () {
  32590. return 1;
  32591. }).toJSON = value;
  32592. try {
  32593. stringifySupported =
  32594. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  32595. // primitives as object literals.
  32596. stringify(0) === "0" &&
  32597. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  32598. // literals.
  32599. stringify(new Number()) === "0" &&
  32600. stringify(new String()) == '""' &&
  32601. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  32602. // does not define a canonical JSON representation (this applies to
  32603. // objects with `toJSON` properties as well, *unless* they are nested
  32604. // within an object or array).
  32605. stringify(getClass) === undef &&
  32606. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  32607. // FF 3.1b3 pass this test.
  32608. stringify(undef) === undef &&
  32609. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  32610. // respectively, if the value is omitted entirely.
  32611. stringify() === undef &&
  32612. // FF 3.1b1, 2 throw an error if the given value is not a number,
  32613. // string, array, object, Boolean, or `null` literal. This applies to
  32614. // objects with custom `toJSON` methods as well, unless they are nested
  32615. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  32616. // methods entirely.
  32617. stringify(value) === "1" &&
  32618. stringify([value]) == "[1]" &&
  32619. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  32620. // `"[null]"`.
  32621. stringify([undef]) == "[null]" &&
  32622. // YUI 3.0.0b1 fails to serialize `null` literals.
  32623. stringify(null) == "null" &&
  32624. // FF 3.1b1, 2 halts serialization if an array contains a function:
  32625. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  32626. // elides non-JSON values from objects and arrays, unless they
  32627. // define custom `toJSON` methods.
  32628. stringify([undef, getClass, null]) == "[null,null,null]" &&
  32629. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  32630. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  32631. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  32632. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  32633. stringify(null, value) === "1" &&
  32634. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  32635. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  32636. // serialize extended years.
  32637. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  32638. // The milliseconds are optional in ES 5, but required in 5.1.
  32639. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  32640. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  32641. // four-digit years instead of six-digit years. Credits: @Yaffle.
  32642. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  32643. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  32644. // values less than 1000. Credits: @Yaffle.
  32645. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  32646. } catch (exception) {
  32647. stringifySupported = false;
  32648. }
  32649. }
  32650. isSupported = stringifySupported;
  32651. }
  32652. // Test `JSON.parse`.
  32653. if (name == "json-parse") {
  32654. var parse = JSON3.parse;
  32655. if (typeof parse == "function") {
  32656. try {
  32657. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  32658. // Conforming implementations should also coerce the initial argument to
  32659. // a string prior to parsing.
  32660. if (parse("0") === 0 && !parse(false)) {
  32661. // Simple parsing test.
  32662. value = parse(serialized);
  32663. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  32664. if (parseSupported) {
  32665. try {
  32666. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  32667. parseSupported = !parse('"\t"');
  32668. } catch (exception) {}
  32669. if (parseSupported) {
  32670. try {
  32671. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  32672. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  32673. // certain octal literals.
  32674. parseSupported = parse("01") !== 1;
  32675. } catch (exception) {}
  32676. }
  32677. if (parseSupported) {
  32678. try {
  32679. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  32680. // points. These environments, along with FF 3.1b1 and 2,
  32681. // also allow trailing commas in JSON objects and arrays.
  32682. parseSupported = parse("1.") !== 1;
  32683. } catch (exception) {}
  32684. }
  32685. }
  32686. }
  32687. } catch (exception) {
  32688. parseSupported = false;
  32689. }
  32690. }
  32691. isSupported = parseSupported;
  32692. }
  32693. }
  32694. return has[name] = !!isSupported;
  32695. }
  32696. if (!has("json")) {
  32697. // Common `[[Class]]` name aliases.
  32698. var functionClass = "[object Function]";
  32699. var dateClass = "[object Date]";
  32700. var numberClass = "[object Number]";
  32701. var stringClass = "[object String]";
  32702. var arrayClass = "[object Array]";
  32703. var booleanClass = "[object Boolean]";
  32704. // Detect incomplete support for accessing string characters by index.
  32705. var charIndexBuggy = has("bug-string-char-index");
  32706. // Define additional utility methods if the `Date` methods are buggy.
  32707. if (!isExtended) {
  32708. var floor = Math.floor;
  32709. // A mapping between the months of the year and the number of days between
  32710. // January 1st and the first of the respective month.
  32711. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  32712. // Internal: Calculates the number of days between the Unix epoch and the
  32713. // first day of the given month.
  32714. var getDay = function (year, month) {
  32715. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  32716. };
  32717. }
  32718. // Internal: Determines if a property is a direct property of the given
  32719. // object. Delegates to the native `Object#hasOwnProperty` method.
  32720. if (!(isProperty = {}.hasOwnProperty)) {
  32721. isProperty = function (property) {
  32722. var members = {}, constructor;
  32723. if ((members.__proto__ = null, members.__proto__ = {
  32724. // The *proto* property cannot be set multiple times in recent
  32725. // versions of Firefox and SeaMonkey.
  32726. "toString": 1
  32727. }, members).toString != getClass) {
  32728. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  32729. // supports the mutable *proto* property.
  32730. isProperty = function (property) {
  32731. // Capture and break the object's prototype chain (see section 8.6.2
  32732. // of the ES 5.1 spec). The parenthesized expression prevents an
  32733. // unsafe transformation by the Closure Compiler.
  32734. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  32735. // Restore the original prototype chain.
  32736. this.__proto__ = original;
  32737. return result;
  32738. };
  32739. } else {
  32740. // Capture a reference to the top-level `Object` constructor.
  32741. constructor = members.constructor;
  32742. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  32743. // other environments.
  32744. isProperty = function (property) {
  32745. var parent = (this.constructor || constructor).prototype;
  32746. return property in this && !(property in parent && this[property] === parent[property]);
  32747. };
  32748. }
  32749. members = null;
  32750. return isProperty.call(this, property);
  32751. };
  32752. }
  32753. // Internal: A set of primitive types used by `isHostType`.
  32754. var PrimitiveTypes = {
  32755. 'boolean': 1,
  32756. 'number': 1,
  32757. 'string': 1,
  32758. 'undefined': 1
  32759. };
  32760. // Internal: Determines if the given object `property` value is a
  32761. // non-primitive.
  32762. var isHostType = function (object, property) {
  32763. var type = typeof object[property];
  32764. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  32765. };
  32766. // Internal: Normalizes the `for...in` iteration algorithm across
  32767. // environments. Each enumerated key is yielded to a `callback` function.
  32768. forEach = function (object, callback) {
  32769. var size = 0, Properties, members, property;
  32770. // Tests for bugs in the current environment's `for...in` algorithm. The
  32771. // `valueOf` property inherits the non-enumerable flag from
  32772. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  32773. (Properties = function () {
  32774. this.valueOf = 0;
  32775. }).prototype.valueOf = 0;
  32776. // Iterate over a new instance of the `Properties` class.
  32777. members = new Properties();
  32778. for (property in members) {
  32779. // Ignore all properties inherited from `Object.prototype`.
  32780. if (isProperty.call(members, property)) {
  32781. size++;
  32782. }
  32783. }
  32784. Properties = members = null;
  32785. // Normalize the iteration algorithm.
  32786. if (!size) {
  32787. // A list of non-enumerable properties inherited from `Object.prototype`.
  32788. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  32789. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  32790. // properties.
  32791. forEach = function (object, callback) {
  32792. var isFunction = getClass.call(object) == functionClass, property, length;
  32793. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  32794. for (property in object) {
  32795. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  32796. // certain conditions; IE does not.
  32797. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  32798. callback(property);
  32799. }
  32800. }
  32801. // Manually invoke the callback for each non-enumerable property.
  32802. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  32803. };
  32804. } else if (size == 2) {
  32805. // Safari <= 2.0.4 enumerates shadowed properties twice.
  32806. forEach = function (object, callback) {
  32807. // Create a set of iterated properties.
  32808. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  32809. for (property in object) {
  32810. // Store each property name to prevent double enumeration. The
  32811. // `prototype` property of functions is not enumerated due to cross-
  32812. // environment inconsistencies.
  32813. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  32814. callback(property);
  32815. }
  32816. }
  32817. };
  32818. } else {
  32819. // No bugs detected; use the standard `for...in` algorithm.
  32820. forEach = function (object, callback) {
  32821. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  32822. for (property in object) {
  32823. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  32824. callback(property);
  32825. }
  32826. }
  32827. // Manually invoke the callback for the `constructor` property due to
  32828. // cross-environment inconsistencies.
  32829. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  32830. callback(property);
  32831. }
  32832. };
  32833. }
  32834. return forEach(object, callback);
  32835. };
  32836. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  32837. // `filter` argument may specify either a function that alters how object and
  32838. // array members are serialized, or an array of strings and numbers that
  32839. // indicates which properties should be serialized. The optional `width`
  32840. // argument may be either a string or number that specifies the indentation
  32841. // level of the output.
  32842. if (!has("json-stringify")) {
  32843. // Internal: A map of control characters and their escaped equivalents.
  32844. var Escapes = {
  32845. 92: "\\\\",
  32846. 34: '\\"',
  32847. 8: "\\b",
  32848. 12: "\\f",
  32849. 10: "\\n",
  32850. 13: "\\r",
  32851. 9: "\\t"
  32852. };
  32853. // Internal: Converts `value` into a zero-padded string such that its
  32854. // length is at least equal to `width`. The `width` must be <= 6.
  32855. var leadingZeroes = "000000";
  32856. var toPaddedString = function (width, value) {
  32857. // The `|| 0` expression is necessary to work around a bug in
  32858. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  32859. return (leadingZeroes + (value || 0)).slice(-width);
  32860. };
  32861. // Internal: Double-quotes a string `value`, replacing all ASCII control
  32862. // characters (characters with code unit values between 0 and 31) with
  32863. // their escaped equivalents. This is an implementation of the
  32864. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  32865. var unicodePrefix = "\\u00";
  32866. var quote = function (value) {
  32867. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  32868. if (isLarge) {
  32869. symbols = value.split("");
  32870. }
  32871. for (; index < length; index++) {
  32872. var charCode = value.charCodeAt(index);
  32873. // If the character is a control character, append its Unicode or
  32874. // shorthand escape sequence; otherwise, append the character as-is.
  32875. switch (charCode) {
  32876. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  32877. result += Escapes[charCode];
  32878. break;
  32879. default:
  32880. if (charCode < 32) {
  32881. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  32882. break;
  32883. }
  32884. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  32885. }
  32886. }
  32887. return result + '"';
  32888. };
  32889. // Internal: Recursively serializes an object. Implements the
  32890. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  32891. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  32892. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  32893. try {
  32894. // Necessary for host object support.
  32895. value = object[property];
  32896. } catch (exception) {}
  32897. if (typeof value == "object" && value) {
  32898. className = getClass.call(value);
  32899. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  32900. if (value > -1 / 0 && value < 1 / 0) {
  32901. // Dates are serialized according to the `Date#toJSON` method
  32902. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  32903. // for the ISO 8601 date time string format.
  32904. if (getDay) {
  32905. // Manually compute the year, month, date, hours, minutes,
  32906. // seconds, and milliseconds if the `getUTC*` methods are
  32907. // buggy. Adapted from @Yaffle's `date-shim` project.
  32908. date = floor(value / 864e5);
  32909. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  32910. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  32911. date = 1 + date - getDay(year, month);
  32912. // The `time` value specifies the time within the day (see ES
  32913. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  32914. // to compute `A modulo B`, as the `%` operator does not
  32915. // correspond to the `modulo` operation for negative numbers.
  32916. time = (value % 864e5 + 864e5) % 864e5;
  32917. // The hours, minutes, seconds, and milliseconds are obtained by
  32918. // decomposing the time within the day. See section 15.9.1.10.
  32919. hours = floor(time / 36e5) % 24;
  32920. minutes = floor(time / 6e4) % 60;
  32921. seconds = floor(time / 1e3) % 60;
  32922. milliseconds = time % 1e3;
  32923. } else {
  32924. year = value.getUTCFullYear();
  32925. month = value.getUTCMonth();
  32926. date = value.getUTCDate();
  32927. hours = value.getUTCHours();
  32928. minutes = value.getUTCMinutes();
  32929. seconds = value.getUTCSeconds();
  32930. milliseconds = value.getUTCMilliseconds();
  32931. }
  32932. // Serialize extended years correctly.
  32933. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  32934. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  32935. // Months, dates, hours, minutes, and seconds should have two
  32936. // digits; milliseconds should have three.
  32937. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  32938. // Milliseconds are optional in ES 5.0, but required in 5.1.
  32939. "." + toPaddedString(3, milliseconds) + "Z";
  32940. } else {
  32941. value = null;
  32942. }
  32943. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  32944. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  32945. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  32946. // ignores all `toJSON` methods on these objects unless they are
  32947. // defined directly on an instance.
  32948. value = value.toJSON(property);
  32949. }
  32950. }
  32951. if (callback) {
  32952. // If a replacement function was provided, call it to obtain the value
  32953. // for serialization.
  32954. value = callback.call(object, property, value);
  32955. }
  32956. if (value === null) {
  32957. return "null";
  32958. }
  32959. className = getClass.call(value);
  32960. if (className == booleanClass) {
  32961. // Booleans are represented literally.
  32962. return "" + value;
  32963. } else if (className == numberClass) {
  32964. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  32965. // `"null"`.
  32966. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  32967. } else if (className == stringClass) {
  32968. // Strings are double-quoted and escaped.
  32969. return quote("" + value);
  32970. }
  32971. // Recursively serialize objects and arrays.
  32972. if (typeof value == "object") {
  32973. // Check for cyclic structures. This is a linear search; performance
  32974. // is inversely proportional to the number of unique nested objects.
  32975. for (length = stack.length; length--;) {
  32976. if (stack[length] === value) {
  32977. // Cyclic structures cannot be serialized by `JSON.stringify`.
  32978. throw TypeError();
  32979. }
  32980. }
  32981. // Add the object to the stack of traversed objects.
  32982. stack.push(value);
  32983. results = [];
  32984. // Save the current indentation level and indent one additional level.
  32985. prefix = indentation;
  32986. indentation += whitespace;
  32987. if (className == arrayClass) {
  32988. // Recursively serialize array elements.
  32989. for (index = 0, length = value.length; index < length; index++) {
  32990. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  32991. results.push(element === undef ? "null" : element);
  32992. }
  32993. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  32994. } else {
  32995. // Recursively serialize object members. Members are selected from
  32996. // either a user-specified list of property names, or the object
  32997. // itself.
  32998. forEach(properties || value, function (property) {
  32999. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  33000. if (element !== undef) {
  33001. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  33002. // is not the empty string, let `member` {quote(property) + ":"}
  33003. // be the concatenation of `member` and the `space` character."
  33004. // The "`space` character" refers to the literal space
  33005. // character, not the `space` {width} argument provided to
  33006. // `JSON.stringify`.
  33007. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  33008. }
  33009. });
  33010. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  33011. }
  33012. // Remove the object from the traversed object stack.
  33013. stack.pop();
  33014. return result;
  33015. }
  33016. };
  33017. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  33018. JSON3.stringify = function (source, filter, width) {
  33019. var whitespace, callback, properties, className;
  33020. if (typeof filter == "function" || typeof filter == "object" && filter) {
  33021. if ((className = getClass.call(filter)) == functionClass) {
  33022. callback = filter;
  33023. } else if (className == arrayClass) {
  33024. // Convert the property names array into a makeshift set.
  33025. properties = {};
  33026. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  33027. }
  33028. }
  33029. if (width) {
  33030. if ((className = getClass.call(width)) == numberClass) {
  33031. // Convert the `width` to an integer and create a string containing
  33032. // `width` number of space characters.
  33033. if ((width -= width % 1) > 0) {
  33034. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  33035. }
  33036. } else if (className == stringClass) {
  33037. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  33038. }
  33039. }
  33040. // Opera <= 7.54u2 discards the values associated with empty string keys
  33041. // (`""`) only if they are used directly within an object member list
  33042. // (e.g., `!("" in { "": 1})`).
  33043. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  33044. };
  33045. }
  33046. // Public: Parses a JSON source string.
  33047. if (!has("json-parse")) {
  33048. var fromCharCode = String.fromCharCode;
  33049. // Internal: A map of escaped control characters and their unescaped
  33050. // equivalents.
  33051. var Unescapes = {
  33052. 92: "\\",
  33053. 34: '"',
  33054. 47: "/",
  33055. 98: "\b",
  33056. 116: "\t",
  33057. 110: "\n",
  33058. 102: "\f",
  33059. 114: "\r"
  33060. };
  33061. // Internal: Stores the parser state.
  33062. var Index, Source;
  33063. // Internal: Resets the parser state and throws a `SyntaxError`.
  33064. var abort = function() {
  33065. Index = Source = null;
  33066. throw SyntaxError();
  33067. };
  33068. // Internal: Returns the next token, or `"$"` if the parser has reached
  33069. // the end of the source string. A token may be a string, number, `null`
  33070. // literal, or Boolean literal.
  33071. var lex = function () {
  33072. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  33073. while (Index < length) {
  33074. charCode = source.charCodeAt(Index);
  33075. switch (charCode) {
  33076. case 9: case 10: case 13: case 32:
  33077. // Skip whitespace tokens, including tabs, carriage returns, line
  33078. // feeds, and space characters.
  33079. Index++;
  33080. break;
  33081. case 123: case 125: case 91: case 93: case 58: case 44:
  33082. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  33083. // the current position.
  33084. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  33085. Index++;
  33086. return value;
  33087. case 34:
  33088. // `"` delimits a JSON string; advance to the next character and
  33089. // begin parsing the string. String tokens are prefixed with the
  33090. // sentinel `@` character to distinguish them from punctuators and
  33091. // end-of-string tokens.
  33092. for (value = "@", Index++; Index < length;) {
  33093. charCode = source.charCodeAt(Index);
  33094. if (charCode < 32) {
  33095. // Unescaped ASCII control characters (those with a code unit
  33096. // less than the space character) are not permitted.
  33097. abort();
  33098. } else if (charCode == 92) {
  33099. // A reverse solidus (`\`) marks the beginning of an escaped
  33100. // control character (including `"`, `\`, and `/`) or Unicode
  33101. // escape sequence.
  33102. charCode = source.charCodeAt(++Index);
  33103. switch (charCode) {
  33104. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  33105. // Revive escaped control characters.
  33106. value += Unescapes[charCode];
  33107. Index++;
  33108. break;
  33109. case 117:
  33110. // `\u` marks the beginning of a Unicode escape sequence.
  33111. // Advance to the first character and validate the
  33112. // four-digit code point.
  33113. begin = ++Index;
  33114. for (position = Index + 4; Index < position; Index++) {
  33115. charCode = source.charCodeAt(Index);
  33116. // A valid sequence comprises four hexdigits (case-
  33117. // insensitive) that form a single hexadecimal value.
  33118. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  33119. // Invalid Unicode escape sequence.
  33120. abort();
  33121. }
  33122. }
  33123. // Revive the escaped character.
  33124. value += fromCharCode("0x" + source.slice(begin, Index));
  33125. break;
  33126. default:
  33127. // Invalid escape sequence.
  33128. abort();
  33129. }
  33130. } else {
  33131. if (charCode == 34) {
  33132. // An unescaped double-quote character marks the end of the
  33133. // string.
  33134. break;
  33135. }
  33136. charCode = source.charCodeAt(Index);
  33137. begin = Index;
  33138. // Optimize for the common case where a string is valid.
  33139. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  33140. charCode = source.charCodeAt(++Index);
  33141. }
  33142. // Append the string as-is.
  33143. value += source.slice(begin, Index);
  33144. }
  33145. }
  33146. if (source.charCodeAt(Index) == 34) {
  33147. // Advance to the next character and return the revived string.
  33148. Index++;
  33149. return value;
  33150. }
  33151. // Unterminated string.
  33152. abort();
  33153. default:
  33154. // Parse numbers and literals.
  33155. begin = Index;
  33156. // Advance past the negative sign, if one is specified.
  33157. if (charCode == 45) {
  33158. isSigned = true;
  33159. charCode = source.charCodeAt(++Index);
  33160. }
  33161. // Parse an integer or floating-point value.
  33162. if (charCode >= 48 && charCode <= 57) {
  33163. // Leading zeroes are interpreted as octal literals.
  33164. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  33165. // Illegal octal literal.
  33166. abort();
  33167. }
  33168. isSigned = false;
  33169. // Parse the integer component.
  33170. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  33171. // Floats cannot contain a leading decimal point; however, this
  33172. // case is already accounted for by the parser.
  33173. if (source.charCodeAt(Index) == 46) {
  33174. position = ++Index;
  33175. // Parse the decimal component.
  33176. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  33177. if (position == Index) {
  33178. // Illegal trailing decimal.
  33179. abort();
  33180. }
  33181. Index = position;
  33182. }
  33183. // Parse exponents. The `e` denoting the exponent is
  33184. // case-insensitive.
  33185. charCode = source.charCodeAt(Index);
  33186. if (charCode == 101 || charCode == 69) {
  33187. charCode = source.charCodeAt(++Index);
  33188. // Skip past the sign following the exponent, if one is
  33189. // specified.
  33190. if (charCode == 43 || charCode == 45) {
  33191. Index++;
  33192. }
  33193. // Parse the exponential component.
  33194. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  33195. if (position == Index) {
  33196. // Illegal empty exponent.
  33197. abort();
  33198. }
  33199. Index = position;
  33200. }
  33201. // Coerce the parsed value to a JavaScript number.
  33202. return +source.slice(begin, Index);
  33203. }
  33204. // A negative sign may only precede numbers.
  33205. if (isSigned) {
  33206. abort();
  33207. }
  33208. // `true`, `false`, and `null` literals.
  33209. if (source.slice(Index, Index + 4) == "true") {
  33210. Index += 4;
  33211. return true;
  33212. } else if (source.slice(Index, Index + 5) == "false") {
  33213. Index += 5;
  33214. return false;
  33215. } else if (source.slice(Index, Index + 4) == "null") {
  33216. Index += 4;
  33217. return null;
  33218. }
  33219. // Unrecognized token.
  33220. abort();
  33221. }
  33222. }
  33223. // Return the sentinel `$` character if the parser has reached the end
  33224. // of the source string.
  33225. return "$";
  33226. };
  33227. // Internal: Parses a JSON `value` token.
  33228. var get = function (value) {
  33229. var results, hasMembers;
  33230. if (value == "$") {
  33231. // Unexpected end of input.
  33232. abort();
  33233. }
  33234. if (typeof value == "string") {
  33235. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  33236. // Remove the sentinel `@` character.
  33237. return value.slice(1);
  33238. }
  33239. // Parse object and array literals.
  33240. if (value == "[") {
  33241. // Parses a JSON array, returning a new JavaScript array.
  33242. results = [];
  33243. for (;; hasMembers || (hasMembers = true)) {
  33244. value = lex();
  33245. // A closing square bracket marks the end of the array literal.
  33246. if (value == "]") {
  33247. break;
  33248. }
  33249. // If the array literal contains elements, the current token
  33250. // should be a comma separating the previous element from the
  33251. // next.
  33252. if (hasMembers) {
  33253. if (value == ",") {
  33254. value = lex();
  33255. if (value == "]") {
  33256. // Unexpected trailing `,` in array literal.
  33257. abort();
  33258. }
  33259. } else {
  33260. // A `,` must separate each array element.
  33261. abort();
  33262. }
  33263. }
  33264. // Elisions and leading commas are not permitted.
  33265. if (value == ",") {
  33266. abort();
  33267. }
  33268. results.push(get(value));
  33269. }
  33270. return results;
  33271. } else if (value == "{") {
  33272. // Parses a JSON object, returning a new JavaScript object.
  33273. results = {};
  33274. for (;; hasMembers || (hasMembers = true)) {
  33275. value = lex();
  33276. // A closing curly brace marks the end of the object literal.
  33277. if (value == "}") {
  33278. break;
  33279. }
  33280. // If the object literal contains members, the current token
  33281. // should be a comma separator.
  33282. if (hasMembers) {
  33283. if (value == ",") {
  33284. value = lex();
  33285. if (value == "}") {
  33286. // Unexpected trailing `,` in object literal.
  33287. abort();
  33288. }
  33289. } else {
  33290. // A `,` must separate each object member.
  33291. abort();
  33292. }
  33293. }
  33294. // Leading commas are not permitted, object property names must be
  33295. // double-quoted strings, and a `:` must separate each property
  33296. // name and value.
  33297. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  33298. abort();
  33299. }
  33300. results[value.slice(1)] = get(lex());
  33301. }
  33302. return results;
  33303. }
  33304. // Unexpected token encountered.
  33305. abort();
  33306. }
  33307. return value;
  33308. };
  33309. // Internal: Updates a traversed object member.
  33310. var update = function(source, property, callback) {
  33311. var element = walk(source, property, callback);
  33312. if (element === undef) {
  33313. delete source[property];
  33314. } else {
  33315. source[property] = element;
  33316. }
  33317. };
  33318. // Internal: Recursively traverses a parsed JSON object, invoking the
  33319. // `callback` function for each value. This is an implementation of the
  33320. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  33321. var walk = function (source, property, callback) {
  33322. var value = source[property], length;
  33323. if (typeof value == "object" && value) {
  33324. // `forEach` can't be used to traverse an array in Opera <= 8.54
  33325. // because its `Object#hasOwnProperty` implementation returns `false`
  33326. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  33327. if (getClass.call(value) == arrayClass) {
  33328. for (length = value.length; length--;) {
  33329. update(value, length, callback);
  33330. }
  33331. } else {
  33332. forEach(value, function (property) {
  33333. update(value, property, callback);
  33334. });
  33335. }
  33336. }
  33337. return callback.call(source, property, value);
  33338. };
  33339. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  33340. JSON3.parse = function (source, callback) {
  33341. var result, value;
  33342. Index = 0;
  33343. Source = "" + source;
  33344. result = get(lex());
  33345. // If a JSON string contains multiple tokens, it is invalid.
  33346. if (lex() != "$") {
  33347. abort();
  33348. }
  33349. // Reset the parser state.
  33350. Index = Source = null;
  33351. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  33352. };
  33353. }
  33354. }
  33355. // Export for asynchronous module loaders.
  33356. if (isLoader) {
  33357. define(function () {
  33358. return JSON3;
  33359. });
  33360. }
  33361. }(this));
  33362. },{}],161:[function(require,module,exports){
  33363. module.exports = toArray
  33364. function toArray(list, index) {
  33365. var array = []
  33366. index = index || 0
  33367. for (var i = index || 0; i < list.length; i++) {
  33368. array[i - index] = list[i]
  33369. }
  33370. return array
  33371. }
  33372. },{}],162:[function(require,module,exports){
  33373. var MediaStreamType = {
  33374. VIDEO_TYPE: "Video",
  33375. AUDIO_TYPE: "Audio"
  33376. };
  33377. module.exports = MediaStreamType;
  33378. },{}],163:[function(require,module,exports){
  33379. var RTCEvents = {
  33380. RTC_READY: "rtc.ready",
  33381. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  33382. LASTN_CHANGED: "rtc.lastn_changed",
  33383. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  33384. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  33385. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  33386. AUDIO_MUTE: "rtc.audio_mute",
  33387. VIDEO_MUTE: "rtc.video_mute"
  33388. };
  33389. module.exports = RTCEvents;
  33390. },{}],164:[function(require,module,exports){
  33391. var Resolutions = {
  33392. "1080": {
  33393. width: 1920,
  33394. height: 1080,
  33395. order: 7
  33396. },
  33397. "fullhd": {
  33398. width: 1920,
  33399. height: 1080,
  33400. order: 7
  33401. },
  33402. "720": {
  33403. width: 1280,
  33404. height: 720,
  33405. order: 6
  33406. },
  33407. "hd": {
  33408. width: 1280,
  33409. height: 720,
  33410. order: 6
  33411. },
  33412. "960": {
  33413. width: 960,
  33414. height: 720,
  33415. order: 5
  33416. },
  33417. "640": {
  33418. width: 640,
  33419. height: 480,
  33420. order: 4
  33421. },
  33422. "vga": {
  33423. width: 640,
  33424. height: 480,
  33425. order: 4
  33426. },
  33427. "360": {
  33428. width: 640,
  33429. height: 360,
  33430. order: 3
  33431. },
  33432. "320": {
  33433. width: 320,
  33434. height: 240,
  33435. order: 2
  33436. },
  33437. "180": {
  33438. width: 320,
  33439. height: 180,
  33440. order: 1
  33441. }
  33442. };
  33443. module.exports = Resolutions;
  33444. },{}],165:[function(require,module,exports){
  33445. var StreamEventTypes = {
  33446. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  33447. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  33448. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  33449. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  33450. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  33451. };
  33452. module.exports = StreamEventTypes;
  33453. },{}],166:[function(require,module,exports){
  33454. var UIEvents = {
  33455. NICKNAME_CHANGED: "UI.nickname_changed",
  33456. SELECTED_ENDPOINT: "UI.selected_endpoint",
  33457. PINNED_ENDPOINT: "UI.pinned_endpoint",
  33458. LARGEVIDEO_INIT: "UI.largevideo_init"
  33459. };
  33460. module.exports = UIEvents;
  33461. },{}],167:[function(require,module,exports){
  33462. var AuthenticationEvents = {
  33463. /**
  33464. * Event callback arguments:
  33465. * function(authenticationEnabled, userIdentity)
  33466. * authenticationEnabled - indicates whether authentication has been enabled
  33467. * in this session
  33468. * userIdentity - if user has been logged in then it contains user name. If
  33469. * contains 'null' or 'undefined' then user is not logged in.
  33470. */
  33471. IDENTITY_UPDATED: "authentication.identity_updated"
  33472. };
  33473. module.exports = AuthenticationEvents;
  33474. },{}],168:[function(require,module,exports){
  33475. var CQEvents = {
  33476. LOCALSTATS_UPDATED: "cq.localstats_updated",
  33477. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  33478. STOP: "cq.stop"
  33479. };
  33480. module.exports = CQEvents;
  33481. },{}],169:[function(require,module,exports){
  33482. var DesktopSharingEventTypes = {
  33483. INIT: "ds.init",
  33484. SWITCHING_DONE: "ds.switching_done",
  33485. NEW_STREAM_CREATED: "ds.new_stream_created"
  33486. };
  33487. module.exports = DesktopSharingEventTypes;
  33488. },{}],170:[function(require,module,exports){
  33489. var Events = {
  33490. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  33491. };
  33492. module.exports = Events;
  33493. },{}],171:[function(require,module,exports){
  33494. module.exports = {
  33495. getLanguages : function () {
  33496. var languages = [];
  33497. for(var lang in this)
  33498. {
  33499. if(typeof this[lang] === "string")
  33500. languages.push(this[lang]);
  33501. }
  33502. return languages;
  33503. },
  33504. EN: "en",
  33505. BG: "bg",
  33506. DE: "de",
  33507. TR: "tr",
  33508. FR: "fr"
  33509. }
  33510. },{}],172:[function(require,module,exports){
  33511. var XMPPEvents = {
  33512. // Designates an event indicating that the connection to the XMPP server
  33513. // failed.
  33514. CONNECTION_FAILED: "xmpp.connection.failed",
  33515. // Designates an event indicating that the media (ICE) connection was
  33516. // interrupted. This should go to the RTC module.
  33517. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  33518. // Designates an event indicating that the media (ICE) connection was
  33519. // restored. This should go to the RTC module.
  33520. CONNECTION_RESTORED: "xmpp.connection.restored",
  33521. // Designates an event indicating that an offer (e.g. Jingle
  33522. // session-initiate) was received.
  33523. CALL_INCOMING: "xmpp.callincoming.jingle",
  33524. // Designates an event indicating that we were kicked from the XMPP MUC.
  33525. KICKED: "xmpp.kicked",
  33526. // Designates an event indicating that the userID for a specific JID has
  33527. // changed.
  33528. USER_ID_CHANGED: "xmpp.user_id_changed",
  33529. // Designates an event indicating that we have joined the XMPP MUC.
  33530. MUC_JOINED: "xmpp.muc_joined",
  33531. // Designates an event indicating that a participant joined the XMPP MUC.
  33532. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  33533. // Designates an event indicating that a participant left the XMPP MUC.
  33534. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  33535. // Designates an event indicating that the MUC role of a participant has
  33536. // changed.
  33537. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  33538. // Designates an event indicating that the XMPP MUC was destroyed.
  33539. MUC_DESTROYED: "xmpp.muc_destroyed",
  33540. // Designates an event indicating that the display name of a participant
  33541. // has changed.
  33542. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  33543. // Designates an event indicating that we received statistics from a
  33544. // participant in the MUC.
  33545. REMOTE_STATS: "xmpp.remote_stats",
  33546. // Designates an event indicating that our role in the XMPP MUC has changed.
  33547. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  33548. // Designates an event indicating that the subject of the XMPP MUC has
  33549. // changed.
  33550. SUBJECT_CHANGED: "xmpp.subject_changed",
  33551. // Designates an event indicating that an XMPP message in the MUC was
  33552. // received.
  33553. MESSAGE_RECEIVED: "xmpp.message_received",
  33554. // Designates an event indicating that we sent an XMPP message to the MUC.
  33555. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  33556. // Designates an event indicating that the video type (e.g. 'camera' or
  33557. // 'screen') for a participant has changed.
  33558. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  33559. // Designates an event indicating that a participant in the XMPP MUC has
  33560. // advertised that they have audio muted (or unmuted).
  33561. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  33562. // Designates an event indicating that a participant in the XMPP MUC has
  33563. // advertised that they have video muted (or unmuted).
  33564. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  33565. // Designates an event indicating that the focus has asked us to mute our
  33566. // audio.
  33567. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  33568. // Designates an event indicating that a moderator in the room changed the
  33569. // "start muted" settings for the conference.
  33570. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  33571. // Designates an event indicating that we should join the conference with
  33572. // audio and/or video muted.
  33573. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  33574. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  33575. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  33576. PASSWORD_REQUIRED: "xmpp.password_required",
  33577. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  33578. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  33579. ETHERPAD: "xmpp.etherpad",
  33580. DEVICE_AVAILABLE: "xmpp.device_available",
  33581. BRIDGE_DOWN: "xmpp.bridge_down",
  33582. PRESENCE_STATUS: "xmpp.presence_status",
  33583. RESERVATION_ERROR: "xmpp.room_reservation_error",
  33584. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  33585. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  33586. // TODO: only used in a hack, should probably be removed.
  33587. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  33588. // TODO: only used in a hack, should probably be removed.
  33589. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  33590. // TODO: only used in a hack, should probably be removed.
  33591. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  33592. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  33593. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  33594. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  33595. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  33596. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  33597. // xmpp is connected and obtained user media
  33598. READY_TO_JOIN: 'xmpp.ready_to_join'
  33599. };
  33600. module.exports = XMPPEvents;
  33601. },{}],173:[function(require,module,exports){
  33602. // Copyright Joyent, Inc. and other Node contributors.
  33603. //
  33604. // Permission is hereby granted, free of charge, to any person obtaining a
  33605. // copy of this software and associated documentation files (the
  33606. // "Software"), to deal in the Software without restriction, including
  33607. // without limitation the rights to use, copy, modify, merge, publish,
  33608. // distribute, sublicense, and/or sell copies of the Software, and to permit
  33609. // persons to whom the Software is furnished to do so, subject to the
  33610. // following conditions:
  33611. //
  33612. // The above copyright notice and this permission notice shall be included
  33613. // in all copies or substantial portions of the Software.
  33614. //
  33615. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  33616. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33617. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  33618. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  33619. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  33620. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  33621. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  33622. function EventEmitter() {
  33623. this._events = this._events || {};
  33624. this._maxListeners = this._maxListeners || undefined;
  33625. }
  33626. module.exports = EventEmitter;
  33627. // Backwards-compat with node 0.10.x
  33628. EventEmitter.EventEmitter = EventEmitter;
  33629. EventEmitter.prototype._events = undefined;
  33630. EventEmitter.prototype._maxListeners = undefined;
  33631. // By default EventEmitters will print a warning if more than 10 listeners are
  33632. // added to it. This is a useful default which helps finding memory leaks.
  33633. EventEmitter.defaultMaxListeners = 10;
  33634. // Obviously not all Emitters should be limited to 10. This function allows
  33635. // that to be increased. Set to zero for unlimited.
  33636. EventEmitter.prototype.setMaxListeners = function(n) {
  33637. if (!isNumber(n) || n < 0 || isNaN(n))
  33638. throw TypeError('n must be a positive number');
  33639. this._maxListeners = n;
  33640. return this;
  33641. };
  33642. EventEmitter.prototype.emit = function(type) {
  33643. var er, handler, len, args, i, listeners;
  33644. if (!this._events)
  33645. this._events = {};
  33646. // If there is no 'error' event listener then throw.
  33647. if (type === 'error') {
  33648. if (!this._events.error ||
  33649. (isObject(this._events.error) && !this._events.error.length)) {
  33650. er = arguments[1];
  33651. if (er instanceof Error) {
  33652. throw er; // Unhandled 'error' event
  33653. }
  33654. throw TypeError('Uncaught, unspecified "error" event.');
  33655. }
  33656. }
  33657. handler = this._events[type];
  33658. if (isUndefined(handler))
  33659. return false;
  33660. if (isFunction(handler)) {
  33661. switch (arguments.length) {
  33662. // fast cases
  33663. case 1:
  33664. handler.call(this);
  33665. break;
  33666. case 2:
  33667. handler.call(this, arguments[1]);
  33668. break;
  33669. case 3:
  33670. handler.call(this, arguments[1], arguments[2]);
  33671. break;
  33672. // slower
  33673. default:
  33674. len = arguments.length;
  33675. args = new Array(len - 1);
  33676. for (i = 1; i < len; i++)
  33677. args[i - 1] = arguments[i];
  33678. handler.apply(this, args);
  33679. }
  33680. } else if (isObject(handler)) {
  33681. len = arguments.length;
  33682. args = new Array(len - 1);
  33683. for (i = 1; i < len; i++)
  33684. args[i - 1] = arguments[i];
  33685. listeners = handler.slice();
  33686. len = listeners.length;
  33687. for (i = 0; i < len; i++)
  33688. listeners[i].apply(this, args);
  33689. }
  33690. return true;
  33691. };
  33692. EventEmitter.prototype.addListener = function(type, listener) {
  33693. var m;
  33694. if (!isFunction(listener))
  33695. throw TypeError('listener must be a function');
  33696. if (!this._events)
  33697. this._events = {};
  33698. // To avoid recursion in the case that type === "newListener"! Before
  33699. // adding it to the listeners, first emit "newListener".
  33700. if (this._events.newListener)
  33701. this.emit('newListener', type,
  33702. isFunction(listener.listener) ?
  33703. listener.listener : listener);
  33704. if (!this._events[type])
  33705. // Optimize the case of one listener. Don't need the extra array object.
  33706. this._events[type] = listener;
  33707. else if (isObject(this._events[type]))
  33708. // If we've already got an array, just append.
  33709. this._events[type].push(listener);
  33710. else
  33711. // Adding the second element, need to change to array.
  33712. this._events[type] = [this._events[type], listener];
  33713. // Check for listener leak
  33714. if (isObject(this._events[type]) && !this._events[type].warned) {
  33715. var m;
  33716. if (!isUndefined(this._maxListeners)) {
  33717. m = this._maxListeners;
  33718. } else {
  33719. m = EventEmitter.defaultMaxListeners;
  33720. }
  33721. if (m && m > 0 && this._events[type].length > m) {
  33722. this._events[type].warned = true;
  33723. console.error('(node) warning: possible EventEmitter memory ' +
  33724. 'leak detected. %d listeners added. ' +
  33725. 'Use emitter.setMaxListeners() to increase limit.',
  33726. this._events[type].length);
  33727. if (typeof console.trace === 'function') {
  33728. // not supported in IE 10
  33729. console.trace();
  33730. }
  33731. }
  33732. }
  33733. return this;
  33734. };
  33735. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  33736. EventEmitter.prototype.once = function(type, listener) {
  33737. if (!isFunction(listener))
  33738. throw TypeError('listener must be a function');
  33739. var fired = false;
  33740. function g() {
  33741. this.removeListener(type, g);
  33742. if (!fired) {
  33743. fired = true;
  33744. listener.apply(this, arguments);
  33745. }
  33746. }
  33747. g.listener = listener;
  33748. this.on(type, g);
  33749. return this;
  33750. };
  33751. // emits a 'removeListener' event iff the listener was removed
  33752. EventEmitter.prototype.removeListener = function(type, listener) {
  33753. var list, position, length, i;
  33754. if (!isFunction(listener))
  33755. throw TypeError('listener must be a function');
  33756. if (!this._events || !this._events[type])
  33757. return this;
  33758. list = this._events[type];
  33759. length = list.length;
  33760. position = -1;
  33761. if (list === listener ||
  33762. (isFunction(list.listener) && list.listener === listener)) {
  33763. delete this._events[type];
  33764. if (this._events.removeListener)
  33765. this.emit('removeListener', type, listener);
  33766. } else if (isObject(list)) {
  33767. for (i = length; i-- > 0;) {
  33768. if (list[i] === listener ||
  33769. (list[i].listener && list[i].listener === listener)) {
  33770. position = i;
  33771. break;
  33772. }
  33773. }
  33774. if (position < 0)
  33775. return this;
  33776. if (list.length === 1) {
  33777. list.length = 0;
  33778. delete this._events[type];
  33779. } else {
  33780. list.splice(position, 1);
  33781. }
  33782. if (this._events.removeListener)
  33783. this.emit('removeListener', type, listener);
  33784. }
  33785. return this;
  33786. };
  33787. EventEmitter.prototype.removeAllListeners = function(type) {
  33788. var key, listeners;
  33789. if (!this._events)
  33790. return this;
  33791. // not listening for removeListener, no need to emit
  33792. if (!this._events.removeListener) {
  33793. if (arguments.length === 0)
  33794. this._events = {};
  33795. else if (this._events[type])
  33796. delete this._events[type];
  33797. return this;
  33798. }
  33799. // emit removeListener for all listeners on all events
  33800. if (arguments.length === 0) {
  33801. for (key in this._events) {
  33802. if (key === 'removeListener') continue;
  33803. this.removeAllListeners(key);
  33804. }
  33805. this.removeAllListeners('removeListener');
  33806. this._events = {};
  33807. return this;
  33808. }
  33809. listeners = this._events[type];
  33810. if (isFunction(listeners)) {
  33811. this.removeListener(type, listeners);
  33812. } else {
  33813. // LIFO order
  33814. while (listeners.length)
  33815. this.removeListener(type, listeners[listeners.length - 1]);
  33816. }
  33817. delete this._events[type];
  33818. return this;
  33819. };
  33820. EventEmitter.prototype.listeners = function(type) {
  33821. var ret;
  33822. if (!this._events || !this._events[type])
  33823. ret = [];
  33824. else if (isFunction(this._events[type]))
  33825. ret = [this._events[type]];
  33826. else
  33827. ret = this._events[type].slice();
  33828. return ret;
  33829. };
  33830. EventEmitter.listenerCount = function(emitter, type) {
  33831. var ret;
  33832. if (!emitter._events || !emitter._events[type])
  33833. ret = 0;
  33834. else if (isFunction(emitter._events[type]))
  33835. ret = 1;
  33836. else
  33837. ret = emitter._events[type].length;
  33838. return ret;
  33839. };
  33840. function isFunction(arg) {
  33841. return typeof arg === 'function';
  33842. }
  33843. function isNumber(arg) {
  33844. return typeof arg === 'number';
  33845. }
  33846. function isObject(arg) {
  33847. return typeof arg === 'object' && arg !== null;
  33848. }
  33849. function isUndefined(arg) {
  33850. return arg === void 0;
  33851. }
  33852. },{}],174:[function(require,module,exports){
  33853. // shim for using process in browser
  33854. var process = module.exports = {};
  33855. var queue = [];
  33856. var draining = false;
  33857. var currentQueue;
  33858. var queueIndex = -1;
  33859. function cleanUpNextTick() {
  33860. draining = false;
  33861. if (currentQueue.length) {
  33862. queue = currentQueue.concat(queue);
  33863. } else {
  33864. queueIndex = -1;
  33865. }
  33866. if (queue.length) {
  33867. drainQueue();
  33868. }
  33869. }
  33870. function drainQueue() {
  33871. if (draining) {
  33872. return;
  33873. }
  33874. var timeout = setTimeout(cleanUpNextTick);
  33875. draining = true;
  33876. var len = queue.length;
  33877. while(len) {
  33878. currentQueue = queue;
  33879. queue = [];
  33880. while (++queueIndex < len) {
  33881. currentQueue[queueIndex].run();
  33882. }
  33883. queueIndex = -1;
  33884. len = queue.length;
  33885. }
  33886. currentQueue = null;
  33887. draining = false;
  33888. clearTimeout(timeout);
  33889. }
  33890. process.nextTick = function (fun) {
  33891. var args = new Array(arguments.length - 1);
  33892. if (arguments.length > 1) {
  33893. for (var i = 1; i < arguments.length; i++) {
  33894. args[i - 1] = arguments[i];
  33895. }
  33896. }
  33897. queue.push(new Item(fun, args));
  33898. if (queue.length === 1 && !draining) {
  33899. setTimeout(drainQueue, 0);
  33900. }
  33901. };
  33902. // v8 likes predictible objects
  33903. function Item(fun, array) {
  33904. this.fun = fun;
  33905. this.array = array;
  33906. }
  33907. Item.prototype.run = function () {
  33908. this.fun.apply(null, this.array);
  33909. };
  33910. process.title = 'browser';
  33911. process.browser = true;
  33912. process.env = {};
  33913. process.argv = [];
  33914. process.version = ''; // empty string to avoid regexp issues
  33915. process.versions = {};
  33916. function noop() {}
  33917. process.on = noop;
  33918. process.addListener = noop;
  33919. process.once = noop;
  33920. process.off = noop;
  33921. process.removeListener = noop;
  33922. process.removeAllListeners = noop;
  33923. process.emit = noop;
  33924. process.binding = function (name) {
  33925. throw new Error('process.binding is not supported');
  33926. };
  33927. // TODO(shtylman)
  33928. process.cwd = function () { return '/' };
  33929. process.chdir = function (dir) {
  33930. throw new Error('process.chdir is not supported');
  33931. };
  33932. process.umask = function() { return 0; };
  33933. },{}]},{},[1])(1)
  33934. });