Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

app.bundle.js 969KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557
  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. /**
  3. * Implements API class that communicates with external api class
  4. * and provides interface to access Jitsi Meet features by external
  5. * applications that embed Jitsi Meet
  6. */
  7. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8. /**
  9. * List of the available commands.
  10. * @type {{
  11. * displayName: inputDisplayNameHandler,
  12. * muteAudio: toggleAudio,
  13. * muteVideo: toggleVideo,
  14. * filmStrip: toggleFilmStrip
  15. * }}
  16. */
  17. var commands =
  18. {
  19. displayName: APP.UI.inputDisplayNameHandler,
  20. muteAudio: APP.UI.toggleAudio,
  21. muteVideo: APP.UI.toggleVideo,
  22. toggleFilmStrip: APP.UI.toggleFilmStrip,
  23. toggleChat: APP.UI.toggleChat,
  24. toggleContactList: APP.UI.toggleContactList
  25. };
  26. /**
  27. * Maps the supported events and their status
  28. * (true it the event is enabled and false if it is disabled)
  29. * @type {{
  30. * incomingMessage: boolean,
  31. * outgoingMessage: boolean,
  32. * displayNameChange: boolean,
  33. * participantJoined: boolean,
  34. * participantLeft: boolean
  35. * }}
  36. */
  37. var events =
  38. {
  39. incomingMessage: false,
  40. outgoingMessage:false,
  41. displayNameChange: false,
  42. participantJoined: false,
  43. participantLeft: false
  44. };
  45. var displayName = {};
  46. /**
  47. * Processes commands from external applicaiton.
  48. * @param message the object with the command
  49. */
  50. function processCommand(message)
  51. {
  52. if(message.action != "execute")
  53. {
  54. console.error("Unknown action of the message");
  55. return;
  56. }
  57. for(var key in message)
  58. {
  59. if(commands[key])
  60. commands[key].apply(null, message[key]);
  61. }
  62. }
  63. /**
  64. * Processes events objects from external applications
  65. * @param event the event
  66. */
  67. function processEvent(event) {
  68. if(!event.action)
  69. {
  70. console.error("Event with no action is received.");
  71. return;
  72. }
  73. var i = 0;
  74. switch(event.action)
  75. {
  76. case "add":
  77. for(; i < event.events.length; i++)
  78. {
  79. events[event.events[i]] = true;
  80. }
  81. break;
  82. case "remove":
  83. for(; i < event.events.length; i++)
  84. {
  85. events[event.events[i]] = false;
  86. }
  87. break;
  88. default:
  89. console.error("Unknown action for event.");
  90. }
  91. }
  92. /**
  93. * Sends message to the external application.
  94. * @param object
  95. */
  96. function sendMessage(object) {
  97. window.parent.postMessage(JSON.stringify(object), "*");
  98. }
  99. /**
  100. * Processes a message event from the external application
  101. * @param event the message event
  102. */
  103. function processMessage(event)
  104. {
  105. var message;
  106. try {
  107. message = JSON.parse(event.data);
  108. } catch (e) {}
  109. if(!message.type)
  110. return;
  111. switch (message.type)
  112. {
  113. case "command":
  114. processCommand(message);
  115. break;
  116. case "event":
  117. processEvent(message);
  118. break;
  119. default:
  120. console.error("Unknown type of the message");
  121. return;
  122. }
  123. }
  124. function setupListeners() {
  125. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  126. API.triggerEvent("participantJoined", {jid: from});
  127. });
  128. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  129. if (from != myjid)
  130. API.triggerEvent("incomingMessage",
  131. {"from": from, "nick": nick, "message": txt});
  132. });
  133. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  134. API.triggerEvent("participantLeft", {jid: jid});
  135. });
  136. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  137. name = displayName[jid];
  138. if(!name || name != newDisplayName) {
  139. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  140. displayName[jid] = newDisplayName;
  141. }
  142. });
  143. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  144. APP.API.triggerEvent("outgoingMessage", {"message": body});
  145. });
  146. }
  147. var API = {
  148. /**
  149. * Check whether the API should be enabled or not.
  150. * @returns {boolean}
  151. */
  152. isEnabled: function () {
  153. var hash = location.hash;
  154. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  155. return true;
  156. return false;
  157. },
  158. /**
  159. * Initializes the APIConnector. Setups message event listeners that will
  160. * receive information from external applications that embed Jitsi Meet.
  161. * It also sends a message to the external application that APIConnector
  162. * is initialized.
  163. */
  164. init: function () {
  165. if (window.addEventListener)
  166. {
  167. window.addEventListener('message',
  168. processMessage, false);
  169. }
  170. else
  171. {
  172. window.attachEvent('onmessage', processMessage);
  173. }
  174. sendMessage({type: "system", loaded: true});
  175. setupListeners();
  176. },
  177. /**
  178. * Checks whether the event is enabled ot not.
  179. * @param name the name of the event.
  180. * @returns {*}
  181. */
  182. isEventEnabled: function (name) {
  183. return events[name];
  184. },
  185. /**
  186. * Sends event object to the external application that has been subscribed
  187. * for that event.
  188. * @param name the name event
  189. * @param object data associated with the event
  190. */
  191. triggerEvent: function (name, object) {
  192. if(this.isEnabled() && this.isEventEnabled(name))
  193. sendMessage({
  194. type: "event", action: "result", event: name, result: object});
  195. },
  196. /**
  197. * Removes the listeners.
  198. */
  199. dispose: function () {
  200. if(window.removeEventListener)
  201. {
  202. window.removeEventListener("message",
  203. processMessage, false);
  204. }
  205. else
  206. {
  207. window.detachEvent('onmessage', processMessage);
  208. }
  209. }
  210. };
  211. module.exports = API;
  212. },{"../../service/xmpp/XMPPEvents":105}],2:[function(require,module,exports){
  213. /* global APP */
  214. /**
  215. * A module for sending DTMF tones.
  216. */
  217. var DTMFSender;
  218. var initDtmfSender = function() {
  219. // TODO: This needs to reset this if the peerconnection changes
  220. // (e.g. the call is re-made)
  221. if (DTMFSender)
  222. return;
  223. var localAudio = APP.RTC.localAudio;
  224. if (localAudio && localAudio.getTracks().length > 0)
  225. {
  226. var peerconnection
  227. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  228. if (peerconnection) {
  229. DTMFSender =
  230. peerconnection.peerconnection
  231. .createDTMFSender(localAudio.getTracks()[0]);
  232. console.log("Initialized DTMFSender");
  233. }
  234. else {
  235. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  236. }
  237. }
  238. else {
  239. console.log("Failed to initialize DTMFSender: no audio track.");
  240. }
  241. };
  242. var DTMF = {
  243. sendTones: function (tones, duration, pause) {
  244. if (!DTMFSender)
  245. initDtmfSender();
  246. if (DTMFSender){
  247. DTMFSender.insertDTMF(tones,
  248. (duration || 200),
  249. (pause || 200));
  250. }
  251. }
  252. };
  253. module.exports = DTMF;
  254. },{}],3:[function(require,module,exports){
  255. /* global Strophe, focusedVideoSrc*/
  256. // cache datachannels to avoid garbage collection
  257. // https://code.google.com/p/chromium/issues/detail?id=405545
  258. var RTCEvents = require("../../service/RTC/RTCEvents");
  259. var _dataChannels = [];
  260. var eventEmitter = null;
  261. var DataChannels =
  262. {
  263. /**
  264. * Callback triggered by PeerConnection when new data channel is opened
  265. * on the bridge.
  266. * @param event the event info object.
  267. */
  268. onDataChannel: function (event)
  269. {
  270. var dataChannel = event.channel;
  271. dataChannel.onopen = function () {
  272. console.info("Data channel opened by the Videobridge!", dataChannel);
  273. // Code sample for sending string and/or binary data
  274. // Sends String message to the bridge
  275. //dataChannel.send("Hello bridge!");
  276. // Sends 12 bytes binary message to the bridge
  277. //dataChannel.send(new ArrayBuffer(12));
  278. // when the data channel becomes available, tell the bridge about video
  279. // selections so that it can do adaptive simulcast,
  280. // we want the notification to trigger even if userJid is undefined,
  281. // or null.
  282. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  283. // we want the notification to trigger even if userJid is undefined,
  284. // or null.
  285. onSelectedEndpointChanged(userJid);
  286. };
  287. dataChannel.onerror = function (error) {
  288. console.error("Data Channel Error:", error, dataChannel);
  289. };
  290. dataChannel.onmessage = function (event) {
  291. var data = event.data;
  292. // JSON
  293. var obj;
  294. try {
  295. obj = JSON.parse(data);
  296. }
  297. catch (e) {
  298. console.error(
  299. "Failed to parse data channel message as JSON: ",
  300. data,
  301. dataChannel);
  302. }
  303. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  304. var colibriClass = obj.colibriClass;
  305. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  306. // Endpoint ID from the Videobridge.
  307. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  308. console.info(
  309. "Data channel new dominant speaker event: ",
  310. dominantSpeakerEndpoint);
  311. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  312. }
  313. else if ("InLastNChangeEvent" === colibriClass)
  314. {
  315. var oldValue = obj.oldValue;
  316. var newValue = obj.newValue;
  317. // Make sure that oldValue and newValue are of type boolean.
  318. var type;
  319. if ((type = typeof oldValue) !== 'boolean') {
  320. if (type === 'string') {
  321. oldValue = (oldValue == "true");
  322. } else {
  323. oldValue = new Boolean(oldValue).valueOf();
  324. }
  325. }
  326. if ((type = typeof newValue) !== 'boolean') {
  327. if (type === 'string') {
  328. newValue = (newValue == "true");
  329. } else {
  330. newValue = new Boolean(newValue).valueOf();
  331. }
  332. }
  333. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  334. }
  335. else if ("LastNEndpointsChangeEvent" === colibriClass)
  336. {
  337. // The new/latest list of last-n endpoint IDs.
  338. var lastNEndpoints = obj.lastNEndpoints;
  339. // The list of endpoint IDs which are entering the list of
  340. // last-n at this time i.e. were not in the old list of last-n
  341. // endpoint IDs.
  342. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  343. var stream = obj.stream;
  344. console.log(
  345. "Data channel new last-n event: ",
  346. lastNEndpoints, endpointsEnteringLastN, obj);
  347. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  348. lastNEndpoints, endpointsEnteringLastN, obj);
  349. }
  350. else if ("SimulcastLayersChangedEvent" === colibriClass)
  351. {
  352. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  353. obj.endpointSimulcastLayers);
  354. }
  355. else if ("SimulcastLayersChangingEvent" === colibriClass)
  356. {
  357. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  358. obj.endpointSimulcastLayers);
  359. }
  360. else if ("StartSimulcastLayerEvent" === colibriClass)
  361. {
  362. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  363. }
  364. else if ("StopSimulcastLayerEvent" === colibriClass)
  365. {
  366. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  367. }
  368. else
  369. {
  370. console.debug("Data channel JSON-formatted message: ", obj);
  371. }
  372. }
  373. };
  374. dataChannel.onclose = function ()
  375. {
  376. console.info("The Data Channel closed", dataChannel);
  377. var idx = _dataChannels.indexOf(dataChannel);
  378. if (idx > -1)
  379. _dataChannels = _dataChannels.splice(idx, 1);
  380. };
  381. _dataChannels.push(dataChannel);
  382. },
  383. /**
  384. * Binds "ondatachannel" event listener to given PeerConnection instance.
  385. * @param peerConnection WebRTC peer connection instance.
  386. */
  387. init: function (peerConnection, emitter) {
  388. if(!config.openSctp)
  389. return;
  390. peerConnection.ondatachannel = this.onDataChannel;
  391. eventEmitter = emitter;
  392. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  393. // Although it's not a requirement to open separate channels from both bridge
  394. // and peer as single channel can be used for sending and receiving data.
  395. // So either channel opened by the bridge or the one opened here is enough
  396. // for communication with the bridge.
  397. /*var dataChannelOptions =
  398. {
  399. reliable: true
  400. };
  401. var dataChannel
  402. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  403. // Can be used only when is in open state
  404. dataChannel.onopen = function ()
  405. {
  406. dataChannel.send("My channel !!!");
  407. };
  408. dataChannel.onmessage = function (event)
  409. {
  410. var msgData = event.data;
  411. console.info("Got My Data Channel Message:", msgData, dataChannel);
  412. };*/
  413. },
  414. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  415. handlePinnedEndpointEvent: onPinnedEndpointChanged
  416. };
  417. function onSelectedEndpointChanged(userResource)
  418. {
  419. console.log('selected endpoint changed: ', userResource);
  420. if (_dataChannels && _dataChannels.length != 0)
  421. {
  422. _dataChannels.some(function (dataChannel) {
  423. if (dataChannel.readyState == 'open')
  424. {
  425. console.log('sending selected endpoint changed '
  426. + 'notification to the bridge: ', userResource);
  427. dataChannel.send(JSON.stringify({
  428. 'colibriClass': 'SelectedEndpointChangedEvent',
  429. 'selectedEndpoint':
  430. (!userResource || userResource === null)?
  431. null : userResource
  432. }));
  433. return true;
  434. }
  435. });
  436. }
  437. }
  438. function onPinnedEndpointChanged(userResource)
  439. {
  440. console.log('pinned endpoint changed: ', userResource);
  441. if (_dataChannels && _dataChannels.length != 0)
  442. {
  443. _dataChannels.some(function (dataChannel) {
  444. if (dataChannel.readyState == 'open')
  445. {
  446. dataChannel.send(JSON.stringify({
  447. 'colibriClass': 'PinnedEndpointChangedEvent',
  448. 'pinnedEndpoint':
  449. (!userResource || userResource == null)?
  450. null : userResource
  451. }));
  452. return true;
  453. }
  454. });
  455. }
  456. }
  457. module.exports = DataChannels;
  458. },{"../../service/RTC/RTCEvents":96}],4:[function(require,module,exports){
  459. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  460. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  461. {
  462. this.stream = stream;
  463. this.eventEmitter = eventEmitter;
  464. this.type = type;
  465. this.videoType = videoType;
  466. this.isGUMStream = true;
  467. if(isGUMStream === false)
  468. this.isGUMStream = isGUMStream;
  469. var self = this;
  470. if(type == "audio")
  471. {
  472. this.getTracks = function () {
  473. return self.stream.getAudioTracks();
  474. };
  475. }
  476. else
  477. {
  478. this.getTracks = function () {
  479. return self.stream.getVideoTracks();
  480. };
  481. }
  482. this.stream.onended = function()
  483. {
  484. self.streamEnded();
  485. };
  486. }
  487. LocalStream.prototype.streamEnded = function () {
  488. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  489. }
  490. LocalStream.prototype.getOriginalStream = function()
  491. {
  492. return this.stream;
  493. }
  494. LocalStream.prototype.isAudioStream = function () {
  495. return this.type === "audio";
  496. };
  497. LocalStream.prototype.setMute = function(mute)
  498. {
  499. if((window.location.protocol != "https:" && this.isGUMStream) ||
  500. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  501. {
  502. var tracks = this.getTracks();
  503. for (var idx = 0; idx < tracks.length; idx++) {
  504. tracks[idx].enabled = mute;
  505. }
  506. }
  507. else
  508. {
  509. if(mute === false) {
  510. APP.xmpp.removeStream(this.stream);
  511. this.stream.stop();
  512. }
  513. else
  514. {
  515. var self = this;
  516. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  517. (this.isAudioStream() ? ["audio"] : ["video"]),
  518. function (stream) {
  519. if(self.isAudioStream())
  520. {
  521. APP.RTC.changeLocalAudio(stream, function () {});
  522. }
  523. else
  524. {
  525. APP.RTC.changeLocalVideo(stream, false, function () {});
  526. }
  527. });
  528. }
  529. }
  530. };
  531. LocalStream.prototype.isMuted = function () {
  532. var tracks = [];
  533. if(this.type == "audio")
  534. {
  535. tracks = this.stream.getAudioTracks();
  536. }
  537. else
  538. {
  539. if(this.stream.ended)
  540. return true;
  541. tracks = this.stream.getVideoTracks();
  542. }
  543. for (var idx = 0; idx < tracks.length; idx++) {
  544. if(tracks[idx].enabled)
  545. return false;
  546. }
  547. return true;
  548. }
  549. LocalStream.prototype.getId = function () {
  550. return this.stream.getTracks()[0].id;
  551. }
  552. module.exports = LocalStream;
  553. },{"../../service/RTC/StreamEventTypes.js":98}],5:[function(require,module,exports){
  554. ////These lines should be uncommented when require works in app.js
  555. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  556. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  557. /**
  558. * Creates a MediaStream object for the given data, session id and ssrc.
  559. * It is a wrapper class for the MediaStream.
  560. *
  561. * @param data the data object from which we obtain the stream,
  562. * the peerjid, etc.
  563. * @param sid the session id
  564. * @param ssrc the ssrc corresponding to this MediaStream
  565. *
  566. * @constructor
  567. */
  568. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  569. // XXX(gp) to minimize headaches in the future, we should build our
  570. // abstractions around tracks and not streams. ORTC is track based API.
  571. // Mozilla expects m-lines to represent media tracks.
  572. //
  573. // Practically, what I'm saying is that we should have a MediaTrack class
  574. // and not a MediaStream class.
  575. //
  576. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  577. // a track might have an associated RTX and FEC sources.
  578. this.sid = sid;
  579. this.stream = data.stream;
  580. this.peerjid = data.peerjid;
  581. this.ssrc = ssrc;
  582. this.type = (this.stream.getVideoTracks().length > 0)?
  583. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  584. this.videoType = null;
  585. this.muted = false;
  586. this.eventEmitter = eventEmitter;
  587. }
  588. MediaStream.prototype.getOriginalStream = function()
  589. {
  590. return this.stream;
  591. };
  592. MediaStream.prototype.setMute = function (value)
  593. {
  594. this.stream.muted = value;
  595. this.muted = value;
  596. };
  597. MediaStream.prototype.setVideoType = function (value) {
  598. if(this.videoType === value)
  599. return;
  600. this.videoType = value;
  601. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  602. this.peerjid);
  603. };
  604. module.exports = MediaStream;
  605. },{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/StreamEventTypes":98}],6:[function(require,module,exports){
  606. var EventEmitter = require("events");
  607. var RTCUtils = require("./RTCUtils.js");
  608. var LocalStream = require("./LocalStream.js");
  609. var DataChannels = require("./DataChannels");
  610. var MediaStream = require("./MediaStream.js");
  611. var DesktopSharingEventTypes
  612. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  613. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  614. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  615. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  616. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  617. var UIEvents = require("../../service/UI/UIEvents");
  618. var eventEmitter = new EventEmitter();
  619. function getMediaStreamUsage()
  620. {
  621. var result = {
  622. audio: true,
  623. video: true
  624. };
  625. /** There are some issues with the desktop sharing
  626. * when this property is enabled.
  627. * WARNING: We must change the implementation to start video/audio if we
  628. * receive from the focus that the peer is not muted.
  629. var isSecureConnection = window.location.protocol == "https:";
  630. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  631. {
  632. result = {
  633. audio: false,
  634. video: false
  635. };
  636. }
  637. **/
  638. return result;
  639. }
  640. var RTC = {
  641. rtcUtils: null,
  642. devices: {
  643. audio: true,
  644. video: true
  645. },
  646. localStreams: [],
  647. remoteStreams: {},
  648. localAudio: null,
  649. localVideo: null,
  650. addStreamListener: function (listener, eventType) {
  651. eventEmitter.on(eventType, listener);
  652. },
  653. addListener: function (type, listener) {
  654. eventEmitter.on(type, listener);
  655. },
  656. removeStreamListener: function (listener, eventType) {
  657. if(!(eventType instanceof StreamEventTypes))
  658. throw "Illegal argument";
  659. eventEmitter.removeListener(eventType, listener);
  660. },
  661. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  662. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  663. //in firefox we have only one stream object
  664. if(this.localStreams.length == 0 ||
  665. this.localStreams[0].getOriginalStream() != stream)
  666. this.localStreams.push(localStream);
  667. if(isMuted === true)
  668. localStream.setMute(false);
  669. if(type == "audio")
  670. {
  671. this.localAudio = localStream;
  672. }
  673. else
  674. {
  675. this.localVideo = localStream;
  676. }
  677. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  678. if(change)
  679. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  680. eventEmitter.emit(eventType, localStream, isMuted);
  681. return localStream;
  682. },
  683. removeLocalStream: function (stream) {
  684. for(var i = 0; i < this.localStreams.length; i++)
  685. {
  686. if(this.localStreams[i].getOriginalStream() === stream) {
  687. delete this.localStreams[i];
  688. return;
  689. }
  690. }
  691. },
  692. createRemoteStream: function (data, sid, thessrc) {
  693. var remoteStream = new MediaStream(data, sid, thessrc,
  694. this.getBrowserType(), eventEmitter);
  695. var jid = data.peerjid || APP.xmpp.myJid();
  696. if(!this.remoteStreams[jid]) {
  697. this.remoteStreams[jid] = {};
  698. }
  699. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  700. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  701. return remoteStream;
  702. },
  703. getBrowserType: function () {
  704. return this.rtcUtils.browser;
  705. },
  706. getPCConstraints: function () {
  707. return this.rtcUtils.pc_constraints;
  708. },
  709. getUserMediaWithConstraints:function(um, success_callback,
  710. failure_callback, resolution,
  711. bandwidth, fps, desktopStream)
  712. {
  713. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  714. failure_callback, resolution, bandwidth, fps, desktopStream);
  715. },
  716. attachMediaStream: function (element, stream) {
  717. this.rtcUtils.attachMediaStream(element, stream);
  718. },
  719. getStreamID: function (stream) {
  720. return this.rtcUtils.getStreamID(stream);
  721. },
  722. getVideoSrc: function (element) {
  723. return this.rtcUtils.getVideoSrc(element);
  724. },
  725. setVideoSrc: function (element, src) {
  726. this.rtcUtils.setVideoSrc(element, src);
  727. },
  728. dispose: function() {
  729. if (this.rtcUtils) {
  730. this.rtcUtils = null;
  731. }
  732. },
  733. stop: function () {
  734. this.dispose();
  735. },
  736. start: function () {
  737. var self = this;
  738. APP.desktopsharing.addListener(
  739. function (stream, isUsingScreenStream, callback) {
  740. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  741. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  742. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  743. for(var i = 0; i < changedStreams.length; i++) {
  744. var type = changedStreams[i].type;
  745. if (type != "audio") {
  746. var peerStreams = self.remoteStreams[jid];
  747. if(!peerStreams)
  748. continue;
  749. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  750. if(!videoStream)
  751. continue;
  752. videoStream.setVideoType(changedStreams[i].type);
  753. }
  754. }
  755. });
  756. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  757. DataChannels.init(event.peerconnection, eventEmitter);
  758. });
  759. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  760. DataChannels.handleSelectedEndpointEvent);
  761. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  762. DataChannels.handlePinnedEndpointEvent);
  763. this.rtcUtils = new RTCUtils(this);
  764. this.rtcUtils.obtainAudioAndVideoPermissions(
  765. null, null, getMediaStreamUsage());
  766. },
  767. muteRemoteVideoStream: function (jid, value) {
  768. var stream;
  769. if(this.remoteStreams[jid] &&
  770. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  771. {
  772. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  773. }
  774. if(!stream)
  775. return true;
  776. if (value != stream.muted) {
  777. stream.setMute(value);
  778. return true;
  779. }
  780. return false;
  781. },
  782. switchVideoStreams: function (new_stream) {
  783. this.localVideo.stream = new_stream;
  784. this.localStreams = [];
  785. //in firefox we have only one stream object
  786. if (this.localAudio.getOriginalStream() != new_stream)
  787. this.localStreams.push(this.localAudio);
  788. this.localStreams.push(this.localVideo);
  789. },
  790. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  791. var oldStream = this.localVideo.getOriginalStream();
  792. var type = (isUsingScreenStream? "screen" : "video");
  793. var localCallback = callback;
  794. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  795. {
  796. localCallback = function() {
  797. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  798. callback();
  799. };
  800. }
  801. var videoStream = this.rtcUtils.createStream(stream, true);
  802. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  803. // Stop the stream to trigger onended event for old stream
  804. oldStream.stop();
  805. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  806. },
  807. changeLocalAudio: function (stream, callback) {
  808. var oldStream = this.localAudio.getOriginalStream();
  809. var newStream = this.rtcUtils.createStream(stream);
  810. this.localAudio = this.createLocalStream(newStream, "audio", true);
  811. // Stop the stream to trigger onended event for old stream
  812. oldStream.stop();
  813. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  814. },
  815. /**
  816. * Checks if video identified by given src is desktop stream.
  817. * @param videoSrc eg.
  818. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  819. * @returns {boolean}
  820. */
  821. isVideoSrcDesktop: function (jid) {
  822. if(!jid)
  823. return false;
  824. var isDesktop = false;
  825. var stream = null;
  826. if (APP.xmpp.myJid() === jid) {
  827. // local video
  828. stream = this.localVideo;
  829. } else {
  830. var peerStreams = this.remoteStreams[jid];
  831. if(!peerStreams)
  832. return false;
  833. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  834. }
  835. if(stream)
  836. isDesktop = (stream.videoType === "screen");
  837. return isDesktop;
  838. },
  839. setVideoMute: function(mute, callback, options) {
  840. if(!this.localVideo)
  841. return;
  842. if (mute == APP.RTC.localVideo.isMuted())
  843. {
  844. APP.xmpp.sendVideoInfoPresence(mute);
  845. if(callback)
  846. callback(mute);
  847. }
  848. else
  849. {
  850. APP.RTC.localVideo.setMute(!mute);
  851. APP.xmpp.setVideoMute(
  852. mute,
  853. callback,
  854. options);
  855. }
  856. },
  857. setDeviceAvailability: function (devices) {
  858. if(!devices)
  859. return;
  860. if(devices.audio === true || devices.audio === false)
  861. this.devices.audio = devices.audio;
  862. if(devices.video === true || devices.video === false)
  863. this.devices.video = devices.video;
  864. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  865. }
  866. };
  867. module.exports = RTC;
  868. },{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/RTCEvents.js":96,"../../service/RTC/StreamEventTypes.js":98,"../../service/UI/UIEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/xmpp/XMPPEvents":105,"./DataChannels":3,"./LocalStream.js":4,"./MediaStream.js":5,"./RTCUtils.js":7,"events":65}],7:[function(require,module,exports){
  869. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  870. var Resolutions = require("../../service/RTC/Resolutions");
  871. var currentResolution = null;
  872. function getPreviousResolution(resolution) {
  873. if(!Resolutions[resolution])
  874. return null;
  875. var order = Resolutions[resolution].order;
  876. var res = null;
  877. var resName = null;
  878. for(var i in Resolutions)
  879. {
  880. var tmp = Resolutions[i];
  881. if(res == null || (res.order < tmp.order && tmp.order < order))
  882. {
  883. resName = i;
  884. res = tmp;
  885. }
  886. }
  887. return resName;
  888. }
  889. function setResolutionConstraints(constraints, resolution, isAndroid)
  890. {
  891. if (resolution && !constraints.video || isAndroid) {
  892. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  893. }
  894. if(Resolutions[resolution])
  895. {
  896. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  897. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  898. }
  899. else
  900. {
  901. if (isAndroid) {
  902. constraints.video.mandatory.minWidth = 320;
  903. constraints.video.mandatory.minHeight = 240;
  904. constraints.video.mandatory.maxFrameRate = 15;
  905. }
  906. }
  907. if (constraints.video.mandatory.minWidth)
  908. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  909. if (constraints.video.mandatory.minHeight)
  910. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  911. }
  912. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  913. {
  914. var constraints = {audio: false, video: false};
  915. if (um.indexOf('video') >= 0) {
  916. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  917. }
  918. if (um.indexOf('audio') >= 0) {
  919. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  920. }
  921. if (um.indexOf('screen') >= 0) {
  922. constraints.video = {
  923. mandatory: {
  924. chromeMediaSource: "screen",
  925. googLeakyBucket: true,
  926. maxWidth: window.screen.width,
  927. maxHeight: window.screen.height,
  928. maxFrameRate: 3
  929. },
  930. optional: []
  931. };
  932. }
  933. if (um.indexOf('desktop') >= 0) {
  934. constraints.video = {
  935. mandatory: {
  936. chromeMediaSource: "desktop",
  937. chromeMediaSourceId: desktopStream,
  938. googLeakyBucket: true,
  939. maxWidth: window.screen.width,
  940. maxHeight: window.screen.height,
  941. maxFrameRate: 3
  942. },
  943. optional: []
  944. };
  945. }
  946. if (constraints.audio) {
  947. // if it is good enough for hangouts...
  948. constraints.audio.optional.push(
  949. {googEchoCancellation: true},
  950. {googAutoGainControl: true},
  951. {googNoiseSupression: true},
  952. {googHighpassFilter: true},
  953. {googNoisesuppression2: true},
  954. {googEchoCancellation2: true},
  955. {googAutoGainControl2: true}
  956. );
  957. }
  958. if (constraints.video) {
  959. constraints.video.optional.push(
  960. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  961. );
  962. if (um.indexOf('video') >= 0) {
  963. constraints.video.optional.push(
  964. {googLeakyBucket: true}
  965. );
  966. }
  967. }
  968. if (um.indexOf('video') >= 0) {
  969. setResolutionConstraints(constraints, resolution, isAndroid);
  970. }
  971. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  972. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  973. constraints.video.optional.push({bandwidth: bandwidth});
  974. }
  975. if (fps) { // for some cameras it might be necessary to request 30fps
  976. // so they choose 30fps mjpg over 10fps yuy2
  977. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  978. constraints.video.mandatory.minFrameRate = fps;
  979. }
  980. return constraints;
  981. }
  982. function RTCUtils(RTCService)
  983. {
  984. this.service = RTCService;
  985. if (navigator.mozGetUserMedia) {
  986. console.log('This appears to be Firefox');
  987. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  988. if (version >= 38
  989. && !config.enableSimulcast && config.useBundle && config.useRtcpMux) {
  990. this.peerconnection = mozRTCPeerConnection;
  991. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  992. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  993. this.pc_constraints = {};
  994. this.attachMediaStream = function (element, stream) {
  995. // srcObject is being standardized and FF will eventually
  996. // support that unprefixed. FF also supports the
  997. // "element.src = URL.createObjectURL(...)" combo, but that
  998. // will be deprecated in favour of srcObject.
  999. //
  1000. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1001. // https://github.com/webrtc/samples/issues/302
  1002. if(!element[0])
  1003. return;
  1004. element[0].mozSrcObject = stream;
  1005. element[0].play();
  1006. };
  1007. this.getStreamID = function (stream) {
  1008. var tracks = stream.getVideoTracks();
  1009. if(!tracks || tracks.length == 0)
  1010. {
  1011. tracks = stream.getAudioTracks();
  1012. }
  1013. return tracks[0].id.replace(/[\{,\}]/g,"");
  1014. };
  1015. this.getVideoSrc = function (element) {
  1016. if(!element)
  1017. return null;
  1018. return element.mozSrcObject;
  1019. };
  1020. this.setVideoSrc = function (element, src) {
  1021. if(element)
  1022. element.mozSrcObject = src;
  1023. };
  1024. RTCSessionDescription = mozRTCSessionDescription;
  1025. RTCIceCandidate = mozRTCIceCandidate;
  1026. } else {
  1027. window.location.href = 'unsupported_browser.html';
  1028. return;
  1029. }
  1030. } else if (navigator.webkitGetUserMedia) {
  1031. console.log('This appears to be Chrome');
  1032. this.peerconnection = webkitRTCPeerConnection;
  1033. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1034. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1035. this.attachMediaStream = function (element, stream) {
  1036. element.attr('src', webkitURL.createObjectURL(stream));
  1037. };
  1038. this.getStreamID = function (stream) {
  1039. // streams from FF endpoints have the characters '{' and '}'
  1040. // that make jQuery choke.
  1041. return stream.id.replace(/[\{,\}]/g,"");
  1042. };
  1043. this.getVideoSrc = function (element) {
  1044. if(!element)
  1045. return null;
  1046. return element.getAttribute("src");
  1047. };
  1048. this.setVideoSrc = function (element, src) {
  1049. if(element)
  1050. element.setAttribute("src", src);
  1051. };
  1052. // DTLS should now be enabled by default but..
  1053. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1054. if (navigator.userAgent.indexOf('Android') != -1) {
  1055. this.pc_constraints = {}; // disable DTLS on Android
  1056. }
  1057. if (!webkitMediaStream.prototype.getVideoTracks) {
  1058. webkitMediaStream.prototype.getVideoTracks = function () {
  1059. return this.videoTracks;
  1060. };
  1061. }
  1062. if (!webkitMediaStream.prototype.getAudioTracks) {
  1063. webkitMediaStream.prototype.getAudioTracks = function () {
  1064. return this.audioTracks;
  1065. };
  1066. }
  1067. }
  1068. else
  1069. {
  1070. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1071. window.location.href = 'unsupported_browser.html';
  1072. return;
  1073. }
  1074. }
  1075. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1076. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1077. desktopStream)
  1078. {
  1079. currentResolution = resolution;
  1080. // Check if we are running on Android device
  1081. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1082. var constraints = getConstraints(
  1083. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1084. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1085. var self = this;
  1086. try {
  1087. if (config.enableSimulcast
  1088. && constraints.video
  1089. && constraints.video.chromeMediaSource !== 'screen'
  1090. && constraints.video.chromeMediaSource !== 'desktop'
  1091. && !isAndroid
  1092. // We currently do not support FF, as it doesn't have multistream support.
  1093. && !isFF) {
  1094. APP.simulcast.getUserMedia(constraints, function (stream) {
  1095. console.log('onUserMediaSuccess');
  1096. self.setAvailableDevices(um, true);
  1097. success_callback(stream);
  1098. },
  1099. function (error) {
  1100. console.warn('Failed to get access to local media. Error ', error);
  1101. self.setAvailableDevices(um, false);
  1102. if (failure_callback) {
  1103. failure_callback(error);
  1104. }
  1105. });
  1106. } else {
  1107. this.getUserMedia(constraints,
  1108. function (stream) {
  1109. console.log('onUserMediaSuccess');
  1110. self.setAvailableDevices(um, true);
  1111. success_callback(stream);
  1112. },
  1113. function (error) {
  1114. self.setAvailableDevices(um, false);
  1115. console.warn('Failed to get access to local media. Error ',
  1116. error, constraints);
  1117. if (failure_callback) {
  1118. failure_callback(error);
  1119. }
  1120. });
  1121. }
  1122. } catch (e) {
  1123. console.error('GUM failed: ', e);
  1124. if(failure_callback) {
  1125. failure_callback(e);
  1126. }
  1127. }
  1128. };
  1129. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1130. var devices = {};
  1131. if(um.indexOf("video") != -1)
  1132. {
  1133. devices.video = available;
  1134. }
  1135. if(um.indexOf("audio") != -1)
  1136. {
  1137. devices.audio = available;
  1138. }
  1139. this.service.setDeviceAvailability(devices);
  1140. }
  1141. /**
  1142. * We ask for audio and video combined stream in order to get permissions and
  1143. * not to ask twice.
  1144. */
  1145. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1146. function(devices, callback, usageOptions)
  1147. {
  1148. var self = this;
  1149. // Get AV
  1150. var successCallback = function (stream) {
  1151. if(callback)
  1152. callback(stream, usageOptions);
  1153. else
  1154. self.successCallback(stream, usageOptions);
  1155. };
  1156. if(!devices)
  1157. devices = ['audio', 'video'];
  1158. var newDevices = [];
  1159. if(usageOptions)
  1160. for(var i = 0; i < devices.length; i++)
  1161. {
  1162. var device = devices[i];
  1163. if(usageOptions[device] === true)
  1164. newDevices.push(device);
  1165. }
  1166. else
  1167. newDevices = devices;
  1168. if(newDevices.length === 0)
  1169. {
  1170. successCallback();
  1171. return;
  1172. }
  1173. if (navigator.mozGetUserMedia) {
  1174. // With FF we can't split the stream into audio and video because FF
  1175. // doesn't support media stream constructors. So, we need to get the
  1176. // audio stream separately from the video stream using two distinct GUM
  1177. // calls. Not very user friendly :-( but we don't have many other
  1178. // options neither.
  1179. //
  1180. // Note that we pack those 2 streams in a single object and pass it to
  1181. // the successCallback method.
  1182. self.getUserMediaWithConstraints(
  1183. ['audio'],
  1184. function (audioStream) {
  1185. self.getUserMediaWithConstraints(
  1186. ['video'],
  1187. function (videoStream) {
  1188. return self.successCallback({
  1189. audioStream: audioStream,
  1190. videoStream: videoStream
  1191. });
  1192. },
  1193. function (error) {
  1194. console.error('failed to obtain video stream - stop',
  1195. error);
  1196. return self.successCallback(null);
  1197. },
  1198. config.resolution || '360');
  1199. },
  1200. function (error) {
  1201. console.error('failed to obtain audio stream - stop',
  1202. error);
  1203. return self.successCallback(null);
  1204. }
  1205. );
  1206. } else {
  1207. this.getUserMediaWithConstraints(
  1208. newDevices,
  1209. function (stream) {
  1210. successCallback(stream);
  1211. },
  1212. function (error) {
  1213. self.errorCallback(error);
  1214. },
  1215. config.resolution || '360');
  1216. }
  1217. }
  1218. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1219. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1220. // an object with two properties: audioStream, videoStream.
  1221. if(stream && !navigator.mozGetUserMedia)
  1222. console.log('got', stream, stream.getAudioTracks().length,
  1223. stream.getVideoTracks().length);
  1224. this.handleLocalStream(stream, usageOptions);
  1225. };
  1226. RTCUtils.prototype.errorCallback = function (error) {
  1227. var self = this;
  1228. console.error('failed to obtain audio/video stream - trying audio only', error);
  1229. var resolution = getPreviousResolution(currentResolution);
  1230. if(typeof error == "object" && error.constraintName && error.name
  1231. && (error.name == "ConstraintNotSatisfiedError" ||
  1232. error.name == "OverconstrainedError") &&
  1233. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1234. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1235. && resolution != null)
  1236. {
  1237. self.getUserMediaWithConstraints(['audio', 'video'],
  1238. function (stream) {
  1239. return self.successCallback(stream);
  1240. }, function (error) {
  1241. return self.errorCallback(error);
  1242. }, resolution);
  1243. }
  1244. else
  1245. {
  1246. self.getUserMediaWithConstraints(
  1247. ['audio'],
  1248. function (stream) {
  1249. return self.successCallback(stream);
  1250. },
  1251. function (error) {
  1252. console.error('failed to obtain audio/video stream - stop',
  1253. error);
  1254. return self.successCallback(null);
  1255. }
  1256. );
  1257. }
  1258. }
  1259. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1260. {
  1261. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1262. // an object with two properties: audioStream, videoStream.
  1263. var audioStream, videoStream;
  1264. if(window.webkitMediaStream)
  1265. {
  1266. audioStream = new webkitMediaStream();
  1267. videoStream = new webkitMediaStream();
  1268. if(stream) {
  1269. var audioTracks = stream.getAudioTracks();
  1270. for (var i = 0; i < audioTracks.length; i++) {
  1271. audioStream.addTrack(audioTracks[i]);
  1272. }
  1273. var videoTracks = stream.getVideoTracks();
  1274. for (i = 0; i < videoTracks.length; i++) {
  1275. videoStream.addTrack(videoTracks[i]);
  1276. }
  1277. }
  1278. }
  1279. else
  1280. {//firefox
  1281. audioStream = stream.audioStream;
  1282. videoStream = stream.videoStream;
  1283. }
  1284. var audioMuted = (usageOptions && usageOptions.audio === false),
  1285. videoMuted = (usageOptions && usageOptions.video === false);
  1286. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1287. videoGUM = (!usageOptions || usageOptions.video !== false);
  1288. this.service.createLocalStream(audioStream, "audio", null, null,
  1289. audioMuted, audioGUM);
  1290. this.service.createLocalStream(videoStream, "video", null, null,
  1291. videoMuted, videoGUM);
  1292. };
  1293. RTCUtils.prototype.createStream = function(stream, isVideo)
  1294. {
  1295. var newStream = null;
  1296. if(window.webkitMediaStream)
  1297. {
  1298. newStream = new webkitMediaStream();
  1299. if(newStream)
  1300. {
  1301. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  1302. for (i = 0; i < tracks.length; i++) {
  1303. newStream.addTrack(tracks[i]);
  1304. }
  1305. }
  1306. }
  1307. else
  1308. newStream = stream;
  1309. return newStream;
  1310. };
  1311. module.exports = RTCUtils;
  1312. },{"../../service/RTC/RTCBrowserType.js":95,"../../service/RTC/Resolutions":97}],8:[function(require,module,exports){
  1313. var UI = {};
  1314. var VideoLayout = require("./videolayout/VideoLayout.js");
  1315. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1316. var Prezi = require("./prezi/Prezi.js");
  1317. var Etherpad = require("./etherpad/Etherpad.js");
  1318. var Chat = require("./side_pannels/chat/Chat.js");
  1319. var Toolbar = require("./toolbars/Toolbar");
  1320. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1321. var BottomToolbar = require("./toolbars/BottomToolbar");
  1322. var ContactList = require("./side_pannels/contactlist/ContactList");
  1323. var Avatar = require("./avatar/Avatar");
  1324. var EventEmitter = require("events");
  1325. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1326. var Settings = require("./../settings/Settings");
  1327. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1328. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1329. UI.messageHandler = require("./util/MessageHandler");
  1330. var messageHandler = UI.messageHandler;
  1331. var Authentication = require("./authentication/Authentication");
  1332. var UIUtil = require("./util/UIUtil");
  1333. var NicknameHandler = require("./util/NicknameHandler");
  1334. var CQEvents = require("../../service/connectionquality/CQEvents");
  1335. var DesktopSharingEventTypes
  1336. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1337. var RTCEvents = require("../../service/RTC/RTCEvents");
  1338. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1339. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1340. var MemberEvents = require("../../service/members/Events");
  1341. var eventEmitter = new EventEmitter();
  1342. var roomName = null;
  1343. function notifyForInitialMute()
  1344. {
  1345. messageHandler.notify(null, "notify.mutedTitle", "connected",
  1346. "notify.muted", null, {timeOut: 120000});
  1347. }
  1348. function setupPrezi()
  1349. {
  1350. $("#reloadPresentationLink").click(function()
  1351. {
  1352. Prezi.reloadPresentation();
  1353. });
  1354. }
  1355. function setupChat()
  1356. {
  1357. Chat.init();
  1358. $("#toggle_smileys").click(function() {
  1359. Chat.toggleSmileys();
  1360. });
  1361. }
  1362. function setupToolbars() {
  1363. Toolbar.init(UI);
  1364. Toolbar.setupButtonsFromConfig();
  1365. BottomToolbar.init();
  1366. }
  1367. function streamHandler(stream, isMuted) {
  1368. switch (stream.type)
  1369. {
  1370. case "audio":
  1371. VideoLayout.changeLocalAudio(stream, isMuted);
  1372. break;
  1373. case "video":
  1374. VideoLayout.changeLocalVideo(stream, isMuted);
  1375. break;
  1376. case "stream":
  1377. VideoLayout.changeLocalStream(stream, isMuted);
  1378. break;
  1379. }
  1380. }
  1381. function onXmppConnectionFailed(stropheErrorMsg) {
  1382. var title = APP.translation.generateTranslatonHTML(
  1383. "dialog.error");
  1384. var message;
  1385. if (stropheErrorMsg) {
  1386. message = APP.translation.generateTranslatonHTML(
  1387. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  1388. } else {
  1389. message = APP.translation.generateTranslatonHTML(
  1390. "dialog.connectError");
  1391. }
  1392. messageHandler.openDialog(
  1393. title, message, true, {}, function (e, v, m, f) { return false; });
  1394. }
  1395. function onDisposeConference(unload) {
  1396. Toolbar.showAuthenticateButton(false);
  1397. }
  1398. function onDisplayNameChanged(jid, displayName) {
  1399. ContactList.onDisplayNameChange(jid, displayName);
  1400. SettingsMenu.onDisplayNameChange(jid, displayName);
  1401. VideoLayout.onDisplayNameChanged(jid, displayName);
  1402. }
  1403. function registerListeners() {
  1404. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1405. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1406. APP.RTC.addStreamListener(function (stream) {
  1407. VideoLayout.onRemoteStreamAdded(stream);
  1408. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1409. APP.RTC.addStreamListener(function (jid) {
  1410. VideoLayout.onVideoTypeChanged(jid);
  1411. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1412. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1413. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1414. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1415. });
  1416. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1417. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1418. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1419. endpointsEnteringLastN, stream);
  1420. });
  1421. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1422. function (endpointSimulcastLayers) {
  1423. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1424. });
  1425. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1426. function (endpointSimulcastLayers) {
  1427. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1428. });
  1429. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1430. function (devices) {
  1431. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1432. })
  1433. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1434. {
  1435. var resourceJid;
  1436. if(jid === APP.statistics.LOCAL_JID)
  1437. {
  1438. resourceJid = AudioLevels.LOCAL_LEVEL;
  1439. if(APP.RTC.localAudio.isMuted())
  1440. {
  1441. audioLevel = 0;
  1442. }
  1443. }
  1444. else
  1445. {
  1446. resourceJid = Strophe.getResourceFromJid(jid);
  1447. }
  1448. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1449. UI.getLargeVideoState().userResourceJid);
  1450. });
  1451. APP.desktopsharing.addListener(function () {
  1452. ToolbarToggler.showDesktopSharingButton();
  1453. }, DesktopSharingEventTypes.INIT);
  1454. APP.desktopsharing.addListener(
  1455. Toolbar.changeDesktopSharingButtonState,
  1456. DesktopSharingEventTypes.SWITCHING_DONE);
  1457. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1458. VideoLayout.updateLocalConnectionStats);
  1459. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1460. VideoLayout.updateConnectionStats);
  1461. APP.connectionquality.addListener(CQEvents.STOP,
  1462. VideoLayout.onStatsStop);
  1463. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  1464. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1465. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1466. messageHandler.openMessageDialog(
  1467. 'dialog.serviceUnavailable',
  1468. 'dialog.gracefulShutdown'
  1469. );
  1470. });
  1471. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1472. var title = APP.translation.generateTranslatonHTML(
  1473. "dialog.reservationError");
  1474. var message = APP.translation.generateTranslatonHTML(
  1475. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1476. messageHandler.openDialog(
  1477. title,
  1478. message,
  1479. true, {},
  1480. function (event, value, message, formVals)
  1481. {
  1482. return false;
  1483. }
  1484. );
  1485. });
  1486. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1487. messageHandler.openMessageDialog("dialog.sessTerminated",
  1488. "dialog.kickMessage");
  1489. });
  1490. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1491. //FIXME: use Session Terminated from translation, but
  1492. // 'reason' text comes from XMPP packet and is not translated
  1493. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1494. messageHandler.openDialog(
  1495. title, reason, true, {},
  1496. function (event, value, message, formVals)
  1497. {
  1498. return false;
  1499. }
  1500. );
  1501. });
  1502. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1503. messageHandler.showError("dialog.error",
  1504. "dialog.bridgeUnavailable");
  1505. });
  1506. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1507. Avatar.setUserAvatar(from, id);
  1508. });
  1509. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1510. for(stream in changedStreams)
  1511. {
  1512. // might need to update the direction if participant just went from sendrecv to recvonly
  1513. if (stream.type === 'video' || stream.type === 'screen') {
  1514. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1515. switch (stream.direction) {
  1516. case 'sendrecv':
  1517. el.show();
  1518. break;
  1519. case 'recvonly':
  1520. el.hide();
  1521. // FIXME: Check if we have to change large video
  1522. //VideoLayout.updateLargeVideo(el);
  1523. break;
  1524. }
  1525. }
  1526. }
  1527. });
  1528. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1529. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1530. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1531. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1532. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1533. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1534. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1535. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1536. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1537. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1538. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1539. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1540. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1541. onAuthenticationRequired);
  1542. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1543. function (resource, devices) {
  1544. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1545. });
  1546. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1547. onDtmfSupportChanged);
  1548. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  1549. SettingsMenu.setStartMuted(audio, video);
  1550. });
  1551. }
  1552. /**
  1553. * Mutes/unmutes the local video.
  1554. *
  1555. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1556. * @param options an object which specifies optional arguments such as the
  1557. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1558. * specifies whether the method was initiated in response to a user command (in
  1559. * contrast to an automatic decision taken by the application logic)
  1560. */
  1561. function setVideoMute(mute, options) {
  1562. APP.RTC.setVideoMute(mute,
  1563. UI.setVideoMuteButtonsState,
  1564. options);
  1565. }
  1566. function bindEvents()
  1567. {
  1568. /**
  1569. * Resizes and repositions videos in full screen mode.
  1570. */
  1571. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1572. function () {
  1573. VideoLayout.resizeLargeVideoContainer();
  1574. VideoLayout.positionLarge();
  1575. }
  1576. );
  1577. $(window).resize(function () {
  1578. VideoLayout.resizeLargeVideoContainer();
  1579. VideoLayout.positionLarge();
  1580. });
  1581. }
  1582. UI.start = function (init) {
  1583. document.title = interfaceConfig.APP_NAME;
  1584. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1585. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1586. {
  1587. $("#videoconference_page").hide();
  1588. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1589. setupWelcomePage();
  1590. return;
  1591. }
  1592. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1593. var leftWatermarkDiv
  1594. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1595. leftWatermarkDiv.css({display: 'block'});
  1596. leftWatermarkDiv.parent().get(0).href
  1597. = interfaceConfig.JITSI_WATERMARK_LINK;
  1598. }
  1599. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1600. var rightWatermarkDiv
  1601. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1602. rightWatermarkDiv.css({display: 'block'});
  1603. rightWatermarkDiv.parent().get(0).href
  1604. = interfaceConfig.BRAND_WATERMARK_LINK;
  1605. rightWatermarkDiv.get(0).style.backgroundImage
  1606. = "url(images/rightwatermark.png)";
  1607. }
  1608. if (interfaceConfig.SHOW_POWERED_BY) {
  1609. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1610. }
  1611. $("#welcome_page").hide();
  1612. VideoLayout.resizeLargeVideoContainer();
  1613. $("#videospace").mousemove(function () {
  1614. return ToolbarToggler.showToolbar();
  1615. });
  1616. // Set the defaults for prompt dialogs.
  1617. jQuery.prompt.setDefaults({persistent: false});
  1618. VideoLayout.init(eventEmitter);
  1619. AudioLevels.init();
  1620. NicknameHandler.init(eventEmitter);
  1621. registerListeners();
  1622. bindEvents();
  1623. setupPrezi();
  1624. setupToolbars();
  1625. setupChat();
  1626. document.title = interfaceConfig.APP_NAME;
  1627. $("#downloadlog").click(function (event) {
  1628. dump(event.target);
  1629. });
  1630. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1631. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1632. {
  1633. $("#videoconference_page").hide();
  1634. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1635. setupWelcomePage();
  1636. return;
  1637. }
  1638. $("#welcome_page").hide();
  1639. // Display notice message at the top of the toolbar
  1640. if (config.noticeMessage) {
  1641. $('#noticeText').text(config.noticeMessage);
  1642. $('#notice').css({display: 'block'});
  1643. }
  1644. document.getElementById('largeVideo').volume = 0;
  1645. if (!$('#settings').is(':visible')) {
  1646. console.log('init');
  1647. init();
  1648. } else {
  1649. loginInfo.onsubmit = function (e) {
  1650. if (e.preventDefault) e.preventDefault();
  1651. $('#settings').hide();
  1652. init();
  1653. };
  1654. }
  1655. toastr.options = {
  1656. "closeButton": true,
  1657. "debug": false,
  1658. "positionClass": "notification-bottom-right",
  1659. "onclick": null,
  1660. "showDuration": "300",
  1661. "hideDuration": "1000",
  1662. "timeOut": "2000",
  1663. "extendedTimeOut": "1000",
  1664. "showEasing": "swing",
  1665. "hideEasing": "linear",
  1666. "showMethod": "fadeIn",
  1667. "hideMethod": "fadeOut",
  1668. "reposition": function() {
  1669. if(PanelToggler.isVisible()) {
  1670. $("#toast-container").addClass("notification-bottom-right-center");
  1671. } else {
  1672. $("#toast-container").removeClass("notification-bottom-right-center");
  1673. }
  1674. },
  1675. "newestOnTop": false
  1676. };
  1677. SettingsMenu.init();
  1678. };
  1679. function chatAddError(errorMessage, originalText)
  1680. {
  1681. return Chat.chatAddError(errorMessage, originalText);
  1682. };
  1683. function chatSetSubject(text)
  1684. {
  1685. return Chat.chatSetSubject(text);
  1686. };
  1687. function updateChatConversation(from, displayName, message) {
  1688. return Chat.updateChatConversation(from, displayName, message);
  1689. };
  1690. function onMucJoined(jid, info) {
  1691. Toolbar.updateRoomUrl(window.location.href);
  1692. var meHTML = APP.translation.generateTranslatonHTML("me");
  1693. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1694. var settings = Settings.getSettings();
  1695. // Add myself to the contact list.
  1696. ContactList.addContact(jid, settings.email || settings.uid);
  1697. // Once we've joined the muc show the toolbar
  1698. ToolbarToggler.showToolbar();
  1699. var displayName = !config.displayJids
  1700. ? info.displayName : Strophe.getResourceFromJid(jid);
  1701. if (displayName)
  1702. onDisplayNameChanged('localVideoContainer', displayName);
  1703. VideoLayout.mucJoined();
  1704. }
  1705. function initEtherpad(name) {
  1706. Etherpad.init(name);
  1707. };
  1708. function onMucMemberLeft(jid) {
  1709. console.log('left.muc', jid);
  1710. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1711. '>.displayname').html();
  1712. messageHandler.notify(displayName,'notify.somebody',
  1713. 'disconnected',
  1714. 'notify.disconnected');
  1715. // Need to call this with a slight delay, otherwise the element couldn't be
  1716. // found for some reason.
  1717. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1718. window.setTimeout(function () {
  1719. var container = document.getElementById(
  1720. 'participant_' + Strophe.getResourceFromJid(jid));
  1721. if (container) {
  1722. ContactList.removeContact(jid);
  1723. VideoLayout.removeConnectionIndicator(jid);
  1724. // hide here, wait for video to close before removing
  1725. $(container).hide();
  1726. VideoLayout.resizeThumbnails();
  1727. }
  1728. }, 10);
  1729. VideoLayout.participantLeft(jid);
  1730. };
  1731. function onLocalRoleChanged(jid, info, pres, isModerator)
  1732. {
  1733. console.info("My role changed, new role: " + info.role);
  1734. onModeratorStatusChanged(isModerator);
  1735. VideoLayout.showModeratorIndicator();
  1736. SettingsMenu.onRoleChanged();
  1737. if (isModerator) {
  1738. Authentication.closeAuthenticationWindow();
  1739. messageHandler.notify(null, "notify.me",
  1740. 'connected', "notify.moderator");
  1741. }
  1742. }
  1743. function onModeratorStatusChanged(isModerator) {
  1744. Toolbar.showSipCallButton(isModerator);
  1745. Toolbar.showRecordingButton(
  1746. isModerator); //&&
  1747. // FIXME:
  1748. // Recording visible if
  1749. // there are at least 2(+ 1 focus) participants
  1750. //Object.keys(connection.emuc.members).length >= 3);
  1751. if (isModerator && config.etherpad_base) {
  1752. Etherpad.init();
  1753. }
  1754. };
  1755. function onPasswordRequired(callback) {
  1756. // password is required
  1757. Toolbar.lockLockButton();
  1758. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1759. message += APP.translation.translateString(
  1760. "dialog.passwordRequired");
  1761. message += '</h2>' +
  1762. '<input name="lockKey" type="text" data-i18n=' +
  1763. '"[placeholder]dialog.password" placeholder="' +
  1764. APP.translation.translateString("dialog.password") +
  1765. '" autofocus>';
  1766. messageHandler.openTwoButtonDialog(null, null, null, message,
  1767. true,
  1768. "dialog.Ok",
  1769. function (e, v, m, f) {},
  1770. null,
  1771. function (e, v, m, f) {
  1772. if (v) {
  1773. var lockKey = f.lockKey;
  1774. if (lockKey) {
  1775. Toolbar.setSharedKey(lockKey);
  1776. callback(lockKey);
  1777. }
  1778. }
  1779. },
  1780. ':input:first'
  1781. );
  1782. }
  1783. /**
  1784. * The dialpad button is shown iff there is at least one member that supports
  1785. * DTMF (e.g. jigasi).
  1786. */
  1787. function onDtmfSupportChanged(dtmfSupport) {
  1788. //TODO: enable when the UI is ready
  1789. //Toolbar.showDialPadButton(dtmfSupport);
  1790. }
  1791. function onMucMemberJoined(jid, id, displayName) {
  1792. messageHandler.notify(displayName,'notify.somebody',
  1793. 'connected',
  1794. 'notify.connected');
  1795. // Add Peer's container
  1796. VideoLayout.ensurePeerContainerExists(jid,id);
  1797. }
  1798. function onMucPresenceStatus( jid, info) {
  1799. VideoLayout.setPresenceStatus(
  1800. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1801. }
  1802. function onMucRoleChanged(role, displayName) {
  1803. VideoLayout.showModeratorIndicator();
  1804. if (role === 'moderator') {
  1805. var messageKey, messageOptions = {};
  1806. if (!displayName) {
  1807. messageKey = "notify.grantedToUnknown";
  1808. }
  1809. else
  1810. {
  1811. messageKey = "notify.grantedTo";
  1812. messageOptions = {to: displayName};
  1813. }
  1814. messageHandler.notify(
  1815. displayName,'notify.somebody',
  1816. 'connected', messageKey,
  1817. messageOptions);
  1818. }
  1819. }
  1820. function onAuthenticationRequired(intervalCallback) {
  1821. Authentication.openAuthenticationDialog(
  1822. roomName, intervalCallback, function () {
  1823. Toolbar.authenticateClicked();
  1824. });
  1825. };
  1826. function onLastNChanged(oldValue, newValue) {
  1827. if (config.muteLocalVideoIfNotInLastN) {
  1828. setVideoMute(!newValue, { 'byUser': false });
  1829. }
  1830. }
  1831. UI.toggleSmileys = function () {
  1832. Chat.toggleSmileys();
  1833. };
  1834. UI.getSettings = function () {
  1835. return Settings.getSettings();
  1836. };
  1837. UI.toggleFilmStrip = function () {
  1838. return BottomToolbar.toggleFilmStrip();
  1839. };
  1840. UI.toggleChat = function () {
  1841. return BottomToolbar.toggleChat();
  1842. };
  1843. UI.toggleContactList = function () {
  1844. return BottomToolbar.toggleContactList();
  1845. };
  1846. UI.inputDisplayNameHandler = function (value) {
  1847. VideoLayout.inputDisplayNameHandler(value);
  1848. };
  1849. UI.getLargeVideoState = function()
  1850. {
  1851. return VideoLayout.getLargeVideoState();
  1852. };
  1853. UI.generateRoomName = function() {
  1854. if(roomName)
  1855. return roomName;
  1856. var roomnode = null;
  1857. var path = window.location.pathname;
  1858. // determinde the room node from the url
  1859. // TODO: just the roomnode or the whole bare jid?
  1860. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1861. // custom function might be responsible for doing the pushstate
  1862. roomnode = config.getroomnode(path);
  1863. } else {
  1864. /* fall back to default strategy
  1865. * this is making assumptions about how the URL->room mapping happens.
  1866. * It currently assumes deployment at root, with a rewrite like the
  1867. * following one (for nginx):
  1868. location ~ ^/([a-zA-Z0-9]+)$ {
  1869. rewrite ^/(.*)$ / break;
  1870. }
  1871. */
  1872. if (path.length > 1) {
  1873. roomnode = path.substr(1).toLowerCase();
  1874. } else {
  1875. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1876. roomnode = word.toLowerCase();
  1877. window.history.pushState('VideoChat',
  1878. 'Room: ' + word, window.location.pathname + word);
  1879. }
  1880. }
  1881. roomName = roomnode + '@' + config.hosts.muc;
  1882. return roomName;
  1883. };
  1884. UI.connectionIndicatorShowMore = function(id)
  1885. {
  1886. return VideoLayout.connectionIndicators[id].showMore();
  1887. };
  1888. UI.showLoginPopup = function(callback)
  1889. {
  1890. console.log('password is required');
  1891. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1892. message += APP.translation.translateString(
  1893. "dialog.passwordRequired");
  1894. message += '</h2>' +
  1895. '<input name="username" type="text" ' +
  1896. 'placeholder="user@domain.net" autofocus>' +
  1897. '<input name="password" ' +
  1898. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1899. ' placeholder="user password">';
  1900. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1901. true,
  1902. "dialog.Ok",
  1903. function (e, v, m, f) {
  1904. if (v) {
  1905. if (f.username !== null && f.password != null) {
  1906. callback(f.username, f.password);
  1907. }
  1908. }
  1909. },
  1910. null, null, ':input:first'
  1911. );
  1912. }
  1913. UI.checkForNicknameAndJoin = function () {
  1914. Authentication.closeAuthenticationDialog();
  1915. Authentication.stopInterval();
  1916. var nick = null;
  1917. if (config.useNicks) {
  1918. nick = window.prompt('Your nickname (optional)');
  1919. }
  1920. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1921. };
  1922. function dump(elem, filename) {
  1923. elem = elem.parentNode;
  1924. elem.download = filename || 'meetlog.json';
  1925. elem.href = 'data:application/json;charset=utf-8,\n';
  1926. var data = APP.xmpp.populateData();
  1927. var metadata = {};
  1928. metadata.time = new Date();
  1929. metadata.url = window.location.href;
  1930. metadata.ua = navigator.userAgent;
  1931. var log = APP.xmpp.getLogger();
  1932. if (log) {
  1933. metadata.xmpp = log;
  1934. }
  1935. data.metadata = metadata;
  1936. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1937. return false;
  1938. }
  1939. UI.getRoomName = function () {
  1940. return roomName;
  1941. };
  1942. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  1943. if(muteAudio || muteVideo) notifyForInitialMute();
  1944. if(muteAudio) UI.setAudioMuted(true);
  1945. if(muteVideo) UI.setVideoMute(true);
  1946. }
  1947. /**
  1948. * Mutes/unmutes the local video.
  1949. */
  1950. UI.toggleVideo = function () {
  1951. setVideoMute(!APP.RTC.localVideo.isMuted());
  1952. };
  1953. /**
  1954. * Mutes / unmutes audio for the local participant.
  1955. */
  1956. UI.toggleAudio = function() {
  1957. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1958. };
  1959. /**
  1960. * Sets muted audio state for the local participant.
  1961. */
  1962. UI.setAudioMuted = function (mute, earlyMute) {
  1963. var audioMute = null;
  1964. if(earlyMute)
  1965. audioMute = function (mute, cb) {
  1966. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  1967. };
  1968. else
  1969. audioMute = function (mute, cb) {
  1970. return APP.xmpp.setAudioMute(mute, cb);
  1971. }
  1972. if(!audioMute(mute, function () {
  1973. VideoLayout.showLocalAudioIndicator(mute);
  1974. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1975. }))
  1976. {
  1977. // We still click the button.
  1978. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1979. return;
  1980. }
  1981. }
  1982. UI.addListener = function (type, listener) {
  1983. eventEmitter.on(type, listener);
  1984. }
  1985. UI.clickOnVideo = function (videoNumber) {
  1986. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1987. if (remoteVideos.length > videoNumber) {
  1988. remoteVideos[videoNumber].click();
  1989. }
  1990. }
  1991. //Used by torture
  1992. UI.showToolbar = function () {
  1993. return ToolbarToggler.showToolbar();
  1994. }
  1995. //Used by torture
  1996. UI.dockToolbar = function (isDock) {
  1997. return ToolbarToggler.dockToolbar(isDock);
  1998. }
  1999. UI.setVideoMuteButtonsState = function (mute) {
  2000. var video = $('#video');
  2001. var communicativeClass = "icon-camera";
  2002. var muteClass = "icon-camera icon-camera-disabled";
  2003. if (mute) {
  2004. video.removeClass(communicativeClass);
  2005. video.addClass(muteClass);
  2006. } else {
  2007. video.removeClass(muteClass);
  2008. video.addClass(communicativeClass);
  2009. }
  2010. }
  2011. UI.setVideoMute = setVideoMute;
  2012. module.exports = UI;
  2013. },{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/connectionquality/CQEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"./../settings/Settings":39,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":13,"./etherpad/Etherpad.js":14,"./prezi/Prezi.js":15,"./side_pannels/SidePanelToggler":17,"./side_pannels/chat/Chat.js":18,"./side_pannels/contactlist/ContactList":22,"./side_pannels/settings/SettingsMenu":23,"./toolbars/BottomToolbar":24,"./toolbars/Toolbar":25,"./toolbars/ToolbarToggler":26,"./util/MessageHandler":28,"./util/NicknameHandler":29,"./util/UIUtil":30,"./videolayout/VideoLayout.js":32,"./welcome_page/RoomnameGenerator":33,"./welcome_page/WelcomePage":34,"events":65}],9:[function(require,module,exports){
  2014. var CanvasUtil = require("./CanvasUtils");
  2015. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2016. function initActiveSpeakerAudioLevels() {
  2017. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2018. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2019. // Draw a circle.
  2020. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2021. // Add a shadow around the circle
  2022. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2023. ASDrawContext.shadowOffsetX = 0;
  2024. ASDrawContext.shadowOffsetY = 0;
  2025. }
  2026. /**
  2027. * The audio Levels plugin.
  2028. */
  2029. var AudioLevels = (function(my) {
  2030. var audioLevelCanvasCache = {};
  2031. my.LOCAL_LEVEL = 'local';
  2032. my.init = function () {
  2033. initActiveSpeakerAudioLevels();
  2034. }
  2035. /**
  2036. * Updates the audio level canvas for the given peerJid. If the canvas
  2037. * didn't exist we create it.
  2038. */
  2039. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2040. var resourceJid = null;
  2041. var videoSpanId = null;
  2042. if (!peerJid)
  2043. videoSpanId = 'localVideoContainer';
  2044. else {
  2045. resourceJid = Strophe.getResourceFromJid(peerJid);
  2046. videoSpanId = 'participant_' + resourceJid;
  2047. }
  2048. var videoSpan = document.getElementById(videoSpanId);
  2049. if (!videoSpan) {
  2050. if (resourceJid)
  2051. console.error("No video element for jid", resourceJid);
  2052. else
  2053. console.error("No video element for local video.");
  2054. return;
  2055. }
  2056. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2057. var videoSpaceWidth = $('#remoteVideos').width();
  2058. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2059. var thumbnailWidth = thumbnailSize[0];
  2060. var thumbnailHeight = thumbnailSize[1];
  2061. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2062. audioLevelCanvas = document.createElement('canvas');
  2063. audioLevelCanvas.className = "audiolevel";
  2064. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2065. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2066. resizeAudioLevelCanvas( audioLevelCanvas,
  2067. thumbnailWidth,
  2068. thumbnailHeight);
  2069. videoSpan.appendChild(audioLevelCanvas);
  2070. } else {
  2071. audioLevelCanvas = audioLevelCanvas.get(0);
  2072. resizeAudioLevelCanvas( audioLevelCanvas,
  2073. thumbnailWidth,
  2074. thumbnailHeight);
  2075. }
  2076. };
  2077. /**
  2078. * Updates the audio level UI for the given resourceJid.
  2079. *
  2080. * @param resourceJid the resource jid indicating the video element for
  2081. * which we draw the audio level
  2082. * @param audioLevel the newAudio level to render
  2083. */
  2084. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2085. drawAudioLevelCanvas(resourceJid, audioLevel);
  2086. var videoSpanId = getVideoSpanId(resourceJid);
  2087. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2088. if (!audioLevelCanvas)
  2089. return;
  2090. var drawContext = audioLevelCanvas.getContext('2d');
  2091. var canvasCache = audioLevelCanvasCache[resourceJid];
  2092. drawContext.clearRect (0, 0,
  2093. audioLevelCanvas.width, audioLevelCanvas.height);
  2094. drawContext.drawImage(canvasCache, 0, 0);
  2095. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2096. if(!APP.xmpp.myJid()) {
  2097. return;
  2098. }
  2099. resourceJid = APP.xmpp.myResource();
  2100. }
  2101. if(resourceJid === largeVideoResourceJid) {
  2102. window.requestAnimationFrame(function () {
  2103. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2104. });
  2105. }
  2106. };
  2107. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2108. if($("#activeSpeaker").css("visibility") == "hidden")
  2109. return;
  2110. ASDrawContext.clearRect(0, 0, 300, 300);
  2111. if(audioLevel == 0)
  2112. return;
  2113. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2114. // Fill the shape.
  2115. ASDrawContext.fill();
  2116. };
  2117. /**
  2118. * Resizes the given audio level canvas to match the given thumbnail size.
  2119. */
  2120. function resizeAudioLevelCanvas(audioLevelCanvas,
  2121. thumbnailWidth,
  2122. thumbnailHeight) {
  2123. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2124. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2125. }
  2126. /**
  2127. * Draws the audio level canvas into the cached canvas object.
  2128. *
  2129. * @param resourceJid the resource jid indicating the video element for
  2130. * which we draw the audio level
  2131. * @param audioLevel the newAudio level to render
  2132. */
  2133. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2134. if (!audioLevelCanvasCache[resourceJid]) {
  2135. var videoSpanId = getVideoSpanId(resourceJid);
  2136. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2137. /*
  2138. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2139. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2140. * error. Since audio levels are frequently updated, the errors have
  2141. * been observed to pile into the console, strain the CPU.
  2142. */
  2143. if (audioLevelCanvasOrig)
  2144. {
  2145. audioLevelCanvasCache[resourceJid]
  2146. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2147. }
  2148. }
  2149. var canvas = audioLevelCanvasCache[resourceJid];
  2150. if (!canvas)
  2151. return;
  2152. var drawContext = canvas.getContext('2d');
  2153. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2154. var shadowLevel = getShadowLevel(audioLevel);
  2155. if (shadowLevel > 0)
  2156. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2157. CanvasUtil.drawRoundRectGlow( drawContext,
  2158. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2159. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2160. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2161. interfaceConfig.CANVAS_RADIUS,
  2162. interfaceConfig.SHADOW_COLOR,
  2163. shadowLevel);
  2164. }
  2165. /**
  2166. * Returns the shadow/glow level for the given audio level.
  2167. *
  2168. * @param audioLevel the audio level from which we determine the shadow
  2169. * level
  2170. */
  2171. function getShadowLevel (audioLevel) {
  2172. var shadowLevel = 0;
  2173. if (audioLevel <= 0.3) {
  2174. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2175. }
  2176. else if (audioLevel <= 0.6) {
  2177. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2178. }
  2179. else {
  2180. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2181. }
  2182. return shadowLevel;
  2183. }
  2184. /**
  2185. * Returns the video span id corresponding to the given resourceJid or local
  2186. * user.
  2187. */
  2188. function getVideoSpanId(resourceJid) {
  2189. var videoSpanId = null;
  2190. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2191. || (APP.xmpp.myResource() && resourceJid
  2192. === APP.xmpp.myResource()))
  2193. videoSpanId = 'localVideoContainer';
  2194. else
  2195. videoSpanId = 'participant_' + resourceJid;
  2196. return videoSpanId;
  2197. }
  2198. /**
  2199. * Indicates that the remote video has been resized.
  2200. */
  2201. $(document).bind('remotevideo.resized', function (event, width, height) {
  2202. var resized = false;
  2203. $('#remoteVideos>span>canvas').each(function() {
  2204. var canvas = $(this).get(0);
  2205. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2206. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2207. resized = true;
  2208. }
  2209. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2210. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2211. resized = true;
  2212. }
  2213. });
  2214. if (resized)
  2215. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2216. audioLevelCanvasCache[resourceJid].width
  2217. = width + interfaceConfig.CANVAS_EXTRA;
  2218. audioLevelCanvasCache[resourceJid].height
  2219. = height + interfaceConfig.CANVAS_EXTRA;
  2220. });
  2221. });
  2222. return my;
  2223. })(AudioLevels || {});
  2224. module.exports = AudioLevels;
  2225. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  2226. /**
  2227. * Utility class for drawing canvas shapes.
  2228. */
  2229. var CanvasUtil = (function(my) {
  2230. /**
  2231. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2232. * of the glow.
  2233. *
  2234. * @param drawContext the context of the canvas to draw to
  2235. * @param x the x coordinate of the round rectangle
  2236. * @param y the y coordinate of the round rectangle
  2237. * @param w the width of the round rectangle
  2238. * @param h the height of the round rectangle
  2239. * @param glowColor the color of the glow
  2240. * @param glowWidth the width of the glow
  2241. */
  2242. my.drawRoundRectGlow
  2243. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2244. // Save the previous state of the context.
  2245. drawContext.save();
  2246. if (w < 2 * r) r = w / 2;
  2247. if (h < 2 * r) r = h / 2;
  2248. // Draw a round rectangle.
  2249. drawContext.beginPath();
  2250. drawContext.moveTo(x+r, y);
  2251. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2252. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2253. drawContext.arcTo(x, y+h, x, y, r);
  2254. drawContext.arcTo(x, y, x+w, y, r);
  2255. drawContext.closePath();
  2256. // Add a shadow around the rectangle
  2257. drawContext.shadowColor = glowColor;
  2258. drawContext.shadowBlur = glowWidth;
  2259. drawContext.shadowOffsetX = 0;
  2260. drawContext.shadowOffsetY = 0;
  2261. // Fill the shape.
  2262. drawContext.fill();
  2263. drawContext.save();
  2264. drawContext.restore();
  2265. // 1) Uncomment this line to use Composite Operation, which is doing the
  2266. // same as the clip function below and is also antialiasing the round
  2267. // border, but is said to be less fast performance wise.
  2268. // drawContext.globalCompositeOperation='destination-out';
  2269. drawContext.beginPath();
  2270. drawContext.moveTo(x+r, y);
  2271. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2272. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2273. drawContext.arcTo(x, y+h, x, y, r);
  2274. drawContext.arcTo(x, y, x+w, y, r);
  2275. drawContext.closePath();
  2276. // 2) Uncomment this line to use Composite Operation, which is doing the
  2277. // same as the clip function below and is also antialiasing the round
  2278. // border, but is said to be less fast performance wise.
  2279. // drawContext.fill();
  2280. // Comment these two lines if choosing to do the same with composite
  2281. // operation above 1 and 2.
  2282. drawContext.clip();
  2283. drawContext.clearRect(0, 0, 277, 200);
  2284. // Restore the previous context state.
  2285. drawContext.restore();
  2286. };
  2287. /**
  2288. * Clones the given canvas.
  2289. *
  2290. * @return the new cloned canvas.
  2291. */
  2292. my.cloneCanvas = function (oldCanvas) {
  2293. /*
  2294. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2295. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2296. * levels are frequently updated, the errors have been observed to pile
  2297. * into the console, strain the CPU.
  2298. */
  2299. if (!oldCanvas)
  2300. return oldCanvas;
  2301. //create a new canvas
  2302. var newCanvas = document.createElement('canvas');
  2303. var context = newCanvas.getContext('2d');
  2304. //set dimensions
  2305. newCanvas.width = oldCanvas.width;
  2306. newCanvas.height = oldCanvas.height;
  2307. //apply the old canvas to the new one
  2308. context.drawImage(oldCanvas, 0, 0);
  2309. //return the new canvas
  2310. return newCanvas;
  2311. };
  2312. return my;
  2313. })(CanvasUtil || {});
  2314. module.exports = CanvasUtil;
  2315. },{}],11:[function(require,module,exports){
  2316. /* global $, APP*/
  2317. var LoginDialog = require('./LoginDialog');
  2318. var Moderator = require('../../xmpp/moderator');
  2319. /* Initial "authentication required" dialog */
  2320. var authDialog = null;
  2321. /* Loop retry ID that wits for other user to create the room */
  2322. var authRetryId = null;
  2323. var authenticationWindow = null;
  2324. var Authentication = {
  2325. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2326. // This is the loop that will wait for the room to be created by
  2327. // someone else. 'auth_required.moderator' will bring us back here.
  2328. authRetryId = window.setTimeout(intervalCallback, 5000);
  2329. // Show prompt only if it's not open
  2330. if (authDialog !== null) {
  2331. return;
  2332. }
  2333. // extract room name from 'room@muc.server.net'
  2334. var room = roomName.substr(0, roomName.indexOf('@'));
  2335. var title
  2336. = APP.translation.generateTranslatonHTML("dialog.WaitingForHost");
  2337. var msg
  2338. = APP.translation.generateTranslatonHTML(
  2339. "dialog.WaitForHostMsg", {room: room});
  2340. var buttonTxt
  2341. = APP.translation.generateTranslatonHTML("dialog.IamHost");
  2342. var buttons = [];
  2343. buttons.push({title: buttonTxt, value: "authNow"});
  2344. authDialog = APP.UI.messageHandler.openDialog(
  2345. title,
  2346. msg,
  2347. true,
  2348. buttons,
  2349. function (onSubmitEvent, submitValue) {
  2350. // Do not close the dialog yet
  2351. onSubmitEvent.preventDefault();
  2352. // Open login popup
  2353. if (submitValue === 'authNow') {
  2354. callback();
  2355. }
  2356. }
  2357. );
  2358. },
  2359. closeAuthenticationWindow: function () {
  2360. if (authenticationWindow) {
  2361. authenticationWindow.close();
  2362. authenticationWindow = null;
  2363. }
  2364. },
  2365. xmppAuthenticate: function () {
  2366. var loginDialog = LoginDialog.show(
  2367. function (connection, state) {
  2368. if (!state) {
  2369. // User cancelled
  2370. loginDialog.close();
  2371. return;
  2372. } else if (state == APP.xmpp.Status.CONNECTED) {
  2373. loginDialog.close();
  2374. Authentication.stopInterval();
  2375. Authentication.closeAuthenticationDialog();
  2376. // Close the connection as anonymous one will be used
  2377. // to create the conference. Session-id will authorize
  2378. // the request.
  2379. connection.disconnect();
  2380. var roomName = APP.UI.generateRoomName();
  2381. Moderator.allocateConferenceFocus(roomName, function () {
  2382. // If it's not "on the fly" authentication now join
  2383. // the conference room
  2384. if (!APP.xmpp.getMUCJoined()) {
  2385. APP.UI.checkForNicknameAndJoin();
  2386. }
  2387. });
  2388. }
  2389. }, true);
  2390. },
  2391. focusAuthenticationWindow: function () {
  2392. // If auth window exists just bring it to the front
  2393. if (authenticationWindow) {
  2394. authenticationWindow.focus();
  2395. return;
  2396. }
  2397. },
  2398. closeAuthenticationDialog: function () {
  2399. // Close authentication dialog if opened
  2400. if (authDialog) {
  2401. authDialog.close();
  2402. authDialog = null;
  2403. }
  2404. },
  2405. createAuthenticationWindow: function (callback, url) {
  2406. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2407. url, 910, 660,
  2408. // On closed
  2409. function () {
  2410. // Close authentication dialog if opened
  2411. Authentication.closeAuthenticationDialog();
  2412. callback();
  2413. authenticationWindow = null;
  2414. });
  2415. return authenticationWindow;
  2416. },
  2417. stopInterval: function () {
  2418. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2419. if (authRetryId) {
  2420. window.clearTimeout(authRetryId);
  2421. authRetryId = null;
  2422. }
  2423. }
  2424. };
  2425. module.exports = Authentication;
  2426. },{"../../xmpp/moderator":54,"./LoginDialog":12}],12:[function(require,module,exports){
  2427. /* global $, APP, config*/
  2428. var XMPP = require('../../xmpp/xmpp');
  2429. var Moderator = require('../../xmpp/moderator');
  2430. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2431. // anonymous domain is not enabled
  2432. /**
  2433. * Creates new <tt>Dialog</tt> instance.
  2434. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2435. * when we either fail to connect or succeed(check Strophe.Status).
  2436. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2437. * in order to create session-id after the connection is established.
  2438. * @constructor
  2439. */
  2440. function Dialog(callback, obtainSession) {
  2441. var self = this;
  2442. var stop = false;
  2443. var connection = APP.xmpp.createConnection();
  2444. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2445. message += APP.translation.translateString("dialog.passwordRequired");
  2446. message += '</h2>' +
  2447. '<input name="username" type="text" ' +
  2448. 'placeholder="user@domain.net" autofocus>' +
  2449. '<input name="password" ' +
  2450. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2451. ' placeholder="user password">';
  2452. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2453. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2454. var states = {
  2455. login: {
  2456. html: message,
  2457. buttons: [
  2458. { title: okButton, value: true},
  2459. { title: cancelButton, value: false}
  2460. ],
  2461. focus: ':input:first',
  2462. submit: function (e, v, m, f) {
  2463. e.preventDefault();
  2464. if (v) {
  2465. var jid = f.username;
  2466. var password = f.password;
  2467. if (jid && password) {
  2468. stop = false;
  2469. connection.reset();
  2470. connDialog.goToState('connecting');
  2471. connection.connect(jid, password, stateHandler);
  2472. }
  2473. } else {
  2474. // User cancelled
  2475. stop = true;
  2476. callback();
  2477. }
  2478. }
  2479. },
  2480. connecting: {
  2481. title: APP.translation.translateString('dialog.connecting'),
  2482. html: '<div id="connectionStatus"></div>',
  2483. buttons: [],
  2484. defaultButton: 0
  2485. },
  2486. finished: {
  2487. title: APP.translation.translateString('dialog.error'),
  2488. html: '<div id="errorMessage"></div>',
  2489. buttons: [
  2490. {
  2491. title: APP.translation.translateString('dialog.retry'),
  2492. value: 'retry'
  2493. },
  2494. {
  2495. title: APP.translation.translateString('dialog.Cancel'),
  2496. value: 'cancel'
  2497. },
  2498. ],
  2499. defaultButton: 0,
  2500. submit: function (e, v, m, f) {
  2501. e.preventDefault();
  2502. if (v === 'retry')
  2503. connDialog.goToState('login');
  2504. else
  2505. callback();
  2506. }
  2507. }
  2508. };
  2509. var connDialog
  2510. = APP.UI.messageHandler.openDialogWithStates(states,
  2511. { persistent: true, closeText: '' }, null);
  2512. var stateHandler = function (status, message) {
  2513. if (stop) {
  2514. return;
  2515. }
  2516. var translateKey = "connection." + XMPP.getStatusString(status);
  2517. var statusStr = APP.translation.translateString(translateKey);
  2518. // Display current state
  2519. var connectionStatus =
  2520. connDialog.getState('connecting').find('#connectionStatus');
  2521. connectionStatus.text(statusStr);
  2522. switch (status) {
  2523. case XMPP.Status.CONNECTED:
  2524. stop = true;
  2525. if (!obtainSession) {
  2526. callback(connection, status);
  2527. return;
  2528. }
  2529. // Obtaining session-id status
  2530. connectionStatus.text(
  2531. APP.translation.translateString(
  2532. 'connection.FETCH_SESSION_ID'));
  2533. // Authenticate with Jicofo and obtain session-id
  2534. var roomName = APP.UI.generateRoomName();
  2535. // Jicofo will return new session-id when connected
  2536. // from authenticated domain
  2537. connection.sendIQ(
  2538. Moderator.createConferenceIq(roomName),
  2539. function (result) {
  2540. connectionStatus.text(
  2541. APP.translation.translateString(
  2542. 'connection.GOT_SESSION_ID'));
  2543. stop = true;
  2544. // Parse session-id
  2545. Moderator.parseSessionId(result);
  2546. callback(connection, status);
  2547. },
  2548. function (error) {
  2549. console.error("Auth on the fly failed", error);
  2550. stop = true;
  2551. var errorMsg =
  2552. APP.translation.translateString(
  2553. 'connection.GET_SESSION_ID_ERROR') +
  2554. $(error).find('>error').attr('code');
  2555. self.displayError(errorMsg);
  2556. connection.disconnect();
  2557. });
  2558. break;
  2559. case XMPP.Status.AUTHFAIL:
  2560. case XMPP.Status.CONNFAIL:
  2561. case XMPP.Status.DISCONNECTED:
  2562. stop = true;
  2563. callback(connection, status);
  2564. var errorMessage = statusStr;
  2565. if (message)
  2566. {
  2567. errorMessage += ': ' + message;
  2568. }
  2569. self.displayError(errorMessage);
  2570. break;
  2571. default:
  2572. break;
  2573. }
  2574. };
  2575. /**
  2576. * Displays error message in 'finished' state which allows either to cancel
  2577. * or retry.
  2578. * @param message the final message to be displayed.
  2579. */
  2580. this.displayError = function (message) {
  2581. var finishedState = connDialog.getState('finished');
  2582. var errorMessageElem = finishedState.find('#errorMessage');
  2583. errorMessageElem.text(message);
  2584. connDialog.goToState('finished');
  2585. };
  2586. /**
  2587. * Closes LoginDialog.
  2588. */
  2589. this.close = function () {
  2590. stop = true;
  2591. connDialog.close();
  2592. };
  2593. }
  2594. var LoginDialog = {
  2595. /**
  2596. * Displays login prompt used to establish new XMPP connection. Given
  2597. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2598. * called when we connect successfully(status === CONNECTED) or when we fail
  2599. * to do so. On connection failure program can call Dialog.close() method in
  2600. * order to cancel or do nothing to let the user retry.
  2601. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2602. * called when we either fail to connect or succeed(check
  2603. * Strophe.Status).
  2604. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2605. * Jicofo in order to create session-id after the connection is
  2606. * established.
  2607. * @returns {Dialog}
  2608. */
  2609. show: function (callback, obtainSession) {
  2610. return new Dialog(callback, obtainSession);
  2611. }
  2612. };
  2613. module.exports = LoginDialog;
  2614. },{"../../xmpp/moderator":54,"../../xmpp/xmpp":62}],13:[function(require,module,exports){
  2615. var Settings = require("../../settings/Settings");
  2616. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2617. var users = {};
  2618. var activeSpeakerJid;
  2619. function setVisibility(selector, show) {
  2620. if (selector && selector.length > 0) {
  2621. selector.css("visibility", show ? "visible" : "hidden");
  2622. }
  2623. }
  2624. function isUserMuted(jid) {
  2625. // XXX(gp) we may want to rename this method to something like
  2626. // isUserStreaming, for example.
  2627. if (jid && jid != APP.xmpp.myJid()) {
  2628. var resource = Strophe.getResourceFromJid(jid);
  2629. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2630. return true;
  2631. }
  2632. }
  2633. if(jid && jid == APP.xmpp.myJid())
  2634. {
  2635. var localVideo = APP.RTC.localVideo;
  2636. return (!localVideo || localVideo.isMuted());
  2637. }
  2638. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2639. return null;
  2640. }
  2641. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2642. }
  2643. function getGravatarUrl(id, size) {
  2644. if(id === APP.xmpp.myJid() || !id) {
  2645. id = Settings.getSettings().uid;
  2646. }
  2647. return 'https://www.gravatar.com/avatar/' +
  2648. MD5.hexdigest(id.trim().toLowerCase()) +
  2649. "?d=wavatar&size=" + (size || "30");
  2650. }
  2651. var Avatar = {
  2652. /**
  2653. * Sets the user's avatar in the settings menu(if local user), contact list
  2654. * and thumbnail
  2655. * @param jid jid of the user
  2656. * @param id email or userID to be used as a hash
  2657. */
  2658. setUserAvatar: function (jid, id) {
  2659. if (id) {
  2660. if (users[jid] === id) {
  2661. return;
  2662. }
  2663. users[jid] = id;
  2664. }
  2665. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2666. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2667. var resourceJid = Strophe.getResourceFromJid(jid);
  2668. var thumbnail = $('#participant_' + resourceJid);
  2669. var avatar = $('#avatar_' + resourceJid);
  2670. // set the avatar in the settings menu if it is local user and get the
  2671. // local video container
  2672. if (jid === APP.xmpp.myJid()) {
  2673. $('#avatar').get(0).src = thumbUrl;
  2674. thumbnail = $('#localVideoContainer');
  2675. }
  2676. // set the avatar in the contact list
  2677. var contact = $('#' + resourceJid + '>img');
  2678. if (contact && contact.length > 0) {
  2679. contact.get(0).src = contactListUrl;
  2680. }
  2681. // set the avatar in the thumbnail
  2682. if (avatar && avatar.length > 0) {
  2683. avatar[0].src = thumbUrl;
  2684. } else {
  2685. if (thumbnail && thumbnail.length > 0) {
  2686. avatar = document.createElement('img');
  2687. avatar.id = 'avatar_' + resourceJid;
  2688. avatar.className = 'userAvatar';
  2689. avatar.src = thumbUrl;
  2690. thumbnail.append(avatar);
  2691. }
  2692. }
  2693. //if the user is the current active speaker - update the active speaker
  2694. // avatar
  2695. if (jid === activeSpeakerJid) {
  2696. this.updateActiveSpeakerAvatarSrc(jid);
  2697. }
  2698. },
  2699. /**
  2700. * Hides or shows the user's avatar
  2701. * @param jid jid of the user
  2702. * @param show whether we should show the avatar or not
  2703. * video because there is no dominant speaker and no focused speaker
  2704. */
  2705. showUserAvatar: function (jid, show) {
  2706. if (users[jid]) {
  2707. var resourceJid = Strophe.getResourceFromJid(jid);
  2708. var video = $('#participant_' + resourceJid + '>video');
  2709. var avatar = $('#avatar_' + resourceJid);
  2710. if (jid === APP.xmpp.myJid()) {
  2711. video = $('#localVideoWrapper>video');
  2712. }
  2713. if (show === undefined || show === null) {
  2714. show = isUserMuted(jid);
  2715. }
  2716. //if the user is the currently focused, the dominant speaker or if
  2717. //there is no focused and no dominant speaker and the large video is
  2718. //currently shown
  2719. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2720. setVisibility($("#largeVideo"), !show);
  2721. setVisibility($('#activeSpeaker'), show);
  2722. setVisibility(avatar, false);
  2723. setVisibility(video, false);
  2724. } else {
  2725. if (video && video.length > 0) {
  2726. setVisibility(video, !show);
  2727. }
  2728. setVisibility(avatar, show);
  2729. }
  2730. }
  2731. },
  2732. /**
  2733. * Updates the src of the active speaker avatar
  2734. * @param jid of the current active speaker
  2735. */
  2736. updateActiveSpeakerAvatarSrc: function (jid) {
  2737. if (!jid) {
  2738. jid = APP.xmpp.findJidFromResource(
  2739. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2740. }
  2741. var avatar = $("#activeSpeakerAvatar")[0];
  2742. var url = getGravatarUrl(users[jid],
  2743. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2744. if (jid === activeSpeakerJid && avatar.src === url) {
  2745. return;
  2746. }
  2747. activeSpeakerJid = jid;
  2748. var isMuted = isUserMuted(jid);
  2749. if (jid && isMuted !== null) {
  2750. avatar.src = url;
  2751. setVisibility($("#largeVideo"), !isMuted);
  2752. Avatar.showUserAvatar(jid, isMuted);
  2753. }
  2754. }
  2755. };
  2756. module.exports = Avatar;
  2757. },{"../../../service/RTC/MediaStreamTypes":94,"../../settings/Settings":39,"../videolayout/VideoLayout":32}],14:[function(require,module,exports){
  2758. /* global $, config,
  2759. setLargeVideoVisible, Util */
  2760. var VideoLayout = require("../videolayout/VideoLayout");
  2761. var Prezi = require("../prezi/Prezi");
  2762. var UIUtil = require("../util/UIUtil");
  2763. var etherpadName = null;
  2764. var etherpadIFrame = null;
  2765. var domain = null;
  2766. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2767. /**
  2768. * Resizes the etherpad.
  2769. */
  2770. function resize() {
  2771. if ($('#etherpad>iframe').length) {
  2772. var remoteVideos = $('#remoteVideos');
  2773. var availableHeight
  2774. = window.innerHeight - remoteVideos.outerHeight();
  2775. var availableWidth = UIUtil.getAvailableVideoWidth();
  2776. $('#etherpad>iframe').width(availableWidth);
  2777. $('#etherpad>iframe').height(availableHeight);
  2778. }
  2779. }
  2780. /**
  2781. * Shares the Etherpad name with other participants.
  2782. */
  2783. function shareEtherpad() {
  2784. APP.xmpp.addToPresence("etherpad", etherpadName);
  2785. }
  2786. /**
  2787. * Creates the Etherpad button and adds it to the toolbar.
  2788. */
  2789. function enableEtherpadButton() {
  2790. if (!$('#etherpadButton').is(":visible"))
  2791. $('#etherpadButton').css({display: 'inline-block'});
  2792. }
  2793. /**
  2794. * Creates the IFrame for the etherpad.
  2795. */
  2796. function createIFrame() {
  2797. etherpadIFrame = document.createElement('iframe');
  2798. etherpadIFrame.src = domain + etherpadName + options;
  2799. etherpadIFrame.frameBorder = 0;
  2800. etherpadIFrame.scrolling = "no";
  2801. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2802. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2803. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2804. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2805. etherpadIFrame.onload = function() {
  2806. document.domain = document.domain;
  2807. bubbleIframeMouseMove(etherpadIFrame);
  2808. setTimeout(function() {
  2809. // the iframes inside of the etherpad are
  2810. // not yet loaded when the etherpad iframe is loaded
  2811. var outer = etherpadIFrame.
  2812. contentDocument.getElementsByName("ace_outer")[0];
  2813. bubbleIframeMouseMove(outer);
  2814. var inner = outer.
  2815. contentDocument.getElementsByName("ace_inner")[0];
  2816. bubbleIframeMouseMove(inner);
  2817. }, 2000);
  2818. };
  2819. }
  2820. function bubbleIframeMouseMove(iframe){
  2821. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2822. iframe.contentWindow.onmousemove = function(e){
  2823. if(existingOnMouseMove) existingOnMouseMove(e);
  2824. var evt = document.createEvent("MouseEvents");
  2825. var boundingClientRect = iframe.getBoundingClientRect();
  2826. evt.initMouseEvent(
  2827. "mousemove",
  2828. true, // bubbles
  2829. false, // not cancelable
  2830. window,
  2831. e.detail,
  2832. e.screenX,
  2833. e.screenY,
  2834. e.clientX + boundingClientRect.left,
  2835. e.clientY + boundingClientRect.top,
  2836. e.ctrlKey,
  2837. e.altKey,
  2838. e.shiftKey,
  2839. e.metaKey,
  2840. e.button,
  2841. null // no related element
  2842. );
  2843. iframe.dispatchEvent(evt);
  2844. };
  2845. }
  2846. /**
  2847. * On video selected event.
  2848. */
  2849. $(document).bind('video.selected', function (event, isPresentation) {
  2850. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2851. Etherpad.toggleEtherpad(isPresentation);
  2852. });
  2853. var Etherpad = {
  2854. /**
  2855. * Initializes the etherpad.
  2856. */
  2857. init: function (name) {
  2858. if (config.etherpad_base && !etherpadName) {
  2859. domain = config.etherpad_base;
  2860. if (!name) {
  2861. // In case we're the focus we generate the name.
  2862. etherpadName = Math.random().toString(36).substring(7) +
  2863. '_' + (new Date().getTime()).toString();
  2864. shareEtherpad();
  2865. }
  2866. else
  2867. etherpadName = name;
  2868. enableEtherpadButton();
  2869. /**
  2870. * Resizes the etherpad, when the window is resized.
  2871. */
  2872. $(window).resize(function () {
  2873. resize();
  2874. });
  2875. }
  2876. },
  2877. /**
  2878. * Opens/hides the Etherpad.
  2879. */
  2880. toggleEtherpad: function (isPresentation) {
  2881. if (!etherpadIFrame)
  2882. createIFrame();
  2883. var largeVideo = null;
  2884. if (Prezi.isPresentationVisible())
  2885. largeVideo = $('#presentation>iframe');
  2886. else
  2887. largeVideo = $('#largeVideo');
  2888. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2889. $('#activeSpeaker').css('visibility', 'hidden');
  2890. largeVideo.fadeOut(300, function () {
  2891. if (Prezi.isPresentationVisible()) {
  2892. largeVideo.css({opacity: '0'});
  2893. } else {
  2894. VideoLayout.setLargeVideoVisible(false);
  2895. }
  2896. });
  2897. $('#etherpad>iframe').fadeIn(300, function () {
  2898. document.body.style.background = '#eeeeee';
  2899. $('#etherpad>iframe').css({visibility: 'visible'});
  2900. $('#etherpad').css({zIndex: 2});
  2901. });
  2902. }
  2903. else if ($('#etherpad>iframe')) {
  2904. $('#etherpad>iframe').fadeOut(300, function () {
  2905. $('#etherpad>iframe').css({visibility: 'hidden'});
  2906. $('#etherpad').css({zIndex: 0});
  2907. document.body.style.background = 'black';
  2908. });
  2909. if (!isPresentation) {
  2910. $('#largeVideo').fadeIn(300, function () {
  2911. VideoLayout.setLargeVideoVisible(true);
  2912. });
  2913. }
  2914. }
  2915. resize();
  2916. },
  2917. isVisible: function() {
  2918. var etherpadIframe = $('#etherpad>iframe');
  2919. return etherpadIframe && etherpadIframe.is(':visible');
  2920. }
  2921. };
  2922. module.exports = Etherpad;
  2923. },{"../prezi/Prezi":15,"../util/UIUtil":30,"../videolayout/VideoLayout":32}],15:[function(require,module,exports){
  2924. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2925. var UIUtil = require("../util/UIUtil");
  2926. var VideoLayout = require("../videolayout/VideoLayout");
  2927. var messageHandler = require("../util/MessageHandler");
  2928. var PreziPlayer = require("./PreziPlayer");
  2929. var preziPlayer = null;
  2930. var Prezi = {
  2931. /**
  2932. * Reloads the current presentation.
  2933. */
  2934. reloadPresentation: function() {
  2935. var iframe = document.getElementById(preziPlayer.options.preziId);
  2936. iframe.src = iframe.src;
  2937. },
  2938. /**
  2939. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2940. * otherwise.
  2941. */
  2942. isPresentationVisible: function () {
  2943. return ($('#presentation>iframe') != null
  2944. && $('#presentation>iframe').css('opacity') == 1);
  2945. },
  2946. /**
  2947. * Opens the Prezi dialog, from which the user could choose a presentation
  2948. * to load.
  2949. */
  2950. openPreziDialog: function() {
  2951. var myprezi = APP.xmpp.getPrezi();
  2952. if (myprezi) {
  2953. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2954. null,
  2955. "dialog.removePreziMsg",
  2956. null,
  2957. false,
  2958. "dialog.Remove",
  2959. function(e,v,m,f) {
  2960. if(v) {
  2961. APP.xmpp.removePreziFromPresence();
  2962. }
  2963. }
  2964. );
  2965. }
  2966. else if (preziPlayer != null) {
  2967. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2968. null, "dialog.sharePreziMsg",
  2969. null,
  2970. false,
  2971. "dialog.Ok",
  2972. function(e,v,m,f) {
  2973. $.prompt.close();
  2974. }
  2975. );
  2976. }
  2977. else {
  2978. var html = APP.translation.generateTranslatonHTML(
  2979. "dialog.sharePreziTitle");
  2980. var cancelButton = APP.translation.generateTranslatonHTML(
  2981. "dialog.Cancel");
  2982. var shareButton = APP.translation.generateTranslatonHTML(
  2983. "dialog.Share");
  2984. var backButton = APP.translation.generateTranslatonHTML(
  2985. "dialog.Back");
  2986. var buttons = [];
  2987. var buttons1 = [];
  2988. // Cancel button to both states
  2989. buttons.push({title: cancelButton, value: false});
  2990. buttons1.push({title: cancelButton, value: false});
  2991. // Share button
  2992. buttons.push({title: shareButton, value: true});
  2993. // Back button
  2994. buttons1.push({title: backButton, value: true});
  2995. var linkError = APP.translation.generateTranslatonHTML(
  2996. "dialog.preziLinkError");
  2997. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  2998. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  2999. var openPreziState = {
  3000. state0: {
  3001. html: '<h2>' + html + '</h2>' +
  3002. '<input name="preziUrl" type="text" ' +
  3003. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  3004. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  3005. '\' placeholder="' + defaultUrl + '" autofocus>',
  3006. persistent: false,
  3007. buttons: buttons,
  3008. focus: ':input:first',
  3009. defaultButton: 0,
  3010. submit: function (e, v, m, f) {
  3011. e.preventDefault();
  3012. if(v)
  3013. {
  3014. var preziUrl = f.preziUrl;
  3015. if (preziUrl)
  3016. {
  3017. var urlValue
  3018. = encodeURI(UIUtil.escapeHtml(preziUrl));
  3019. if (urlValue.indexOf('http://prezi.com/') != 0
  3020. && urlValue.indexOf('https://prezi.com/') != 0)
  3021. {
  3022. $.prompt.goToState('state1');
  3023. return false;
  3024. }
  3025. else {
  3026. var presIdTmp = urlValue.substring(
  3027. urlValue.indexOf("prezi.com/") + 10);
  3028. if (!isAlphanumeric(presIdTmp)
  3029. || presIdTmp.indexOf('/') < 2) {
  3030. $.prompt.goToState('state1');
  3031. return false;
  3032. }
  3033. else {
  3034. APP.xmpp.addToPresence("prezi", urlValue);
  3035. $.prompt.close();
  3036. }
  3037. }
  3038. }
  3039. }
  3040. else
  3041. $.prompt.close();
  3042. }
  3043. },
  3044. state1: {
  3045. html: '<h2>' + html + '</h2>' +
  3046. linkError,
  3047. persistent: false,
  3048. buttons: buttons1,
  3049. focus: ':input:first',
  3050. defaultButton: 1,
  3051. submit: function (e, v, m, f) {
  3052. e.preventDefault();
  3053. if (v === 0)
  3054. $.prompt.close();
  3055. else
  3056. $.prompt.goToState('state0');
  3057. }
  3058. }
  3059. };
  3060. messageHandler.openDialogWithStates(openPreziState);
  3061. }
  3062. }
  3063. };
  3064. /**
  3065. * A new presentation has been added.
  3066. *
  3067. * @param event the event indicating the add of a presentation
  3068. * @param jid the jid from which the presentation was added
  3069. * @param presUrl url of the presentation
  3070. * @param currentSlide the current slide to which we should move
  3071. */
  3072. function presentationAdded(event, jid, presUrl, currentSlide) {
  3073. console.log("presentation added", presUrl);
  3074. var presId = getPresentationId(presUrl);
  3075. var elementId = 'participant_'
  3076. + Strophe.getResourceFromJid(jid)
  3077. + '_' + presId;
  3078. // We explicitly don't specify the peer jid here, because we don't want
  3079. // this video to be dealt with as a peer related one (for example we
  3080. // don't want to show a mute/kick menu for this one, etc.).
  3081. VideoLayout.addRemoteVideoContainer(null, elementId);
  3082. VideoLayout.resizeThumbnails();
  3083. var controlsEnabled = false;
  3084. if (jid === APP.xmpp.myJid())
  3085. controlsEnabled = true;
  3086. setPresentationVisible(true);
  3087. $('#largeVideoContainer').hover(
  3088. function (event) {
  3089. if (Prezi.isPresentationVisible()) {
  3090. var reloadButtonRight = window.innerWidth
  3091. - $('#presentation>iframe').offset().left
  3092. - $('#presentation>iframe').width();
  3093. $('#reloadPresentation').css({ right: reloadButtonRight,
  3094. display:'inline-block'});
  3095. }
  3096. },
  3097. function (event) {
  3098. if (!Prezi.isPresentationVisible())
  3099. $('#reloadPresentation').css({display:'none'});
  3100. else {
  3101. var e = event.toElement || event.relatedTarget;
  3102. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  3103. $('#reloadPresentation').css({display:'none'});
  3104. }
  3105. });
  3106. preziPlayer = new PreziPlayer(
  3107. 'presentation',
  3108. {preziId: presId,
  3109. width: getPresentationWidth(),
  3110. height: getPresentationHeihgt(),
  3111. controls: controlsEnabled,
  3112. debug: true
  3113. });
  3114. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3115. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3116. console.log("prezi status", event.value);
  3117. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3118. if (jid != APP.xmpp.myJid())
  3119. preziPlayer.flyToStep(currentSlide);
  3120. }
  3121. });
  3122. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3123. console.log("event value", event.value);
  3124. APP.xmpp.addToPresence("preziSlide", event.value);
  3125. });
  3126. $("#" + elementId).css( 'background-image',
  3127. 'url(../images/avatarprezi.png)');
  3128. $("#" + elementId).click(
  3129. function () {
  3130. setPresentationVisible(true);
  3131. }
  3132. );
  3133. };
  3134. /**
  3135. * A presentation has been removed.
  3136. *
  3137. * @param event the event indicating the remove of a presentation
  3138. * @param jid the jid for which the presentation was removed
  3139. * @param the url of the presentation
  3140. */
  3141. function presentationRemoved(event, jid, presUrl) {
  3142. console.log('presentation removed', presUrl);
  3143. var presId = getPresentationId(presUrl);
  3144. setPresentationVisible(false);
  3145. $('#participant_'
  3146. + Strophe.getResourceFromJid(jid)
  3147. + '_' + presId).remove();
  3148. $('#presentation>iframe').remove();
  3149. if (preziPlayer != null) {
  3150. preziPlayer.destroy();
  3151. preziPlayer = null;
  3152. }
  3153. };
  3154. /**
  3155. * Indicates if the given string is an alphanumeric string.
  3156. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3157. * purpose of checking URIs.
  3158. */
  3159. function isAlphanumeric(unsafeText) {
  3160. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3161. return regex.test(unsafeText);
  3162. }
  3163. /**
  3164. * Returns the presentation id from the given url.
  3165. */
  3166. function getPresentationId (presUrl) {
  3167. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3168. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3169. }
  3170. /**
  3171. * Returns the presentation width.
  3172. */
  3173. function getPresentationWidth() {
  3174. var availableWidth = UIUtil.getAvailableVideoWidth();
  3175. var availableHeight = getPresentationHeihgt();
  3176. var aspectRatio = 16.0 / 9.0;
  3177. if (availableHeight < availableWidth / aspectRatio) {
  3178. availableWidth = Math.floor(availableHeight * aspectRatio);
  3179. }
  3180. return availableWidth;
  3181. }
  3182. /**
  3183. * Returns the presentation height.
  3184. */
  3185. function getPresentationHeihgt() {
  3186. var remoteVideos = $('#remoteVideos');
  3187. return window.innerHeight - remoteVideos.outerHeight();
  3188. }
  3189. /**
  3190. * Resizes the presentation iframe.
  3191. */
  3192. function resize() {
  3193. if ($('#presentation>iframe')) {
  3194. $('#presentation>iframe').width(getPresentationWidth());
  3195. $('#presentation>iframe').height(getPresentationHeihgt());
  3196. }
  3197. }
  3198. /**
  3199. * Shows/hides a presentation.
  3200. */
  3201. function setPresentationVisible(visible) {
  3202. var prezi = $('#presentation>iframe');
  3203. if (visible) {
  3204. // Trigger the video.selected event to indicate a change in the
  3205. // large video.
  3206. $(document).trigger("video.selected", [true]);
  3207. $('#largeVideo').fadeOut(300);
  3208. prezi.fadeIn(300, function() {
  3209. prezi.css({opacity:'1'});
  3210. ToolbarToggler.dockToolbar(true);
  3211. VideoLayout.setLargeVideoVisible(false);
  3212. });
  3213. $('#activeSpeaker').css('visibility', 'hidden');
  3214. }
  3215. else {
  3216. if (prezi.css('opacity') == '1') {
  3217. prezi.fadeOut(300, function () {
  3218. prezi.css({opacity:'0'});
  3219. $('#reloadPresentation').css({display:'none'});
  3220. $('#largeVideo').fadeIn(300, function() {
  3221. VideoLayout.setLargeVideoVisible(true);
  3222. ToolbarToggler.dockToolbar(false);
  3223. });
  3224. });
  3225. }
  3226. }
  3227. }
  3228. /**
  3229. * Presentation has been removed.
  3230. */
  3231. $(document).bind('presentationremoved.muc', presentationRemoved);
  3232. /**
  3233. * Presentation has been added.
  3234. */
  3235. $(document).bind('presentationadded.muc', presentationAdded);
  3236. /*
  3237. * Indicates presentation slide change.
  3238. */
  3239. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3240. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3241. preziPlayer.flyToStep(current);
  3242. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3243. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3244. preziPlayer.flyToStep(current, i);
  3245. }
  3246. }
  3247. });
  3248. /**
  3249. * On video selected event.
  3250. */
  3251. $(document).bind('video.selected', function (event, isPresentation) {
  3252. if (!isPresentation && $('#presentation>iframe')) {
  3253. setPresentationVisible(false);
  3254. }
  3255. });
  3256. $(window).resize(function () {
  3257. resize();
  3258. });
  3259. module.exports = Prezi;
  3260. },{"../toolbars/ToolbarToggler":26,"../util/MessageHandler":28,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./PreziPlayer":16}],16:[function(require,module,exports){
  3261. (function() {
  3262. "use strict";
  3263. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3264. window.PreziPlayer = (function() {
  3265. PreziPlayer.API_VERSION = 1;
  3266. PreziPlayer.CURRENT_STEP = 'currentStep';
  3267. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3268. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3269. PreziPlayer.STATUS_LOADING = 'loading';
  3270. PreziPlayer.STATUS_READY = 'ready';
  3271. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3272. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3273. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3274. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3275. PreziPlayer.EVENT_STATUS = "statusChange";
  3276. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3277. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3278. PreziPlayer.domain = "https://prezi.com";
  3279. PreziPlayer.path = "/player/";
  3280. PreziPlayer.players = {};
  3281. PreziPlayer.binded_methods = ['changesHandler'];
  3282. PreziPlayer.createMultiplePlayers = function(optionArray){
  3283. for(var i=0; i<optionArray.length; i++) {
  3284. var optionSet = optionArray[i];
  3285. new PreziPlayer(optionSet.id, optionSet);
  3286. };
  3287. };
  3288. PreziPlayer.messageReceived = function(event){
  3289. var message, item, player;
  3290. try {
  3291. message = JSON.parse(event.data);
  3292. if (message.id && (player = PreziPlayer.players[message.id])) {
  3293. if (player.options.debug === true) {
  3294. if (console && console.log)
  3295. console.log('received', message);
  3296. }
  3297. if (message.type === "changes") {
  3298. player.changesHandler(message);
  3299. }
  3300. for (var i = 0; i < player.callbacks.length; i++) {
  3301. item = player.callbacks[i];
  3302. if (item && message.type === item.event) {
  3303. item.callback(message);
  3304. }
  3305. }
  3306. }
  3307. } catch (e) { }
  3308. };
  3309. function PreziPlayer(id, options) {
  3310. var params, paramString = "", _this = this;
  3311. if (PreziPlayer.players[id]){
  3312. PreziPlayer.players[id].destroy();
  3313. }
  3314. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3315. var method_name = PreziPlayer.binded_methods[i];
  3316. _this[method_name] = __bind(_this[method_name], _this);
  3317. };
  3318. options = options || {};
  3319. this.options = options;
  3320. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3321. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3322. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3323. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3324. this.callbacks = [];
  3325. this.id = id;
  3326. this.embedTo = document.getElementById(id);
  3327. if (!this.embedTo) {
  3328. throw "The element id is not available.";
  3329. }
  3330. this.iframe = document.createElement('iframe');
  3331. params = [
  3332. { name: 'oid', value: options.preziId },
  3333. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3334. { name: 'controls', value: options.controls ? 1 : 0 }
  3335. ];
  3336. for(var i=0; i<params.length; i++) {
  3337. var param = params[i];
  3338. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3339. };
  3340. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3341. this.iframe.frameBorder = 0;
  3342. this.iframe.scrolling = "no";
  3343. this.iframe.width = options.width || 640;
  3344. this.iframe.height = options.height || 480;
  3345. this.embedTo.innerHTML = '';
  3346. // JITSI: IN CASE SOMETHING GOES WRONG.
  3347. try {
  3348. this.embedTo.appendChild(this.iframe);
  3349. }
  3350. catch (err) {
  3351. console.log("CATCH ERROR");
  3352. }
  3353. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3354. // crashes for us.
  3355. this.initPollInterval = setInterval(function(){
  3356. _this.sendMessage({'action': 'init'});
  3357. }, 500);
  3358. PreziPlayer.players[id] = this;
  3359. }
  3360. PreziPlayer.prototype.changesHandler = function(message) {
  3361. var key, value, j, item;
  3362. if (this.initPollInterval) {
  3363. clearInterval(this.initPollInterval);
  3364. this.initPollInterval = false;
  3365. }
  3366. for (key in message.data) {
  3367. if (message.data.hasOwnProperty(key)){
  3368. value = message.data[key];
  3369. this.values[key] = value;
  3370. for (j=0; j<this.callbacks.length; j++) {
  3371. item = this.callbacks[j];
  3372. if (item && item.event === key + "Change"){
  3373. item.callback({type: item.event, value: value});
  3374. }
  3375. }
  3376. }
  3377. }
  3378. };
  3379. PreziPlayer.prototype.destroy = function() {
  3380. if (this.initPollInterval) {
  3381. clearInterval(this.initPollInterval);
  3382. this.initPollInterval = false;
  3383. }
  3384. this.embedTo.innerHTML = '';
  3385. };
  3386. PreziPlayer.prototype.sendMessage = function(message) {
  3387. if (this.options.debug === true) {
  3388. if (console && console.log) console.log('sent', message);
  3389. }
  3390. message.version = PreziPlayer.API_VERSION;
  3391. message.id = this.id;
  3392. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3393. };
  3394. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3395. PreziPlayer.prototype.flyToNextStep = function() {
  3396. return this.sendMessage({
  3397. 'action': 'present',
  3398. 'data': ['moveToNextStep']
  3399. });
  3400. };
  3401. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3402. PreziPlayer.prototype.flyToPreviousStep = function() {
  3403. return this.sendMessage({
  3404. 'action': 'present',
  3405. 'data': ['moveToPrevStep']
  3406. });
  3407. };
  3408. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3409. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3410. var obj = this;
  3411. // check animation_step
  3412. if (animation_step > 0 &&
  3413. obj.values.animationCountOnSteps &&
  3414. obj.values.animationCountOnSteps[step] <= animation_step) {
  3415. animation_step = obj.values.animationCountOnSteps[step];
  3416. }
  3417. // jump to animation steps by calling flyToNextStep()
  3418. function doAnimationSteps() {
  3419. if (obj.values.isMoving == true) {
  3420. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3421. return;
  3422. }
  3423. while (animation_step-- > 0) {
  3424. obj.flyToNextStep(); // do the animation steps
  3425. }
  3426. }
  3427. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3428. // jump to the step
  3429. return this.sendMessage({
  3430. 'action': 'present',
  3431. 'data': ['moveToStep', step]
  3432. });
  3433. };
  3434. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3435. PreziPlayer.prototype.flyToObject = function(objectId) {
  3436. return this.sendMessage({
  3437. 'action': 'present',
  3438. 'data': ['moveToObject', objectId]
  3439. });
  3440. };
  3441. PreziPlayer.prototype.play = function(defaultDelay) {
  3442. return this.sendMessage({
  3443. 'action': 'present',
  3444. 'data': ['startAutoPlay', defaultDelay]
  3445. });
  3446. };
  3447. PreziPlayer.prototype.stop = function() {
  3448. return this.sendMessage({
  3449. 'action': 'present',
  3450. 'data': ['stopAutoPlay']
  3451. });
  3452. };
  3453. PreziPlayer.prototype.pause = function(defaultDelay) {
  3454. return this.sendMessage({
  3455. 'action': 'present',
  3456. 'data': ['pauseAutoPlay', defaultDelay]
  3457. });
  3458. };
  3459. PreziPlayer.prototype.getCurrentStep = function() {
  3460. return this.values.currentStep;
  3461. };
  3462. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3463. return this.values.currentAnimationStep;
  3464. };
  3465. PreziPlayer.prototype.getCurrentObject = function() {
  3466. return this.values.currentObject;
  3467. };
  3468. PreziPlayer.prototype.getStatus = function() {
  3469. return this.values.status;
  3470. };
  3471. PreziPlayer.prototype.isPlaying = function() {
  3472. return this.values.isAutoPlaying;
  3473. };
  3474. PreziPlayer.prototype.getStepCount = function() {
  3475. return this.values.stepCount;
  3476. };
  3477. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3478. return this.values.animationCountOnSteps;
  3479. };
  3480. PreziPlayer.prototype.getTitle = function() {
  3481. return this.values.title;
  3482. };
  3483. PreziPlayer.prototype.setDimensions = function(dims) {
  3484. for (var parameter in dims) {
  3485. this.iframe[parameter] = dims[parameter];
  3486. }
  3487. }
  3488. PreziPlayer.prototype.getDimensions = function() {
  3489. return {
  3490. width: parseInt(this.iframe.width, 10),
  3491. height: parseInt(this.iframe.height, 10)
  3492. }
  3493. }
  3494. PreziPlayer.prototype.on = function(event, callback) {
  3495. this.callbacks.push({
  3496. event: event,
  3497. callback: callback
  3498. });
  3499. };
  3500. PreziPlayer.prototype.off = function(event, callback) {
  3501. var j, item;
  3502. if (event === undefined) {
  3503. this.callbacks = [];
  3504. }
  3505. j = this.callbacks.length;
  3506. while (j--) {
  3507. item = this.callbacks[j];
  3508. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3509. this.callbacks.splice(j, 1);
  3510. }
  3511. }
  3512. };
  3513. if (window.addEventListener) {
  3514. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3515. } else {
  3516. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3517. }
  3518. return PreziPlayer;
  3519. })();
  3520. })();
  3521. module.exports = PreziPlayer;
  3522. },{}],17:[function(require,module,exports){
  3523. var Chat = require("./chat/Chat");
  3524. var ContactList = require("./contactlist/ContactList");
  3525. var Settings = require("./../../settings/Settings");
  3526. var SettingsMenu = require("./settings/SettingsMenu");
  3527. var VideoLayout = require("../videolayout/VideoLayout");
  3528. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3529. var UIUtil = require("../util/UIUtil");
  3530. /**
  3531. * Toggler for the chat, contact list, settings menu, etc..
  3532. */
  3533. var PanelToggler = (function(my) {
  3534. var currentlyOpen = null;
  3535. var buttons = {
  3536. '#chatspace': '#chatBottomButton',
  3537. '#contactlist': '#contactListButton',
  3538. '#settingsmenu': '#settingsButton'
  3539. };
  3540. /**
  3541. * Resizes the video area
  3542. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3543. * @param completeFunction a function to be called when the video space is resized
  3544. */
  3545. var resizeVideoArea = function(isClosing, completeFunction) {
  3546. var videospace = $('#videospace');
  3547. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3548. var videospaceWidth = window.innerWidth - panelSize[0];
  3549. var videospaceHeight = window.innerHeight;
  3550. var videoSize
  3551. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3552. var videoWidth = videoSize[0];
  3553. var videoHeight = videoSize[1];
  3554. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3555. videoHeight,
  3556. videospaceWidth,
  3557. videospaceHeight);
  3558. var horizontalIndent = videoPosition[0];
  3559. var verticalIndent = videoPosition[1];
  3560. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3561. var thumbnailsWidth = thumbnailSize[0];
  3562. var thumbnailsHeight = thumbnailSize[1];
  3563. //for chat
  3564. videospace.animate({
  3565. right: panelSize[0],
  3566. width: videospaceWidth,
  3567. height: videospaceHeight
  3568. },
  3569. {
  3570. queue: false,
  3571. duration: 500,
  3572. complete: completeFunction
  3573. });
  3574. $('#remoteVideos').animate({
  3575. height: thumbnailsHeight
  3576. },
  3577. {
  3578. queue: false,
  3579. duration: 500
  3580. });
  3581. $('#remoteVideos>span').animate({
  3582. height: thumbnailsHeight,
  3583. width: thumbnailsWidth
  3584. },
  3585. {
  3586. queue: false,
  3587. duration: 500,
  3588. complete: function () {
  3589. $(document).trigger(
  3590. "remotevideo.resized",
  3591. [thumbnailsWidth,
  3592. thumbnailsHeight]);
  3593. }
  3594. });
  3595. $('#largeVideoContainer').animate({
  3596. width: videospaceWidth,
  3597. height: videospaceHeight
  3598. },
  3599. {
  3600. queue: false,
  3601. duration: 500
  3602. });
  3603. $('#largeVideo').animate({
  3604. width: videoWidth,
  3605. height: videoHeight,
  3606. top: verticalIndent,
  3607. bottom: verticalIndent,
  3608. left: horizontalIndent,
  3609. right: horizontalIndent
  3610. },
  3611. {
  3612. queue: false,
  3613. duration: 500
  3614. });
  3615. };
  3616. /**
  3617. * Toggles the windows in the side panel
  3618. * @param object the window that should be shown
  3619. * @param selector the selector for the element containing the panel
  3620. * @param onOpenComplete function to be called when the panel is opened
  3621. * @param onOpen function to be called if the window is going to be opened
  3622. * @param onClose function to be called if the window is going to be closed
  3623. */
  3624. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3625. UIUtil.buttonClick(buttons[selector], "active");
  3626. if (object.isVisible()) {
  3627. $("#toast-container").animate({
  3628. right: '5px'
  3629. },
  3630. {
  3631. queue: false,
  3632. duration: 500
  3633. });
  3634. $(selector).hide("slide", {
  3635. direction: "right",
  3636. queue: false,
  3637. duration: 500
  3638. });
  3639. if(typeof onClose === "function") {
  3640. onClose();
  3641. }
  3642. currentlyOpen = null;
  3643. }
  3644. else {
  3645. // Undock the toolbar when the chat is shown and if we're in a
  3646. // video mode.
  3647. if (VideoLayout.isLargeVideoVisible()) {
  3648. ToolbarToggler.dockToolbar(false);
  3649. }
  3650. if(currentlyOpen) {
  3651. var current = $(currentlyOpen);
  3652. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3653. current.css('z-index', 4);
  3654. setTimeout(function () {
  3655. current.css('display', 'none');
  3656. current.css('z-index', 5);
  3657. }, 500);
  3658. }
  3659. $("#toast-container").animate({
  3660. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3661. },
  3662. {
  3663. queue: false,
  3664. duration: 500
  3665. });
  3666. $(selector).show("slide", {
  3667. direction: "right",
  3668. queue: false,
  3669. duration: 500,
  3670. complete: onOpenComplete
  3671. });
  3672. if(typeof onOpen === "function") {
  3673. onOpen();
  3674. }
  3675. currentlyOpen = selector;
  3676. }
  3677. };
  3678. /**
  3679. * Opens / closes the chat area.
  3680. */
  3681. my.toggleChat = function() {
  3682. var chatCompleteFunction = Chat.isVisible() ?
  3683. function() {} : function () {
  3684. Chat.scrollChatToBottom();
  3685. $('#chatspace').trigger('shown');
  3686. };
  3687. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3688. toggle(Chat,
  3689. '#chatspace',
  3690. function () {
  3691. // Request the focus in the nickname field or the chat input field.
  3692. if ($('#nickname').css('visibility') === 'visible') {
  3693. $('#nickinput').focus();
  3694. } else {
  3695. $('#usermsg').focus();
  3696. }
  3697. },
  3698. null,
  3699. Chat.resizeChat,
  3700. null);
  3701. };
  3702. /**
  3703. * Opens / closes the contact list area.
  3704. */
  3705. my.toggleContactList = function () {
  3706. var completeFunction = ContactList.isVisible() ?
  3707. function() {} : function () { $('#contactlist').trigger('shown');};
  3708. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3709. toggle(ContactList,
  3710. '#contactlist',
  3711. null,
  3712. function() {
  3713. ContactList.setVisualNotification(false);
  3714. },
  3715. null);
  3716. };
  3717. /**
  3718. * Opens / closes the settings menu
  3719. */
  3720. my.toggleSettingsMenu = function() {
  3721. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3722. toggle(SettingsMenu,
  3723. '#settingsmenu',
  3724. null,
  3725. function() {
  3726. var settings = Settings.getSettings();
  3727. $('#setDisplayName').get(0).value = settings.displayName;
  3728. $('#setEmail').get(0).value = settings.email;
  3729. },
  3730. null);
  3731. };
  3732. /**
  3733. * Returns the size of the side panel.
  3734. */
  3735. my.getPanelSize = function () {
  3736. var availableHeight = window.innerHeight;
  3737. var availableWidth = window.innerWidth;
  3738. var panelWidth = 200;
  3739. if (availableWidth * 0.2 < 200) {
  3740. panelWidth = availableWidth * 0.2;
  3741. }
  3742. return [panelWidth, availableHeight];
  3743. };
  3744. my.isVisible = function() {
  3745. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3746. };
  3747. return my;
  3748. }(PanelToggler || {}));
  3749. module.exports = PanelToggler;
  3750. },{"../toolbars/ToolbarToggler":26,"../util/UIUtil":30,"../videolayout/VideoLayout":32,"./../../settings/Settings":39,"./chat/Chat":18,"./contactlist/ContactList":22,"./settings/SettingsMenu":23}],18:[function(require,module,exports){
  3751. /* global $, Util, nickname:true */
  3752. var Replacement = require("./Replacement");
  3753. var CommandsProcessor = require("./Commands");
  3754. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3755. var smileys = require("./smileys.json").smileys;
  3756. var NicknameHandler = require("../../util/NicknameHandler");
  3757. var UIUtil = require("../../util/UIUtil");
  3758. var UIEvents = require("../../../../service/UI/UIEvents");
  3759. var notificationInterval = false;
  3760. var unreadMessages = 0;
  3761. /**
  3762. * Shows/hides a visual notification, indicating that a message has arrived.
  3763. */
  3764. function setVisualNotification(show) {
  3765. var unreadMsgElement = document.getElementById('unreadMessages');
  3766. var unreadMsgBottomElement
  3767. = document.getElementById('bottomUnreadMessages');
  3768. var glower = $('#chatButton');
  3769. var bottomGlower = $('#chatBottomButton');
  3770. if (unreadMessages) {
  3771. unreadMsgElement.innerHTML = unreadMessages.toString();
  3772. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3773. ToolbarToggler.dockToolbar(true);
  3774. var chatButtonElement
  3775. = document.getElementById('chatButton').parentNode;
  3776. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3777. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3778. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3779. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3780. unreadMsgElement.setAttribute(
  3781. 'style',
  3782. 'top:' + topIndent +
  3783. '; left:' + leftIndent + ';');
  3784. var chatBottomButtonElement
  3785. = document.getElementById('chatBottomButton').parentNode;
  3786. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3787. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3788. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3789. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3790. unreadMsgBottomElement.setAttribute(
  3791. 'style',
  3792. 'top:' + bottomTopIndent +
  3793. '; left:' + bottomLeftIndent + ';');
  3794. if (!glower.hasClass('icon-chat-simple')) {
  3795. glower.removeClass('icon-chat');
  3796. glower.addClass('icon-chat-simple');
  3797. }
  3798. }
  3799. else {
  3800. unreadMsgElement.innerHTML = '';
  3801. unreadMsgBottomElement.innerHTML = '';
  3802. glower.removeClass('icon-chat-simple');
  3803. glower.addClass('icon-chat');
  3804. }
  3805. if (show && !notificationInterval) {
  3806. notificationInterval = window.setInterval(function () {
  3807. glower.toggleClass('active');
  3808. bottomGlower.toggleClass('active glowing');
  3809. }, 800);
  3810. }
  3811. else if (!show && notificationInterval) {
  3812. window.clearInterval(notificationInterval);
  3813. notificationInterval = false;
  3814. glower.removeClass('active');
  3815. bottomGlower.removeClass('glowing');
  3816. bottomGlower.addClass('active');
  3817. }
  3818. }
  3819. /**
  3820. * Returns the current time in the format it is shown to the user
  3821. * @returns {string}
  3822. */
  3823. function getCurrentTime() {
  3824. var now = new Date();
  3825. var hour = now.getHours();
  3826. var minute = now.getMinutes();
  3827. var second = now.getSeconds();
  3828. if(hour.toString().length === 1) {
  3829. hour = '0'+hour;
  3830. }
  3831. if(minute.toString().length === 1) {
  3832. minute = '0'+minute;
  3833. }
  3834. if(second.toString().length === 1) {
  3835. second = '0'+second;
  3836. }
  3837. return hour+':'+minute+':'+second;
  3838. }
  3839. function toggleSmileys()
  3840. {
  3841. var smileys = $('#smileysContainer');
  3842. if(!smileys.is(':visible')) {
  3843. smileys.show("slide", { direction: "down", duration: 300});
  3844. } else {
  3845. smileys.hide("slide", { direction: "down", duration: 300});
  3846. }
  3847. $('#usermsg').focus();
  3848. }
  3849. function addClickFunction(smiley, number) {
  3850. smiley.onclick = function addSmileyToMessage() {
  3851. var usermsg = $('#usermsg');
  3852. var message = usermsg.val();
  3853. message += smileys['smiley' + number];
  3854. usermsg.val(message);
  3855. usermsg.get(0).setSelectionRange(message.length, message.length);
  3856. toggleSmileys();
  3857. usermsg.focus();
  3858. };
  3859. }
  3860. /**
  3861. * Adds the smileys container to the chat
  3862. */
  3863. function addSmileys() {
  3864. var smileysContainer = document.createElement('div');
  3865. smileysContainer.id = 'smileysContainer';
  3866. for(var i = 1; i <= 21; i++) {
  3867. var smileyContainer = document.createElement('div');
  3868. smileyContainer.id = 'smiley' + i;
  3869. smileyContainer.className = 'smileyContainer';
  3870. var smiley = document.createElement('img');
  3871. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3872. smiley.className = 'smiley';
  3873. addClickFunction(smiley, i);
  3874. smileyContainer.appendChild(smiley);
  3875. smileysContainer.appendChild(smileyContainer);
  3876. }
  3877. $("#chatspace").append(smileysContainer);
  3878. }
  3879. /**
  3880. * Resizes the chat conversation.
  3881. */
  3882. function resizeChatConversation() {
  3883. var msgareaHeight = $('#usermsg').outerHeight();
  3884. var chatspace = $('#chatspace');
  3885. var width = chatspace.width();
  3886. var chat = $('#chatconversation');
  3887. var smileys = $('#smileysarea');
  3888. smileys.height(msgareaHeight);
  3889. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3890. $('#smileysContainer').css('bottom', msgareaHeight);
  3891. chat.width(width - 10);
  3892. chat.height(window.innerHeight - 15 - msgareaHeight);
  3893. }
  3894. /**
  3895. * Chat related user interface.
  3896. */
  3897. var Chat = (function (my) {
  3898. /**
  3899. * Initializes chat related interface.
  3900. */
  3901. my.init = function () {
  3902. if(NicknameHandler.getNickname())
  3903. Chat.setChatConversationMode(true);
  3904. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3905. function (nickname) {
  3906. Chat.setChatConversationMode(true);
  3907. });
  3908. $('#nickinput').keydown(function (event) {
  3909. if (event.keyCode === 13) {
  3910. event.preventDefault();
  3911. var val = UIUtil.escapeHtml(this.value);
  3912. this.value = '';
  3913. if (!NicknameHandler.getNickname()) {
  3914. NicknameHandler.setNickname(val);
  3915. return;
  3916. }
  3917. }
  3918. });
  3919. $('#usermsg').keydown(function (event) {
  3920. if (event.keyCode === 13) {
  3921. event.preventDefault();
  3922. var value = this.value;
  3923. $('#usermsg').val('').trigger('autosize.resize');
  3924. this.focus();
  3925. var command = new CommandsProcessor(value);
  3926. if(command.isCommand())
  3927. {
  3928. command.processCommand();
  3929. }
  3930. else
  3931. {
  3932. var message = UIUtil.escapeHtml(value);
  3933. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3934. }
  3935. }
  3936. });
  3937. var onTextAreaResize = function () {
  3938. resizeChatConversation();
  3939. Chat.scrollChatToBottom();
  3940. };
  3941. $('#usermsg').autosize({callback: onTextAreaResize});
  3942. $("#chatspace").bind("shown",
  3943. function () {
  3944. unreadMessages = 0;
  3945. setVisualNotification(false);
  3946. });
  3947. addSmileys();
  3948. };
  3949. /**
  3950. * Appends the given message to the chat conversation.
  3951. */
  3952. my.updateChatConversation = function (from, displayName, message) {
  3953. var divClassName = '';
  3954. if (APP.xmpp.myJid() === from) {
  3955. divClassName = "localuser";
  3956. }
  3957. else {
  3958. divClassName = "remoteuser";
  3959. if (!Chat.isVisible()) {
  3960. unreadMessages++;
  3961. UIUtil.playSoundNotification('chatNotification');
  3962. setVisualNotification(true);
  3963. }
  3964. }
  3965. // replace links and smileys
  3966. // Strophe already escapes special symbols on sending,
  3967. // so we escape here only tags to avoid double &amp;
  3968. var escMessage = message.replace(/</g, '&lt;').
  3969. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3970. var escDisplayName = UIUtil.escapeHtml(displayName);
  3971. message = Replacement.processReplacements(escMessage);
  3972. var messageContainer =
  3973. '<div class="chatmessage">'+
  3974. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3975. '<div class="username ' + divClassName +'">' + escDisplayName +
  3976. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3977. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3978. '</div>';
  3979. $('#chatconversation').append(messageContainer);
  3980. $('#chatconversation').animate(
  3981. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3982. };
  3983. /**
  3984. * Appends error message to the conversation
  3985. * @param errorMessage the received error message.
  3986. * @param originalText the original message.
  3987. */
  3988. my.chatAddError = function(errorMessage, originalText)
  3989. {
  3990. errorMessage = UIUtil.escapeHtml(errorMessage);
  3991. originalText = UIUtil.escapeHtml(originalText);
  3992. $('#chatconversation').append(
  3993. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3994. (originalText? (' \"'+ originalText + '\"') : "") +
  3995. ' was not sent.' +
  3996. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3997. $('#chatconversation').animate(
  3998. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3999. };
  4000. /**
  4001. * Sets the subject to the UI
  4002. * @param subject the subject
  4003. */
  4004. my.chatSetSubject = function(subject)
  4005. {
  4006. if(subject)
  4007. subject = subject.trim();
  4008. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  4009. if(subject === "")
  4010. {
  4011. $("#subject").css({display: "none"});
  4012. }
  4013. else
  4014. {
  4015. $("#subject").css({display: "block"});
  4016. }
  4017. };
  4018. /**
  4019. * Sets the chat conversation mode.
  4020. */
  4021. my.setChatConversationMode = function (isConversationMode) {
  4022. if (isConversationMode) {
  4023. $('#nickname').css({visibility: 'hidden'});
  4024. $('#chatconversation').css({visibility: 'visible'});
  4025. $('#usermsg').css({visibility: 'visible'});
  4026. $('#smileysarea').css({visibility: 'visible'});
  4027. $('#usermsg').focus();
  4028. }
  4029. };
  4030. /**
  4031. * Resizes the chat area.
  4032. */
  4033. my.resizeChat = function () {
  4034. var chatSize = require("../SidePanelToggler").getPanelSize();
  4035. $('#chatspace').width(chatSize[0]);
  4036. $('#chatspace').height(chatSize[1]);
  4037. resizeChatConversation();
  4038. };
  4039. /**
  4040. * Indicates if the chat is currently visible.
  4041. */
  4042. my.isVisible = function () {
  4043. return $('#chatspace').is(":visible");
  4044. };
  4045. /**
  4046. * Shows and hides the window with the smileys
  4047. */
  4048. my.toggleSmileys = toggleSmileys;
  4049. /**
  4050. * Scrolls chat to the bottom.
  4051. */
  4052. my.scrollChatToBottom = function() {
  4053. setTimeout(function () {
  4054. $('#chatconversation').scrollTop(
  4055. $('#chatconversation')[0].scrollHeight);
  4056. }, 5);
  4057. };
  4058. return my;
  4059. }(Chat || {}));
  4060. module.exports = Chat;
  4061. },{"../../../../service/UI/UIEvents":99,"../../toolbars/ToolbarToggler":26,"../../util/NicknameHandler":29,"../../util/UIUtil":30,"../SidePanelToggler":17,"./Commands":19,"./Replacement":20,"./smileys.json":21}],19:[function(require,module,exports){
  4062. var UIUtil = require("../../util/UIUtil");
  4063. /**
  4064. * List with supported commands. The keys are the names of the commands and
  4065. * the value is the function that processes the message.
  4066. * @type {{String: function}}
  4067. */
  4068. var commands = {
  4069. "topic" : processTopic
  4070. };
  4071. /**
  4072. * Extracts the command from the message.
  4073. * @param message the received message
  4074. * @returns {string} the command
  4075. */
  4076. function getCommand(message)
  4077. {
  4078. if(message)
  4079. {
  4080. for(var command in commands)
  4081. {
  4082. if(message.indexOf("/" + command) == 0)
  4083. return command;
  4084. }
  4085. }
  4086. return "";
  4087. };
  4088. /**
  4089. * Processes the data for topic command.
  4090. * @param commandArguments the arguments of the topic command.
  4091. */
  4092. function processTopic(commandArguments)
  4093. {
  4094. var topic = UIUtil.escapeHtml(commandArguments);
  4095. APP.xmpp.setSubject(topic);
  4096. }
  4097. /**
  4098. * Constructs new CommandProccessor instance from a message that
  4099. * handles commands received via chat messages.
  4100. * @param message the message
  4101. * @constructor
  4102. */
  4103. function CommandsProcessor(message)
  4104. {
  4105. var command = getCommand(message);
  4106. /**
  4107. * Returns the name of the command.
  4108. * @returns {String} the command
  4109. */
  4110. this.getCommand = function()
  4111. {
  4112. return command;
  4113. };
  4114. var messageArgument = message.substr(command.length + 2);
  4115. /**
  4116. * Returns the arguments of the command.
  4117. * @returns {string}
  4118. */
  4119. this.getArgument = function()
  4120. {
  4121. return messageArgument;
  4122. };
  4123. }
  4124. /**
  4125. * Checks whether this instance is valid command or not.
  4126. * @returns {boolean}
  4127. */
  4128. CommandsProcessor.prototype.isCommand = function()
  4129. {
  4130. if(this.getCommand())
  4131. return true;
  4132. return false;
  4133. };
  4134. /**
  4135. * Processes the command.
  4136. */
  4137. CommandsProcessor.prototype.processCommand = function()
  4138. {
  4139. if(!this.isCommand())
  4140. return;
  4141. commands[this.getCommand()](this.getArgument());
  4142. };
  4143. module.exports = CommandsProcessor;
  4144. },{"../../util/UIUtil":30}],20:[function(require,module,exports){
  4145. var Smileys = require("./smileys.json");
  4146. /**
  4147. * Processes links and smileys in "body"
  4148. */
  4149. function processReplacements(body)
  4150. {
  4151. //make links clickable
  4152. body = linkify(body);
  4153. //add smileys
  4154. body = smilify(body);
  4155. return body;
  4156. }
  4157. /**
  4158. * Finds and replaces all links in the links in "body"
  4159. * with their <a href=""></a>
  4160. */
  4161. function linkify(inputText)
  4162. {
  4163. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4164. //URLs starting with http://, https://, or ftp://
  4165. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4166. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4167. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4168. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4169. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4170. //Change email addresses to mailto:: links.
  4171. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4172. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4173. return replacedText;
  4174. }
  4175. /**
  4176. * Replaces common smiley strings with images
  4177. */
  4178. function smilify(body)
  4179. {
  4180. if(!body) {
  4181. return body;
  4182. }
  4183. var regexs = Smileys["regexs"];
  4184. for(var smiley in regexs) {
  4185. if(regexs.hasOwnProperty(smiley)) {
  4186. body = body.replace(regexs[smiley],
  4187. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4188. }
  4189. }
  4190. return body;
  4191. }
  4192. module.exports = {
  4193. processReplacements: processReplacements,
  4194. linkify: linkify
  4195. };
  4196. },{"./smileys.json":21}],21:[function(require,module,exports){
  4197. module.exports={
  4198. "smileys": {
  4199. "smiley1": ":)",
  4200. "smiley2": ":(",
  4201. "smiley3": ":D",
  4202. "smiley4": "(y)",
  4203. "smiley5": " :P",
  4204. "smiley6": "(wave)",
  4205. "smiley7": "(blush)",
  4206. "smiley8": "(chuckle)",
  4207. "smiley9": "(shocked)",
  4208. "smiley10": ":*",
  4209. "smiley11": "(n)",
  4210. "smiley12": "(search)",
  4211. "smiley13": " <3",
  4212. "smiley14": "(oops)",
  4213. "smiley15": "(angry)",
  4214. "smiley16": "(angel)",
  4215. "smiley17": "(sick)",
  4216. "smiley18": ";(",
  4217. "smiley19": "(bomb)",
  4218. "smiley20": "(clap)",
  4219. "smiley21": " ;)"
  4220. },
  4221. "regexs": {
  4222. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4223. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4224. "smiley1": /(:-\)|:\))/gi,
  4225. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4226. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4227. "smiley6": /(\(wave\))/gi,
  4228. "smiley7": /(\(blush\))/gi,
  4229. "smiley8": /(\(chuckle\))/gi,
  4230. "smiley9": /(:-0|\(shocked\))/gi,
  4231. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4232. "smiley11": /(\(n\))/gi,
  4233. "smiley12": /(\(search\))/g,
  4234. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4235. "smiley14": /(\(oops\))/gi,
  4236. "smiley15": /(\(angry\))/gi,
  4237. "smiley16": /(\(angel\))/gi,
  4238. "smiley17": /(\(sick\))/gi,
  4239. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4240. "smiley19": /(\(bomb\))/gi,
  4241. "smiley20": /(\(clap\))/gi,
  4242. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4243. }
  4244. }
  4245. },{}],22:[function(require,module,exports){
  4246. var numberOfContacts = 0;
  4247. var notificationInterval;
  4248. /**
  4249. * Updates the number of participants in the contact list button and sets
  4250. * the glow
  4251. * @param delta indicates whether a new user has joined (1) or someone has
  4252. * left(-1)
  4253. */
  4254. function updateNumberOfParticipants(delta) {
  4255. //when the user is alone we don't show the number of participants
  4256. if(numberOfContacts === 0) {
  4257. $("#numberOfParticipants").text('');
  4258. numberOfContacts += delta;
  4259. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4260. ContactList.setVisualNotification(true);
  4261. numberOfContacts += delta;
  4262. $("#numberOfParticipants").text(numberOfContacts);
  4263. }
  4264. }
  4265. /**
  4266. * Creates the avatar element.
  4267. *
  4268. * @return the newly created avatar element
  4269. */
  4270. function createAvatar(id) {
  4271. var avatar = document.createElement('img');
  4272. avatar.className = "icon-avatar avatar";
  4273. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4274. return avatar;
  4275. }
  4276. /**
  4277. * Creates the display name paragraph.
  4278. *
  4279. * @param displayName the display name to set
  4280. */
  4281. function createDisplayNameParagraph(key, displayName) {
  4282. var p = document.createElement('p');
  4283. if(displayName)
  4284. p.innerText = displayName;
  4285. else if(key)
  4286. {
  4287. p.setAttribute("data-i18n",key);
  4288. p.innerText = APP.translation.translateString(key);
  4289. }
  4290. return p;
  4291. }
  4292. function stopGlowing(glower) {
  4293. window.clearInterval(notificationInterval);
  4294. notificationInterval = false;
  4295. glower.removeClass('glowing');
  4296. if (!ContactList.isVisible()) {
  4297. glower.removeClass('active');
  4298. }
  4299. }
  4300. /**
  4301. * Contact list.
  4302. */
  4303. var ContactList = {
  4304. /**
  4305. * Indicates if the chat is currently visible.
  4306. *
  4307. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4308. * otherwise
  4309. */
  4310. isVisible: function () {
  4311. return $('#contactlist').is(":visible");
  4312. },
  4313. /**
  4314. * Adds a contact for the given peerJid if such doesn't yet exist.
  4315. *
  4316. * @param peerJid the peerJid corresponding to the contact
  4317. * @param id the user's email or userId used to get the user's avatar
  4318. */
  4319. ensureAddContact: function (peerJid, id) {
  4320. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4321. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4322. if (!contact || contact.length <= 0)
  4323. ContactList.addContact(peerJid, id);
  4324. },
  4325. /**
  4326. * Adds a contact for the given peer jid.
  4327. *
  4328. * @param peerJid the jid of the contact to add
  4329. * @param id the email or userId of the user
  4330. */
  4331. addContact: function (peerJid, id) {
  4332. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4333. var contactlist = $('#contactlist>ul');
  4334. var newContact = document.createElement('li');
  4335. newContact.id = resourceJid;
  4336. newContact.className = "clickable";
  4337. newContact.onclick = function (event) {
  4338. if (event.currentTarget.className === "clickable") {
  4339. $(ContactList).trigger('contactclicked', [peerJid]);
  4340. }
  4341. };
  4342. newContact.appendChild(createAvatar(id));
  4343. newContact.appendChild(createDisplayNameParagraph("participant"));
  4344. var clElement = contactlist.get(0);
  4345. if (resourceJid === APP.xmpp.myResource()
  4346. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4347. clElement.insertBefore(newContact,
  4348. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4349. }
  4350. else {
  4351. clElement.appendChild(newContact);
  4352. }
  4353. updateNumberOfParticipants(1);
  4354. },
  4355. /**
  4356. * Removes a contact for the given peer jid.
  4357. *
  4358. * @param peerJid the peerJid corresponding to the contact to remove
  4359. */
  4360. removeContact: function (peerJid) {
  4361. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4362. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4363. if (contact && contact.length > 0) {
  4364. var contactlist = $('#contactlist>ul');
  4365. contactlist.get(0).removeChild(contact.get(0));
  4366. updateNumberOfParticipants(-1);
  4367. }
  4368. },
  4369. setVisualNotification: function (show, stopGlowingIn) {
  4370. var glower = $('#contactListButton');
  4371. if (show && !notificationInterval) {
  4372. notificationInterval = window.setInterval(function () {
  4373. glower.toggleClass('active glowing');
  4374. }, 800);
  4375. }
  4376. else if (!show && notificationInterval) {
  4377. stopGlowing(glower);
  4378. }
  4379. if (stopGlowingIn) {
  4380. setTimeout(function () {
  4381. stopGlowing(glower);
  4382. }, stopGlowingIn);
  4383. }
  4384. },
  4385. setClickable: function (resourceJid, isClickable) {
  4386. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4387. if (isClickable) {
  4388. contact.addClass('clickable');
  4389. } else {
  4390. contact.removeClass('clickable');
  4391. }
  4392. },
  4393. onDisplayNameChange: function (peerJid, displayName) {
  4394. if (peerJid === 'localVideoContainer')
  4395. peerJid = APP.xmpp.myJid();
  4396. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4397. var contactName = $('#contactlist #' + resourceJid + '>p');
  4398. if (contactName && displayName && displayName.length > 0)
  4399. contactName.html(displayName);
  4400. }
  4401. };
  4402. module.exports = ContactList;
  4403. },{}],23:[function(require,module,exports){
  4404. var Avatar = require("../../avatar/Avatar");
  4405. var Settings = require("./../../../settings/Settings");
  4406. var UIUtil = require("../../util/UIUtil");
  4407. var languages = require("../../../../service/translation/languages");
  4408. function generateLanguagesSelectBox()
  4409. {
  4410. var currentLang = APP.translation.getCurrentLanguage();
  4411. var html = "<select id=\"languages_selectbox\">";
  4412. var langArray = languages.getLanguages();
  4413. for(var i = 0; i < langArray.length; i++)
  4414. {
  4415. var lang = langArray[i];
  4416. html += "<option ";
  4417. if(lang === currentLang)
  4418. html += "selected ";
  4419. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4420. html += "</option>";
  4421. }
  4422. return html + "</select>";
  4423. }
  4424. var SettingsMenu = {
  4425. init: function () {
  4426. $("#startMutedOptions").before(generateLanguagesSelectBox());
  4427. APP.translation.translateElement($("#languages_selectbox"));
  4428. $('#settingsmenu>input').keyup(function(event){
  4429. if(event.keyCode === 13) {//enter
  4430. SettingsMenu.update();
  4431. }
  4432. });
  4433. if(APP.xmpp.isModerator())
  4434. {
  4435. $("#startMutedOptions").css("display", "block");
  4436. }
  4437. else
  4438. {
  4439. $("#startMutedOptions").css("display", "none");
  4440. }
  4441. $("#updateSettings").click(function () {
  4442. SettingsMenu.update();
  4443. });
  4444. },
  4445. onRoleChanged: function () {
  4446. if(APP.xmpp.isModerator())
  4447. {
  4448. $("#startMutedOptions").css("display", "block");
  4449. }
  4450. else
  4451. {
  4452. $("#startMutedOptions").css("display", "none");
  4453. }
  4454. },
  4455. setStartMuted: function (audio, video) {
  4456. $("#startAudioMuted").attr("checked", audio);
  4457. $("#startVideoMuted").attr("checked", video);
  4458. },
  4459. update: function() {
  4460. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4461. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4462. if(newDisplayName) {
  4463. var displayName = Settings.setDisplayName(newDisplayName);
  4464. APP.xmpp.addToPresence("displayName", displayName, true);
  4465. }
  4466. var language = $("#languages_selectbox").val();
  4467. APP.translation.setLanguage(language);
  4468. Settings.setLanguage(language);
  4469. APP.xmpp.addToPresence("email", newEmail);
  4470. var email = Settings.setEmail(newEmail);
  4471. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  4472. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  4473. APP.xmpp.addToPresence("startMuted",
  4474. [startAudioMuted, startVideoMuted]);
  4475. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4476. },
  4477. isVisible: function() {
  4478. return $('#settingsmenu').is(':visible');
  4479. },
  4480. setDisplayName: function(newDisplayName) {
  4481. var displayName = Settings.setDisplayName(newDisplayName);
  4482. $('#setDisplayName').get(0).value = displayName;
  4483. },
  4484. onDisplayNameChange: function(peerJid, newDisplayName) {
  4485. if(peerJid === 'localVideoContainer' ||
  4486. peerJid === APP.xmpp.myJid()) {
  4487. this.setDisplayName(newDisplayName);
  4488. }
  4489. }
  4490. };
  4491. module.exports = SettingsMenu;
  4492. },{"../../../../service/translation/languages":104,"../../avatar/Avatar":13,"../../util/UIUtil":30,"./../../../settings/Settings":39}],24:[function(require,module,exports){
  4493. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4494. var buttonHandlers = {
  4495. "bottom_toolbar_contact_list": function () {
  4496. BottomToolbar.toggleContactList();
  4497. },
  4498. "bottom_toolbar_film_strip": function () {
  4499. BottomToolbar.toggleFilmStrip();
  4500. },
  4501. "bottom_toolbar_chat": function () {
  4502. BottomToolbar.toggleChat();
  4503. }
  4504. };
  4505. var BottomToolbar = (function (my) {
  4506. my.init = function () {
  4507. for(var k in buttonHandlers)
  4508. $("#" + k).click(buttonHandlers[k]);
  4509. };
  4510. my.toggleChat = function() {
  4511. PanelToggler.toggleChat();
  4512. };
  4513. my.toggleContactList = function() {
  4514. PanelToggler.toggleContactList();
  4515. };
  4516. my.toggleFilmStrip = function() {
  4517. var filmstrip = $("#remoteVideos");
  4518. filmstrip.toggleClass("hidden");
  4519. };
  4520. $(document).bind("remotevideo.resized", function (event, width, height) {
  4521. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4522. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4523. });
  4524. return my;
  4525. }(BottomToolbar || {}));
  4526. module.exports = BottomToolbar;
  4527. },{"../side_pannels/SidePanelToggler":17}],25:[function(require,module,exports){
  4528. /* global APP,$, buttonClick, config, lockRoom,
  4529. setSharedKey, Util */
  4530. var messageHandler = require("../util/MessageHandler");
  4531. var BottomToolbar = require("./BottomToolbar");
  4532. var Prezi = require("../prezi/Prezi");
  4533. var Etherpad = require("../etherpad/Etherpad");
  4534. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4535. var Authentication = require("../authentication/Authentication");
  4536. var UIUtil = require("../util/UIUtil");
  4537. var AuthenticationEvents
  4538. = require("../../../service/authentication/AuthenticationEvents");
  4539. var roomUrl = null;
  4540. var sharedKey = '';
  4541. var UI = null;
  4542. var buttonHandlers =
  4543. {
  4544. "toolbar_button_mute": function () {
  4545. return APP.UI.toggleAudio();
  4546. },
  4547. "toolbar_button_camera": function () {
  4548. return APP.UI.toggleVideo();
  4549. },
  4550. /*"toolbar_button_authentication": function () {
  4551. return Toolbar.authenticateClicked();
  4552. },*/
  4553. "toolbar_button_record": function () {
  4554. return toggleRecording();
  4555. },
  4556. "toolbar_button_security": function () {
  4557. return Toolbar.openLockDialog();
  4558. },
  4559. "toolbar_button_link": function () {
  4560. return Toolbar.openLinkDialog();
  4561. },
  4562. "toolbar_button_chat": function () {
  4563. return BottomToolbar.toggleChat();
  4564. },
  4565. "toolbar_button_prezi": function () {
  4566. return Prezi.openPreziDialog();
  4567. },
  4568. "toolbar_button_etherpad": function () {
  4569. return Etherpad.toggleEtherpad(0);
  4570. },
  4571. "toolbar_button_desktopsharing": function () {
  4572. return APP.desktopsharing.toggleScreenSharing();
  4573. },
  4574. "toolbar_button_fullScreen": function()
  4575. {
  4576. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4577. return Toolbar.toggleFullScreen();
  4578. },
  4579. "toolbar_button_sip": function () {
  4580. return callSipButtonClicked();
  4581. },
  4582. "toolbar_button_dialpad": function () {
  4583. return dialpadButtonClicked();
  4584. },
  4585. "toolbar_button_settings": function () {
  4586. PanelToggler.toggleSettingsMenu();
  4587. },
  4588. "toolbar_button_hangup": function () {
  4589. return hangup();
  4590. },
  4591. "toolbar_button_login": function () {
  4592. Toolbar.authenticateClicked();
  4593. },
  4594. "toolbar_button_logout": function () {
  4595. // Ask for confirmation
  4596. messageHandler.openTwoButtonDialog(
  4597. "dialog.logoutTitle",
  4598. null,
  4599. "dialog.logoutQuestion",
  4600. null,
  4601. false,
  4602. "dialog.Yes",
  4603. function (evt, yes) {
  4604. if (yes) {
  4605. APP.xmpp.logout(function (url) {
  4606. if (url) {
  4607. window.location.href = url;
  4608. } else {
  4609. hangup();
  4610. }
  4611. });
  4612. }
  4613. });
  4614. }
  4615. };
  4616. function hangup() {
  4617. APP.xmpp.disposeConference();
  4618. if(config.enableWelcomePage)
  4619. {
  4620. setTimeout(function()
  4621. {
  4622. window.localStorage.welcomePageDisabled = false;
  4623. window.location.pathname = "/";
  4624. }, 10000);
  4625. }
  4626. var title = APP.translation.generateTranslatonHTML(
  4627. "dialog.sessTerminated");
  4628. var msg = APP.translation.generateTranslatonHTML(
  4629. "dialog.hungUp");
  4630. var button = APP.translation.generateTranslatonHTML(
  4631. "dialog.joinAgain");
  4632. var buttons = [];
  4633. buttons.push({title: button, value: true});
  4634. UI.messageHandler.openDialog(
  4635. title,
  4636. msg,
  4637. true,
  4638. buttons,
  4639. function(event, value, message, formVals)
  4640. {
  4641. window.location.reload();
  4642. return false;
  4643. }
  4644. );
  4645. }
  4646. /**
  4647. * Starts or stops the recording for the conference.
  4648. */
  4649. function toggleRecording() {
  4650. APP.xmpp.toggleRecording(function (callback) {
  4651. var msg = APP.translation.generateTranslatonHTML(
  4652. "dialog.recordingToken");
  4653. var token = APP.translation.translateString("dialog.token");
  4654. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4655. '<h2>' + msg + '</h2>' +
  4656. '<input name="recordingToken" type="text" ' +
  4657. ' data-i18n="[placeholder]dialog.token" ' +
  4658. 'placeholder="' + token + '" autofocus>',
  4659. false,
  4660. "dialog.Save",
  4661. function (e, v, m, f) {
  4662. if (v) {
  4663. var token = f.recordingToken;
  4664. if (token) {
  4665. callback(UIUtil.escapeHtml(token));
  4666. }
  4667. }
  4668. },
  4669. null,
  4670. function () { },
  4671. ':input:first'
  4672. );
  4673. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4674. }
  4675. /**
  4676. * Locks / unlocks the room.
  4677. */
  4678. function lockRoom(lock) {
  4679. var currentSharedKey = '';
  4680. if (lock)
  4681. currentSharedKey = sharedKey;
  4682. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4683. // password is required
  4684. if (sharedKey)
  4685. {
  4686. console.log('set room password');
  4687. Toolbar.lockLockButton();
  4688. }
  4689. else
  4690. {
  4691. console.log('removed room password');
  4692. Toolbar.unlockLockButton();
  4693. }
  4694. }, function (err) {
  4695. console.warn('setting password failed', err);
  4696. messageHandler.showError("dialog.lockTitle",
  4697. "dialog.lockMessage");
  4698. Toolbar.setSharedKey('');
  4699. }, function () {
  4700. console.warn('room passwords not supported');
  4701. messageHandler.showError("dialog.warning",
  4702. "dialog.passwordNotSupported");
  4703. Toolbar.setSharedKey('');
  4704. });
  4705. };
  4706. /**
  4707. * Invite participants to conference.
  4708. */
  4709. function inviteParticipants() {
  4710. if (roomUrl === null)
  4711. return;
  4712. var sharedKeyText = "";
  4713. if (sharedKey && sharedKey.length > 0) {
  4714. sharedKeyText =
  4715. APP.translation.translateString("email.sharedKey",
  4716. {sharedKey: sharedKey});
  4717. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4718. }
  4719. var supportedBrowsers = "Chromium, Google Chrome " +
  4720. APP.translation.translateString("email.and") + " Opera";
  4721. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4722. var subject = APP.translation.translateString("email.subject",
  4723. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4724. var body = APP.translation.translateString("email.body",
  4725. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4726. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4727. body = body.replace(/\n/g, "%0D%0A");
  4728. if (window.localStorage.displayname) {
  4729. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4730. }
  4731. if (interfaceConfig.INVITATION_POWERED_BY) {
  4732. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4733. }
  4734. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4735. }
  4736. function dialpadButtonClicked()
  4737. {
  4738. //TODO show the dialpad window
  4739. }
  4740. function callSipButtonClicked()
  4741. {
  4742. var defaultNumber
  4743. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4744. var sipMsg = APP.translation.generateTranslatonHTML(
  4745. "dialog.sipMsg");
  4746. messageHandler.openTwoButtonDialog(null, null, null,
  4747. '<h2>' + sipMsg + '</h2>' +
  4748. '<input name="sipNumber" type="text"' +
  4749. ' value="' + defaultNumber + '" autofocus>',
  4750. false,
  4751. "dialog.Dial",
  4752. function (e, v, m, f) {
  4753. if (v) {
  4754. var numberInput = f.sipNumber;
  4755. if (numberInput) {
  4756. APP.xmpp.dial(
  4757. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4758. }
  4759. }
  4760. },
  4761. null, null, ':input:first'
  4762. );
  4763. }
  4764. var Toolbar = (function (my) {
  4765. my.init = function (ui) {
  4766. for(var k in buttonHandlers)
  4767. $("#" + k).click(buttonHandlers[k]);
  4768. UI = ui;
  4769. // Update login info
  4770. APP.xmpp.addListener(
  4771. AuthenticationEvents.IDENTITY_UPDATED,
  4772. function (authenticationEnabled, userIdentity) {
  4773. var loggedIn = false;
  4774. if (userIdentity) {
  4775. loggedIn = true;
  4776. }
  4777. Toolbar.showAuthenticateButton(authenticationEnabled);
  4778. if (authenticationEnabled) {
  4779. Toolbar.setAuthenticatedIdentity(userIdentity);
  4780. Toolbar.showLoginButton(!loggedIn);
  4781. Toolbar.showLogoutButton(loggedIn);
  4782. }
  4783. }
  4784. );
  4785. },
  4786. /**
  4787. * Sets shared key
  4788. * @param sKey the shared key
  4789. */
  4790. my.setSharedKey = function (sKey) {
  4791. sharedKey = sKey;
  4792. };
  4793. my.authenticateClicked = function () {
  4794. Authentication.focusAuthenticationWindow();
  4795. if (!APP.xmpp.isExternalAuthEnabled()) {
  4796. Authentication.xmppAuthenticate();
  4797. return;
  4798. }
  4799. // Get authentication URL
  4800. if (!APP.xmpp.getMUCJoined()) {
  4801. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4802. // If conference has not been started yet - redirect to login page
  4803. window.location.href = url;
  4804. });
  4805. } else {
  4806. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4807. // Otherwise - open popup with authentication URL
  4808. var authenticationWindow = Authentication.createAuthenticationWindow(
  4809. function () {
  4810. // On popup closed - retry room allocation
  4811. APP.xmpp.allocateConferenceFocus(
  4812. APP.UI.getRoomName(),
  4813. function () { console.info("AUTH DONE"); }
  4814. );
  4815. }, url);
  4816. if (!authenticationWindow) {
  4817. messageHandler.openMessageDialog(
  4818. null, "dialog.popupError");
  4819. }
  4820. });
  4821. }
  4822. };
  4823. /**
  4824. * Updates the room invite url.
  4825. */
  4826. my.updateRoomUrl = function (newRoomUrl) {
  4827. roomUrl = newRoomUrl;
  4828. // If the invite dialog has been already opened we update the information.
  4829. var inviteLink = document.getElementById('inviteLinkRef');
  4830. if (inviteLink) {
  4831. inviteLink.value = roomUrl;
  4832. inviteLink.select();
  4833. $('#inviteLinkRef').parent()
  4834. .find('button[value=true]').prop('disabled', false);
  4835. }
  4836. };
  4837. /**
  4838. * Disables and enables some of the buttons.
  4839. */
  4840. my.setupButtonsFromConfig = function () {
  4841. if (config.disablePrezi)
  4842. {
  4843. $("#prezi_button").css({display: "none"});
  4844. }
  4845. };
  4846. /**
  4847. * Opens the lock room dialog.
  4848. */
  4849. my.openLockDialog = function () {
  4850. // Only the focus is able to set a shared key.
  4851. if (!APP.xmpp.isModerator()) {
  4852. if (sharedKey) {
  4853. messageHandler.openMessageDialog(null,
  4854. "dialog.passwordError");
  4855. } else {
  4856. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4857. }
  4858. } else {
  4859. if (sharedKey) {
  4860. messageHandler.openTwoButtonDialog(null, null,
  4861. "dialog.passwordCheck",
  4862. null,
  4863. false,
  4864. "dialog.Remove",
  4865. function (e, v) {
  4866. if (v) {
  4867. Toolbar.setSharedKey('');
  4868. lockRoom(false);
  4869. }
  4870. });
  4871. } else {
  4872. var msg = APP.translation.generateTranslatonHTML(
  4873. "dialog.passwordMsg");
  4874. var yourPassword = APP.translation.translateString(
  4875. "dialog.yourPassword");
  4876. messageHandler.openTwoButtonDialog(null, null, null,
  4877. '<h2>' + msg + '</h2>' +
  4878. '<input name="lockKey" type="text"' +
  4879. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4880. 'placeholder="' + yourPassword + '" autofocus>',
  4881. false,
  4882. "dialog.Save",
  4883. function (e, v, m, f) {
  4884. if (v) {
  4885. var lockKey = f.lockKey;
  4886. if (lockKey) {
  4887. Toolbar.setSharedKey(
  4888. UIUtil.escapeHtml(lockKey));
  4889. lockRoom(true);
  4890. }
  4891. }
  4892. },
  4893. null, null, 'input:first'
  4894. );
  4895. }
  4896. }
  4897. };
  4898. /**
  4899. * Opens the invite link dialog.
  4900. */
  4901. my.openLinkDialog = function () {
  4902. var inviteAttreibutes;
  4903. if (roomUrl === null) {
  4904. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4905. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4906. } else {
  4907. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4908. }
  4909. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4910. null, null,
  4911. '<input id="inviteLinkRef" type="text" ' +
  4912. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4913. false,
  4914. "dialog.Invite",
  4915. function (e, v) {
  4916. if (v) {
  4917. if (roomUrl) {
  4918. inviteParticipants();
  4919. }
  4920. }
  4921. },
  4922. function (event) {
  4923. if (roomUrl) {
  4924. document.getElementById('inviteLinkRef').select();
  4925. } else {
  4926. if (event && event.target)
  4927. $(event.target)
  4928. .find('button[value=true]').prop('disabled', true);
  4929. }
  4930. }
  4931. );
  4932. };
  4933. /**
  4934. * Opens the settings dialog.
  4935. * FIXME: not used ?
  4936. */
  4937. my.openSettingsDialog = function () {
  4938. var settings1 = APP.translation.generateTranslatonHTML(
  4939. "dialog.settings1");
  4940. var settings2 = APP.translation.generateTranslatonHTML(
  4941. "dialog.settings2");
  4942. var settings3 = APP.translation.generateTranslatonHTML(
  4943. "dialog.settings3");
  4944. var yourPassword = APP.translation.translateString(
  4945. "dialog.yourPassword");
  4946. messageHandler.openTwoButtonDialog(null,
  4947. '<h2>' + settings1 + '</h2>' +
  4948. '<input type="checkbox" id="initMuted">' +
  4949. settings2 + '<br/>' +
  4950. '<input type="checkbox" id="requireNicknames">' +
  4951. settings3 +
  4952. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4953. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4954. null,
  4955. null,
  4956. false,
  4957. "dialog.Save",
  4958. function () {
  4959. document.getElementById('lockKey').focus();
  4960. },
  4961. function (e, v) {
  4962. if (v) {
  4963. if ($('#initMuted').is(":checked")) {
  4964. // it is checked
  4965. }
  4966. if ($('#requireNicknames').is(":checked")) {
  4967. // it is checked
  4968. }
  4969. /*
  4970. var lockKey = document.getElementById('lockKey');
  4971. if (lockKey.value) {
  4972. setSharedKey(lockKey.value);
  4973. lockRoom(true);
  4974. }
  4975. */
  4976. }
  4977. }
  4978. );
  4979. };
  4980. /**
  4981. * Toggles the application in and out of full screen mode
  4982. * (a.k.a. presentation mode in Chrome).
  4983. */
  4984. my.toggleFullScreen = function () {
  4985. var fsElement = document.documentElement;
  4986. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4987. //Enter Full Screen
  4988. if (fsElement.mozRequestFullScreen) {
  4989. fsElement.mozRequestFullScreen();
  4990. }
  4991. else {
  4992. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4993. }
  4994. } else {
  4995. //Exit Full Screen
  4996. if (document.mozCancelFullScreen) {
  4997. document.mozCancelFullScreen();
  4998. } else {
  4999. document.webkitCancelFullScreen();
  5000. }
  5001. }
  5002. };
  5003. /**
  5004. * Unlocks the lock button state.
  5005. */
  5006. my.unlockLockButton = function () {
  5007. if ($("#lockIcon").hasClass("icon-security-locked"))
  5008. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5009. };
  5010. /**
  5011. * Updates the lock button state to locked.
  5012. */
  5013. my.lockLockButton = function () {
  5014. if ($("#lockIcon").hasClass("icon-security"))
  5015. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5016. };
  5017. /**
  5018. * Shows or hides authentication button
  5019. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  5020. */
  5021. my.showAuthenticateButton = function (show) {
  5022. if (show) {
  5023. $('#authentication').css({display: "inline"});
  5024. }
  5025. else {
  5026. $('#authentication').css({display: "none"});
  5027. }
  5028. };
  5029. // Shows or hides the 'recording' button.
  5030. my.showRecordingButton = function (show) {
  5031. if (!config.enableRecording) {
  5032. return;
  5033. }
  5034. if (show) {
  5035. $('#recording').css({display: "inline"});
  5036. }
  5037. else {
  5038. $('#recording').css({display: "none"});
  5039. }
  5040. };
  5041. // Sets the state of the recording button
  5042. my.setRecordingButtonState = function (isRecording) {
  5043. var selector = $('#recordButton');
  5044. if (isRecording) {
  5045. selector.removeClass("icon-recEnable");
  5046. selector.addClass("icon-recEnable active");
  5047. } else {
  5048. selector.removeClass("icon-recEnable active");
  5049. selector.addClass("icon-recEnable");
  5050. }
  5051. };
  5052. // Shows or hides SIP calls button
  5053. my.showSipCallButton = function (show) {
  5054. if (APP.xmpp.isSipGatewayEnabled() && show) {
  5055. $('#sipCallButton').css({display: "inline-block"});
  5056. } else {
  5057. $('#sipCallButton').css({display: "none"});
  5058. }
  5059. };
  5060. // Shows or hides the dialpad button
  5061. my.showDialPadButton = function (show) {
  5062. if (show) {
  5063. $('#dialPadButton').css({display: "inline-block"});
  5064. } else {
  5065. $('#dialPadButton').css({display: "none"});
  5066. }
  5067. };
  5068. /**
  5069. * Displays user authenticated identity name(login).
  5070. * @param authIdentity identity name to be displayed.
  5071. */
  5072. my.setAuthenticatedIdentity = function (authIdentity) {
  5073. if (authIdentity) {
  5074. var selector = $('#toolbar_auth_identity');
  5075. selector.css({display: "list-item"});
  5076. selector.text(authIdentity);
  5077. } else {
  5078. $('#toolbar_auth_identity').css({display: "none"});
  5079. }
  5080. };
  5081. /**
  5082. * Shows/hides login button.
  5083. * @param show <tt>true</tt> to show
  5084. */
  5085. my.showLoginButton = function (show) {
  5086. if (show) {
  5087. $('#toolbar_button_login').css({display: "list-item"});
  5088. } else {
  5089. $('#toolbar_button_login').css({display: "none"});
  5090. }
  5091. };
  5092. /**
  5093. * Shows/hides logout button.
  5094. * @param show <tt>true</tt> to show
  5095. */
  5096. my.showLogoutButton = function (show) {
  5097. if (show) {
  5098. $('#toolbar_button_logout').css({display: "list-item"});
  5099. } else {
  5100. $('#toolbar_button_logout').css({display: "none"});
  5101. }
  5102. };
  5103. /**
  5104. * Sets the state of the button. The button has blue glow if desktop
  5105. * streaming is active.
  5106. * @param active the state of the desktop streaming.
  5107. */
  5108. my.changeDesktopSharingButtonState = function (active) {
  5109. var button = $("#desktopsharing > a");
  5110. if (active)
  5111. {
  5112. button.addClass("glow");
  5113. }
  5114. else
  5115. {
  5116. button.removeClass("glow");
  5117. }
  5118. };
  5119. return my;
  5120. }(Toolbar || {}));
  5121. module.exports = Toolbar;
  5122. },{"../../../service/authentication/AuthenticationEvents":100,"../authentication/Authentication":11,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/SidePanelToggler":17,"../util/MessageHandler":28,"../util/UIUtil":30,"./BottomToolbar":24}],26:[function(require,module,exports){
  5123. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  5124. var toolbarTimeoutObject,
  5125. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  5126. function showDesktopSharingButton() {
  5127. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  5128. $('#desktopsharing').css({display: "inline"});
  5129. } else {
  5130. $('#desktopsharing').css({display: "none"});
  5131. }
  5132. }
  5133. /**
  5134. * Hides the toolbar.
  5135. */
  5136. function hideToolbar() {
  5137. var header = $("#header"),
  5138. bottomToolbar = $("#bottomToolbar");
  5139. var isToolbarHover = false;
  5140. header.find('*').each(function () {
  5141. var id = $(this).attr('id');
  5142. if ($("#" + id + ":hover").length > 0) {
  5143. isToolbarHover = true;
  5144. }
  5145. });
  5146. if ($("#bottomToolbar:hover").length > 0) {
  5147. isToolbarHover = true;
  5148. }
  5149. clearTimeout(toolbarTimeoutObject);
  5150. toolbarTimeoutObject = null;
  5151. if (!isToolbarHover) {
  5152. header.hide("slide", { direction: "up", duration: 300});
  5153. $('#subject').animate({top: "-=40"}, 300);
  5154. if ($("#remoteVideos").hasClass("hidden")) {
  5155. bottomToolbar.hide(
  5156. "slide", {direction: "right", duration: 300});
  5157. }
  5158. }
  5159. else {
  5160. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5161. }
  5162. }
  5163. var ToolbarToggler = {
  5164. /**
  5165. * Shows the main toolbar.
  5166. */
  5167. showToolbar: function () {
  5168. var header = $("#header"),
  5169. bottomToolbar = $("#bottomToolbar");
  5170. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5171. header.show("slide", { direction: "up", duration: 300});
  5172. $('#subject').animate({top: "+=40"}, 300);
  5173. if (!bottomToolbar.is(":visible")) {
  5174. bottomToolbar.show(
  5175. "slide", {direction: "right", duration: 300});
  5176. }
  5177. if (toolbarTimeoutObject) {
  5178. clearTimeout(toolbarTimeoutObject);
  5179. toolbarTimeoutObject = null;
  5180. }
  5181. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5182. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5183. }
  5184. if (APP.xmpp.isModerator())
  5185. {
  5186. // TODO: Enable settings functionality.
  5187. // Need to uncomment the settings button in index.html.
  5188. // $('#settingsButton').css({visibility:"visible"});
  5189. }
  5190. // Show/hide desktop sharing button
  5191. showDesktopSharingButton();
  5192. },
  5193. /**
  5194. * Docks/undocks the toolbar.
  5195. *
  5196. * @param isDock indicates what operation to perform
  5197. */
  5198. dockToolbar: function (isDock) {
  5199. if (isDock) {
  5200. // First make sure the toolbar is shown.
  5201. if (!$('#header').is(':visible')) {
  5202. this.showToolbar();
  5203. }
  5204. // Then clear the time out, to dock the toolbar.
  5205. if (toolbarTimeoutObject) {
  5206. clearTimeout(toolbarTimeoutObject);
  5207. toolbarTimeoutObject = null;
  5208. }
  5209. }
  5210. else {
  5211. if (!$('#header').is(':visible')) {
  5212. this.showToolbar();
  5213. }
  5214. else {
  5215. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5216. }
  5217. }
  5218. },
  5219. showDesktopSharingButton: showDesktopSharingButton
  5220. };
  5221. module.exports = ToolbarToggler;
  5222. },{}],27:[function(require,module,exports){
  5223. var JitsiPopover = (function () {
  5224. /**
  5225. * Constructs new JitsiPopover and attaches it to the element
  5226. * @param element jquery selector
  5227. * @param options the options for the popover.
  5228. * @constructor
  5229. */
  5230. function JitsiPopover(element, options)
  5231. {
  5232. this.options = {
  5233. skin: "white",
  5234. content: ""
  5235. };
  5236. if(options)
  5237. {
  5238. if(options.skin)
  5239. this.options.skin = options.skin;
  5240. if(options.content)
  5241. this.options.content = options.content;
  5242. }
  5243. this.elementIsHovered = false;
  5244. this.popoverIsHovered = false;
  5245. this.popoverShown = false;
  5246. element.data("jitsi_popover", this);
  5247. this.element = element;
  5248. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5249. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5250. '<div class="jitsiPopupmenuPadding"></div></div>';
  5251. var self = this;
  5252. this.element.on("mouseenter", function () {
  5253. self.elementIsHovered = true;
  5254. self.show();
  5255. }).on("mouseleave", function () {
  5256. self.elementIsHovered = false;
  5257. setTimeout(function () {
  5258. self.hide();
  5259. }, 10);
  5260. });
  5261. }
  5262. /**
  5263. * Shows the popover
  5264. */
  5265. JitsiPopover.prototype.show = function () {
  5266. this.createPopover();
  5267. this.popoverShown = true;
  5268. };
  5269. /**
  5270. * Hides the popover
  5271. */
  5272. JitsiPopover.prototype.hide = function () {
  5273. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5274. {
  5275. this.forceHide();
  5276. }
  5277. };
  5278. /**
  5279. * Hides the popover
  5280. */
  5281. JitsiPopover.prototype.forceHide = function () {
  5282. $(".jitsipopover").remove();
  5283. this.popoverShown = false;
  5284. };
  5285. /**
  5286. * Creates the popover html
  5287. */
  5288. JitsiPopover.prototype.createPopover = function () {
  5289. $("body").append(this.template);
  5290. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5291. var self = this;
  5292. $(".jitsipopover").on("mouseenter", function () {
  5293. self.popoverIsHovered = true;
  5294. }).on("mouseleave", function () {
  5295. self.popoverIsHovered = false;
  5296. self.hide();
  5297. });
  5298. this.refreshPosition();
  5299. };
  5300. /**
  5301. * Refreshes the position of the popover
  5302. */
  5303. JitsiPopover.prototype.refreshPosition = function () {
  5304. $(".jitsipopover").position({
  5305. my: "bottom",
  5306. at: "top",
  5307. collision: "fit",
  5308. of: this.element,
  5309. using: function (position, elements) {
  5310. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5311. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5312. $(".jitsipopover > .arrow").css({left: calcLeft});
  5313. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5314. }
  5315. });
  5316. };
  5317. /**
  5318. * Updates the content of popover.
  5319. * @param content new content
  5320. */
  5321. JitsiPopover.prototype.updateContent = function (content) {
  5322. this.options.content = content;
  5323. if(!this.popoverShown)
  5324. return;
  5325. $(".jitsipopover").remove();
  5326. this.createPopover();
  5327. };
  5328. return JitsiPopover;
  5329. })();
  5330. module.exports = JitsiPopover;
  5331. },{}],28:[function(require,module,exports){
  5332. /* global $, APP, jQuery, toastr */
  5333. var messageHandler = (function(my) {
  5334. /**
  5335. * Shows a message to the user.
  5336. *
  5337. * @param titleString the title of the message
  5338. * @param messageString the text of the message
  5339. */
  5340. my.openMessageDialog = function(titleKey, messageKey) {
  5341. var title = null;
  5342. if(titleKey)
  5343. {
  5344. title = APP.translation.generateTranslatonHTML(titleKey);
  5345. }
  5346. var message = APP.translation.generateTranslatonHTML(messageKey);
  5347. $.prompt(message,
  5348. {
  5349. title: title,
  5350. persistent: false
  5351. }
  5352. );
  5353. };
  5354. /**
  5355. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5356. *
  5357. * @param titleString the title of the message
  5358. * @param msgString the text of the message
  5359. * @param persistent boolean value which determines whether the message is persistent or not
  5360. * @param leftButton the fist button's text
  5361. * @param submitFunction function to be called on submit
  5362. * @param loadedFunction function to be called after the prompt is fully loaded
  5363. * @param closeFunction function to be called after the prompt is closed
  5364. * @param focus optional focus selector or button index to be focused after
  5365. * the dialog is opened
  5366. * @param defaultButton index of default button which will be activated when
  5367. * the user press 'enter'. Indexed from 0.
  5368. */
  5369. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5370. persistent, leftButtonKey, submitFunction, loadedFunction,
  5371. closeFunction, focus, defaultButton)
  5372. {
  5373. var buttons = [];
  5374. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5375. buttons.push({ title: leftButton, value: true});
  5376. var cancelButton
  5377. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5378. buttons.push({title: cancelButton, value: false});
  5379. var message = msgString, title = titleString;
  5380. if (titleKey)
  5381. {
  5382. title = APP.translation.generateTranslatonHTML(titleKey);
  5383. }
  5384. if (msgKey) {
  5385. message = APP.translation.generateTranslatonHTML(msgKey);
  5386. }
  5387. $.prompt(message, {
  5388. title: title,
  5389. persistent: false,
  5390. buttons: buttons,
  5391. defaultButton: defaultButton,
  5392. focus: focus,
  5393. loaded: loadedFunction,
  5394. submit: submitFunction,
  5395. close: closeFunction
  5396. });
  5397. };
  5398. /**
  5399. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5400. *
  5401. * @param titleString the title of the message
  5402. * @param msgString the text of the message
  5403. * @param persistent boolean value which determines whether the message is persistent or not
  5404. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5405. * that will be passed to submitFunction
  5406. * @param submitFunction function to be called on submit
  5407. * @param loadedFunction function to be called after the prompt is fully loaded
  5408. */
  5409. my.openDialog = function (titleString, msgString, persistent, buttons,
  5410. submitFunction, loadedFunction) {
  5411. var args = {
  5412. title: titleString,
  5413. persistent: persistent,
  5414. buttons: buttons,
  5415. defaultButton: 1,
  5416. loaded: loadedFunction,
  5417. submit: submitFunction
  5418. };
  5419. if (persistent) {
  5420. args.closeText = '';
  5421. }
  5422. return new Impromptu(msgString, args);
  5423. };
  5424. /**
  5425. * Closes currently opened dialog.
  5426. */
  5427. my.closeDialog = function () {
  5428. $.prompt.close();
  5429. };
  5430. /**
  5431. * Shows a dialog with different states to the user.
  5432. *
  5433. * @param statesObject object containing all the states of the dialog
  5434. */
  5435. my.openDialogWithStates = function (statesObject, options) {
  5436. return new Impromptu(statesObject, options);
  5437. };
  5438. /**
  5439. * Opens new popup window for given <tt>url</tt> centered over current
  5440. * window.
  5441. *
  5442. * @param url the URL to be displayed in the popup window
  5443. * @param w the width of the popup window
  5444. * @param h the height of the popup window
  5445. * @param onPopupClosed optional callback function called when popup window
  5446. * has been closed.
  5447. *
  5448. * @returns popup window object if opened successfully or undefined
  5449. * in case we failed to open it(popup blocked)
  5450. */
  5451. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5452. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5453. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5454. var popup = window.open(
  5455. url, '_blank',
  5456. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5457. if (popup && onPopupClosed) {
  5458. var pollTimer = window.setInterval(function () {
  5459. if (popup.closed !== false) {
  5460. window.clearInterval(pollTimer);
  5461. onPopupClosed();
  5462. }
  5463. }, 200);
  5464. }
  5465. return popup;
  5466. };
  5467. /**
  5468. * Shows a dialog prompting the user to send an error report.
  5469. *
  5470. * @param titleString the title of the message
  5471. * @param msgString the text of the message
  5472. * @param error the error that is being reported
  5473. */
  5474. my.openReportDialog = function(titleKey, msgKey, error) {
  5475. my.openMessageDialog(titleKey, msgKey);
  5476. console.log(error);
  5477. //FIXME send the error to the server
  5478. };
  5479. /**
  5480. * Shows an error dialog to the user.
  5481. * @param title the title of the message
  5482. * @param message the text of the messafe
  5483. */
  5484. my.showError = function(titleKey, msgKey) {
  5485. if(!titleKey) {
  5486. titleKey = "dialog.oops";
  5487. }
  5488. if(!msgKey)
  5489. {
  5490. msgKey = "dialog.defaultError";
  5491. }
  5492. messageHandler.openMessageDialog(titleKey, msgKey);
  5493. };
  5494. my.notify = function(displayName, displayNameKey,
  5495. cls, messageKey, messageArguments, options) {
  5496. var displayNameSpan = '<span class="nickname" ';
  5497. if(displayName)
  5498. {
  5499. displayNameSpan += ">" + displayName;
  5500. }
  5501. else
  5502. {
  5503. displayNameSpan += "data-i18n='" + displayNameKey +
  5504. "'>" + APP.translation.translateString(displayNameKey);
  5505. }
  5506. displayNameSpan += "</span>";
  5507. toastr.info(
  5508. displayNameSpan + '<br>' +
  5509. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5510. (messageArguments?
  5511. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5512. : "") + ">" +
  5513. APP.translation.translateString(messageKey,
  5514. messageArguments) +
  5515. '</span>', null, options);
  5516. };
  5517. return my;
  5518. }(messageHandler || {}));
  5519. module.exports = messageHandler;
  5520. },{}],29:[function(require,module,exports){
  5521. var UIEvents = require("../../../service/UI/UIEvents");
  5522. var nickname = null;
  5523. var eventEmitter = null;
  5524. var NickanameHandler = {
  5525. init: function (emitter) {
  5526. eventEmitter = emitter;
  5527. var storedDisplayName = window.localStorage.displayname;
  5528. if (storedDisplayName) {
  5529. nickname = storedDisplayName;
  5530. }
  5531. },
  5532. setNickname: function (newNickname) {
  5533. if (!newNickname || nickname === newNickname)
  5534. return;
  5535. nickname = newNickname;
  5536. window.localStorage.displayname = nickname;
  5537. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5538. },
  5539. getNickname: function () {
  5540. return nickname;
  5541. },
  5542. addListener: function (type, listener) {
  5543. eventEmitter.on(type, listener);
  5544. }
  5545. };
  5546. module.exports = NickanameHandler;
  5547. },{"../../../service/UI/UIEvents":99}],30:[function(require,module,exports){
  5548. /**
  5549. * Created by hristo on 12/22/14.
  5550. */
  5551. module.exports = {
  5552. /**
  5553. * Returns the available video width.
  5554. */
  5555. getAvailableVideoWidth: function () {
  5556. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5557. var rightPanelWidth
  5558. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5559. return window.innerWidth - rightPanelWidth;
  5560. },
  5561. /**
  5562. * Changes the style class of the element given by id.
  5563. */
  5564. buttonClick: function(id, classname) {
  5565. $(id).toggleClass(classname); // add the class to the clicked element
  5566. },
  5567. /**
  5568. * Returns the text width for the given element.
  5569. *
  5570. * @param el the element
  5571. */
  5572. getTextWidth: function (el) {
  5573. return (el.clientWidth + 1);
  5574. },
  5575. /**
  5576. * Returns the text height for the given element.
  5577. *
  5578. * @param el the element
  5579. */
  5580. getTextHeight: function (el) {
  5581. return (el.clientHeight + 1);
  5582. },
  5583. /**
  5584. * Plays the sound given by id.
  5585. *
  5586. * @param id the identifier of the audio element.
  5587. */
  5588. playSoundNotification: function (id) {
  5589. document.getElementById(id).play();
  5590. },
  5591. /**
  5592. * Escapes the given text.
  5593. */
  5594. escapeHtml: function (unsafeText) {
  5595. return $('<div/>').text(unsafeText).html();
  5596. },
  5597. imageToGrayScale: function (canvas) {
  5598. var context = canvas.getContext('2d');
  5599. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5600. var pixels = imgData.data;
  5601. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5602. var grayscale
  5603. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5604. pixels[i ] = grayscale; // red
  5605. pixels[i+1] = grayscale; // green
  5606. pixels[i+2] = grayscale; // blue
  5607. // pixels[i+3] is alpha
  5608. }
  5609. // redraw the image in black & white
  5610. context.putImageData(imgData, 0, 0);
  5611. },
  5612. setTooltip: function (element, key, position) {
  5613. element.setAttribute("data-i18n", "[data-content]" + key);
  5614. element.setAttribute("data-toggle", "popover");
  5615. element.setAttribute("data-placement", position);
  5616. element.setAttribute("data-html", true);
  5617. element.setAttribute("data-container", "body");
  5618. }
  5619. };
  5620. },{"../side_pannels/SidePanelToggler":17}],31:[function(require,module,exports){
  5621. var JitsiPopover = require("../util/JitsiPopover");
  5622. /**
  5623. * Constructs new connection indicator.
  5624. * @param videoContainer the video container associated with the indicator.
  5625. * @constructor
  5626. */
  5627. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5628. {
  5629. this.videoContainer = videoContainer;
  5630. this.bandwidth = null;
  5631. this.packetLoss = null;
  5632. this.bitrate = null;
  5633. this.showMoreValue = false;
  5634. this.resolution = null;
  5635. this.transport = [];
  5636. this.popover = null;
  5637. this.jid = jid;
  5638. this.create();
  5639. this.videoLayout = VideoLayout;
  5640. }
  5641. /**
  5642. * Values for the connection quality
  5643. * @type {{98: string,
  5644. * 81: string,
  5645. * 64: string,
  5646. * 47: string,
  5647. * 30: string,
  5648. * 0: string}}
  5649. */
  5650. ConnectionIndicator.connectionQualityValues = {
  5651. 98: "18px", //full
  5652. 81: "15px",//4 bars
  5653. 64: "11px",//3 bars
  5654. 47: "7px",//2 bars
  5655. 30: "3px",//1 bar
  5656. 0: "0px"//empty
  5657. };
  5658. ConnectionIndicator.getIP = function(value)
  5659. {
  5660. return value.substring(0, value.lastIndexOf(":"));
  5661. };
  5662. ConnectionIndicator.getPort = function(value)
  5663. {
  5664. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5665. };
  5666. ConnectionIndicator.getStringFromArray = function (array) {
  5667. var res = "";
  5668. for(var i = 0; i < array.length; i++)
  5669. {
  5670. res += (i === 0? "" : ", ") + array[i];
  5671. }
  5672. return res;
  5673. };
  5674. /**
  5675. * Generates the html content.
  5676. * @returns {string} the html content.
  5677. */
  5678. ConnectionIndicator.prototype.generateText = function () {
  5679. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5680. var translate = APP.translation.translateString;
  5681. if(this.bitrate === null)
  5682. {
  5683. downloadBitrate = "N/A";
  5684. uploadBitrate = "N/A";
  5685. }
  5686. else
  5687. {
  5688. downloadBitrate =
  5689. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5690. uploadBitrate =
  5691. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5692. }
  5693. if(this.packetLoss === null)
  5694. {
  5695. packetLoss = "N/A";
  5696. }
  5697. else
  5698. {
  5699. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5700. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5701. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5702. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5703. }
  5704. var resolutionValue = null;
  5705. if(this.resolution && this.jid != null)
  5706. {
  5707. var keys = Object.keys(this.resolution);
  5708. if(keys.length == 1)
  5709. {
  5710. for(var ssrc in this.resolution)
  5711. {
  5712. resolutionValue = this.resolution[ssrc];
  5713. }
  5714. }
  5715. else if(keys.length > 1)
  5716. {
  5717. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5718. resolutionValue = this.resolution[displayedSsrc];
  5719. }
  5720. }
  5721. if(this.jid === null)
  5722. {
  5723. resolution = "";
  5724. if(this.resolution === null || !Object.keys(this.resolution) ||
  5725. Object.keys(this.resolution).length === 0)
  5726. {
  5727. resolution = "N/A";
  5728. }
  5729. else
  5730. for(i in this.resolution)
  5731. {
  5732. resolutionValue = this.resolution[i];
  5733. if(resolutionValue)
  5734. {
  5735. if(resolutionValue.height &&
  5736. resolutionValue.width)
  5737. {
  5738. resolution += (resolution === ""? "" : ", ") +
  5739. resolutionValue.width + "x" +
  5740. resolutionValue.height;
  5741. }
  5742. }
  5743. }
  5744. }
  5745. else if(!resolutionValue ||
  5746. !resolutionValue.height ||
  5747. !resolutionValue.width)
  5748. {
  5749. resolution = "N/A";
  5750. }
  5751. else
  5752. {
  5753. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5754. }
  5755. var result = "<table style='width:100%'>" +
  5756. "<tr>" +
  5757. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5758. translate("connectionindicator.bitrate") + "</span></td>" +
  5759. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5760. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5761. uploadBitrate + "</td>" +
  5762. "</tr><tr>" +
  5763. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5764. translate("connectionindicator.packetloss") + "</span></td>" +
  5765. "<td>" + packetLoss + "</td>" +
  5766. "</tr><tr>" +
  5767. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5768. translate("connectionindicator.resolution") + "</span></td>" +
  5769. "<td>" + resolution + "</td></tr></table>";
  5770. if(this.videoContainer.id == "localVideoContainer") {
  5771. result += "<div class=\"jitsipopover_showmore\" " +
  5772. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5773. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5774. (this.showMoreValue ? "less" : "more") + "'>" +
  5775. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5776. "</div><br />";
  5777. }
  5778. if(this.showMoreValue)
  5779. {
  5780. var downloadBandwidth, uploadBandwidth, transport;
  5781. if(this.bandwidth === null)
  5782. {
  5783. downloadBandwidth = "N/A";
  5784. uploadBandwidth = "N/A";
  5785. }
  5786. else
  5787. {
  5788. downloadBandwidth = this.bandwidth.download?
  5789. this.bandwidth.download + " Kbps" :
  5790. "N/A";
  5791. uploadBandwidth = this.bandwidth.upload?
  5792. this.bandwidth.upload + " Kbps" :
  5793. "N/A";
  5794. }
  5795. if(!this.transport || this.transport.length === 0)
  5796. {
  5797. transport = "<tr>" +
  5798. "<td><span class='jitsipopover_blue' " +
  5799. "data-i18n='connectionindicator.address'>" +
  5800. translate("connectionindicator.address") + "</span></td>" +
  5801. "<td> N/A</td></tr>";
  5802. }
  5803. else
  5804. {
  5805. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5806. for(i = 0; i < this.transport.length; i++)
  5807. {
  5808. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5809. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5810. var localIP =
  5811. ConnectionIndicator.getIP(this.transport[i].localip);
  5812. var localPort =
  5813. ConnectionIndicator.getPort(this.transport[i].localip);
  5814. if(data.remoteIP.indexOf(ip) == -1)
  5815. {
  5816. data.remoteIP.push(ip);
  5817. }
  5818. if(data.remotePort.indexOf(port) == -1)
  5819. {
  5820. data.remotePort.push(port);
  5821. }
  5822. if(data.localIP.indexOf(localIP) == -1)
  5823. {
  5824. data.localIP.push(localIP);
  5825. }
  5826. if(data.localPort.indexOf(localPort) == -1)
  5827. {
  5828. data.localPort.push(localPort);
  5829. }
  5830. }
  5831. var local_address_key = "connectionindicator.localaddress";
  5832. var remote_address_key = "connectionindicator.remoteaddress";
  5833. var localTransport =
  5834. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5835. local_address_key +"' data-i18n-options='" +
  5836. JSON.stringify({count: data.localIP.length}) + "'>" +
  5837. translate(local_address_key, {count: data.localIP.length}) +
  5838. "</span></td><td> " +
  5839. ConnectionIndicator.getStringFromArray(data.localIP) +
  5840. "</td></tr>";
  5841. transport =
  5842. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5843. remote_address_key + "' data-i18n-options='" +
  5844. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5845. translate(remote_address_key,
  5846. {count: data.remoteIP.length}) +
  5847. "</span></td><td> " +
  5848. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5849. "</td></tr>";
  5850. var key_remote = "connectionindicator.remoteport",
  5851. key_local = "connectionindicator.localport";
  5852. transport += "<tr>" +
  5853. "<td>" +
  5854. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5855. "' data-i18n-options='" +
  5856. JSON.stringify({count: this.transport.length}) + "'>" +
  5857. translate(key_remote, {count: this.transport.length}) +
  5858. "</span></td><td>";
  5859. localTransport += "<tr>" +
  5860. "<td>" +
  5861. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5862. "' data-i18n-options='" +
  5863. JSON.stringify({count: this.transport.length}) + "'>" +
  5864. translate(key_local, {count: this.transport.length}) +
  5865. "</span></td><td>";
  5866. transport +=
  5867. ConnectionIndicator.getStringFromArray(data.remotePort);
  5868. localTransport +=
  5869. ConnectionIndicator.getStringFromArray(data.localPort);
  5870. transport += "</td></tr>";
  5871. transport += localTransport + "</td></tr>";
  5872. transport +="<tr>" +
  5873. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5874. translate("connectionindicator.transport") + "</span></td>" +
  5875. "<td>" + this.transport[0].type + "</td></tr>";
  5876. }
  5877. result += "<table style='width:100%'>" +
  5878. "<tr>" +
  5879. "<td>" +
  5880. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5881. translate("connectionindicator.bandwidth") + "</span>" +
  5882. "</td><td>" +
  5883. "<span class='jitsipopover_green'>&darr;</span>" +
  5884. downloadBandwidth +
  5885. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5886. uploadBandwidth + "</td></tr>";
  5887. result += transport + "</table>";
  5888. }
  5889. return result;
  5890. };
  5891. /**
  5892. * Shows or hide the additional information.
  5893. */
  5894. ConnectionIndicator.prototype.showMore = function () {
  5895. this.showMoreValue = !this.showMoreValue;
  5896. this.updatePopoverData();
  5897. };
  5898. function createIcon(classes)
  5899. {
  5900. var icon = document.createElement("span");
  5901. for(var i in classes)
  5902. {
  5903. icon.classList.add(classes[i]);
  5904. }
  5905. icon.appendChild(
  5906. document.createElement("i")).classList.add("icon-connection");
  5907. return icon;
  5908. }
  5909. /**
  5910. * Creates the indicator
  5911. */
  5912. ConnectionIndicator.prototype.create = function () {
  5913. this.connectionIndicatorContainer = document.createElement("div");
  5914. this.connectionIndicatorContainer.className = "connectionindicator";
  5915. this.connectionIndicatorContainer.style.display = "none";
  5916. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5917. this.popover = new JitsiPopover(
  5918. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5919. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5920. APP.translation.translateString("connectionindicator.na") + "</div>",
  5921. skin: "black"});
  5922. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5923. createIcon(["connection", "connection_empty"]));
  5924. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5925. createIcon(["connection", "connection_full"]));
  5926. };
  5927. /**
  5928. * Removes the indicator
  5929. */
  5930. ConnectionIndicator.prototype.remove = function()
  5931. {
  5932. this.connectionIndicatorContainer.remove();
  5933. this.popover.forceHide();
  5934. };
  5935. /**
  5936. * Updates the data of the indicator
  5937. * @param percent the percent of connection quality
  5938. * @param object the statistics data.
  5939. */
  5940. ConnectionIndicator.prototype.updateConnectionQuality =
  5941. function (percent, object) {
  5942. if(percent === null)
  5943. {
  5944. this.connectionIndicatorContainer.style.display = "none";
  5945. this.popover.forceHide();
  5946. return;
  5947. }
  5948. else
  5949. {
  5950. if(this.connectionIndicatorContainer.style.display == "none") {
  5951. this.connectionIndicatorContainer.style.display = "block";
  5952. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5953. }
  5954. }
  5955. this.bandwidth = object.bandwidth;
  5956. this.bitrate = object.bitrate;
  5957. this.packetLoss = object.packetLoss;
  5958. this.transport = object.transport;
  5959. if(object.resolution)
  5960. {
  5961. this.resolution = object.resolution;
  5962. }
  5963. for(var quality in ConnectionIndicator.connectionQualityValues)
  5964. {
  5965. if(percent >= quality)
  5966. {
  5967. this.fullIcon.style.width =
  5968. ConnectionIndicator.connectionQualityValues[quality];
  5969. }
  5970. }
  5971. this.updatePopoverData();
  5972. };
  5973. /**
  5974. * Updates the resolution
  5975. * @param resolution the new resolution
  5976. */
  5977. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5978. this.resolution = resolution;
  5979. this.updatePopoverData();
  5980. };
  5981. /**
  5982. * Updates the content of the popover
  5983. */
  5984. ConnectionIndicator.prototype.updatePopoverData = function () {
  5985. this.popover.updateContent(
  5986. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5987. APP.translation.translateElement($(".connection_info"));
  5988. };
  5989. /**
  5990. * Hides the popover
  5991. */
  5992. ConnectionIndicator.prototype.hide = function () {
  5993. this.popover.forceHide();
  5994. };
  5995. /**
  5996. * Hides the indicator
  5997. */
  5998. ConnectionIndicator.prototype.hideIndicator = function () {
  5999. this.connectionIndicatorContainer.style.display = "none";
  6000. if(this.popover)
  6001. this.popover.forceHide();
  6002. };
  6003. module.exports = ConnectionIndicator;
  6004. },{"../util/JitsiPopover":27}],32:[function(require,module,exports){
  6005. var AudioLevels = require("../audio_levels/AudioLevels");
  6006. var Avatar = require("../avatar/Avatar");
  6007. var Chat = require("../side_pannels/chat/Chat");
  6008. var ContactList = require("../side_pannels/contactlist/ContactList");
  6009. var UIUtil = require("../util/UIUtil");
  6010. var ConnectionIndicator = require("./ConnectionIndicator");
  6011. var NicknameHandler = require("../util/NicknameHandler");
  6012. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  6013. var UIEvents = require("../../../service/UI/UIEvents");
  6014. var currentDominantSpeaker = null;
  6015. var lastNCount = config.channelLastN;
  6016. var localLastNCount = config.channelLastN;
  6017. var localLastNSet = [];
  6018. var lastNEndpointsCache = [];
  6019. var lastNPickupJid = null;
  6020. var largeVideoState = {
  6021. updateInProgress: false,
  6022. newSrc: ''
  6023. };
  6024. var eventEmitter = null;
  6025. /**
  6026. * Currently focused video "src"(displayed in large video).
  6027. * @type {String}
  6028. */
  6029. var focusedVideoInfo = null;
  6030. /**
  6031. * Indicates if we have muted our audio before the conference has started.
  6032. * @type {boolean}
  6033. */
  6034. var preMuted = false;
  6035. var mutedAudios = {};
  6036. var flipXLocalVideo = true;
  6037. var currentVideoWidth = null;
  6038. var currentVideoHeight = null;
  6039. var localVideoSrc = null;
  6040. function videoactive( videoelem) {
  6041. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  6042. // ignore mixedmslabela0 and v0
  6043. videoelem.show();
  6044. VideoLayout.resizeThumbnails();
  6045. var videoParent = videoelem.parent();
  6046. var parentResourceJid = null;
  6047. if (videoParent)
  6048. parentResourceJid
  6049. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  6050. // Update the large video to the last added video only if there's no
  6051. // current dominant, focused speaker or prezi playing or update it to
  6052. // the current dominant speaker.
  6053. if ((!focusedVideoInfo &&
  6054. !VideoLayout.getDominantSpeakerResourceJid() &&
  6055. !require("../prezi/Prezi").isPresentationVisible()) ||
  6056. (parentResourceJid &&
  6057. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  6058. VideoLayout.updateLargeVideo(
  6059. APP.RTC.getVideoSrc(videoelem[0]),
  6060. 1,
  6061. parentResourceJid);
  6062. }
  6063. VideoLayout.showModeratorIndicator();
  6064. }
  6065. }
  6066. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  6067. // XXX(gp) so, every call to this function is *always* preceded by a call
  6068. // to the RTC.attachMediaStream() function but that call is *not* followed
  6069. // by an update to the videoSrcToSsrc map!
  6070. //
  6071. // The above way of doing things results in video SRCs that don't correspond
  6072. // to any SSRC for a short period of time (to be more precise, for as long
  6073. // the waitForRemoteVideo takes to complete). This causes problems (see
  6074. // bellow).
  6075. //
  6076. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  6077. // a second time in here and only then update the videoSrcToSsrc map? Why
  6078. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  6079. // is called the first time? I actually do that in the lastN changed event
  6080. // handler because the "orphan" video SRC is causing troubles there. The
  6081. // purpose of this method would then be to fire the "videoactive.jingle".
  6082. //
  6083. // Food for though I guess :-)
  6084. if (selector.removed || !selector.parent().is(":visible")) {
  6085. console.warn("Media removed before had started", selector);
  6086. return;
  6087. }
  6088. if (stream.id === 'mixedmslabel') return;
  6089. if (selector[0].currentTime > 0) {
  6090. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6091. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  6092. videoactive(selector);
  6093. } else {
  6094. setTimeout(function () {
  6095. waitForRemoteVideo(selector, ssrc, stream, jid);
  6096. }, 250);
  6097. }
  6098. }
  6099. /**
  6100. * Returns an array of the video horizontal and vertical indents,
  6101. * so that if fits its parent.
  6102. *
  6103. * @return an array with 2 elements, the horizontal indent and the vertical
  6104. * indent
  6105. */
  6106. function getCameraVideoPosition(videoWidth,
  6107. videoHeight,
  6108. videoSpaceWidth,
  6109. videoSpaceHeight) {
  6110. // Parent height isn't completely calculated when we position the video in
  6111. // full screen mode and this is why we use the screen height in this case.
  6112. // Need to think it further at some point and implement it properly.
  6113. var isFullScreen = document.fullScreen ||
  6114. document.mozFullScreen ||
  6115. document.webkitIsFullScreen;
  6116. if (isFullScreen)
  6117. videoSpaceHeight = window.innerHeight;
  6118. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6119. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  6120. return [horizontalIndent, verticalIndent];
  6121. }
  6122. /**
  6123. * Returns an array of the video horizontal and vertical indents.
  6124. * Centers horizontally and top aligns vertically.
  6125. *
  6126. * @return an array with 2 elements, the horizontal indent and the vertical
  6127. * indent
  6128. */
  6129. function getDesktopVideoPosition(videoWidth,
  6130. videoHeight,
  6131. videoSpaceWidth,
  6132. videoSpaceHeight) {
  6133. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6134. var verticalIndent = 0;// Top aligned
  6135. return [horizontalIndent, verticalIndent];
  6136. }
  6137. /**
  6138. * Returns an array of the video dimensions, so that it covers the screen.
  6139. * It leaves no empty areas, but some parts of the video might not be visible.
  6140. *
  6141. * @return an array with 2 elements, the video width and the video height
  6142. */
  6143. function getCameraVideoSize(videoWidth,
  6144. videoHeight,
  6145. videoSpaceWidth,
  6146. videoSpaceHeight) {
  6147. if (!videoWidth)
  6148. videoWidth = currentVideoWidth;
  6149. if (!videoHeight)
  6150. videoHeight = currentVideoHeight;
  6151. var aspectRatio = videoWidth / videoHeight;
  6152. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6153. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6154. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6155. availableHeight = videoSpaceHeight;
  6156. availableWidth = availableHeight * aspectRatio;
  6157. }
  6158. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6159. availableWidth = videoSpaceWidth;
  6160. availableHeight = availableWidth / aspectRatio;
  6161. }
  6162. return [availableWidth, availableHeight];
  6163. }
  6164. /**
  6165. * Sets the display name for the given video span id.
  6166. */
  6167. function setDisplayName(videoSpanId, displayName, key) {
  6168. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  6169. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  6170. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6171. // If we already have a display name for this video.
  6172. if (nameSpan.length > 0) {
  6173. var nameSpanElement = nameSpan.get(0);
  6174. if (nameSpanElement.id === 'localDisplayName' &&
  6175. $('#localDisplayName').text() !== displayName) {
  6176. if (displayName && displayName.length > 0)
  6177. {
  6178. var meHTML = APP.translation.generateTranslatonHTML("me");
  6179. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6180. }
  6181. else
  6182. $('#localDisplayName').html(defaultLocalDisplayName);
  6183. } else {
  6184. if (displayName && displayName.length > 0)
  6185. {
  6186. $('#' + videoSpanId + '_name').html(displayName);
  6187. }
  6188. else if (key && key.length > 0)
  6189. {
  6190. var nameHtml = APP.translation.generateTranslatonHTML(key);
  6191. $('#' + videoSpanId + '_name').html(nameHtml);
  6192. }
  6193. else
  6194. $('#' + videoSpanId + '_name').text(
  6195. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  6196. }
  6197. } else {
  6198. var editButton = null;
  6199. nameSpan = document.createElement('span');
  6200. nameSpan.className = 'displayname';
  6201. $('#' + videoSpanId)[0].appendChild(nameSpan);
  6202. if (videoSpanId === 'localVideoContainer') {
  6203. editButton = createEditDisplayNameButton();
  6204. if (displayName && displayName.length > 0) {
  6205. var meHTML = APP.translation.generateTranslatonHTML("me");
  6206. nameSpan.innerHTML = displayName + meHTML;
  6207. }
  6208. else
  6209. nameSpan.innerHTML = defaultLocalDisplayName;
  6210. }
  6211. else {
  6212. if (displayName && displayName.length > 0) {
  6213. nameSpan.innerText = displayName;
  6214. }
  6215. else
  6216. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6217. }
  6218. if (!editButton) {
  6219. nameSpan.id = videoSpanId + '_name';
  6220. } else {
  6221. nameSpan.id = 'localDisplayName';
  6222. $('#' + videoSpanId)[0].appendChild(editButton);
  6223. //translates popover of edit button
  6224. APP.translation.translateElement($("a.displayname"));
  6225. var editableText = document.createElement('input');
  6226. editableText.className = 'displayname';
  6227. editableText.type = 'text';
  6228. editableText.id = 'editDisplayName';
  6229. if (displayName && displayName.length) {
  6230. editableText.value
  6231. = displayName;
  6232. }
  6233. var defaultNickname = APP.translation.translateString(
  6234. "defaultNickname", {name: "Jane Pink"});
  6235. editableText.setAttribute('style', 'display:none;');
  6236. editableText.setAttribute('data-18n',
  6237. '[placeholder]defaultNickname');
  6238. editableText.setAttribute("data-i18n-options",
  6239. JSON.stringify({name: "Jane Pink"}));
  6240. editableText.setAttribute("placeholder", defaultNickname);
  6241. $('#' + videoSpanId)[0].appendChild(editableText);
  6242. $('#localVideoContainer .displayname')
  6243. .bind("click", function (e) {
  6244. e.preventDefault();
  6245. e.stopPropagation();
  6246. $('#localDisplayName').hide();
  6247. $('#editDisplayName').show();
  6248. $('#editDisplayName').focus();
  6249. $('#editDisplayName').select();
  6250. $('#editDisplayName').one("focusout", function (e) {
  6251. VideoLayout.inputDisplayNameHandler(this.value);
  6252. });
  6253. $('#editDisplayName').on('keydown', function (e) {
  6254. if (e.keyCode === 13) {
  6255. e.preventDefault();
  6256. VideoLayout.inputDisplayNameHandler(this.value);
  6257. }
  6258. });
  6259. });
  6260. }
  6261. }
  6262. }
  6263. /**
  6264. * Gets the selector of video thumbnail container for the user identified by
  6265. * given <tt>userJid</tt>
  6266. * @param resourceJid user's Jid for whom we want to get the video container.
  6267. */
  6268. function getParticipantContainer(resourceJid)
  6269. {
  6270. if (!resourceJid)
  6271. return null;
  6272. if (resourceJid === APP.xmpp.myResource())
  6273. return $("#localVideoContainer");
  6274. else
  6275. return $("#participant_" + resourceJid);
  6276. }
  6277. /**
  6278. * Sets the size and position of the given video element.
  6279. *
  6280. * @param video the video element to position
  6281. * @param width the desired video width
  6282. * @param height the desired video height
  6283. * @param horizontalIndent the left and right indent
  6284. * @param verticalIndent the top and bottom indent
  6285. */
  6286. function positionVideo(video,
  6287. width,
  6288. height,
  6289. horizontalIndent,
  6290. verticalIndent) {
  6291. video.width(width);
  6292. video.height(height);
  6293. video.css({ top: verticalIndent + 'px',
  6294. bottom: verticalIndent + 'px',
  6295. left: horizontalIndent + 'px',
  6296. right: horizontalIndent + 'px'});
  6297. }
  6298. /**
  6299. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6300. * given <tt>parentElement</tt>.
  6301. *
  6302. * @param jid the jid indicating the video for which we're adding a menu.
  6303. * @param parentElement the parent element where this menu will be added
  6304. */
  6305. function addRemoteVideoMenu(jid, parentElement) {
  6306. var spanElement = document.createElement('span');
  6307. spanElement.className = 'remotevideomenu';
  6308. parentElement.appendChild(spanElement);
  6309. var menuElement = document.createElement('i');
  6310. menuElement.className = 'fa fa-angle-down';
  6311. menuElement.title = 'Remote user controls';
  6312. spanElement.appendChild(menuElement);
  6313. // <ul class="popupmenu">
  6314. // <li><a href="#">Mute</a></li>
  6315. // <li><a href="#">Eject</a></li>
  6316. // </ul>
  6317. var popupmenuElement = document.createElement('ul');
  6318. popupmenuElement.className = 'popupmenu';
  6319. popupmenuElement.id
  6320. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6321. spanElement.appendChild(popupmenuElement);
  6322. var muteMenuItem = document.createElement('li');
  6323. var muteLinkItem = document.createElement('a');
  6324. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6325. if (!mutedAudios[jid]) {
  6326. muteLinkItem.innerHTML = mutedIndicator +
  6327. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6328. muteLinkItem.className = 'mutelink';
  6329. }
  6330. else {
  6331. muteLinkItem.innerHTML = mutedIndicator +
  6332. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6333. muteLinkItem.className = 'mutelink disabled';
  6334. }
  6335. muteLinkItem.onclick = function(){
  6336. if ($(this).attr('disabled') != undefined) {
  6337. event.preventDefault();
  6338. }
  6339. var isMute = mutedAudios[jid] == true;
  6340. APP.xmpp.setMute(jid, !isMute);
  6341. popupmenuElement.setAttribute('style', 'display:none;');
  6342. if (isMute) {
  6343. this.innerHTML = mutedIndicator +
  6344. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6345. this.className = 'mutelink disabled';
  6346. }
  6347. else {
  6348. this.innerHTML = mutedIndicator +
  6349. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6350. this.className = 'mutelink';
  6351. }
  6352. };
  6353. muteMenuItem.appendChild(muteLinkItem);
  6354. popupmenuElement.appendChild(muteMenuItem);
  6355. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6356. var ejectMenuItem = document.createElement('li');
  6357. var ejectLinkItem = document.createElement('a');
  6358. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6359. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6360. ejectLinkItem.onclick = function(){
  6361. APP.xmpp.eject(jid);
  6362. popupmenuElement.setAttribute('style', 'display:none;');
  6363. };
  6364. ejectMenuItem.appendChild(ejectLinkItem);
  6365. popupmenuElement.appendChild(ejectMenuItem);
  6366. var paddingSpan = document.createElement('span');
  6367. paddingSpan.className = 'popupmenuPadding';
  6368. popupmenuElement.appendChild(paddingSpan);
  6369. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6370. }
  6371. /**
  6372. * Removes remote video menu element from video element identified by
  6373. * given <tt>videoElementId</tt>.
  6374. *
  6375. * @param videoElementId the id of local or remote video element.
  6376. */
  6377. function removeRemoteVideoMenu(videoElementId) {
  6378. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6379. if (menuSpan.length) {
  6380. menuSpan.remove();
  6381. }
  6382. }
  6383. /**
  6384. * Updates the data for the indicator
  6385. * @param id the id of the indicator
  6386. * @param percent the percent for connection quality
  6387. * @param object the data
  6388. */
  6389. function updateStatsIndicator(id, percent, object) {
  6390. if(VideoLayout.connectionIndicators[id])
  6391. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6392. }
  6393. /**
  6394. * Returns an array of the video dimensions, so that it keeps it's aspect
  6395. * ratio and fits available area with it's larger dimension. This method
  6396. * ensures that whole video will be visible and can leave empty areas.
  6397. *
  6398. * @return an array with 2 elements, the video width and the video height
  6399. */
  6400. function getDesktopVideoSize(videoWidth,
  6401. videoHeight,
  6402. videoSpaceWidth,
  6403. videoSpaceHeight) {
  6404. if (!videoWidth)
  6405. videoWidth = currentVideoWidth;
  6406. if (!videoHeight)
  6407. videoHeight = currentVideoHeight;
  6408. var aspectRatio = videoWidth / videoHeight;
  6409. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6410. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6411. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6412. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6413. {
  6414. availableHeight = videoSpaceHeight;
  6415. availableWidth = availableHeight * aspectRatio;
  6416. }
  6417. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6418. {
  6419. availableWidth = videoSpaceWidth;
  6420. availableHeight = availableWidth / aspectRatio;
  6421. }
  6422. return [availableWidth, availableHeight];
  6423. }
  6424. /**
  6425. * Creates the edit display name button.
  6426. *
  6427. * @returns the edit button
  6428. */
  6429. function createEditDisplayNameButton() {
  6430. var editButton = document.createElement('a');
  6431. editButton.className = 'displayname';
  6432. UIUtil.setTooltip(editButton,
  6433. "videothumbnail.editnickname",
  6434. "top");
  6435. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6436. return editButton;
  6437. }
  6438. /**
  6439. * Creates the element indicating the moderator(owner) of the conference.
  6440. *
  6441. * @param parentElement the parent element where the owner indicator will
  6442. * be added
  6443. */
  6444. function createModeratorIndicatorElement(parentElement) {
  6445. var moderatorIndicator = document.createElement('i');
  6446. moderatorIndicator.className = 'fa fa-star';
  6447. parentElement.appendChild(moderatorIndicator);
  6448. UIUtil.setTooltip(parentElement,
  6449. "videothumbnail.moderator",
  6450. "top");
  6451. }
  6452. var VideoLayout = (function (my) {
  6453. my.connectionIndicators = {};
  6454. // By default we use camera
  6455. my.getVideoSize = getCameraVideoSize;
  6456. my.getVideoPosition = getCameraVideoPosition;
  6457. my.init = function (emitter) {
  6458. // Listen for large video size updates
  6459. document.getElementById('largeVideo')
  6460. .addEventListener('loadedmetadata', function (e) {
  6461. currentVideoWidth = this.videoWidth;
  6462. currentVideoHeight = this.videoHeight;
  6463. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6464. });
  6465. eventEmitter = emitter;
  6466. };
  6467. my.isInLastN = function(resource) {
  6468. return lastNCount < 0 // lastN is disabled, return true
  6469. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6470. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6471. };
  6472. my.changeLocalStream = function (stream, isMuted) {
  6473. VideoLayout.changeLocalVideo(stream, isMuted);
  6474. };
  6475. my.changeLocalAudio = function(stream, isMuted) {
  6476. if(isMuted)
  6477. APP.UI.setAudioMuted(true, true);
  6478. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6479. document.getElementById('localAudio').autoplay = true;
  6480. document.getElementById('localAudio').volume = 0;
  6481. };
  6482. my.changeLocalVideo = function(stream, isMuted) {
  6483. // Set default display name.
  6484. setDisplayName('localVideoContainer');
  6485. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6486. VideoLayout.connectionIndicators["localVideoContainer"]
  6487. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6488. }
  6489. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6490. var localVideo = null;
  6491. function localVideoClick(event) {
  6492. event.stopPropagation();
  6493. VideoLayout.handleVideoThumbClicked(
  6494. APP.RTC.getVideoSrc(localVideo),
  6495. false,
  6496. APP.xmpp.myResource());
  6497. }
  6498. $('#localVideoContainer').click(localVideoClick);
  6499. // Add hover handler
  6500. $('#localVideoContainer').hover(
  6501. function() {
  6502. VideoLayout.showDisplayName('localVideoContainer', true);
  6503. },
  6504. function() {
  6505. if (!VideoLayout.isLargeVideoVisible()
  6506. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6507. VideoLayout.showDisplayName('localVideoContainer', false);
  6508. }
  6509. );
  6510. if(isMuted)
  6511. {
  6512. APP.UI.setVideoMute(true);
  6513. return;
  6514. }
  6515. var flipX = true;
  6516. if(stream.videoType == "screen")
  6517. flipX = false;
  6518. var localVideo = document.createElement('video');
  6519. localVideo.id = 'localVideo_' +
  6520. APP.RTC.getStreamID(stream.getOriginalStream());
  6521. localVideo.autoplay = true;
  6522. localVideo.volume = 0; // is it required if audio is separated ?
  6523. localVideo.oncontextmenu = function () { return false; };
  6524. var localVideoContainer = document.getElementById('localVideoWrapper');
  6525. localVideoContainer.appendChild(localVideo);
  6526. var localVideoSelector = $('#' + localVideo.id);
  6527. // Add click handler to both video and video wrapper elements in case
  6528. // there's no video.
  6529. localVideoSelector.click(localVideoClick);
  6530. // Flip video x axis if needed
  6531. flipXLocalVideo = flipX;
  6532. if (flipX) {
  6533. localVideoSelector.addClass("flipVideoX");
  6534. }
  6535. // Attach WebRTC stream
  6536. var videoStream = APP.simulcast.getLocalVideoStream();
  6537. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6538. // Add stream ended handler
  6539. stream.getOriginalStream().onended = function () {
  6540. localVideoContainer.removeChild(localVideo);
  6541. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6542. };
  6543. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6544. var myResourceJid = APP.xmpp.myResource();
  6545. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6546. myResourceJid);
  6547. };
  6548. my.mucJoined = function () {
  6549. var myResourceJid = APP.xmpp.myResource();
  6550. if(!largeVideoState.userResourceJid)
  6551. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6552. myResourceJid, true);
  6553. };
  6554. /**
  6555. * Adds or removes icons for not available camera and microphone.
  6556. * @param resourceJid the jid of user
  6557. * @param devices available devices
  6558. */
  6559. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6560. if(!devices)
  6561. return;
  6562. var container = null
  6563. if(!resourceJid)
  6564. {
  6565. container = $("#localVideoContainer")[0];
  6566. }
  6567. else
  6568. {
  6569. container = $("#participant_" + resourceJid)[0];
  6570. }
  6571. if(!container)
  6572. return;
  6573. $("#" + container.id + " > .noMic").remove();
  6574. $("#" + container.id + " > .noVideo").remove();
  6575. if(!devices.audio)
  6576. {
  6577. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6578. }
  6579. if(!devices.video)
  6580. {
  6581. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6582. }
  6583. if(!devices.audio && !devices.video)
  6584. {
  6585. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6586. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6587. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6588. }
  6589. }
  6590. /**
  6591. * Checks if removed video is currently displayed and tries to display
  6592. * another one instead.
  6593. * @param removedVideoSrc src stream identifier of the video.
  6594. */
  6595. my.updateRemovedVideo = function(removedVideoSrc) {
  6596. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6597. // this is currently displayed as large
  6598. // pick the last visible video in the row
  6599. // if nobody else is left, this picks the local video
  6600. var pick
  6601. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6602. .get(0);
  6603. if (!pick) {
  6604. console.info("Last visible video no longer exists");
  6605. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6606. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6607. // Try local video
  6608. console.info("Fallback to local video...");
  6609. pick = $('#remoteVideos>span>span>video').get(0);
  6610. }
  6611. }
  6612. var src = null, volume = null;
  6613. // mute if localvideo
  6614. if (pick) {
  6615. var container = pick.parentNode;
  6616. src = APP.RTC.getVideoSrc(pick);
  6617. volume = pick.volume;
  6618. } else {
  6619. console.warn("Failed to elect large video");
  6620. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  6621. }
  6622. var jid = null;
  6623. if(container)
  6624. {
  6625. if(container.id == "localVideoWrapper")
  6626. {
  6627. jid = APP.xmpp.myResource();
  6628. }
  6629. else
  6630. {
  6631. jid = VideoLayout.getPeerContainerResourceJid(container);
  6632. }
  6633. }
  6634. else
  6635. return;
  6636. VideoLayout.updateLargeVideo(src, volume, jid);
  6637. }
  6638. };
  6639. my.onRemoteStreamAdded = function (stream) {
  6640. var container;
  6641. var remotes = document.getElementById('remoteVideos');
  6642. if (stream.peerjid) {
  6643. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6644. container = document.getElementById(
  6645. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6646. } else {
  6647. var id = stream.getOriginalStream().id;
  6648. if (id !== 'mixedmslabel'
  6649. // FIXME: default stream is added always with new focus
  6650. // (to be investigated)
  6651. && id !== 'default') {
  6652. console.error('can not associate stream',
  6653. id,
  6654. 'with a participant');
  6655. // We don't want to add it here since it will cause troubles
  6656. return;
  6657. }
  6658. // FIXME: for the mixed ms we dont need a video -- currently
  6659. container = document.createElement('span');
  6660. container.id = 'mixedstream';
  6661. container.className = 'videocontainer';
  6662. remotes.appendChild(container);
  6663. UIUtil.playSoundNotification('userJoined');
  6664. }
  6665. if (container) {
  6666. VideoLayout.addRemoteStreamElement( container,
  6667. stream.sid,
  6668. stream.getOriginalStream(),
  6669. stream.peerjid,
  6670. stream.ssrc);
  6671. }
  6672. }
  6673. my.getLargeVideoState = function () {
  6674. return largeVideoState;
  6675. };
  6676. /**
  6677. * Updates the large video with the given new video source.
  6678. */
  6679. my.updateLargeVideo = function(newSrc, vol, resourceJid, forceUpdate) {
  6680. console.log('hover in', newSrc, resourceJid);
  6681. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc || forceUpdate) {
  6682. $('#activeSpeaker').css('visibility', 'hidden');
  6683. // Due to the simulcast the localVideoSrc may have changed when the
  6684. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6685. // isVideoSrcDesktop methods will not function correctly.
  6686. //
  6687. // Also, again due to the simulcast, the updateLargeVideo method can
  6688. // be called multiple times almost simultaneously. Therefore, we
  6689. // store the state here and update only once.
  6690. largeVideoState.newSrc = newSrc;
  6691. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6692. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6693. APP.xmpp.findJidFromResource(resourceJid));
  6694. if(largeVideoState.userResourceJid) {
  6695. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6696. } else {
  6697. largeVideoState.oldResourceJid = null;
  6698. }
  6699. largeVideoState.userResourceJid = resourceJid;
  6700. // Screen stream is already rotated
  6701. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6702. var userChanged = false;
  6703. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6704. userChanged = true;
  6705. // we want the notification to trigger even if userJid is undefined,
  6706. // or null.
  6707. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6708. largeVideoState.userResourceJid);
  6709. }
  6710. if (!largeVideoState.updateInProgress) {
  6711. largeVideoState.updateInProgress = true;
  6712. var doUpdate = function () {
  6713. Avatar.updateActiveSpeakerAvatarSrc(
  6714. APP.xmpp.findJidFromResource(
  6715. largeVideoState.userResourceJid));
  6716. if (!userChanged && largeVideoState.preload &&
  6717. largeVideoState.preload !== null &&
  6718. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6719. {
  6720. console.info('Switching to preloaded video');
  6721. var attributes = $('#largeVideo').prop("attributes");
  6722. // loop through largeVideo attributes and apply them on
  6723. // preload.
  6724. $.each(attributes, function () {
  6725. if (this.name !== 'id' && this.name !== 'src') {
  6726. largeVideoState.preload.attr(this.name, this.value);
  6727. }
  6728. });
  6729. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6730. $('#largeVideo').attr('id', 'previousLargeVideo');
  6731. largeVideoState.preload.attr('id', 'largeVideo');
  6732. $('#previousLargeVideo').remove();
  6733. largeVideoState.preload.on('loadedmetadata', function (e) {
  6734. currentVideoWidth = this.videoWidth;
  6735. currentVideoHeight = this.videoHeight;
  6736. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6737. });
  6738. largeVideoState.preload = null;
  6739. largeVideoState.preload_ssrc = 0;
  6740. } else {
  6741. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6742. }
  6743. var videoTransform = document.getElementById('largeVideo')
  6744. .style.webkitTransform;
  6745. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6746. document.getElementById('largeVideo').style.webkitTransform
  6747. = "scaleX(-1)";
  6748. }
  6749. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6750. document.getElementById('largeVideo').style.webkitTransform
  6751. = "none";
  6752. }
  6753. // Change the way we'll be measuring and positioning large video
  6754. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6755. ? getDesktopVideoSize
  6756. : getCameraVideoSize;
  6757. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6758. ? getDesktopVideoPosition
  6759. : getCameraVideoPosition;
  6760. // Only if the large video is currently visible.
  6761. // Disable previous dominant speaker video.
  6762. if (largeVideoState.oldResourceJid) {
  6763. VideoLayout.enableDominantSpeaker(
  6764. largeVideoState.oldResourceJid,
  6765. false);
  6766. }
  6767. // Enable new dominant speaker in the remote videos section.
  6768. if (largeVideoState.userResourceJid) {
  6769. VideoLayout.enableDominantSpeaker(
  6770. largeVideoState.userResourceJid,
  6771. true);
  6772. }
  6773. if (userChanged && largeVideoState.isVisible) {
  6774. // using "this" should be ok because we're called
  6775. // from within the fadeOut event.
  6776. $(this).fadeIn(300);
  6777. }
  6778. if(userChanged) {
  6779. Avatar.showUserAvatar(
  6780. APP.xmpp.findJidFromResource(
  6781. largeVideoState.oldResourceJid));
  6782. }
  6783. largeVideoState.updateInProgress = false;
  6784. };
  6785. if (userChanged) {
  6786. $('#largeVideo').fadeOut(300, doUpdate);
  6787. } else {
  6788. doUpdate();
  6789. }
  6790. }
  6791. } else {
  6792. Avatar.showUserAvatar(
  6793. APP.xmpp.findJidFromResource(
  6794. largeVideoState.userResourceJid));
  6795. }
  6796. };
  6797. my.handleVideoThumbClicked = function(videoSrc,
  6798. noPinnedEndpointChangedEvent,
  6799. resourceJid) {
  6800. // Restore style for previously focused video
  6801. var oldContainer = null;
  6802. if(focusedVideoInfo) {
  6803. var focusResourceJid = focusedVideoInfo.resourceJid;
  6804. oldContainer = getParticipantContainer(focusResourceJid);
  6805. }
  6806. if (oldContainer) {
  6807. oldContainer.removeClass("videoContainerFocused");
  6808. }
  6809. // Unlock current focused.
  6810. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6811. {
  6812. focusedVideoInfo = null;
  6813. var dominantSpeakerVideo = null;
  6814. // Enable the currently set dominant speaker.
  6815. if (currentDominantSpeaker) {
  6816. dominantSpeakerVideo
  6817. = $('#participant_' + currentDominantSpeaker + '>video')
  6818. .get(0);
  6819. if (dominantSpeakerVideo) {
  6820. VideoLayout.updateLargeVideo(
  6821. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6822. 1,
  6823. currentDominantSpeaker);
  6824. }
  6825. }
  6826. if (!noPinnedEndpointChangedEvent) {
  6827. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6828. }
  6829. return;
  6830. }
  6831. // Lock new video
  6832. focusedVideoInfo = {
  6833. src: videoSrc,
  6834. resourceJid: resourceJid
  6835. };
  6836. // Update focused/pinned interface.
  6837. if (resourceJid)
  6838. {
  6839. var container = getParticipantContainer(resourceJid);
  6840. container.addClass("videoContainerFocused");
  6841. if (!noPinnedEndpointChangedEvent) {
  6842. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6843. }
  6844. }
  6845. if ($('#largeVideo').attr('src') === videoSrc &&
  6846. VideoLayout.isLargeVideoOnTop()) {
  6847. return;
  6848. }
  6849. // Triggers a "video.selected" event. The "false" parameter indicates
  6850. // this isn't a prezi.
  6851. $(document).trigger("video.selected", [false]);
  6852. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6853. $('audio').each(function (idx, el) {
  6854. if (el.id.indexOf('mixedmslabel') !== -1) {
  6855. el.volume = 0;
  6856. el.volume = 1;
  6857. }
  6858. });
  6859. };
  6860. /**
  6861. * Positions the large video.
  6862. *
  6863. * @param videoWidth the stream video width
  6864. * @param videoHeight the stream video height
  6865. */
  6866. my.positionLarge = function (videoWidth, videoHeight) {
  6867. var videoSpaceWidth = $('#videospace').width();
  6868. var videoSpaceHeight = window.innerHeight;
  6869. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6870. videoHeight,
  6871. videoSpaceWidth,
  6872. videoSpaceHeight);
  6873. var largeVideoWidth = videoSize[0];
  6874. var largeVideoHeight = videoSize[1];
  6875. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6876. largeVideoHeight,
  6877. videoSpaceWidth,
  6878. videoSpaceHeight);
  6879. var horizontalIndent = videoPosition[0];
  6880. var verticalIndent = videoPosition[1];
  6881. positionVideo($('#largeVideo'),
  6882. largeVideoWidth,
  6883. largeVideoHeight,
  6884. horizontalIndent, verticalIndent);
  6885. };
  6886. /**
  6887. * Shows/hides the large video.
  6888. */
  6889. my.setLargeVideoVisible = function(isVisible) {
  6890. var resourceJid = largeVideoState.userResourceJid;
  6891. if (isVisible) {
  6892. $('#largeVideo').css({visibility: 'visible'});
  6893. $('.watermark').css({visibility: 'visible'});
  6894. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6895. }
  6896. else {
  6897. $('#largeVideo').css({visibility: 'hidden'});
  6898. $('#activeSpeaker').css('visibility', 'hidden');
  6899. $('.watermark').css({visibility: 'hidden'});
  6900. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6901. if(focusedVideoInfo) {
  6902. var focusResourceJid = focusedVideoInfo.resourceJid;
  6903. var oldContainer = getParticipantContainer(focusResourceJid);
  6904. if (oldContainer && oldContainer.length > 0) {
  6905. oldContainer.removeClass("videoContainerFocused");
  6906. }
  6907. focusedVideoInfo = null;
  6908. if(focusResourceJid) {
  6909. Avatar.showUserAvatar(
  6910. APP.xmpp.findJidFromResource(focusResourceJid));
  6911. }
  6912. }
  6913. }
  6914. };
  6915. /**
  6916. * Indicates if the large video is currently visible.
  6917. *
  6918. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6919. */
  6920. my.isLargeVideoVisible = function() {
  6921. return $('#largeVideo').is(':visible');
  6922. };
  6923. my.isLargeVideoOnTop = function () {
  6924. var Etherpad = require("../etherpad/Etherpad");
  6925. var Prezi = require("../prezi/Prezi");
  6926. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6927. };
  6928. /**
  6929. * Checks if container for participant identified by given peerJid exists
  6930. * in the document and creates it eventually.
  6931. *
  6932. * @param peerJid peer Jid to check.
  6933. * @param userId user email or id for setting the avatar
  6934. *
  6935. * @return Returns <tt>true</tt> if the peer container exists,
  6936. * <tt>false</tt> - otherwise
  6937. */
  6938. my.ensurePeerContainerExists = function(peerJid, userId) {
  6939. ContactList.ensureAddContact(peerJid, userId);
  6940. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6941. var videoSpanId = 'participant_' + resourceJid;
  6942. if (!$('#' + videoSpanId).length) {
  6943. var container =
  6944. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6945. Avatar.setUserAvatar(peerJid, userId);
  6946. // Set default display name.
  6947. setDisplayName(videoSpanId);
  6948. VideoLayout.connectionIndicators[videoSpanId] =
  6949. new ConnectionIndicator(container, peerJid, VideoLayout);
  6950. var nickfield = document.createElement('span');
  6951. nickfield.className = "nick";
  6952. nickfield.appendChild(document.createTextNode(resourceJid));
  6953. container.appendChild(nickfield);
  6954. // In case this is not currently in the last n we don't show it.
  6955. if (localLastNCount
  6956. && localLastNCount > 0
  6957. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6958. showPeerContainer(resourceJid, 'hide');
  6959. }
  6960. else
  6961. VideoLayout.resizeThumbnails();
  6962. }
  6963. };
  6964. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6965. var container = document.createElement('span');
  6966. container.id = spanId;
  6967. container.className = 'videocontainer';
  6968. var remotes = document.getElementById('remoteVideos');
  6969. remotes.appendChild(container);
  6970. // If the peerJid is null then this video span couldn't be directly
  6971. // associated with a participant (this could happen in the case of prezi).
  6972. if (APP.xmpp.isModerator() && peerJid !== null)
  6973. addRemoteVideoMenu(peerJid, container);
  6974. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6975. return container;
  6976. };
  6977. /**
  6978. * Creates an audio or video stream element.
  6979. */
  6980. my.createStreamElement = function (sid, stream) {
  6981. var isVideo = stream.getVideoTracks().length > 0;
  6982. var element = isVideo
  6983. ? document.createElement('video')
  6984. : document.createElement('audio');
  6985. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6986. + sid + '_' + APP.RTC.getStreamID(stream);
  6987. element.id = id;
  6988. element.autoplay = true;
  6989. element.oncontextmenu = function () { return false; };
  6990. return element;
  6991. };
  6992. my.addRemoteStreamElement
  6993. = function (container, sid, stream, peerJid, thessrc) {
  6994. var newElementId = null;
  6995. var isVideo = stream.getVideoTracks().length > 0;
  6996. if (container) {
  6997. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6998. newElementId = streamElement.id;
  6999. container.appendChild(streamElement);
  7000. var sel = $('#' + newElementId);
  7001. sel.hide();
  7002. // If the container is currently visible we attach the stream.
  7003. if (!isVideo
  7004. || (container.offsetParent !== null && isVideo)) {
  7005. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  7006. APP.RTC.attachMediaStream(sel, videoStream);
  7007. if (isVideo)
  7008. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  7009. }
  7010. stream.onended = function () {
  7011. console.log('stream ended', this);
  7012. VideoLayout.removeRemoteStreamElement(
  7013. stream, isVideo, container, newElementId);
  7014. // NOTE(gp) it seems that under certain circumstances, the
  7015. // onended event is not fired and thus the contact list is not
  7016. // updated.
  7017. //
  7018. // The onended event of a stream should be fired when the SSRCs
  7019. // corresponding to that stream are removed from the SDP; but
  7020. // this doesn't seem to always be the case, resulting in ghost
  7021. // contacts.
  7022. //
  7023. // In an attempt to fix the ghost contacts problem, I'm moving
  7024. // the removeContact() method call in app.js, inside the
  7025. // 'muc.left' event handler.
  7026. //if (peerJid)
  7027. // ContactList.removeContact(peerJid);
  7028. };
  7029. // Add click handler.
  7030. container.onclick = function (event) {
  7031. /*
  7032. * FIXME It turns out that videoThumb may not exist (if there is
  7033. * no actual video).
  7034. */
  7035. var videoThumb = $('#' + container.id + '>video').get(0);
  7036. if (videoThumb) {
  7037. VideoLayout.handleVideoThumbClicked(
  7038. APP.RTC.getVideoSrc(videoThumb),
  7039. false,
  7040. Strophe.getResourceFromJid(peerJid));
  7041. }
  7042. event.stopPropagation();
  7043. event.preventDefault();
  7044. return false;
  7045. };
  7046. // Add hover handler
  7047. $(container).hover(
  7048. function() {
  7049. VideoLayout.showDisplayName(container.id, true);
  7050. },
  7051. function() {
  7052. var videoSrc = null;
  7053. if ($('#' + container.id + '>video')
  7054. && $('#' + container.id + '>video').length > 0) {
  7055. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  7056. }
  7057. // If the video has been "pinned" by the user we want to
  7058. // keep the display name on place.
  7059. if (!VideoLayout.isLargeVideoVisible()
  7060. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  7061. VideoLayout.showDisplayName(container.id, false);
  7062. }
  7063. );
  7064. }
  7065. return newElementId;
  7066. };
  7067. /**
  7068. * Removes the remote stream element corresponding to the given stream and
  7069. * parent container.
  7070. *
  7071. * @param stream the stream
  7072. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7073. * @param container
  7074. */
  7075. my.removeRemoteStreamElement = function (stream, isVideo, container, id) {
  7076. if (!container)
  7077. return;
  7078. var select = null;
  7079. var removedVideoSrc = null;
  7080. if (isVideo) {
  7081. select = $('#' + id);
  7082. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  7083. }
  7084. else
  7085. select = $('#' + container.id + '>audio');
  7086. // Mark video as removed to cancel waiting loop(if video is removed
  7087. // before has started)
  7088. select.removed = true;
  7089. select.remove();
  7090. var audioCount = $('#' + container.id + '>audio').length;
  7091. var videoCount = $('#' + container.id + '>video').length;
  7092. if (!audioCount && !videoCount) {
  7093. console.log("Remove whole user", container.id);
  7094. if(VideoLayout.connectionIndicators[container.id])
  7095. VideoLayout.connectionIndicators[container.id].remove();
  7096. // Remove whole container
  7097. container.remove();
  7098. UIUtil.playSoundNotification('userLeft');
  7099. VideoLayout.resizeThumbnails();
  7100. }
  7101. if (removedVideoSrc)
  7102. VideoLayout.updateRemovedVideo(removedVideoSrc);
  7103. };
  7104. /**
  7105. * Show/hide peer container for the given resourceJid.
  7106. */
  7107. function showPeerContainer(resourceJid, state) {
  7108. var peerContainer = $('#participant_' + resourceJid);
  7109. if (!peerContainer)
  7110. return;
  7111. var isHide = state === 'hide';
  7112. var resizeThumbnails = false;
  7113. if (!isHide) {
  7114. if (!peerContainer.is(':visible')) {
  7115. resizeThumbnails = true;
  7116. peerContainer.show();
  7117. }
  7118. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7119. if (state == 'show')
  7120. {
  7121. // peerContainer.css('-webkit-filter', '');
  7122. Avatar.showUserAvatar(jid, false);
  7123. }
  7124. else // if (state == 'avatar')
  7125. {
  7126. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  7127. Avatar.showUserAvatar(jid, true);
  7128. }
  7129. }
  7130. else if (peerContainer.is(':visible') && isHide)
  7131. {
  7132. resizeThumbnails = true;
  7133. peerContainer.hide();
  7134. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  7135. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  7136. }
  7137. if (resizeThumbnails) {
  7138. VideoLayout.resizeThumbnails();
  7139. }
  7140. // We want to be able to pin a participant from the contact list, even
  7141. // if he's not in the lastN set!
  7142. // ContactList.setClickable(resourceJid, !isHide);
  7143. };
  7144. my.inputDisplayNameHandler = function (name) {
  7145. NicknameHandler.setNickname(name);
  7146. if (!$('#localDisplayName').is(":visible")) {
  7147. if (NicknameHandler.getNickname())
  7148. {
  7149. var meHTML = APP.translation.generateTranslatonHTML("me");
  7150. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7151. }
  7152. else
  7153. {
  7154. var defaultHTML = APP.translation.generateTranslatonHTML(
  7155. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7156. $('#localDisplayName')
  7157. .html(defaultHTML);
  7158. }
  7159. $('#localDisplayName').show();
  7160. }
  7161. $('#editDisplayName').hide();
  7162. };
  7163. /**
  7164. * Shows/hides the display name on the remote video.
  7165. * @param videoSpanId the identifier of the video span element
  7166. * @param isShow indicates if the display name should be shown or hidden
  7167. */
  7168. my.showDisplayName = function(videoSpanId, isShow) {
  7169. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  7170. if (isShow) {
  7171. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7172. nameSpan.setAttribute("style", "display:inline-block;");
  7173. }
  7174. else {
  7175. if (nameSpan)
  7176. nameSpan.setAttribute("style", "display:none;");
  7177. }
  7178. };
  7179. /**
  7180. * Shows the presence status message for the given video.
  7181. */
  7182. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  7183. if (!$('#' + videoSpanId).length) {
  7184. // No container
  7185. return;
  7186. }
  7187. var statusSpan = $('#' + videoSpanId + '>span.status');
  7188. if (!statusSpan.length) {
  7189. //Add status span
  7190. statusSpan = document.createElement('span');
  7191. statusSpan.className = 'status';
  7192. statusSpan.id = videoSpanId + '_status';
  7193. $('#' + videoSpanId)[0].appendChild(statusSpan);
  7194. statusSpan = $('#' + videoSpanId + '>span.status');
  7195. }
  7196. // Display status
  7197. if (statusMsg && statusMsg.length) {
  7198. $('#' + videoSpanId + '_status').text(statusMsg);
  7199. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7200. }
  7201. else {
  7202. // Hide
  7203. statusSpan.get(0).setAttribute("style", "display:none;");
  7204. }
  7205. };
  7206. /**
  7207. * Shows a visual indicator for the moderator of the conference.
  7208. */
  7209. my.showModeratorIndicator = function () {
  7210. var isModerator = APP.xmpp.isModerator();
  7211. if (isModerator) {
  7212. var indicatorSpan = $('#localVideoContainer .focusindicator');
  7213. if (indicatorSpan.children().length === 0)
  7214. {
  7215. createModeratorIndicatorElement(indicatorSpan[0]);
  7216. //translates text in focus indicator
  7217. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  7218. }
  7219. }
  7220. var members = APP.xmpp.getMembers();
  7221. Object.keys(members).forEach(function (jid) {
  7222. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7223. // Skip server side focus
  7224. return;
  7225. }
  7226. var resourceJid = Strophe.getResourceFromJid(jid);
  7227. var videoSpanId = 'participant_' + resourceJid;
  7228. var videoContainer = document.getElementById(videoSpanId);
  7229. if (!videoContainer) {
  7230. console.error("No video container for " + jid);
  7231. return;
  7232. }
  7233. var member = members[jid];
  7234. if (member.role === 'moderator') {
  7235. // Remove menu if peer is moderator
  7236. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7237. if (menuSpan.length) {
  7238. removeRemoteVideoMenu(videoSpanId);
  7239. }
  7240. // Show moderator indicator
  7241. var indicatorSpan
  7242. = $('#' + videoSpanId + ' .focusindicator');
  7243. if (!indicatorSpan || indicatorSpan.length === 0) {
  7244. indicatorSpan = document.createElement('span');
  7245. indicatorSpan.className = 'focusindicator';
  7246. videoContainer.appendChild(indicatorSpan);
  7247. createModeratorIndicatorElement(indicatorSpan);
  7248. //translates text in focus indicators
  7249. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7250. }
  7251. } else if (isModerator) {
  7252. // We are moderator, but user is not - add menu
  7253. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7254. addRemoteVideoMenu(
  7255. jid,
  7256. document.getElementById('participant_' + resourceJid));
  7257. }
  7258. }
  7259. });
  7260. };
  7261. /**
  7262. * Shows video muted indicator over small videos.
  7263. */
  7264. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7265. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7266. if (isMuted === 'false') {
  7267. if (videoMutedSpan.length > 0) {
  7268. videoMutedSpan.remove();
  7269. }
  7270. }
  7271. else {
  7272. if(videoMutedSpan.length == 0) {
  7273. videoMutedSpan = document.createElement('span');
  7274. videoMutedSpan.className = 'videoMuted';
  7275. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7276. var mutedIndicator = document.createElement('i');
  7277. mutedIndicator.className = 'icon-camera-disabled';
  7278. UIUtil.setTooltip(mutedIndicator,
  7279. "videothumbnail.videomute",
  7280. "top");
  7281. videoMutedSpan.appendChild(mutedIndicator);
  7282. //translate texts for muted indicator
  7283. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7284. }
  7285. VideoLayout.updateMutePosition(videoSpanId);
  7286. }
  7287. };
  7288. my.updateMutePosition = function (videoSpanId) {
  7289. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7290. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7291. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7292. if(connectionIndicator.length > 0
  7293. && connectionIndicator[0].style.display != "none") {
  7294. audioMutedSpan.css({right: "23px"});
  7295. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7296. }
  7297. else
  7298. {
  7299. audioMutedSpan.css({right: "0px"});
  7300. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7301. }
  7302. }
  7303. /**
  7304. * Shows audio muted indicator over small videos.
  7305. * @param {string} isMuted
  7306. */
  7307. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7308. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7309. if (isMuted === 'false') {
  7310. if (audioMutedSpan.length > 0) {
  7311. audioMutedSpan.popover('hide');
  7312. audioMutedSpan.remove();
  7313. }
  7314. }
  7315. else {
  7316. if(audioMutedSpan.length == 0 ) {
  7317. audioMutedSpan = document.createElement('span');
  7318. audioMutedSpan.className = 'audioMuted';
  7319. UIUtil.setTooltip(audioMutedSpan,
  7320. "videothumbnail.mute",
  7321. "top");
  7322. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7323. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7324. var mutedIndicator = document.createElement('i');
  7325. mutedIndicator.className = 'icon-mic-disabled';
  7326. audioMutedSpan.appendChild(mutedIndicator);
  7327. }
  7328. VideoLayout.updateMutePosition(videoSpanId);
  7329. }
  7330. };
  7331. /*
  7332. * Shows or hides the audio muted indicator over the local thumbnail video.
  7333. * @param {boolean} isMuted
  7334. */
  7335. my.showLocalAudioIndicator = function(isMuted) {
  7336. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7337. };
  7338. /**
  7339. * Resizes the large video container.
  7340. */
  7341. my.resizeLargeVideoContainer = function () {
  7342. Chat.resizeChat();
  7343. var availableHeight = window.innerHeight;
  7344. var availableWidth = UIUtil.getAvailableVideoWidth();
  7345. if (availableWidth < 0 || availableHeight < 0) return;
  7346. $('#videospace').width(availableWidth);
  7347. $('#videospace').height(availableHeight);
  7348. $('#largeVideoContainer').width(availableWidth);
  7349. $('#largeVideoContainer').height(availableHeight);
  7350. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7351. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7352. $('#activeSpeaker').css('top', top);
  7353. VideoLayout.resizeThumbnails();
  7354. };
  7355. /**
  7356. * Resizes thumbnails.
  7357. */
  7358. my.resizeThumbnails = function() {
  7359. var videoSpaceWidth = $('#remoteVideos').width();
  7360. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7361. var width = thumbnailSize[0];
  7362. var height = thumbnailSize[1];
  7363. // size videos so that while keeping AR and max height, we have a
  7364. // nice fit
  7365. $('#remoteVideos').height(height);
  7366. $('#remoteVideos>span').width(width);
  7367. $('#remoteVideos>span').height(height);
  7368. $('.userAvatar').css('left', (width - height) / 2);
  7369. $(document).trigger("remotevideo.resized", [width, height]);
  7370. };
  7371. /**
  7372. * Enables the dominant speaker UI.
  7373. *
  7374. * @param resourceJid the jid indicating the video element to
  7375. * activate/deactivate
  7376. * @param isEnable indicates if the dominant speaker should be enabled or
  7377. * disabled
  7378. */
  7379. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7380. var videoSpanId = null;
  7381. var videoContainerId = null;
  7382. if (resourceJid
  7383. === APP.xmpp.myResource()) {
  7384. videoSpanId = 'localVideoWrapper';
  7385. videoContainerId = 'localVideoContainer';
  7386. }
  7387. else {
  7388. videoSpanId = 'participant_' + resourceJid;
  7389. videoContainerId = videoSpanId;
  7390. }
  7391. var displayName = resourceJid;
  7392. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7393. if (nameSpan.length > 0)
  7394. displayName = nameSpan.html();
  7395. console.log("UI enable dominant speaker",
  7396. displayName,
  7397. resourceJid,
  7398. isEnable);
  7399. videoSpan = document.getElementById(videoContainerId);
  7400. if (!videoSpan) {
  7401. return;
  7402. }
  7403. var video = $('#' + videoSpanId + '>video');
  7404. if (video && video.length > 0) {
  7405. if (isEnable) {
  7406. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7407. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7408. if (!videoSpan.classList.contains("dominantspeaker"))
  7409. videoSpan.classList.add("dominantspeaker");
  7410. }
  7411. else {
  7412. VideoLayout.showDisplayName(videoContainerId, false);
  7413. if (videoSpan.classList.contains("dominantspeaker"))
  7414. videoSpan.classList.remove("dominantspeaker");
  7415. }
  7416. }
  7417. Avatar.showUserAvatar(
  7418. APP.xmpp.findJidFromResource(resourceJid));
  7419. };
  7420. /**
  7421. * Calculates the thumbnail size.
  7422. *
  7423. * @param videoSpaceWidth the width of the video space
  7424. */
  7425. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7426. // Calculate the available height, which is the inner window height minus
  7427. // 39px for the header minus 2px for the delimiter lines on the top and
  7428. // bottom of the large video, minus the 36px space inside the remoteVideos
  7429. // container used for highlighting shadow.
  7430. var availableHeight = 100;
  7431. var numvids = $('#remoteVideos>span:visible').length;
  7432. if (localLastNCount && localLastNCount > 0) {
  7433. numvids = Math.min(localLastNCount + 1, numvids);
  7434. }
  7435. // Remove the 3px borders arround videos and border around the remote
  7436. // videos area and the 4 pixels between the local video and the others
  7437. //TODO: Find out where the 4 pixels come from and remove them
  7438. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7439. var availableWidth = availableWinWidth / numvids;
  7440. var aspectRatio = 16.0 / 9.0;
  7441. var maxHeight = Math.min(160, availableHeight);
  7442. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7443. if (availableHeight < availableWidth / aspectRatio) {
  7444. availableWidth = Math.floor(availableHeight * aspectRatio);
  7445. }
  7446. return [availableWidth, availableHeight];
  7447. };
  7448. /**
  7449. * Updates the remote video menu.
  7450. *
  7451. * @param jid the jid indicating the video for which we're adding a menu.
  7452. * @param isMuted indicates the current mute state
  7453. */
  7454. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7455. var muteMenuItem
  7456. = $('#remote_popupmenu_'
  7457. + Strophe.getResourceFromJid(jid)
  7458. + '>li>a.mutelink');
  7459. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7460. if (muteMenuItem.length) {
  7461. var muteLink = muteMenuItem.get(0);
  7462. if (isMuted === 'true') {
  7463. muteLink.innerHTML = mutedIndicator + ' Muted';
  7464. muteLink.className = 'mutelink disabled';
  7465. }
  7466. else {
  7467. muteLink.innerHTML = mutedIndicator + ' Mute';
  7468. muteLink.className = 'mutelink';
  7469. }
  7470. }
  7471. };
  7472. /**
  7473. * Returns the current dominant speaker resource jid.
  7474. */
  7475. my.getDominantSpeakerResourceJid = function () {
  7476. return currentDominantSpeaker;
  7477. };
  7478. /**
  7479. * Returns the corresponding resource jid to the given peer container
  7480. * DOM element.
  7481. *
  7482. * @return the corresponding resource jid to the given peer container
  7483. * DOM element
  7484. */
  7485. my.getPeerContainerResourceJid = function (containerElement) {
  7486. var i = containerElement.id.indexOf('participant_');
  7487. if (i >= 0)
  7488. return containerElement.id.substring(i + 12);
  7489. };
  7490. /**
  7491. * On contact list item clicked.
  7492. */
  7493. $(ContactList).bind('contactclicked', function(event, jid) {
  7494. if (!jid) {
  7495. return;
  7496. }
  7497. var resource = Strophe.getResourceFromJid(jid);
  7498. var videoContainer = $("#participant_" + resource);
  7499. if (videoContainer.length > 0) {
  7500. var videoThumb = $('video', videoContainer).get(0);
  7501. // It is not always the case that a videoThumb exists (if there is
  7502. // no actual video).
  7503. if (videoThumb) {
  7504. if (videoThumb.src && videoThumb.src != '') {
  7505. // We have a video src, great! Let's update the large video
  7506. // now.
  7507. VideoLayout.handleVideoThumbClicked(
  7508. videoThumb.src,
  7509. false,
  7510. Strophe.getResourceFromJid(jid));
  7511. } else {
  7512. // If we don't have a video src for jid, there's absolutely
  7513. // no point in calling handleVideoThumbClicked; Quite
  7514. // simply, it won't work because it needs an src to attach
  7515. // to the large video.
  7516. //
  7517. // Instead, we trigger the pinned endpoint changed event to
  7518. // let the bridge adjust its lastN set for myjid and store
  7519. // the pinned user in the lastNPickupJid variable to be
  7520. // picked up later by the lastN changed event handler.
  7521. lastNPickupJid = jid;
  7522. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7523. Strophe.getResourceFromJid(jid));
  7524. }
  7525. } else if (jid == APP.xmpp.myJid()) {
  7526. $("#localVideoContainer").click();
  7527. }
  7528. }
  7529. });
  7530. /**
  7531. * On audio muted event.
  7532. */
  7533. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7534. /*
  7535. // FIXME: but focus can not mute in this case ? - check
  7536. if (jid === xmpp.myJid()) {
  7537. // The local mute indicator is controlled locally
  7538. return;
  7539. }*/
  7540. var videoSpanId = null;
  7541. if (jid === APP.xmpp.myJid()) {
  7542. videoSpanId = 'localVideoContainer';
  7543. } else {
  7544. VideoLayout.ensurePeerContainerExists(jid);
  7545. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7546. }
  7547. mutedAudios[jid] = isMuted;
  7548. if (APP.xmpp.isModerator()) {
  7549. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7550. }
  7551. if (videoSpanId)
  7552. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7553. });
  7554. /**
  7555. * On video muted event.
  7556. */
  7557. $(document).bind('videomuted.muc', function (event, jid, value) {
  7558. var isMuted = (value === "true");
  7559. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7560. return;
  7561. Avatar.showUserAvatar(jid, isMuted);
  7562. var videoSpanId = null;
  7563. if (jid === APP.xmpp.myJid()) {
  7564. videoSpanId = 'localVideoContainer';
  7565. } else {
  7566. VideoLayout.ensurePeerContainerExists(jid);
  7567. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7568. }
  7569. if (videoSpanId)
  7570. VideoLayout.showVideoIndicator(videoSpanId, value);
  7571. });
  7572. /**
  7573. * Display name changed.
  7574. */
  7575. my.onDisplayNameChanged =
  7576. function (jid, displayName, status) {
  7577. if (jid === 'localVideoContainer'
  7578. || jid === APP.xmpp.myJid()) {
  7579. setDisplayName('localVideoContainer',
  7580. displayName);
  7581. } else {
  7582. VideoLayout.ensurePeerContainerExists(jid);
  7583. setDisplayName(
  7584. 'participant_' + Strophe.getResourceFromJid(jid),
  7585. displayName,
  7586. status);
  7587. }
  7588. };
  7589. /**
  7590. * On dominant speaker changed event.
  7591. */
  7592. my.onDominantSpeakerChanged = function (resourceJid) {
  7593. // We ignore local user events.
  7594. if (resourceJid
  7595. === APP.xmpp.myResource())
  7596. return;
  7597. var members = APP.xmpp.getMembers();
  7598. // Update the current dominant speaker.
  7599. if (resourceJid !== currentDominantSpeaker) {
  7600. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7601. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7602. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7603. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7604. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7605. !members[currentJID].displayName)) {
  7606. setDisplayName(oldSpeakerVideoSpanId, null);
  7607. }
  7608. if(resourceJid && (!members || !members[newJID] ||
  7609. !members[newJID].displayName)) {
  7610. setDisplayName(newSpeakerVideoSpanId, null,
  7611. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7612. }
  7613. currentDominantSpeaker = resourceJid;
  7614. } else {
  7615. return;
  7616. }
  7617. // Obtain container for new dominant speaker.
  7618. var container = document.getElementById(
  7619. 'participant_' + resourceJid);
  7620. // Local video will not have container found, but that's ok
  7621. // since we don't want to switch to local video.
  7622. if (container && !focusedVideoInfo)
  7623. {
  7624. var video = container.getElementsByTagName("video");
  7625. // Update the large video if the video source is already available,
  7626. // otherwise wait for the "videoactive.jingle" event.
  7627. if (video.length && video[0].currentTime > 0)
  7628. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7629. }
  7630. };
  7631. /**
  7632. * On last N change event.
  7633. *
  7634. * @param lastNEndpoints the list of last N endpoints
  7635. * @param endpointsEnteringLastN the list currently entering last N
  7636. * endpoints
  7637. */
  7638. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7639. endpointsEnteringLastN,
  7640. stream) {
  7641. if (lastNCount !== lastNEndpoints.length)
  7642. lastNCount = lastNEndpoints.length;
  7643. lastNEndpointsCache = lastNEndpoints;
  7644. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7645. //
  7646. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7647. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7648. // so E sees them. C is only in E's local LastN set.
  7649. //
  7650. // If F starts talking and LastN = 3, then E should see thumbnails for
  7651. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7652. // enters E's local LastN ejecting C.
  7653. // Increase the local LastN set size, if necessary.
  7654. if (lastNCount > localLastNCount) {
  7655. localLastNCount = lastNCount;
  7656. }
  7657. // Update the local LastN set preserving the order in which the
  7658. // endpoints appeared in the LastN/local LastN set.
  7659. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7660. for (var i = 0; i < localLastNSet.length; i++) {
  7661. if (nextLocalLastNSet.length >= localLastNCount) {
  7662. break;
  7663. }
  7664. var resourceJid = localLastNSet[i];
  7665. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7666. nextLocalLastNSet.push(resourceJid);
  7667. }
  7668. }
  7669. localLastNSet = nextLocalLastNSet;
  7670. var updateLargeVideo = false;
  7671. // Handle LastN/local LastN changes.
  7672. $('#remoteVideos>span').each(function( index, element ) {
  7673. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7674. var isReceived = true;
  7675. if (resourceJid
  7676. && lastNEndpoints.indexOf(resourceJid) < 0
  7677. && localLastNSet.indexOf(resourceJid) < 0) {
  7678. console.log("Remove from last N", resourceJid);
  7679. showPeerContainer(resourceJid, 'hide');
  7680. isReceived = false;
  7681. } else if (resourceJid
  7682. && $('#participant_' + resourceJid).is(':visible')
  7683. && lastNEndpoints.indexOf(resourceJid) < 0
  7684. && localLastNSet.indexOf(resourceJid) >= 0) {
  7685. showPeerContainer(resourceJid, 'avatar');
  7686. isReceived = false;
  7687. }
  7688. if (!isReceived) {
  7689. // resourceJid has dropped out of the server side lastN set, so
  7690. // it is no longer being received. If resourceJid was being
  7691. // displayed in the large video we have to switch to another
  7692. // user.
  7693. var largeVideoResource = largeVideoState.userResourceJid;
  7694. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7695. updateLargeVideo = true;
  7696. }
  7697. }
  7698. });
  7699. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7700. endpointsEnteringLastN = lastNEndpoints;
  7701. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7702. endpointsEnteringLastN.forEach(function (resourceJid) {
  7703. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7704. showPeerContainer(resourceJid, 'show');
  7705. if (!isVisible) {
  7706. console.log("Add to last N", resourceJid);
  7707. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7708. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7709. var sel = $('#participant_' + resourceJid + '>video');
  7710. var videoStream = APP.simulcast.getReceivingVideoStream(
  7711. mediaStream.stream);
  7712. APP.RTC.attachMediaStream(sel, videoStream);
  7713. if (lastNPickupJid == mediaStream.peerjid) {
  7714. // Clean up the lastN pickup jid.
  7715. lastNPickupJid = null;
  7716. // Don't fire the events again, they've already
  7717. // been fired in the contact list click handler.
  7718. VideoLayout.handleVideoThumbClicked(
  7719. $(sel).attr('src'),
  7720. false,
  7721. Strophe.getResourceFromJid(mediaStream.peerjid));
  7722. updateLargeVideo = false;
  7723. }
  7724. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7725. }
  7726. })
  7727. }
  7728. // The endpoint that was being shown in the large video has dropped out
  7729. // of the lastN set and there was no lastN pickup jid. We need to update
  7730. // the large video now.
  7731. if (updateLargeVideo) {
  7732. var resource, container, src;
  7733. var myResource
  7734. = APP.xmpp.myResource();
  7735. // Find out which endpoint to show in the large video.
  7736. for (var i = 0; i < lastNEndpoints.length; i++) {
  7737. resource = lastNEndpoints[i];
  7738. if (!resource || resource === myResource)
  7739. continue;
  7740. container = $("#participant_" + resource);
  7741. if (container.length == 0)
  7742. continue;
  7743. src = $('video', container).attr('src');
  7744. if (!src)
  7745. continue;
  7746. // videoSrcToSsrc needs to be update for this call to succeed.
  7747. VideoLayout.updateLargeVideo(src);
  7748. break;
  7749. }
  7750. }
  7751. };
  7752. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7753. endpointSimulcastLayers.forEach(function (esl) {
  7754. var resource = esl.endpoint;
  7755. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7756. // then ignore the event (= do not preload anything).
  7757. //
  7758. // The bridge could probably stop sending this message if it's for
  7759. // an endpoint that's not in lastN.
  7760. if (lastNCount != -1
  7761. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7762. return;
  7763. }
  7764. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7765. // Get session and stream from primary ssrc.
  7766. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7767. var sid = res.sid;
  7768. var electedStream = res.stream;
  7769. if (sid && electedStream) {
  7770. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7771. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7772. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7773. if (preload) {
  7774. if (largeVideoState.preload)
  7775. {
  7776. $(largeVideoState.preload).remove();
  7777. }
  7778. console.info('Preloading remote video');
  7779. largeVideoState.preload = $('<video autoplay></video>');
  7780. // ssrcs are unique in an rtp session
  7781. largeVideoState.preload_ssrc = primarySSRC;
  7782. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7783. }
  7784. } else {
  7785. console.error('Could not find a stream or a session.', sid, electedStream);
  7786. }
  7787. });
  7788. };
  7789. /**
  7790. * On simulcast layers changed event.
  7791. */
  7792. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7793. endpointSimulcastLayers.forEach(function (esl) {
  7794. var resource = esl.endpoint;
  7795. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7796. // then ignore the event (= do not change large video/thumbnail
  7797. // SRCs).
  7798. //
  7799. // Note that even if we ignore the "changed" event in this event
  7800. // handler, the bridge must continue sending these events because
  7801. // the simulcast code in simulcast.js uses it to know what's going
  7802. // to be streamed by the bridge when/if the endpoint gets back into
  7803. // the lastN set.
  7804. if (lastNCount != -1
  7805. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7806. return;
  7807. }
  7808. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7809. // Get session and stream from primary ssrc.
  7810. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7811. var sid = res.sid;
  7812. var electedStream = res.stream;
  7813. if (sid && electedStream) {
  7814. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7815. console.info('Switching simulcast substream.');
  7816. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7817. var msidParts = msid.split(' ');
  7818. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7819. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7820. == largeVideoState.userResourceJid);
  7821. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7822. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7823. var electedStreamUrl;
  7824. if (largeVideoState.preload_ssrc == primarySSRC)
  7825. {
  7826. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7827. }
  7828. else
  7829. {
  7830. if (largeVideoState.preload
  7831. && largeVideoState.preload != null) {
  7832. $(largeVideoState.preload).remove();
  7833. }
  7834. largeVideoState.preload_ssrc = 0;
  7835. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7836. }
  7837. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7838. if (updateLargeVideo) {
  7839. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7840. Strophe.getResourceFromJid(jid));
  7841. }
  7842. if (updateFocusedVideoSrc) {
  7843. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7844. }
  7845. var videoId;
  7846. if(resource == APP.xmpp.myResource())
  7847. {
  7848. videoId = "localVideoContainer";
  7849. }
  7850. else
  7851. {
  7852. videoId = "participant_" + resource;
  7853. }
  7854. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7855. if(connectionIndicator)
  7856. connectionIndicator.updatePopoverData();
  7857. } else {
  7858. console.error('Could not find a stream or a sid.', sid, electedStream);
  7859. }
  7860. });
  7861. };
  7862. /**
  7863. * Updates local stats
  7864. * @param percent
  7865. * @param object
  7866. */
  7867. my.updateLocalConnectionStats = function (percent, object) {
  7868. var resolution = null;
  7869. if(object.resolution !== null)
  7870. {
  7871. resolution = object.resolution;
  7872. object.resolution = resolution[APP.xmpp.myJid()];
  7873. delete resolution[APP.xmpp.myJid()];
  7874. }
  7875. updateStatsIndicator("localVideoContainer", percent, object);
  7876. for(var jid in resolution)
  7877. {
  7878. if(resolution[jid] === null)
  7879. continue;
  7880. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7881. if(VideoLayout.connectionIndicators[id])
  7882. {
  7883. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7884. }
  7885. }
  7886. };
  7887. /**
  7888. * Updates remote stats.
  7889. * @param jid the jid associated with the stats
  7890. * @param percent the connection quality percent
  7891. * @param object the stats data
  7892. */
  7893. my.updateConnectionStats = function (jid, percent, object) {
  7894. var resourceJid = Strophe.getResourceFromJid(jid);
  7895. var videoSpanId = 'participant_' + resourceJid;
  7896. updateStatsIndicator(videoSpanId, percent, object);
  7897. };
  7898. /**
  7899. * Removes the connection
  7900. * @param jid
  7901. */
  7902. my.removeConnectionIndicator = function (jid) {
  7903. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7904. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7905. };
  7906. /**
  7907. * Hides the connection indicator
  7908. * @param jid
  7909. */
  7910. my.hideConnectionIndicator = function (jid) {
  7911. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7912. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7913. };
  7914. /**
  7915. * Hides all the indicators
  7916. */
  7917. my.onStatsStop = function () {
  7918. for(var indicator in VideoLayout.connectionIndicators)
  7919. {
  7920. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7921. }
  7922. };
  7923. my.participantLeft = function (jid) {
  7924. // Unlock large video
  7925. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7926. {
  7927. console.info("Focused video owner has left the conference");
  7928. focusedVideoInfo = null;
  7929. }
  7930. }
  7931. my.onVideoTypeChanged = function (jid) {
  7932. if(jid &&
  7933. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7934. {
  7935. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7936. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7937. ? getDesktopVideoSize
  7938. : getCameraVideoSize;
  7939. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7940. ? getDesktopVideoPosition
  7941. : getCameraVideoPosition;
  7942. VideoLayout.positionLarge(null, null);
  7943. }
  7944. }
  7945. return my;
  7946. }(VideoLayout || {}));
  7947. module.exports = VideoLayout;
  7948. },{"../../../service/RTC/MediaStreamTypes":94,"../../../service/UI/UIEvents":99,"../audio_levels/AudioLevels":9,"../avatar/Avatar":13,"../etherpad/Etherpad":14,"../prezi/Prezi":15,"../side_pannels/chat/Chat":18,"../side_pannels/contactlist/ContactList":22,"../util/NicknameHandler":29,"../util/UIUtil":30,"./ConnectionIndicator":31}],33:[function(require,module,exports){
  7949. //var nouns = [
  7950. //];
  7951. var pluralNouns = [
  7952. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7953. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7954. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7955. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7956. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7957. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7958. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7959. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7960. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7961. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7962. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7963. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7964. ];
  7965. //var places = [
  7966. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7967. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7968. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7969. // "Bridge"
  7970. //];
  7971. var verbs = [
  7972. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7973. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7974. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7975. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7976. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7977. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7978. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7979. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7980. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7981. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7982. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7983. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7984. ];
  7985. var adverbs = [
  7986. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7987. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7988. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7989. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7990. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7991. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7992. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7993. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7994. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7995. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7996. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7997. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7998. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7999. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  8000. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  8001. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  8002. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  8003. ];
  8004. var adjectives = [
  8005. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  8006. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  8007. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  8008. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  8009. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  8010. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  8011. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  8012. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  8013. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  8014. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  8015. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  8016. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  8017. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  8018. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  8019. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  8020. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  8021. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  8022. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  8023. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  8024. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  8025. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  8026. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  8027. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  8028. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  8029. "Zealous"
  8030. ];
  8031. //var pronouns = [
  8032. //];
  8033. //var conjunctions = [
  8034. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  8035. //];
  8036. /*
  8037. * Maps a string (category name) to the array of words from that category.
  8038. */
  8039. var CATEGORIES =
  8040. {
  8041. //"_NOUN_": nouns,
  8042. "_PLURALNOUN_": pluralNouns,
  8043. //"_PLACE_": places,
  8044. "_VERB_": verbs,
  8045. "_ADVERB_": adverbs,
  8046. "_ADJECTIVE_": adjectives
  8047. //"_PRONOUN_": pronouns,
  8048. //"_CONJUNCTION_": conjunctions,
  8049. };
  8050. var PATTERNS = [
  8051. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  8052. // BeautifulFungiOrSpaghetti
  8053. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  8054. // AmazinglyScaryToy
  8055. //"_ADVERB__ADJECTIVE__NOUN_",
  8056. // NeitherTrashNorRifle
  8057. //"Neither_NOUN_Nor_NOUN_",
  8058. //"Either_NOUN_Or_NOUN_",
  8059. // EitherCopulateOrInvestigate
  8060. //"Either_VERB_Or_VERB_",
  8061. //"Neither_VERB_Nor_VERB_",
  8062. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  8063. //"The_ADVERB__ADJECTIVE__NOUN_",
  8064. //"The_ADVERB__ADJECTIVE__NOUN_s",
  8065. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  8066. // WolvesComputeBadly
  8067. //"_PLURALNOUN__VERB__ADVERB_",
  8068. // UniteFacilitateAndMerge
  8069. //"_VERB__VERB_And_VERB_",
  8070. //NastyWitchesAtThePub
  8071. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  8072. ];
  8073. /*
  8074. * Returns a random element from the array 'arr'
  8075. */
  8076. function randomElement(arr)
  8077. {
  8078. return arr[Math.floor(Math.random() * arr.length)];
  8079. }
  8080. /*
  8081. * Returns true if the string 's' contains one of the
  8082. * template strings.
  8083. */
  8084. function hasTemplate(s)
  8085. {
  8086. for (var template in CATEGORIES){
  8087. if (s.indexOf(template) >= 0){
  8088. return true;
  8089. }
  8090. }
  8091. }
  8092. /**
  8093. * Generates new room name.
  8094. */
  8095. var RoomNameGenerator = {
  8096. generateRoomWithoutSeparator: function()
  8097. {
  8098. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  8099. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  8100. var name = randomElement(PATTERNS);
  8101. var word;
  8102. while (hasTemplate(name)){
  8103. for (var template in CATEGORIES){
  8104. word = randomElement(CATEGORIES[template]);
  8105. name = name.replace(template, word);
  8106. }
  8107. }
  8108. return name;
  8109. }
  8110. }
  8111. module.exports = RoomNameGenerator;
  8112. },{}],34:[function(require,module,exports){
  8113. var animateTimeout, updateTimeout;
  8114. var RoomNameGenerator = require("./RoomnameGenerator");
  8115. function enter_room()
  8116. {
  8117. var val = $("#enter_room_field").val();
  8118. if(!val) {
  8119. val = $("#enter_room_field").attr("room_name");
  8120. }
  8121. if (val) {
  8122. window.location.pathname = "/" + val;
  8123. }
  8124. }
  8125. function animate(word) {
  8126. var currentVal = $("#enter_room_field").attr("placeholder");
  8127. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  8128. animateTimeout = setTimeout(function() {
  8129. animate(word.substring(1, word.length))
  8130. }, 70);
  8131. }
  8132. function update_roomname()
  8133. {
  8134. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  8135. $("#enter_room_field").attr("room_name", word);
  8136. $("#enter_room_field").attr("placeholder", "");
  8137. clearTimeout(animateTimeout);
  8138. animate(word);
  8139. updateTimeout = setTimeout(update_roomname, 10000);
  8140. }
  8141. function setupWelcomePage()
  8142. {
  8143. $("#videoconference_page").hide();
  8144. $("#domain_name").text(
  8145. window.location.protocol + "//" + window.location.host + "/");
  8146. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  8147. var leftWatermarkDiv
  8148. = $("#welcome_page_header div[class='watermark leftwatermark']");
  8149. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  8150. {
  8151. leftWatermarkDiv.css({display: 'block'});
  8152. leftWatermarkDiv.parent().get(0).href
  8153. = interfaceConfig.JITSI_WATERMARK_LINK;
  8154. }
  8155. }
  8156. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  8157. var rightWatermarkDiv
  8158. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8159. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8160. rightWatermarkDiv.css({display: 'block'});
  8161. rightWatermarkDiv.parent().get(0).href
  8162. = interfaceConfig.BRAND_WATERMARK_LINK;
  8163. rightWatermarkDiv.get(0).style.backgroundImage
  8164. = "url(images/rightwatermark.png)";
  8165. }
  8166. }
  8167. if (interfaceConfig.SHOW_POWERED_BY) {
  8168. $("#welcome_page_header>a[class='poweredby']")
  8169. .css({display: 'block'});
  8170. }
  8171. $("#enter_room_button").click(function()
  8172. {
  8173. enter_room();
  8174. });
  8175. $("#enter_room_field").keydown(function (event) {
  8176. if (event.keyCode === 13 /* enter */) {
  8177. enter_room();
  8178. }
  8179. });
  8180. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8181. var updateTimeout;
  8182. var animateTimeout;
  8183. $("#reload_roomname").click(function () {
  8184. clearTimeout(updateTimeout);
  8185. clearTimeout(animateTimeout);
  8186. update_roomname();
  8187. });
  8188. $("#reload_roomname").show();
  8189. update_roomname();
  8190. }
  8191. $("#disable_welcome").click(function () {
  8192. window.localStorage.welcomePageDisabled
  8193. = $("#disable_welcome").is(":checked");
  8194. });
  8195. }
  8196. module.exports = setupWelcomePage;
  8197. },{"./RoomnameGenerator":33}],35:[function(require,module,exports){
  8198. var EventEmitter = require("events");
  8199. var eventEmitter = new EventEmitter();
  8200. var CQEvents = require("../../service/connectionquality/CQEvents");
  8201. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8202. /**
  8203. * local stats
  8204. * @type {{}}
  8205. */
  8206. var stats = {};
  8207. /**
  8208. * remote stats
  8209. * @type {{}}
  8210. */
  8211. var remoteStats = {};
  8212. /**
  8213. * Interval for sending statistics to other participants
  8214. * @type {null}
  8215. */
  8216. var sendIntervalId = null;
  8217. /**
  8218. * Start statistics sending.
  8219. */
  8220. function startSendingStats() {
  8221. sendStats();
  8222. sendIntervalId = setInterval(sendStats, 10000);
  8223. }
  8224. /**
  8225. * Sends statistics to other participants
  8226. */
  8227. function sendStats() {
  8228. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8229. }
  8230. /**
  8231. * Converts statistics to format for sending through XMPP
  8232. * @param stats the statistics
  8233. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8234. */
  8235. function convertToMUCStats(stats) {
  8236. return {
  8237. "bitrate_download": stats.bitrate.download,
  8238. "bitrate_upload": stats.bitrate.upload,
  8239. "packetLoss_total": stats.packetLoss.total,
  8240. "packetLoss_download": stats.packetLoss.download,
  8241. "packetLoss_upload": stats.packetLoss.upload
  8242. };
  8243. }
  8244. /**
  8245. * Converts statitistics to format used by VideoLayout
  8246. * @param stats
  8247. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8248. */
  8249. function parseMUCStats(stats) {
  8250. return {
  8251. bitrate: {
  8252. download: stats.bitrate_download,
  8253. upload: stats.bitrate_upload
  8254. },
  8255. packetLoss: {
  8256. total: stats.packetLoss_total,
  8257. download: stats.packetLoss_download,
  8258. upload: stats.packetLoss_upload
  8259. }
  8260. };
  8261. }
  8262. var ConnectionQuality = {
  8263. init: function () {
  8264. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8265. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8266. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8267. },
  8268. /**
  8269. * Updates the local statistics
  8270. * @param data new statistics
  8271. */
  8272. updateLocalStats: function (data) {
  8273. stats = data;
  8274. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8275. if (sendIntervalId == null) {
  8276. startSendingStats();
  8277. }
  8278. },
  8279. /**
  8280. * Updates remote statistics
  8281. * @param jid the jid associated with the statistics
  8282. * @param data the statistics
  8283. */
  8284. updateRemoteStats: function (jid, data) {
  8285. if (data == null || data.packetLoss_total == null) {
  8286. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8287. return;
  8288. }
  8289. remoteStats[jid] = parseMUCStats(data);
  8290. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8291. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8292. },
  8293. /**
  8294. * Stops statistics sending.
  8295. */
  8296. stopSendingStats: function () {
  8297. clearInterval(sendIntervalId);
  8298. sendIntervalId = null;
  8299. //notify UI about stopping statistics gathering
  8300. eventEmitter.emit(CQEvents.STOP);
  8301. },
  8302. /**
  8303. * Returns the local statistics.
  8304. */
  8305. getStats: function () {
  8306. return stats;
  8307. },
  8308. addListener: function (type, listener) {
  8309. eventEmitter.on(type, listener);
  8310. }
  8311. };
  8312. module.exports = ConnectionQuality;
  8313. },{"../../service/connectionquality/CQEvents":101,"../../service/xmpp/XMPPEvents":105,"events":65}],36:[function(require,module,exports){
  8314. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8315. getUserMediaWithConstraints */
  8316. /**
  8317. * Indicates that desktop stream is currently in use(for toggle purpose).
  8318. * @type {boolean}
  8319. */
  8320. var isUsingScreenStream = false;
  8321. /**
  8322. * Indicates that switch stream operation is in progress and prevent from
  8323. * triggering new events.
  8324. * @type {boolean}
  8325. */
  8326. var switchInProgress = false;
  8327. /**
  8328. * Method used to get screen sharing stream.
  8329. *
  8330. * @type {function (stream_callback, failure_callback}
  8331. */
  8332. var obtainDesktopStream = null;
  8333. /**
  8334. * Indicates whether desktop sharing extension is installed.
  8335. * @type {boolean}
  8336. */
  8337. var extInstalled = false;
  8338. /**
  8339. * Indicates whether update of desktop sharing extension is required.
  8340. * @type {boolean}
  8341. */
  8342. var extUpdateRequired = false;
  8343. /**
  8344. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8345. * it can be <tt>null</tt>.
  8346. *
  8347. * @type {null|boolean}
  8348. */
  8349. var _desktopSharingEnabled = null;
  8350. var EventEmitter = require("events");
  8351. var eventEmitter = new EventEmitter();
  8352. var DesktopSharingEventTypes
  8353. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8354. /**
  8355. * Method obtains desktop stream from WebRTC 'screen' source.
  8356. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8357. */
  8358. function obtainWebRTCScreen(streamCallback, failCallback) {
  8359. APP.RTC.getUserMediaWithConstraints(
  8360. ['screen'],
  8361. streamCallback,
  8362. failCallback
  8363. );
  8364. }
  8365. /**
  8366. * Constructs inline install URL for Chrome desktop streaming extension.
  8367. * The 'chromeExtensionId' must be defined in config.js.
  8368. * @returns {string}
  8369. */
  8370. function getWebStoreInstallUrl()
  8371. {
  8372. return "https://chrome.google.com/webstore/detail/" +
  8373. config.chromeExtensionId;
  8374. }
  8375. /**
  8376. * Checks whether extension update is required.
  8377. * @param minVersion minimal required version
  8378. * @param extVersion current extension version
  8379. * @returns {boolean}
  8380. */
  8381. function isUpdateRequired(minVersion, extVersion)
  8382. {
  8383. try
  8384. {
  8385. var s1 = minVersion.split('.');
  8386. var s2 = extVersion.split('.');
  8387. var len = Math.max(s1.length, s2.length);
  8388. for (var i = 0; i < len; i++)
  8389. {
  8390. var n1 = 0,
  8391. n2 = 0;
  8392. if (i < s1.length)
  8393. n1 = parseInt(s1[i]);
  8394. if (i < s2.length)
  8395. n2 = parseInt(s2[i]);
  8396. if (isNaN(n1) || isNaN(n2))
  8397. {
  8398. return true;
  8399. }
  8400. else if (n1 !== n2)
  8401. {
  8402. return n1 > n2;
  8403. }
  8404. }
  8405. // will happen if boths version has identical numbers in
  8406. // their components (even if one of them is longer, has more components)
  8407. return false;
  8408. }
  8409. catch (e)
  8410. {
  8411. console.error("Failed to parse extension version", e);
  8412. APP.UI.messageHandler.showError("dialog.error",
  8413. "dialog.detectext");
  8414. return true;
  8415. }
  8416. }
  8417. function checkExtInstalled(callback) {
  8418. if (!chrome.runtime) {
  8419. // No API, so no extension for sure
  8420. callback(false, false);
  8421. return;
  8422. }
  8423. chrome.runtime.sendMessage(
  8424. config.chromeExtensionId,
  8425. { getVersion: true },
  8426. function (response) {
  8427. if (!response || !response.version) {
  8428. // Communication failure - assume that no endpoint exists
  8429. console.warn(
  8430. "Extension not installed?: ", chrome.runtime.lastError);
  8431. callback(false, false);
  8432. return;
  8433. }
  8434. // Check installed extension version
  8435. var extVersion = response.version;
  8436. console.log('Extension version is: ' + extVersion);
  8437. var updateRequired
  8438. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8439. callback(!updateRequired, updateRequired);
  8440. }
  8441. );
  8442. }
  8443. function doGetStreamFromExtension(streamCallback, failCallback) {
  8444. // Sends 'getStream' msg to the extension.
  8445. // Extension id must be defined in the config.
  8446. chrome.runtime.sendMessage(
  8447. config.chromeExtensionId,
  8448. { getStream: true, sources: config.desktopSharingSources },
  8449. function (response) {
  8450. if (!response) {
  8451. failCallback(chrome.runtime.lastError);
  8452. return;
  8453. }
  8454. console.log("Response from extension: " + response);
  8455. if (response.streamId) {
  8456. APP.RTC.getUserMediaWithConstraints(
  8457. ['desktop'],
  8458. function (stream) {
  8459. streamCallback(stream);
  8460. },
  8461. failCallback,
  8462. null, null, null,
  8463. response.streamId);
  8464. } else {
  8465. failCallback("Extension failed to get the stream");
  8466. }
  8467. }
  8468. );
  8469. }
  8470. /**
  8471. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8472. * stream for returned stream token.
  8473. */
  8474. function obtainScreenFromExtension(streamCallback, failCallback) {
  8475. if (extInstalled) {
  8476. doGetStreamFromExtension(streamCallback, failCallback);
  8477. } else {
  8478. if (extUpdateRequired) {
  8479. alert(
  8480. 'Jitsi Desktop Streamer requires update. ' +
  8481. 'Changes will take effect after next Chrome restart.');
  8482. }
  8483. chrome.webstore.install(
  8484. getWebStoreInstallUrl(),
  8485. function (arg) {
  8486. console.log("Extension installed successfully", arg);
  8487. // We need to reload the page in order to get the access to
  8488. // chrome.runtime
  8489. window.location.reload(false);
  8490. },
  8491. function (arg) {
  8492. console.log("Failed to install the extension", arg);
  8493. failCallback(arg);
  8494. APP.UI.messageHandler.showError("dialog.error",
  8495. "dialog.failtoinstall");
  8496. }
  8497. );
  8498. }
  8499. }
  8500. /**
  8501. * Call this method to toggle desktop sharing feature.
  8502. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8503. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8504. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8505. * enabled), pass any other string or nothing in order to disable this
  8506. * feature completely.
  8507. */
  8508. function setDesktopSharing(method) {
  8509. // Check if we are running chrome
  8510. if (!navigator.webkitGetUserMedia) {
  8511. obtainDesktopStream = null;
  8512. console.info("Desktop sharing disabled");
  8513. } else if (method == "ext") {
  8514. obtainDesktopStream = obtainScreenFromExtension;
  8515. console.info("Using Chrome extension for desktop sharing");
  8516. } else if (method == "webrtc") {
  8517. obtainDesktopStream = obtainWebRTCScreen;
  8518. console.info("Using Chrome WebRTC for desktop sharing");
  8519. }
  8520. // Reset enabled cache
  8521. _desktopSharingEnabled = null;
  8522. }
  8523. /**
  8524. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8525. * config.js to support inline installs. Host site must be selected as main
  8526. * website of published extension.
  8527. */
  8528. function initInlineInstalls()
  8529. {
  8530. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8531. }
  8532. function getVideoStreamFailed(error) {
  8533. console.error("Failed to obtain the stream to switch to", error);
  8534. switchInProgress = false;
  8535. isUsingScreenStream = false;
  8536. newStreamCreated(null);
  8537. }
  8538. function getDesktopStreamFailed(error) {
  8539. console.error("Failed to obtain the stream to switch to", error);
  8540. switchInProgress = false;
  8541. }
  8542. function streamSwitchDone() {
  8543. switchInProgress = false;
  8544. eventEmitter.emit(
  8545. DesktopSharingEventTypes.SWITCHING_DONE,
  8546. isUsingScreenStream);
  8547. }
  8548. function newStreamCreated(stream)
  8549. {
  8550. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8551. stream, isUsingScreenStream, streamSwitchDone);
  8552. }
  8553. module.exports = {
  8554. isUsingScreenStream: function () {
  8555. return isUsingScreenStream;
  8556. },
  8557. /**
  8558. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8559. * and enabled.
  8560. */
  8561. isDesktopSharingEnabled: function () {
  8562. if (_desktopSharingEnabled === null) {
  8563. if (obtainDesktopStream === obtainScreenFromExtension) {
  8564. // Parse chrome version
  8565. var userAgent = navigator.userAgent.toLowerCase();
  8566. // We can assume that user agent is chrome, because it's
  8567. // enforced when 'ext' streaming method is set
  8568. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8569. console.log("Chrome version" + userAgent, ver);
  8570. _desktopSharingEnabled = ver >= 34;
  8571. } else {
  8572. _desktopSharingEnabled =
  8573. obtainDesktopStream === obtainWebRTCScreen;
  8574. }
  8575. }
  8576. return _desktopSharingEnabled;
  8577. },
  8578. init: function () {
  8579. setDesktopSharing(config.desktopSharing);
  8580. // Initialize Chrome extension inline installs
  8581. if (config.chromeExtensionId) {
  8582. initInlineInstalls();
  8583. // Check if extension is installed
  8584. checkExtInstalled(function (installed, updateRequired) {
  8585. extInstalled = installed;
  8586. extUpdateRequired = updateRequired;
  8587. console.info(
  8588. "Chrome extension installed: " + extInstalled +
  8589. " updateRequired: " + extUpdateRequired);
  8590. });
  8591. }
  8592. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8593. },
  8594. addListener: function (listener, type)
  8595. {
  8596. eventEmitter.on(type, listener);
  8597. },
  8598. removeListener: function (listener, type) {
  8599. eventEmitter.removeListener(type, listener);
  8600. },
  8601. /*
  8602. * Toggles screen sharing.
  8603. */
  8604. toggleScreenSharing: function () {
  8605. if (switchInProgress || !obtainDesktopStream) {
  8606. console.warn("Switch in progress or no method defined");
  8607. return;
  8608. }
  8609. switchInProgress = true;
  8610. if (!isUsingScreenStream)
  8611. {
  8612. // Switch to desktop stream
  8613. obtainDesktopStream(
  8614. function (stream) {
  8615. // We now use screen stream
  8616. isUsingScreenStream = true;
  8617. // Hook 'ended' event to restore camera
  8618. // when screen stream stops
  8619. stream.addEventListener('ended',
  8620. function (e) {
  8621. if (!switchInProgress && isUsingScreenStream) {
  8622. APP.desktopsharing.toggleScreenSharing();
  8623. }
  8624. }
  8625. );
  8626. newStreamCreated(stream);
  8627. },
  8628. getDesktopStreamFailed);
  8629. } else {
  8630. // Disable screen stream
  8631. APP.RTC.getUserMediaWithConstraints(
  8632. ['video'],
  8633. function (stream) {
  8634. // We are now using camera stream
  8635. isUsingScreenStream = false;
  8636. newStreamCreated(stream);
  8637. },
  8638. getVideoStreamFailed, config.resolution || '360'
  8639. );
  8640. }
  8641. }
  8642. };
  8643. },{"../../service/desktopsharing/DesktopSharingEventTypes":102,"events":65}],37:[function(require,module,exports){
  8644. //maps keycode to character, id of popover for given function and function
  8645. var shortcuts = {
  8646. 67: {
  8647. character: "C",
  8648. id: "toggleChatPopover",
  8649. function: APP.UI.toggleChat
  8650. },
  8651. 70: {
  8652. character: "F",
  8653. id: "filmstripPopover",
  8654. function: APP.UI.toggleFilmStrip
  8655. },
  8656. 77: {
  8657. character: "M",
  8658. id: "mutePopover",
  8659. function: APP.UI.toggleAudio
  8660. },
  8661. 84: {
  8662. character: "T",
  8663. function: function() {
  8664. if(!APP.RTC.localAudio.isMuted()) {
  8665. APP.UI.toggleAudio();
  8666. }
  8667. }
  8668. },
  8669. 86: {
  8670. character: "V",
  8671. id: "toggleVideoPopover",
  8672. function: APP.UI.toggleVideo
  8673. }
  8674. };
  8675. var KeyboardShortcut = {
  8676. init: function () {
  8677. window.onkeyup = function(e) {
  8678. var keycode = e.which;
  8679. if(!($(":focus").is("input[type=text]") ||
  8680. $(":focus").is("input[type=password]") ||
  8681. $(":focus").is("textarea"))) {
  8682. if (typeof shortcuts[keycode] === "object") {
  8683. shortcuts[keycode].function();
  8684. }
  8685. else if (keycode >= "0".charCodeAt(0) &&
  8686. keycode <= "9".charCodeAt(0)) {
  8687. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8688. }
  8689. //esc while the smileys are visible hides them
  8690. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8691. APP.UI.toggleSmileys();
  8692. }
  8693. };
  8694. window.onkeydown = function(e) {
  8695. if(!($(":focus").is("input[type=text]") ||
  8696. $(":focus").is("input[type=password]") ||
  8697. $(":focus").is("textarea"))) {
  8698. if(e.which === "T".charCodeAt(0)) {
  8699. if(APP.RTC.localAudio.isMuted()) {
  8700. APP.UI.toggleAudio();
  8701. }
  8702. }
  8703. }
  8704. };
  8705. var self = this;
  8706. $('body').popover({ selector: '[data-toggle=popover]',
  8707. trigger: 'click hover',
  8708. content: function() {
  8709. return this.getAttribute("content") +
  8710. self.getShortcut(this.getAttribute("shortcut"));
  8711. }
  8712. });
  8713. },
  8714. /**
  8715. *
  8716. * @param id indicates the popover associated with the shortcut
  8717. * @returns {string} the keyboard shortcut used for the id given
  8718. */
  8719. getShortcut: function (id) {
  8720. for (var keycode in shortcuts) {
  8721. if (shortcuts.hasOwnProperty(keycode)) {
  8722. if (shortcuts[keycode].id === id) {
  8723. return " (" + shortcuts[keycode].character + ")";
  8724. }
  8725. }
  8726. }
  8727. return "";
  8728. }
  8729. };
  8730. module.exports = KeyboardShortcut;
  8731. },{}],38:[function(require,module,exports){
  8732. /* global APP */
  8733. /**
  8734. * This module is meant to (eventually) contain and manage all information
  8735. * about members/participants of the conference, so that other modules don't
  8736. * have to do it on their own, and so that other modules can access members'
  8737. * information from a single place.
  8738. *
  8739. * Currently this module only manages information about the support of jingle
  8740. * DTMF of the members. Other fields, as well as accessor methods are meant to
  8741. * be added as needed.
  8742. */
  8743. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8744. var Events = require("../../service/members/Events");
  8745. var EventEmitter = require("events");
  8746. var eventEmitter = new EventEmitter();
  8747. /**
  8748. * The actual container.
  8749. */
  8750. var members = {};
  8751. /**
  8752. * There is at least one member that supports DTMF (i.e. is jigasi).
  8753. */
  8754. var atLeastOneDtmf = false;
  8755. function registerListeners() {
  8756. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  8757. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  8758. }
  8759. /**
  8760. * Handles a new member joining the MUC.
  8761. */
  8762. function onMucMemberJoined(jid, id, displayName) {
  8763. var member = {
  8764. displayName: displayName
  8765. };
  8766. APP.xmpp.getConnection().disco.info(
  8767. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  8768. members[jid] = member;
  8769. }
  8770. /**
  8771. * Handles a member leaving the MUC.
  8772. */
  8773. function onMucMemberLeft(jid) {
  8774. delete members[jid];
  8775. updateAtLeastOneDtmf();
  8776. }
  8777. /**
  8778. * Handles the reception of a disco#info packet from a particular JID.
  8779. * @param jid the JID sending the packet.
  8780. * @param iq the packet.
  8781. */
  8782. function onDiscoInfoReceived(jid, iq) {
  8783. if (!members[jid])
  8784. return;
  8785. var supportsDtmf
  8786. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  8787. updateDtmf(jid, supportsDtmf);
  8788. }
  8789. /**
  8790. * Updates the 'supportsDtmf' field for a member.
  8791. * @param jid the jid of the member.
  8792. * @param newValue the new value for the 'supportsDtmf' field.
  8793. */
  8794. function updateDtmf(jid, newValue) {
  8795. var oldValue = members[jid].supportsDtmf;
  8796. members[jid].supportsDtmf = newValue;
  8797. if (newValue != oldValue) {
  8798. updateAtLeastOneDtmf();
  8799. }
  8800. }
  8801. /**
  8802. * Checks each member's 'supportsDtmf' field and updates
  8803. * 'atLastOneSupportsDtmf'.
  8804. */
  8805. function updateAtLeastOneDtmf(){
  8806. var newAtLeastOneDtmf = false;
  8807. for (var key in members) {
  8808. if (typeof members[key].supportsDtmf !== 'undefined'
  8809. && members[key].supportsDtmf) {
  8810. newAtLeastOneDtmf= true;
  8811. break;
  8812. }
  8813. }
  8814. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  8815. atLeastOneDtmf = newAtLeastOneDtmf;
  8816. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  8817. }
  8818. }
  8819. /**
  8820. * Exported interface.
  8821. */
  8822. var Members = {
  8823. start: function(){
  8824. registerListeners();
  8825. },
  8826. addListener: function(type, listener)
  8827. {
  8828. eventEmitter.on(type, listener);
  8829. },
  8830. removeListener: function (type, listener) {
  8831. eventEmitter.removeListener(type, listener);
  8832. }
  8833. };
  8834. module.exports = Members;
  8835. },{"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"events":65}],39:[function(require,module,exports){
  8836. var email = '';
  8837. var displayName = '';
  8838. var userId;
  8839. var language = null;
  8840. function supportsLocalStorage() {
  8841. try {
  8842. return 'localStorage' in window && window.localStorage !== null;
  8843. } catch (e) {
  8844. console.log("localstorage is not supported");
  8845. return false;
  8846. }
  8847. }
  8848. function generateUniqueId() {
  8849. function _p8() {
  8850. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8851. }
  8852. return _p8() + _p8() + _p8() + _p8();
  8853. }
  8854. if (supportsLocalStorage()) {
  8855. if (!window.localStorage.jitsiMeetId) {
  8856. window.localStorage.jitsiMeetId = generateUniqueId();
  8857. console.log("generated id", window.localStorage.jitsiMeetId);
  8858. }
  8859. userId = window.localStorage.jitsiMeetId || '';
  8860. email = window.localStorage.email || '';
  8861. displayName = window.localStorage.displayname || '';
  8862. language = window.localStorage.language;
  8863. } else {
  8864. console.log("local storage is not supported");
  8865. userId = generateUniqueId();
  8866. }
  8867. var Settings =
  8868. {
  8869. setDisplayName: function (newDisplayName) {
  8870. displayName = newDisplayName;
  8871. window.localStorage.displayname = displayName;
  8872. return displayName;
  8873. },
  8874. setEmail: function (newEmail)
  8875. {
  8876. email = newEmail;
  8877. window.localStorage.email = newEmail;
  8878. return email;
  8879. },
  8880. getSettings: function () {
  8881. return {
  8882. email: email,
  8883. displayName: displayName,
  8884. uid: userId,
  8885. language: language
  8886. };
  8887. },
  8888. setLanguage: function (lang) {
  8889. language = lang;
  8890. window.localStorage.language = lang;
  8891. }
  8892. };
  8893. module.exports = Settings;
  8894. },{}],40:[function(require,module,exports){
  8895. /**
  8896. *
  8897. * @constructor
  8898. */
  8899. function SimulcastLogger(name, lvl) {
  8900. this.name = name;
  8901. this.lvl = lvl;
  8902. }
  8903. SimulcastLogger.prototype.log = function (text) {
  8904. if (this.lvl) {
  8905. console.log(text);
  8906. }
  8907. };
  8908. SimulcastLogger.prototype.info = function (text) {
  8909. if (this.lvl > 1) {
  8910. console.info(text);
  8911. }
  8912. };
  8913. SimulcastLogger.prototype.fine = function (text) {
  8914. if (this.lvl > 2) {
  8915. console.log(text);
  8916. }
  8917. };
  8918. SimulcastLogger.prototype.error = function (text) {
  8919. console.error(text);
  8920. };
  8921. module.exports = SimulcastLogger;
  8922. },{}],41:[function(require,module,exports){
  8923. var SimulcastLogger = require("./SimulcastLogger");
  8924. var SimulcastUtils = require("./SimulcastUtils");
  8925. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8926. function SimulcastReceiver() {
  8927. this.simulcastUtils = new SimulcastUtils();
  8928. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8929. }
  8930. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8931. SimulcastReceiver.prototype._remoteMaps = {
  8932. msid2Quality: {},
  8933. ssrc2Msid: {},
  8934. msid2ssrc: {},
  8935. receivingVideoStreams: {}
  8936. };
  8937. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8938. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8939. };
  8940. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8941. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8942. };
  8943. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8944. var sb;
  8945. this.logger.info('Ensuring x-google-conference flag...')
  8946. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8947. // TODO(gp) do that for the audio as well as suggested by fippo.
  8948. // Add the google conference flag
  8949. sb = this.simulcastUtils._getVideoSources(lines);
  8950. sb = ['a=x-google-flag:conference'].concat(sb);
  8951. this.simulcastUtils._replaceVideoSources(lines, sb);
  8952. }
  8953. };
  8954. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8955. this._restoreRemoteVideoSources(sb);
  8956. };
  8957. /**
  8958. * Restores the simulcast groups of the remote description. In
  8959. * transformRemoteDescription we remove those in order for the set remote
  8960. * description to succeed. The focus needs the signal the groups to new
  8961. * participants.
  8962. *
  8963. * @param desc
  8964. * @returns {*}
  8965. */
  8966. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8967. var sb;
  8968. if (!this.simulcastUtils.isValidDescription(desc)) {
  8969. return desc;
  8970. }
  8971. if (config.enableSimulcast) {
  8972. sb = desc.sdp.split('\r\n');
  8973. this._restoreSimulcastGroups(sb);
  8974. desc = new RTCSessionDescription({
  8975. type: desc.type,
  8976. sdp: sb.join('\r\n')
  8977. });
  8978. }
  8979. return desc;
  8980. };
  8981. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8982. var videoSources, sb;
  8983. videoSources = this.parseMedia(lines, ['video'])[0];
  8984. sb = this._compileVideoSources(videoSources);
  8985. this._replaceVideoSources(lines, sb);
  8986. };
  8987. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8988. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8989. videoSource, quality;
  8990. // (re) initialize the remote maps.
  8991. this._remoteMaps.msid2Quality = {};
  8992. this._remoteMaps.ssrc2Msid = {};
  8993. this._remoteMaps.msid2ssrc = {};
  8994. var self = this;
  8995. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8996. remoteVideoSources.groups.forEach(function (group) {
  8997. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8998. quality = 0;
  8999. group.ssrcs.forEach(function (ssrc) {
  9000. videoSource = remoteVideoSources.sources[ssrc];
  9001. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  9002. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  9003. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  9004. });
  9005. }
  9006. });
  9007. }
  9008. };
  9009. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  9010. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  9011. };
  9012. /**
  9013. * Returns a stream with single video track, the one currently being
  9014. * received by this endpoint.
  9015. *
  9016. * @param stream the remote simulcast stream.
  9017. * @returns {webkitMediaStream}
  9018. */
  9019. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  9020. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  9021. var self = this;
  9022. if (config.enableSimulcast) {
  9023. stream.getVideoTracks().some(function (track) {
  9024. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  9025. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  9026. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  9027. if (msid == [stream.id, track.id].join(' ')) {
  9028. electedTrack = track;
  9029. return true;
  9030. }
  9031. });
  9032. });
  9033. if (!electedTrack) {
  9034. // we don't have an elected track, choose by initial quality.
  9035. tracks = stream.getVideoTracks();
  9036. for (i = 0; i < tracks.length; i++) {
  9037. msid = [stream.id, tracks[i].id].join(' ');
  9038. if (this._remoteMaps.msid2Quality[msid] === quality) {
  9039. electedTrack = tracks[i];
  9040. break;
  9041. }
  9042. }
  9043. // TODO(gp) if the initialQuality could not be satisfied, lower
  9044. // the requirement and try again.
  9045. }
  9046. }
  9047. return (electedTrack)
  9048. ? new webkitMediaStream([electedTrack])
  9049. : stream;
  9050. };
  9051. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  9052. var resource = Strophe.getResourceFromJid(jid);
  9053. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  9054. // If we haven't receiving a "changed" event yet, then we must be receiving
  9055. // low quality (that the sender always streams).
  9056. if(!ssrc)
  9057. {
  9058. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9059. var remoteStream = remoteStreamObject.getOriginalStream();
  9060. var tracks = remoteStream.getVideoTracks();
  9061. if (tracks) {
  9062. for (var k = 0; k < tracks.length; k++) {
  9063. var track = tracks[k];
  9064. var msid = [remoteStream.id, track.id].join(' ');
  9065. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  9066. var quality = this._remoteMaps.msid2Quality[msid];
  9067. if (quality == 0) {
  9068. ssrc = _ssrc;
  9069. }
  9070. }
  9071. }
  9072. }
  9073. return ssrc;
  9074. };
  9075. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  9076. {
  9077. var sid, electedStream;
  9078. var i, j, k;
  9079. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9080. if(jid && APP.RTC.remoteStreams[jid])
  9081. {
  9082. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9083. var remoteStream = remoteStreamObject.getOriginalStream();
  9084. var tracks = remoteStream.getVideoTracks();
  9085. if (tracks) {
  9086. for (k = 0; k < tracks.length; k++) {
  9087. var track = tracks[k];
  9088. var msid = [remoteStream.id, track.id].join(' ');
  9089. var tmp = this._remoteMaps.msid2ssrc[msid];
  9090. if (tmp == ssrc) {
  9091. electedStream = new webkitMediaStream([track]);
  9092. sid = remoteStreamObject.sid;
  9093. // stream found, stop.
  9094. break;
  9095. }
  9096. }
  9097. }
  9098. }
  9099. else
  9100. {
  9101. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  9102. }
  9103. return {
  9104. sid: sid,
  9105. stream: electedStream
  9106. };
  9107. };
  9108. /**
  9109. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9110. * SSRC.
  9111. *
  9112. * @param ssrc
  9113. * @returns {*}
  9114. */
  9115. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9116. return this._remoteMaps.ssrc2Msid[ssrc];
  9117. };
  9118. /**
  9119. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9120. * either gets confused and thinks this is an FID group or, if an FID group
  9121. * is already present, it fails to set the remote description.
  9122. *
  9123. * @param desc
  9124. * @returns {*}
  9125. */
  9126. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  9127. if (desc && desc.sdp) {
  9128. var sb = desc.sdp.split('\r\n');
  9129. this._updateRemoteMaps(sb);
  9130. this._cacheRemoteVideoSources(sb);
  9131. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  9132. // need the simulcast group in the _updateRemoteMaps() method.
  9133. this.simulcastUtils._removeSimulcastGroup(sb);
  9134. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  9135. // We don't need the goog conference flag if we're not doing
  9136. // simulcast.
  9137. this._ensureGoogConference(sb);
  9138. }
  9139. desc = new RTCSessionDescription({
  9140. type: desc.type,
  9141. sdp: sb.join('\r\n')
  9142. });
  9143. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  9144. }
  9145. return desc;
  9146. };
  9147. module.exports = SimulcastReceiver;
  9148. },{"../../service/RTC/MediaStreamTypes":94,"./SimulcastLogger":40,"./SimulcastUtils":43}],42:[function(require,module,exports){
  9149. var SimulcastLogger = require("./SimulcastLogger");
  9150. var SimulcastUtils = require("./SimulcastUtils");
  9151. function SimulcastSender() {
  9152. this.simulcastUtils = new SimulcastUtils();
  9153. this.logger = new SimulcastLogger('SimulcastSender', 1);
  9154. }
  9155. SimulcastSender.prototype.displayedLocalVideoStream = null;
  9156. SimulcastSender.prototype._generateGuid = (function () {
  9157. function s4() {
  9158. return Math.floor((1 + Math.random()) * 0x10000)
  9159. .toString(16)
  9160. .substring(1);
  9161. }
  9162. return function () {
  9163. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  9164. s4() + '-' + s4() + s4() + s4();
  9165. };
  9166. }());
  9167. // Returns a random integer between min (included) and max (excluded)
  9168. // Using Math.round() gives a non-uniform distribution!
  9169. SimulcastSender.prototype._generateRandomSSRC = function () {
  9170. var min = 0, max = 0xffffffff;
  9171. return Math.floor(Math.random() * (max - min)) + min;
  9172. };
  9173. SimulcastSender.prototype.getLocalVideoStream = function () {
  9174. return (this.displayedLocalVideoStream != null)
  9175. ? this.displayedLocalVideoStream
  9176. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  9177. : APP.RTC.localVideo.getOriginalStream();
  9178. };
  9179. function NativeSimulcastSender() {
  9180. SimulcastSender.call(this); // call the super constructor.
  9181. }
  9182. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9183. NativeSimulcastSender.prototype._localExplosionMap = {};
  9184. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  9185. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  9186. NativeSimulcastSender.prototype.reset = function () {
  9187. this._localExplosionMap = {};
  9188. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  9189. };
  9190. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  9191. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  9192. };
  9193. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  9194. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  9195. };
  9196. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  9197. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  9198. this.logger.info('Appending simulcast group...');
  9199. // Get the primary SSRC information.
  9200. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9201. // Start building the SIM SSRC group.
  9202. ssrcGroup = ['a=ssrc-group:SIM'];
  9203. // The video source buffer.
  9204. sb = [];
  9205. // Create the simulcast sub-streams.
  9206. for (i = 0; i < numOfSubs; i++) {
  9207. // TODO(gp) prevent SSRC collision.
  9208. simSSRC = this._generateRandomSSRC();
  9209. ssrcGroup.push(simSSRC);
  9210. if (videoSources.base) {
  9211. sb.splice.apply(sb, [sb.length, 0].concat(
  9212. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  9213. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  9214. ));
  9215. }
  9216. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  9217. }
  9218. // Add the group sim layers.
  9219. sb.splice(0, 0, ssrcGroup.join(' '))
  9220. this.simulcastUtils._replaceVideoSources(lines, sb);
  9221. };
  9222. // Does the actual patching.
  9223. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  9224. this.logger.info('Ensuring simulcast group...');
  9225. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  9226. this._appendSimulcastGroup(lines);
  9227. this._cacheLocalVideoSources(lines);
  9228. } else {
  9229. // verify that the ssrcs participating in the SIM group are present
  9230. // in the SDP (needed for presence).
  9231. this._restoreLocalVideoSources(lines);
  9232. }
  9233. };
  9234. /**
  9235. * Produces a single stream with multiple tracks for local video sources.
  9236. *
  9237. * @param lines
  9238. * @private
  9239. */
  9240. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  9241. var sb, msid, sid, tid, videoSources, self;
  9242. this.logger.info('Exploding local video sources...');
  9243. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9244. self = this;
  9245. if (videoSources.groups && videoSources.groups.length !== 0) {
  9246. videoSources.groups.forEach(function (group) {
  9247. if (group.semantics === 'SIM') {
  9248. group.ssrcs.forEach(function (ssrc) {
  9249. // Get the msid for this ssrc..
  9250. if (self._localExplosionMap[ssrc]) {
  9251. // .. either from the explosion map..
  9252. msid = self._localExplosionMap[ssrc];
  9253. } else {
  9254. // .. or generate a new one (msid).
  9255. sid = videoSources.sources[ssrc].msid
  9256. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  9257. tid = self._generateGuid();
  9258. msid = [sid, tid].join(' ');
  9259. self._localExplosionMap[ssrc] = msid;
  9260. }
  9261. // Assign it to the source object.
  9262. videoSources.sources[ssrc].msid = msid;
  9263. // TODO(gp) Change the msid of associated sources.
  9264. });
  9265. }
  9266. });
  9267. }
  9268. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9269. this.simulcastUtils._replaceVideoSources(lines, sb);
  9270. };
  9271. /**
  9272. * GUM for simulcast.
  9273. *
  9274. * @param constraints
  9275. * @param success
  9276. * @param err
  9277. */
  9278. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9279. // There's nothing special to do for native simulcast, so just do a normal GUM.
  9280. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9281. success(hqStream);
  9282. }, err);
  9283. };
  9284. /**
  9285. * Prepares the local description for public usage (i.e. to be signaled
  9286. * through Jingle to the focus).
  9287. *
  9288. * @param desc
  9289. * @returns {RTCSessionDescription}
  9290. */
  9291. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9292. var sb;
  9293. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9294. return desc;
  9295. }
  9296. sb = desc.sdp.split('\r\n');
  9297. this._explodeSimulcastSenderSources(sb);
  9298. desc = new RTCSessionDescription({
  9299. type: desc.type,
  9300. sdp: sb.join('\r\n')
  9301. });
  9302. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  9303. return desc;
  9304. };
  9305. /**
  9306. * Ensures that the simulcast group is present in the answer, _if_ native
  9307. * simulcast is enabled,
  9308. *
  9309. * @param desc
  9310. * @returns {*}
  9311. */
  9312. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  9313. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9314. return desc;
  9315. }
  9316. var sb = desc.sdp.split('\r\n');
  9317. // Even if we have enabled native simulcasting previously
  9318. // (with a call to SLD with an appropriate SDP, for example),
  9319. // createAnswer seems to consistently generate incomplete SDP
  9320. // with missing SSRCS.
  9321. //
  9322. // So, subsequent calls to SLD will have missing SSRCS and presence
  9323. // won't have the complete list of SRCs.
  9324. this._ensureSimulcastGroup(sb);
  9325. desc = new RTCSessionDescription({
  9326. type: desc.type,
  9327. sdp: sb.join('\r\n')
  9328. });
  9329. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  9330. return desc;
  9331. };
  9332. /**
  9333. *
  9334. *
  9335. * @param desc
  9336. * @returns {*}
  9337. */
  9338. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9339. return desc;
  9340. };
  9341. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9342. // Nothing to do here, native simulcast does that auto-magically.
  9343. };
  9344. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9345. function SimpleSimulcastSender() {
  9346. SimulcastSender.call(this);
  9347. }
  9348. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9349. SimpleSimulcastSender.prototype.localStream = null;
  9350. SimpleSimulcastSender.prototype._localMaps = {
  9351. msids: [],
  9352. msid2ssrc: {}
  9353. };
  9354. /**
  9355. * Groups local video sources together in the ssrc-group:SIM group.
  9356. *
  9357. * @param lines
  9358. * @private
  9359. */
  9360. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9361. var sb, videoSources, ssrcs = [], ssrc;
  9362. this.logger.info('Grouping local video sources...');
  9363. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9364. for (ssrc in videoSources.sources) {
  9365. // jitsi-meet destroys/creates streams at various places causing
  9366. // the original local stream ids to change. The only thing that
  9367. // remains unchanged is the trackid.
  9368. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9369. }
  9370. var self = this;
  9371. // TODO(gp) add only "free" sources.
  9372. this._localMaps.msids.forEach(function (msid) {
  9373. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9374. });
  9375. if (!videoSources.groups) {
  9376. videoSources.groups = [];
  9377. }
  9378. videoSources.groups.push({
  9379. 'semantics': 'SIM',
  9380. 'ssrcs': ssrcs
  9381. });
  9382. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9383. this.simulcastUtils._replaceVideoSources(lines, sb);
  9384. };
  9385. /**
  9386. * GUM for simulcast.
  9387. *
  9388. * @param constraints
  9389. * @param success
  9390. * @param err
  9391. */
  9392. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9393. // TODO(gp) what if we request a resolution not supported by the hardware?
  9394. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9395. var lqConstraints = {
  9396. audio: false,
  9397. video: {
  9398. mandatory: {
  9399. maxWidth: 320,
  9400. maxHeight: 180,
  9401. maxFrameRate: 15
  9402. }
  9403. }
  9404. };
  9405. this.logger.info('HQ constraints: ', constraints);
  9406. this.logger.info('LQ constraints: ', lqConstraints);
  9407. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9408. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9409. // reason appears to be that Chrome only acquires the cam once and
  9410. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9411. var self = this;
  9412. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9413. self.localStream = hqStream;
  9414. // reset local maps.
  9415. self._localMaps.msids = [];
  9416. self._localMaps.msid2ssrc = {};
  9417. // add hq trackid to local map
  9418. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9419. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9420. self.displayedLocalVideoStream = lqStream;
  9421. // NOTE(gp) The specification says Array.forEach() will visit
  9422. // the array elements in numeric order, and that it doesn't
  9423. // visit elements that don't exist.
  9424. // add lq trackid to local map
  9425. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9426. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9427. success(self.localStream);
  9428. }, err);
  9429. }, err);
  9430. };
  9431. /**
  9432. * Prepares the local description for public usage (i.e. to be signaled
  9433. * through Jingle to the focus).
  9434. *
  9435. * @param desc
  9436. * @returns {RTCSessionDescription}
  9437. */
  9438. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9439. var sb;
  9440. if (!this.simulcastUtils.isValidDescription(desc)) {
  9441. return desc;
  9442. }
  9443. sb = desc.sdp.split('\r\n');
  9444. this._groupLocalVideoSources(sb);
  9445. desc = new RTCSessionDescription({
  9446. type: desc.type,
  9447. sdp: sb.join('\r\n')
  9448. });
  9449. this.logger.fine('Grouped local video sources');
  9450. this.logger.fine(desc.sdp);
  9451. return desc;
  9452. };
  9453. /**
  9454. * Ensures that the simulcast group is present in the answer, _if_ native
  9455. * simulcast is enabled,
  9456. *
  9457. * @param desc
  9458. * @returns {*}
  9459. */
  9460. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9461. return desc;
  9462. };
  9463. /**
  9464. *
  9465. *
  9466. * @param desc
  9467. * @returns {*}
  9468. */
  9469. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9470. var sb = desc.sdp.split('\r\n');
  9471. this.simulcastUtils._removeSimulcastGroup(sb);
  9472. desc = new RTCSessionDescription({
  9473. type: desc.type,
  9474. sdp: sb.join('\r\n')
  9475. });
  9476. this.logger.fine('Transformed local description');
  9477. this.logger.fine(desc.sdp);
  9478. return desc;
  9479. };
  9480. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9481. var trackid;
  9482. var self = this;
  9483. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9484. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9485. // Search for the track id that corresponds to the ssrc
  9486. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9487. trackid = tid;
  9488. return true;
  9489. }
  9490. }) && self.localStream.getVideoTracks().some(function (track) {
  9491. // Start/stop the track that corresponds to the track id
  9492. if (track.id === trackid) {
  9493. track.enabled = enabled;
  9494. return true;
  9495. }
  9496. })) {
  9497. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9498. $(document).trigger(enabled
  9499. ? 'simulcastlayerstarted'
  9500. : 'simulcastlayerstopped');
  9501. } else {
  9502. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9503. }
  9504. };
  9505. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9506. function NoSimulcastSender() {
  9507. SimulcastSender.call(this);
  9508. }
  9509. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9510. /**
  9511. * GUM for simulcast.
  9512. *
  9513. * @param constraints
  9514. * @param success
  9515. * @param err
  9516. */
  9517. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9518. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9519. success(hqStream);
  9520. }, err);
  9521. };
  9522. /**
  9523. * Prepares the local description for public usage (i.e. to be signaled
  9524. * through Jingle to the focus).
  9525. *
  9526. * @param desc
  9527. * @returns {RTCSessionDescription}
  9528. */
  9529. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9530. return desc;
  9531. };
  9532. /**
  9533. * Ensures that the simulcast group is present in the answer, _if_ native
  9534. * simulcast is enabled,
  9535. *
  9536. * @param desc
  9537. * @returns {*}
  9538. */
  9539. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9540. return desc;
  9541. };
  9542. /**
  9543. *
  9544. *
  9545. * @param desc
  9546. * @returns {*}
  9547. */
  9548. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9549. return desc;
  9550. };
  9551. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9552. };
  9553. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9554. module.exports = {
  9555. "native": NativeSimulcastSender,
  9556. "no": NoSimulcastSender
  9557. }
  9558. },{"./SimulcastLogger":40,"./SimulcastUtils":43}],43:[function(require,module,exports){
  9559. var SimulcastLogger = require("./SimulcastLogger");
  9560. /**
  9561. *
  9562. * @constructor
  9563. */
  9564. function SimulcastUtils() {
  9565. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9566. }
  9567. /**
  9568. *
  9569. * @type {{}}
  9570. * @private
  9571. */
  9572. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9573. /**
  9574. *
  9575. * @param lines
  9576. * @param videoSources
  9577. * @private
  9578. */
  9579. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9580. var i, inVideo = false, index = -1, howMany = 0;
  9581. this.logger.info('Replacing video sources...');
  9582. for (i = 0; i < lines.length; i++) {
  9583. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9584. // Out of video.
  9585. break;
  9586. }
  9587. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9588. // In video.
  9589. inVideo = true;
  9590. }
  9591. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9592. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9593. if (index === -1) {
  9594. index = i;
  9595. }
  9596. howMany++;
  9597. }
  9598. }
  9599. // efficiency baby ;)
  9600. lines.splice.apply(lines,
  9601. [index, howMany].concat(videoSources));
  9602. };
  9603. SimulcastUtils.prototype.isValidDescription = function (desc)
  9604. {
  9605. return desc && desc != null
  9606. && desc.type && desc.type != ''
  9607. && desc.sdp && desc.sdp != '';
  9608. };
  9609. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9610. var i, inVideo = false, sb = [];
  9611. this.logger.info('Getting video sources...');
  9612. for (i = 0; i < lines.length; i++) {
  9613. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9614. // Out of video.
  9615. break;
  9616. }
  9617. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9618. // In video.
  9619. inVideo = true;
  9620. }
  9621. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9622. // In SSRC.
  9623. sb.push(lines[i]);
  9624. }
  9625. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9626. sb.push(lines[i]);
  9627. }
  9628. }
  9629. return sb;
  9630. };
  9631. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9632. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9633. ssrc_attribute, group, semantics, skip = true;
  9634. this.logger.info('Parsing media sources...');
  9635. for (i = 0; i < lines.length; i++) {
  9636. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9637. type = lines[i]
  9638. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9639. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9640. if (!skip) {
  9641. cur_media = {
  9642. 'type': type,
  9643. 'sources': {},
  9644. 'groups': []
  9645. };
  9646. res.push(cur_media);
  9647. }
  9648. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9649. idx = lines[i].indexOf(' ');
  9650. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9651. if (cur_media.sources[ssrc] === undefined) {
  9652. cur_ssrc = {'ssrc': ssrc};
  9653. cur_media.sources[ssrc] = cur_ssrc;
  9654. }
  9655. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9656. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9657. if (cur_media.base === undefined) {
  9658. cur_media.base = cur_ssrc;
  9659. }
  9660. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9661. idx = lines[i].indexOf(' ');
  9662. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9663. ssrcs = lines[i].substr(idx).trim().split(' ');
  9664. group = {
  9665. 'semantics': semantics,
  9666. 'ssrcs': ssrcs
  9667. };
  9668. cur_media.groups.push(group);
  9669. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9670. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9671. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9672. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9673. cur_media.direction = lines[i].substring('a='.length);
  9674. }
  9675. }
  9676. return res;
  9677. };
  9678. /**
  9679. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9680. * given element can be found in the array, or _emptyCompoundIndex if it is
  9681. * not present.
  9682. *
  9683. * Example:
  9684. *
  9685. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9686. *
  9687. * returns {row: 2, column: 14}
  9688. *
  9689. * @param needle
  9690. * @param haystack
  9691. * @param start
  9692. * @returns {}
  9693. * @private
  9694. */
  9695. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9696. var length = haystack.length, idx, i;
  9697. if (!start) {
  9698. start = 0;
  9699. }
  9700. for (i = start; i < length; i++) {
  9701. idx = haystack[i].indexOf(needle);
  9702. if (idx !== -1) {
  9703. return {row: i, column: idx};
  9704. }
  9705. }
  9706. return this._emptyCompoundIndex;
  9707. };
  9708. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9709. var i;
  9710. for (i = lines.length - 1; i >= 0; i--) {
  9711. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9712. lines.splice(i, 1);
  9713. }
  9714. }
  9715. };
  9716. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9717. var sb = [], ssrc, addedSSRCs = [];
  9718. this.logger.info('Compiling video sources...');
  9719. // Add the groups
  9720. if (videoSources.groups && videoSources.groups.length !== 0) {
  9721. videoSources.groups.forEach(function (group) {
  9722. if (group.ssrcs && group.ssrcs.length !== 0) {
  9723. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9724. // if (group.semantics !== 'SIM') {
  9725. group.ssrcs.forEach(function (ssrc) {
  9726. addedSSRCs.push(ssrc);
  9727. sb.splice.apply(sb, [sb.length, 0].concat([
  9728. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9729. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9730. });
  9731. //}
  9732. }
  9733. });
  9734. }
  9735. // Then add any free sources.
  9736. if (videoSources.sources) {
  9737. for (ssrc in videoSources.sources) {
  9738. if (addedSSRCs.indexOf(ssrc) === -1) {
  9739. sb.splice.apply(sb, [sb.length, 0].concat([
  9740. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9741. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9742. }
  9743. }
  9744. }
  9745. return sb;
  9746. };
  9747. module.exports = SimulcastUtils;
  9748. },{"./SimulcastLogger":40}],44:[function(require,module,exports){
  9749. /*jslint plusplus: true */
  9750. /*jslint nomen: true*/
  9751. var SimulcastSender = require("./SimulcastSender");
  9752. var NoSimulcastSender = SimulcastSender["no"];
  9753. var NativeSimulcastSender = SimulcastSender["native"];
  9754. var SimulcastReceiver = require("./SimulcastReceiver");
  9755. var SimulcastUtils = require("./SimulcastUtils");
  9756. var RTCEvents = require("../../service/RTC/RTCEvents");
  9757. /**
  9758. *
  9759. * @constructor
  9760. */
  9761. function SimulcastManager() {
  9762. // Create the simulcast utilities.
  9763. this.simulcastUtils = new SimulcastUtils();
  9764. // Create remote simulcast.
  9765. this.simulcastReceiver = new SimulcastReceiver();
  9766. // Initialize local simulcast.
  9767. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9768. // account constraints.
  9769. if (!config.enableSimulcast) {
  9770. this.simulcastSender = new NoSimulcastSender();
  9771. } else {
  9772. var isChromium = window.chrome,
  9773. vendorName = window.navigator.vendor;
  9774. if(isChromium !== null && isChromium !== undefined
  9775. /* skip opera */
  9776. && vendorName === "Google Inc."
  9777. /* skip Chromium as suggested by fippo */
  9778. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9779. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9780. if (ver > 37) {
  9781. this.simulcastSender = new NativeSimulcastSender();
  9782. } else {
  9783. this.simulcastSender = new NoSimulcastSender();
  9784. }
  9785. } else {
  9786. this.simulcastSender = new NoSimulcastSender();
  9787. }
  9788. }
  9789. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9790. function (endpointSimulcastLayers) {
  9791. endpointSimulcastLayers.forEach(function (esl) {
  9792. var ssrc = esl.simulcastLayer.primarySSRC;
  9793. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9794. });
  9795. });
  9796. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9797. var ssrc = simulcastLayer.primarySSRC;
  9798. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9799. });
  9800. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9801. var ssrc = simulcastLayer.primarySSRC;
  9802. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9803. });
  9804. }
  9805. /**
  9806. * Restores the simulcast groups of the remote description. In
  9807. * transformRemoteDescription we remove those in order for the set remote
  9808. * description to succeed. The focus needs the signal the groups to new
  9809. * participants.
  9810. *
  9811. * @param desc
  9812. * @returns {*}
  9813. */
  9814. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9815. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9816. };
  9817. /**
  9818. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9819. * either gets confused and thinks this is an FID group or, if an FID group
  9820. * is already present, it fails to set the remote description.
  9821. *
  9822. * @param desc
  9823. * @returns {*}
  9824. */
  9825. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9826. return this.simulcastReceiver.transformRemoteDescription(desc);
  9827. };
  9828. /**
  9829. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9830. * SSRC.
  9831. *
  9832. * @param ssrc
  9833. * @returns {*}
  9834. */
  9835. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9836. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9837. };
  9838. /**
  9839. * Returns a stream with single video track, the one currently being
  9840. * received by this endpoint.
  9841. *
  9842. * @param stream the remote simulcast stream.
  9843. * @returns {webkitMediaStream}
  9844. */
  9845. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9846. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9847. };
  9848. /**
  9849. *
  9850. *
  9851. * @param desc
  9852. * @returns {*}
  9853. */
  9854. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9855. return this.simulcastSender.transformLocalDescription(desc);
  9856. };
  9857. /**
  9858. *
  9859. * @returns {*}
  9860. */
  9861. SimulcastManager.prototype.getLocalVideoStream = function() {
  9862. return this.simulcastSender.getLocalVideoStream();
  9863. };
  9864. /**
  9865. * GUM for simulcast.
  9866. *
  9867. * @param constraints
  9868. * @param success
  9869. * @param err
  9870. */
  9871. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9872. this.simulcastSender.getUserMedia(constraints, success, err);
  9873. };
  9874. /**
  9875. * Prepares the local description for public usage (i.e. to be signaled
  9876. * through Jingle to the focus).
  9877. *
  9878. * @param desc
  9879. * @returns {RTCSessionDescription}
  9880. */
  9881. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9882. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9883. };
  9884. /**
  9885. * Ensures that the simulcast group is present in the answer, _if_ native
  9886. * simulcast is enabled,
  9887. *
  9888. * @param desc
  9889. * @returns {*}
  9890. */
  9891. SimulcastManager.prototype.transformAnswer = function (desc) {
  9892. return this.simulcastSender.transformAnswer(desc);
  9893. };
  9894. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9895. return this.simulcastReceiver.getReceivingSSRC(jid);
  9896. };
  9897. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9898. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9899. };
  9900. /**
  9901. *
  9902. * @param lines
  9903. * @param mediatypes
  9904. * @returns {*}
  9905. */
  9906. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9907. var sb = lines.sdp.split('\r\n');
  9908. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9909. };
  9910. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9911. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9912. };
  9913. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9914. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9915. };
  9916. SimulcastManager.prototype.resetSender = function() {
  9917. if (typeof this.simulcastSender.reset === 'function'){
  9918. this.simulcastSender.reset();
  9919. }
  9920. };
  9921. var simulcast = new SimulcastManager();
  9922. module.exports = simulcast;
  9923. },{"../../service/RTC/RTCEvents":96,"./SimulcastReceiver":41,"./SimulcastSender":42,"./SimulcastUtils":43}],45:[function(require,module,exports){
  9924. /**
  9925. * Provides statistics for the local stream.
  9926. */
  9927. /**
  9928. * Size of the webaudio analizer buffer.
  9929. * @type {number}
  9930. */
  9931. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9932. /**
  9933. * Value of the webaudio analizer smoothing time parameter.
  9934. * @type {number}
  9935. */
  9936. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9937. /**
  9938. * Converts time domain data array to audio level.
  9939. * @param array the time domain data array.
  9940. * @returns {number} the audio level
  9941. */
  9942. function timeDomainDataToAudioLevel(samples) {
  9943. var maxVolume = 0;
  9944. var length = samples.length;
  9945. for (var i = 0; i < length; i++) {
  9946. if (maxVolume < samples[i])
  9947. maxVolume = samples[i];
  9948. }
  9949. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9950. };
  9951. /**
  9952. * Animates audio level change
  9953. * @param newLevel the new audio level
  9954. * @param lastLevel the last audio level
  9955. * @returns {Number} the audio level to be set
  9956. */
  9957. function animateLevel(newLevel, lastLevel)
  9958. {
  9959. var value = 0;
  9960. var diff = lastLevel - newLevel;
  9961. if(diff > 0.2)
  9962. {
  9963. value = lastLevel - 0.2;
  9964. }
  9965. else if(diff < -0.4)
  9966. {
  9967. value = lastLevel + 0.4;
  9968. }
  9969. else
  9970. {
  9971. value = newLevel;
  9972. }
  9973. return parseFloat(value.toFixed(3));
  9974. }
  9975. /**
  9976. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9977. *
  9978. * @param stream the local stream
  9979. * @param interval stats refresh interval given in ms.
  9980. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9981. * update.
  9982. * @constructor
  9983. */
  9984. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9985. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9986. this.stream = stream;
  9987. this.intervalId = null;
  9988. this.intervalMilis = interval;
  9989. this.eventEmitter = eventEmitter;
  9990. this.audioLevel = 0;
  9991. this.statisticsService = statisticsService;
  9992. }
  9993. /**
  9994. * Starts the collecting the statistics.
  9995. */
  9996. LocalStatsCollector.prototype.start = function () {
  9997. if (config.disableAudioLevels || !window.AudioContext)
  9998. return;
  9999. var context = new AudioContext();
  10000. var analyser = context.createAnalyser();
  10001. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10002. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10003. var source = context.createMediaStreamSource(this.stream);
  10004. source.connect(analyser);
  10005. var self = this;
  10006. this.intervalId = setInterval(
  10007. function () {
  10008. var array = new Uint8Array(analyser.frequencyBinCount);
  10009. analyser.getByteTimeDomainData(array);
  10010. var audioLevel = timeDomainDataToAudioLevel(array);
  10011. if(audioLevel != self.audioLevel) {
  10012. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10013. self.eventEmitter.emit(
  10014. "statistics.audioLevel",
  10015. self.statisticsService.LOCAL_JID,
  10016. self.audioLevel);
  10017. }
  10018. },
  10019. this.intervalMilis
  10020. );
  10021. };
  10022. /**
  10023. * Stops collecting the statistics.
  10024. */
  10025. LocalStatsCollector.prototype.stop = function () {
  10026. if (this.intervalId) {
  10027. clearInterval(this.intervalId);
  10028. this.intervalId = null;
  10029. }
  10030. };
  10031. module.exports = LocalStatsCollector;
  10032. },{}],46:[function(require,module,exports){
  10033. /* global ssrc2jid */
  10034. /* jshint -W117 */
  10035. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10036. /**
  10037. * Calculates packet lost percent using the number of lost packets and the
  10038. * number of all packet.
  10039. * @param lostPackets the number of lost packets
  10040. * @param totalPackets the number of all packets.
  10041. * @returns {number} packet loss percent
  10042. */
  10043. function calculatePacketLoss(lostPackets, totalPackets) {
  10044. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10045. return 0;
  10046. return Math.round((lostPackets/totalPackets)*100);
  10047. }
  10048. function getStatValue(item, name) {
  10049. if(!keyMap[APP.RTC.getBrowserType()][name])
  10050. throw "The property isn't supported!";
  10051. var key = keyMap[APP.RTC.getBrowserType()][name];
  10052. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  10053. }
  10054. /**
  10055. * Peer statistics data holder.
  10056. * @constructor
  10057. */
  10058. function PeerStats()
  10059. {
  10060. this.ssrc2Loss = {};
  10061. this.ssrc2AudioLevel = {};
  10062. this.ssrc2bitrate = {};
  10063. this.ssrc2resolution = {};
  10064. }
  10065. /**
  10066. * The bandwidth
  10067. * @type {{}}
  10068. */
  10069. PeerStats.bandwidth = {};
  10070. /**
  10071. * The bit rate
  10072. * @type {{}}
  10073. */
  10074. PeerStats.bitrate = {};
  10075. /**
  10076. * The packet loss rate
  10077. * @type {{}}
  10078. */
  10079. PeerStats.packetLoss = null;
  10080. /**
  10081. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10082. * represented by this instance.
  10083. * @param ssrc audio or video RTP stream SSRC.
  10084. * @param lossRate new packet loss rate value to be set.
  10085. */
  10086. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10087. {
  10088. this.ssrc2Loss[ssrc] = lossRate;
  10089. };
  10090. /**
  10091. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10092. * represented by this instance.
  10093. * @param ssrc audio or video RTP stream SSRC.
  10094. * @param resolution new resolution value to be set.
  10095. */
  10096. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10097. {
  10098. if(resolution === null && this.ssrc2resolution[ssrc])
  10099. {
  10100. delete this.ssrc2resolution[ssrc];
  10101. }
  10102. else if(resolution !== null)
  10103. this.ssrc2resolution[ssrc] = resolution;
  10104. };
  10105. /**
  10106. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10107. * represented by this instance.
  10108. * @param ssrc audio or video RTP stream SSRC.
  10109. * @param bitrate new bitrate value to be set.
  10110. */
  10111. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10112. {
  10113. if(this.ssrc2bitrate[ssrc])
  10114. {
  10115. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10116. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10117. }
  10118. else {
  10119. this.ssrc2bitrate[ssrc] = bitrate;
  10120. }
  10121. };
  10122. /**
  10123. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10124. * the stream which belongs to the peer represented by this instance.
  10125. * @param ssrc RTP stream SSRC for which current audio level value will be
  10126. * updated.
  10127. * @param audioLevel the new audio level value to be set. Value is truncated to
  10128. * fit the range from 0 to 1.
  10129. */
  10130. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10131. {
  10132. // Range limit 0 - 1
  10133. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10134. };
  10135. function formatAudioLevel(audioLevel) {
  10136. return Math.min(Math.max(audioLevel, 0), 1);
  10137. }
  10138. /**
  10139. * Array with the transport information.
  10140. * @type {Array}
  10141. */
  10142. PeerStats.transport = [];
  10143. /**
  10144. * <tt>StatsCollector</tt> registers for stats updates of given
  10145. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10146. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10147. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10148. * instance as an event source.
  10149. *
  10150. * @param peerconnection webRTC peer connection object.
  10151. * @param interval stats refresh interval given in ms.
  10152. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10153. * called on stats update.
  10154. * @constructor
  10155. */
  10156. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10157. {
  10158. this.peerconnection = peerconnection;
  10159. this.baselineAudioLevelsReport = null;
  10160. this.currentAudioLevelsReport = null;
  10161. this.currentStatsReport = null;
  10162. this.baselineStatsReport = null;
  10163. this.audioLevelsIntervalId = null;
  10164. this.eventEmitter = eventEmitter;
  10165. /**
  10166. * Gather PeerConnection stats once every this many milliseconds.
  10167. */
  10168. this.GATHER_INTERVAL = 15000;
  10169. /**
  10170. * Log stats via the focus once every this many milliseconds.
  10171. */
  10172. this.LOG_INTERVAL = 60000;
  10173. /**
  10174. * Gather stats and store them in this.statsToBeLogged.
  10175. */
  10176. this.gatherStatsIntervalId = null;
  10177. /**
  10178. * Send the stats already saved in this.statsToBeLogged to be logged via
  10179. * the focus.
  10180. */
  10181. this.logStatsIntervalId = null;
  10182. /**
  10183. * Stores the statistics which will be send to the focus to be logged.
  10184. */
  10185. this.statsToBeLogged =
  10186. {
  10187. timestamps: [],
  10188. stats: {}
  10189. };
  10190. // Updates stats interval
  10191. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10192. this.statsIntervalId = null;
  10193. this.statsIntervalMilis = statsInterval;
  10194. // Map of jids to PeerStats
  10195. this.jid2stats = {};
  10196. }
  10197. module.exports = StatsCollector;
  10198. /**
  10199. * Stops stats updates.
  10200. */
  10201. StatsCollector.prototype.stop = function () {
  10202. if (this.audioLevelsIntervalId) {
  10203. clearInterval(this.audioLevelsIntervalId);
  10204. this.audioLevelsIntervalId = null;
  10205. }
  10206. if (this.statsIntervalId)
  10207. {
  10208. clearInterval(this.statsIntervalId);
  10209. this.statsIntervalId = null;
  10210. }
  10211. if(this.logStatsIntervalId)
  10212. {
  10213. clearInterval(this.logStatsIntervalId);
  10214. this.logStatsIntervalId = null;
  10215. }
  10216. if(this.gatherStatsIntervalId)
  10217. {
  10218. clearInterval(this.gatherStatsIntervalId);
  10219. this.gatherStatsIntervalId = null;
  10220. }
  10221. };
  10222. /**
  10223. * Callback passed to <tt>getStats</tt> method.
  10224. * @param error an error that occurred on <tt>getStats</tt> call.
  10225. */
  10226. StatsCollector.prototype.errorCallback = function (error)
  10227. {
  10228. console.error("Get stats error", error);
  10229. this.stop();
  10230. };
  10231. /**
  10232. * Starts stats updates.
  10233. */
  10234. StatsCollector.prototype.start = function ()
  10235. {
  10236. var self = this;
  10237. if(!config.disableAudioLevels) {
  10238. this.audioLevelsIntervalId = setInterval(
  10239. function () {
  10240. // Interval updates
  10241. self.peerconnection.getStats(
  10242. function (report) {
  10243. var results = null;
  10244. if (!report || !report.result ||
  10245. typeof report.result != 'function') {
  10246. results = report;
  10247. }
  10248. else {
  10249. results = report.result();
  10250. }
  10251. //console.error("Got interval report", results);
  10252. self.currentAudioLevelsReport = results;
  10253. self.processAudioLevelReport();
  10254. self.baselineAudioLevelsReport =
  10255. self.currentAudioLevelsReport;
  10256. },
  10257. self.errorCallback
  10258. );
  10259. },
  10260. self.audioLevelsIntervalMilis
  10261. );
  10262. }
  10263. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10264. this.statsIntervalId = setInterval(
  10265. function () {
  10266. // Interval updates
  10267. self.peerconnection.getStats(
  10268. function (report) {
  10269. var results = null;
  10270. if (!report || !report.result ||
  10271. typeof report.result != 'function') {
  10272. //firefox
  10273. results = report;
  10274. }
  10275. else {
  10276. //chrome
  10277. results = report.result();
  10278. }
  10279. //console.error("Got interval report", results);
  10280. self.currentStatsReport = results;
  10281. try {
  10282. self.processStatsReport();
  10283. }
  10284. catch (e) {
  10285. console.error("Unsupported key:" + e, e);
  10286. }
  10287. self.baselineStatsReport = self.currentStatsReport;
  10288. },
  10289. self.errorCallback
  10290. );
  10291. },
  10292. self.statsIntervalMilis
  10293. );
  10294. }
  10295. if (config.logStats) {
  10296. this.gatherStatsIntervalId = setInterval(
  10297. function () {
  10298. self.peerconnection.getStats(
  10299. function (report) {
  10300. self.addStatsToBeLogged(report.result());
  10301. },
  10302. function () {
  10303. }
  10304. );
  10305. },
  10306. this.GATHER_INTERVAL
  10307. );
  10308. this.logStatsIntervalId = setInterval(
  10309. function() { self.logStats(); },
  10310. this.LOG_INTERVAL);
  10311. }
  10312. };
  10313. /**
  10314. * Checks whether a certain record should be included in the logged statistics.
  10315. */
  10316. function acceptStat(reportId, reportType, statName) {
  10317. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10318. return false;
  10319. if (reportType == "ssrc") {
  10320. if (statName == "googTrackId" ||
  10321. statName == "transportId" ||
  10322. statName == "ssrc")
  10323. return false;
  10324. }
  10325. return true;
  10326. }
  10327. /**
  10328. * Checks whether a certain record should be included in the logged statistics.
  10329. */
  10330. function acceptReport(id, type) {
  10331. if (id.substring(0, 15) == "googCertificate" ||
  10332. id.substring(0, 9) == "googTrack" ||
  10333. id.substring(0, 20) == "googLibjingleSession")
  10334. return false;
  10335. if (type == "googComponent")
  10336. return false;
  10337. return true;
  10338. }
  10339. /**
  10340. * Converts the stats to the format used for logging, and saves the data in
  10341. * this.statsToBeLogged.
  10342. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10343. */
  10344. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10345. var self = this;
  10346. var num_records = this.statsToBeLogged.timestamps.length;
  10347. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10348. reports.map(function (report) {
  10349. if (!acceptReport(report.id, report.type))
  10350. return;
  10351. var stat = self.statsToBeLogged.stats[report.id];
  10352. if (!stat) {
  10353. stat = self.statsToBeLogged.stats[report.id] = {};
  10354. }
  10355. stat.type = report.type;
  10356. report.names().map(function (name) {
  10357. if (!acceptStat(report.id, report.type, name))
  10358. return;
  10359. var values = stat[name];
  10360. if (!values) {
  10361. values = stat[name] = [];
  10362. }
  10363. while (values.length < num_records) {
  10364. values.push(null);
  10365. }
  10366. values.push(report.stat(name));
  10367. });
  10368. });
  10369. };
  10370. StatsCollector.prototype.logStats = function () {
  10371. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10372. return;
  10373. // Reset the stats
  10374. this.statsToBeLogged.stats = {};
  10375. this.statsToBeLogged.timestamps = [];
  10376. };
  10377. var keyMap = {};
  10378. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10379. "ssrc": "ssrc",
  10380. "packetsReceived": "packetsReceived",
  10381. "packetsLost": "packetsLost",
  10382. "packetsSent": "packetsSent",
  10383. "bytesReceived": "bytesReceived",
  10384. "bytesSent": "bytesSent"
  10385. };
  10386. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10387. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10388. "sendBandwidth": "googAvailableSendBandwidth",
  10389. "remoteAddress": "googRemoteAddress",
  10390. "transportType": "googTransportType",
  10391. "localAddress": "googLocalAddress",
  10392. "activeConnection": "googActiveConnection",
  10393. "ssrc": "ssrc",
  10394. "packetsReceived": "packetsReceived",
  10395. "packetsSent": "packetsSent",
  10396. "packetsLost": "packetsLost",
  10397. "bytesReceived": "bytesReceived",
  10398. "bytesSent": "bytesSent",
  10399. "googFrameHeightReceived": "googFrameHeightReceived",
  10400. "googFrameWidthReceived": "googFrameWidthReceived",
  10401. "googFrameHeightSent": "googFrameHeightSent",
  10402. "googFrameWidthSent": "googFrameWidthSent",
  10403. "audioInputLevel": "audioInputLevel",
  10404. "audioOutputLevel": "audioOutputLevel"
  10405. };
  10406. /**
  10407. * Stats processing logic.
  10408. */
  10409. StatsCollector.prototype.processStatsReport = function () {
  10410. if (!this.baselineStatsReport) {
  10411. return;
  10412. }
  10413. for (var idx in this.currentStatsReport) {
  10414. var now = this.currentStatsReport[idx];
  10415. try {
  10416. if (getStatValue(now, 'receiveBandwidth') ||
  10417. getStatValue(now, 'sendBandwidth')) {
  10418. PeerStats.bandwidth = {
  10419. "download": Math.round(
  10420. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10421. "upload": Math.round(
  10422. (getStatValue(now, 'sendBandwidth')) / 1000)
  10423. };
  10424. }
  10425. }
  10426. catch(e){/*not supported*/}
  10427. if(now.type == 'googCandidatePair')
  10428. {
  10429. var ip, type, localIP, active;
  10430. try {
  10431. ip = getStatValue(now, 'remoteAddress');
  10432. type = getStatValue(now, "transportType");
  10433. localIP = getStatValue(now, "localAddress");
  10434. active = getStatValue(now, "activeConnection");
  10435. }
  10436. catch(e){/*not supported*/}
  10437. if(!ip || !type || !localIP || active != "true")
  10438. continue;
  10439. var addressSaved = false;
  10440. for(var i = 0; i < PeerStats.transport.length; i++)
  10441. {
  10442. if(PeerStats.transport[i].ip == ip &&
  10443. PeerStats.transport[i].type == type &&
  10444. PeerStats.transport[i].localip == localIP)
  10445. {
  10446. addressSaved = true;
  10447. }
  10448. }
  10449. if(addressSaved)
  10450. continue;
  10451. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10452. continue;
  10453. }
  10454. if(now.type == "candidatepair")
  10455. {
  10456. if(now.state == "succeeded")
  10457. continue;
  10458. var local = this.currentStatsReport[now.localCandidateId];
  10459. var remote = this.currentStatsReport[now.remoteCandidateId];
  10460. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10461. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10462. }
  10463. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10464. now.type != "inboundrtp") {
  10465. continue;
  10466. }
  10467. var before = this.baselineStatsReport[idx];
  10468. if (!before) {
  10469. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10470. continue;
  10471. }
  10472. var ssrc = getStatValue(now, 'ssrc');
  10473. if(!ssrc)
  10474. continue;
  10475. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10476. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10477. console.warn("No jid for ssrc: " + ssrc);
  10478. continue;
  10479. }
  10480. var jidStats = this.jid2stats[jid];
  10481. if (!jidStats) {
  10482. jidStats = new PeerStats();
  10483. this.jid2stats[jid] = jidStats;
  10484. }
  10485. var isDownloadStream = true;
  10486. var key = 'packetsReceived';
  10487. if (!getStatValue(now, key))
  10488. {
  10489. isDownloadStream = false;
  10490. key = 'packetsSent';
  10491. if (!getStatValue(now, key))
  10492. {
  10493. console.warn("No packetsReceived nor packetSent stat found");
  10494. continue;
  10495. }
  10496. }
  10497. var packetsNow = getStatValue(now, key);
  10498. if(!packetsNow || packetsNow < 0)
  10499. packetsNow = 0;
  10500. var packetsBefore = getStatValue(before, key);
  10501. if(!packetsBefore || packetsBefore < 0)
  10502. packetsBefore = 0;
  10503. var packetRate = packetsNow - packetsBefore;
  10504. if(!packetRate || packetRate < 0)
  10505. packetRate = 0;
  10506. var currentLoss = getStatValue(now, 'packetsLost');
  10507. if(!currentLoss || currentLoss < 0)
  10508. currentLoss = 0;
  10509. var previousLoss = getStatValue(before, 'packetsLost');
  10510. if(!previousLoss || previousLoss < 0)
  10511. previousLoss = 0;
  10512. var lossRate = currentLoss - previousLoss;
  10513. if(!lossRate || lossRate < 0)
  10514. lossRate = 0;
  10515. var packetsTotal = (packetRate + lossRate);
  10516. jidStats.setSsrcLoss(ssrc,
  10517. {"packetsTotal": packetsTotal,
  10518. "packetsLost": lossRate,
  10519. "isDownloadStream": isDownloadStream});
  10520. var bytesReceived = 0, bytesSent = 0;
  10521. if(getStatValue(now, "bytesReceived"))
  10522. {
  10523. bytesReceived = getStatValue(now, "bytesReceived") -
  10524. getStatValue(before, "bytesReceived");
  10525. }
  10526. if(getStatValue(now, "bytesSent"))
  10527. {
  10528. bytesSent = getStatValue(now, "bytesSent") -
  10529. getStatValue(before, "bytesSent");
  10530. }
  10531. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10532. if(bytesReceived <= 0 || time <= 0)
  10533. {
  10534. bytesReceived = 0;
  10535. }
  10536. else
  10537. {
  10538. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10539. }
  10540. if(bytesSent <= 0 || time <= 0)
  10541. {
  10542. bytesSent = 0;
  10543. }
  10544. else
  10545. {
  10546. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10547. }
  10548. jidStats.setSsrcBitrate(ssrc, {
  10549. "download": bytesReceived,
  10550. "upload": bytesSent});
  10551. var resolution = {height: null, width: null};
  10552. try {
  10553. if (getStatValue(now, "googFrameHeightReceived") &&
  10554. getStatValue(now, "googFrameWidthReceived")) {
  10555. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10556. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10557. }
  10558. else if (getStatValue(now, "googFrameHeightSent") &&
  10559. getStatValue(now, "googFrameWidthSent")) {
  10560. resolution.height = getStatValue(now, "googFrameHeightSent");
  10561. resolution.width = getStatValue(now, "googFrameWidthSent");
  10562. }
  10563. }
  10564. catch(e){/*not supported*/}
  10565. if(resolution.height && resolution.width)
  10566. {
  10567. jidStats.setSsrcResolution(ssrc, resolution);
  10568. }
  10569. else
  10570. {
  10571. jidStats.setSsrcResolution(ssrc, null);
  10572. }
  10573. }
  10574. var self = this;
  10575. // Jid stats
  10576. var totalPackets = {download: 0, upload: 0};
  10577. var lostPackets = {download: 0, upload: 0};
  10578. var bitrateDownload = 0;
  10579. var bitrateUpload = 0;
  10580. var resolutions = {};
  10581. Object.keys(this.jid2stats).forEach(
  10582. function (jid)
  10583. {
  10584. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10585. function (ssrc)
  10586. {
  10587. var type = "upload";
  10588. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10589. type = "download";
  10590. totalPackets[type] +=
  10591. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10592. lostPackets[type] +=
  10593. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10594. }
  10595. );
  10596. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10597. function (ssrc) {
  10598. bitrateDownload +=
  10599. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10600. bitrateUpload +=
  10601. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10602. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10603. }
  10604. );
  10605. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10606. }
  10607. );
  10608. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10609. PeerStats.packetLoss = {
  10610. total:
  10611. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10612. totalPackets.download + totalPackets.upload),
  10613. download:
  10614. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10615. upload:
  10616. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10617. };
  10618. this.eventEmitter.emit("statistics.connectionstats",
  10619. {
  10620. "bitrate": PeerStats.bitrate,
  10621. "packetLoss": PeerStats.packetLoss,
  10622. "bandwidth": PeerStats.bandwidth,
  10623. "resolution": resolutions,
  10624. "transport": PeerStats.transport
  10625. });
  10626. PeerStats.transport = [];
  10627. };
  10628. /**
  10629. * Stats processing logic.
  10630. */
  10631. StatsCollector.prototype.processAudioLevelReport = function ()
  10632. {
  10633. if (!this.baselineAudioLevelsReport)
  10634. {
  10635. return;
  10636. }
  10637. for (var idx in this.currentAudioLevelsReport)
  10638. {
  10639. var now = this.currentAudioLevelsReport[idx];
  10640. if (now.type != 'ssrc')
  10641. {
  10642. continue;
  10643. }
  10644. var before = this.baselineAudioLevelsReport[idx];
  10645. if (!before)
  10646. {
  10647. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10648. continue;
  10649. }
  10650. var ssrc = getStatValue(now, 'ssrc');
  10651. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10652. if (!jid && (Date.now() - now.timestamp) < 3000)
  10653. {
  10654. console.warn("No jid for ssrc: " + ssrc);
  10655. continue;
  10656. }
  10657. var jidStats = this.jid2stats[jid];
  10658. if (!jidStats)
  10659. {
  10660. jidStats = new PeerStats();
  10661. this.jid2stats[jid] = jidStats;
  10662. }
  10663. // Audio level
  10664. var audioLevel = null;
  10665. try {
  10666. audioLevel = getStatValue(now, 'audioInputLevel');
  10667. if (!audioLevel)
  10668. audioLevel = getStatValue(now, 'audioOutputLevel');
  10669. }
  10670. catch(e) {/*not supported*/
  10671. console.warn("Audio Levels are not available in the statistics.");
  10672. clearInterval(this.audioLevelsIntervalId);
  10673. return;
  10674. }
  10675. if (audioLevel)
  10676. {
  10677. // TODO: can't find specs about what this value really is,
  10678. // but it seems to vary between 0 and around 32k.
  10679. audioLevel = audioLevel / 32767;
  10680. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10681. if(jid != APP.xmpp.myJid())
  10682. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10683. }
  10684. }
  10685. };
  10686. },{"../../service/RTC/RTCBrowserType":95}],47:[function(require,module,exports){
  10687. /**
  10688. * Created by hristo on 8/4/14.
  10689. */
  10690. var LocalStats = require("./LocalStatsCollector.js");
  10691. var RTPStats = require("./RTPStatsCollector.js");
  10692. var EventEmitter = require("events");
  10693. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10694. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10695. var eventEmitter = new EventEmitter();
  10696. var localStats = null;
  10697. var rtpStats = null;
  10698. function stopLocal()
  10699. {
  10700. if(localStats)
  10701. {
  10702. localStats.stop();
  10703. localStats = null;
  10704. }
  10705. }
  10706. function stopRemote()
  10707. {
  10708. if(rtpStats)
  10709. {
  10710. rtpStats.stop();
  10711. eventEmitter.emit("statistics.stop");
  10712. rtpStats = null;
  10713. }
  10714. }
  10715. function startRemoteStats (peerconnection) {
  10716. if(rtpStats)
  10717. {
  10718. rtpStats.stop();
  10719. rtpStats = null;
  10720. }
  10721. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10722. rtpStats.start();
  10723. }
  10724. function onStreamCreated(stream)
  10725. {
  10726. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10727. return;
  10728. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10729. eventEmitter);
  10730. localStats.start();
  10731. }
  10732. function onDisposeConference(onUnload) {
  10733. stopRemote();
  10734. if(onUnload) {
  10735. stopLocal();
  10736. eventEmitter.removeAllListeners();
  10737. }
  10738. }
  10739. var statistics =
  10740. {
  10741. /**
  10742. * Indicates that this audio level is for local jid.
  10743. * @type {string}
  10744. */
  10745. LOCAL_JID: 'local',
  10746. addAudioLevelListener: function(listener)
  10747. {
  10748. eventEmitter.on("statistics.audioLevel", listener);
  10749. },
  10750. removeAudioLevelListener: function(listener)
  10751. {
  10752. eventEmitter.removeListener("statistics.audioLevel", listener);
  10753. },
  10754. addConnectionStatsListener: function(listener)
  10755. {
  10756. eventEmitter.on("statistics.connectionstats", listener);
  10757. },
  10758. removeConnectionStatsListener: function(listener)
  10759. {
  10760. eventEmitter.removeListener("statistics.connectionstats", listener);
  10761. },
  10762. addRemoteStatsStopListener: function(listener)
  10763. {
  10764. eventEmitter.on("statistics.stop", listener);
  10765. },
  10766. removeRemoteStatsStopListener: function(listener)
  10767. {
  10768. eventEmitter.removeListener("statistics.stop", listener);
  10769. },
  10770. stop: function () {
  10771. stopLocal();
  10772. stopRemote();
  10773. if(eventEmitter)
  10774. {
  10775. eventEmitter.removeAllListeners();
  10776. }
  10777. },
  10778. stopRemoteStatistics: function()
  10779. {
  10780. stopRemote();
  10781. },
  10782. start: function () {
  10783. APP.RTC.addStreamListener(onStreamCreated,
  10784. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10785. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10786. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10787. startRemoteStats(event.peerconnection);
  10788. });
  10789. }
  10790. };
  10791. module.exports = statistics;
  10792. },{"../../service/RTC/StreamEventTypes.js":98,"../../service/xmpp/XMPPEvents":105,"./LocalStatsCollector.js":45,"./RTPStatsCollector.js":46,"events":65}],48:[function(require,module,exports){
  10793. var i18n = require("i18next-client");
  10794. var languages = require("../../service/translation/languages");
  10795. var Settings = require("../settings/Settings");
  10796. var DEFAULT_LANG = languages.EN;
  10797. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10798. return value.replace("__app__", interfaceConfig.APP_NAME);
  10799. });
  10800. var defaultOptions = {
  10801. detectLngQS: "lang",
  10802. useCookie: false,
  10803. fallbackLng: DEFAULT_LANG,
  10804. load: "unspecific",
  10805. resGetPath: 'lang/__ns__-__lng__.json',
  10806. ns: {
  10807. namespaces: ['main', 'languages'],
  10808. defaultNs: 'main'
  10809. },
  10810. lngWhitelist : languages.getLanguages(),
  10811. fallbackOnNull: true,
  10812. fallbackOnEmpty: true,
  10813. useDataAttrOptions: true,
  10814. defaultValueFromContent: false,
  10815. app: interfaceConfig.APP_NAME,
  10816. getAsync: false,
  10817. defaultValueFromContent: false,
  10818. customLoad: function(lng, ns, options, done) {
  10819. var resPath = "lang/__ns__-__lng__.json";
  10820. if(lng === languages.EN)
  10821. resPath = "lang/__ns__.json";
  10822. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10823. i18n.functions.ajax({
  10824. url: url,
  10825. success: function(data, status, xhr) {
  10826. i18n.functions.log('loaded: ' + url);
  10827. done(null, data);
  10828. },
  10829. error : function(xhr, status, error) {
  10830. if ((status && status == 200) ||
  10831. (xhr && xhr.status && xhr.status == 200)) {
  10832. // file loaded but invalid json, stop waste time !
  10833. i18n.functions.error('There is a typo in: ' + url);
  10834. } else if ((status && status == 404) ||
  10835. (xhr && xhr.status && xhr.status == 404)) {
  10836. i18n.functions.log('Does not exist: ' + url);
  10837. } else {
  10838. var theStatus = status ? status :
  10839. ((xhr && xhr.status) ? xhr.status : null);
  10840. i18n.functions.log(theStatus + ' when loading ' + url);
  10841. }
  10842. done(error, {});
  10843. },
  10844. dataType: "json",
  10845. async : options.getAsync
  10846. });
  10847. }
  10848. // options for caching
  10849. // useLocalStorage: true,
  10850. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10851. };
  10852. function initCompleted(t)
  10853. {
  10854. $("[data-i18n]").i18n();
  10855. }
  10856. function checkForParameter() {
  10857. var query = window.location.search.substring(1);
  10858. var vars = query.split("&");
  10859. for (var i=0;i<vars.length;i++) {
  10860. var pair = vars[i].split("=");
  10861. if(pair[0] == "lang")
  10862. {
  10863. return pair[1];
  10864. }
  10865. }
  10866. return null;
  10867. }
  10868. module.exports = {
  10869. init: function (lang) {
  10870. var options = defaultOptions;
  10871. if(!lang)
  10872. {
  10873. lang = checkForParameter();
  10874. if(!lang)
  10875. {
  10876. var settings = Settings.getSettings();
  10877. if(settings)
  10878. lang = settings.language;
  10879. }
  10880. }
  10881. if(lang) {
  10882. options.lng = lang;
  10883. }
  10884. i18n.init(options, initCompleted);
  10885. },
  10886. translateString: function (key, options) {
  10887. return i18n.t(key, options);
  10888. },
  10889. setLanguage: function (lang) {
  10890. if(!lang)
  10891. lang = DEFAULT_LANG;
  10892. i18n.setLng(lang, defaultOptions, initCompleted);
  10893. },
  10894. getCurrentLanguage: function () {
  10895. return i18n.lng();
  10896. },
  10897. translateElement: function (selector) {
  10898. selector.i18n();
  10899. },
  10900. generateTranslatonHTML: function (key, options) {
  10901. var str = "<span data-i18n=\"" + key + "\"";
  10902. if(options)
  10903. {
  10904. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10905. }
  10906. str += ">";
  10907. str += this.translateString(key, options);
  10908. str += "</span>";
  10909. return str;
  10910. }
  10911. };
  10912. },{"../../service/translation/languages":104,"../settings/Settings":39,"i18next-client":66}],49:[function(require,module,exports){
  10913. /* jshint -W117 */
  10914. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10915. var SDPDiffer = require("./SDPDiffer");
  10916. var SDPUtil = require("./SDPUtil");
  10917. var SDP = require("./SDP");
  10918. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10919. var async = require("async");
  10920. // Jingle stuff
  10921. function JingleSession(me, sid, connection, service) {
  10922. this.me = me;
  10923. this.sid = sid;
  10924. this.connection = connection;
  10925. this.initiator = null;
  10926. this.responder = null;
  10927. this.isInitiator = null;
  10928. this.peerjid = null;
  10929. this.state = null;
  10930. this.localSDP = null;
  10931. this.remoteSDP = null;
  10932. this.relayedStreams = [];
  10933. this.startTime = null;
  10934. this.stopTime = null;
  10935. this.media_constraints = null;
  10936. this.pc_constraints = null;
  10937. this.ice_config = {};
  10938. this.drip_container = [];
  10939. this.service = service;
  10940. this.usetrickle = true;
  10941. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10942. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10943. this.hadstuncandidate = false;
  10944. this.hadturncandidate = false;
  10945. this.lasticecandidate = false;
  10946. this.statsinterval = null;
  10947. this.reason = null;
  10948. this.addssrc = [];
  10949. this.removessrc = [];
  10950. this.pendingop = null;
  10951. this.switchstreams = false;
  10952. this.wait = true;
  10953. this.localStreamsSSRC = null;
  10954. /**
  10955. * The indicator which determines whether the (local) video has been muted
  10956. * in response to a user command in contrast to an automatic decision made
  10957. * by the application logic.
  10958. */
  10959. this.videoMuteByUser = false;
  10960. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  10961. // We start with the queue paused. We resume it when the signaling state is
  10962. // stable and the ice connection state is connected.
  10963. this.modifySourcesQueue.pause();
  10964. }
  10965. JingleSession.prototype.updateModifySourcesQueue = function() {
  10966. var signalingState = this.peerconnection.signalingState;
  10967. var iceConnectionState = this.peerconnection.iceConnectionState;
  10968. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  10969. this.modifySourcesQueue.resume();
  10970. } else {
  10971. this.modifySourcesQueue.pause();
  10972. }
  10973. };
  10974. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10975. var self = this;
  10976. if (this.state !== null) {
  10977. console.error('attempt to initiate on session ' + this.sid +
  10978. 'in state ' + this.state);
  10979. return;
  10980. }
  10981. this.isInitiator = isInitiator;
  10982. this.state = 'pending';
  10983. this.initiator = isInitiator ? this.me : peerjid;
  10984. this.responder = !isInitiator ? this.me : peerjid;
  10985. this.peerjid = peerjid;
  10986. this.hadstuncandidate = false;
  10987. this.hadturncandidate = false;
  10988. this.lasticecandidate = false;
  10989. this.peerconnection
  10990. = new TraceablePeerConnection(
  10991. this.connection.jingle.ice_config,
  10992. this.connection.jingle.pc_constraints );
  10993. this.peerconnection.onicecandidate = function (event) {
  10994. self.sendIceCandidate(event.candidate);
  10995. };
  10996. this.peerconnection.onaddstream = function (event) {
  10997. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10998. self.remoteStreamAdded(event);
  10999. };
  11000. this.peerconnection.onremovestream = function (event) {
  11001. // Remove the stream from remoteStreams
  11002. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11003. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11004. };
  11005. this.peerconnection.onsignalingstatechange = function (event) {
  11006. if (!(self && self.peerconnection)) return;
  11007. self.updateModifySourcesQueue();
  11008. };
  11009. this.peerconnection.oniceconnectionstatechange = function (event) {
  11010. if (!(self && self.peerconnection)) return;
  11011. self.updateModifySourcesQueue();
  11012. switch (self.peerconnection.iceConnectionState) {
  11013. case 'connected':
  11014. this.startTime = new Date();
  11015. break;
  11016. case 'disconnected':
  11017. this.stopTime = new Date();
  11018. break;
  11019. }
  11020. onIceConnectionStateChange(self.sid, self);
  11021. };
  11022. // add any local and relayed stream
  11023. APP.RTC.localStreams.forEach(function(stream) {
  11024. self.peerconnection.addStream(stream.getOriginalStream());
  11025. });
  11026. this.relayedStreams.forEach(function(stream) {
  11027. self.peerconnection.addStream(stream);
  11028. });
  11029. };
  11030. function onIceConnectionStateChange(sid, session) {
  11031. switch (session.peerconnection.iceConnectionState) {
  11032. case 'checking':
  11033. session.timeChecking = (new Date()).getTime();
  11034. session.firstconnect = true;
  11035. break;
  11036. case 'completed': // on caller side
  11037. case 'connected':
  11038. if (session.firstconnect) {
  11039. session.firstconnect = false;
  11040. var metadata = {};
  11041. metadata.setupTime
  11042. = (new Date()).getTime() - session.timeChecking;
  11043. session.peerconnection.getStats(function (res) {
  11044. if(res && res.result) {
  11045. res.result().forEach(function (report) {
  11046. if (report.type == 'googCandidatePair' &&
  11047. report.stat('googActiveConnection') == 'true') {
  11048. metadata.localCandidateType
  11049. = report.stat('googLocalCandidateType');
  11050. metadata.remoteCandidateType
  11051. = report.stat('googRemoteCandidateType');
  11052. // log pair as well so we can get nice pie
  11053. // charts
  11054. metadata.candidatePair
  11055. = report.stat('googLocalCandidateType') +
  11056. ';' +
  11057. report.stat('googRemoteCandidateType');
  11058. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11059. {
  11060. metadata.ipv6 = true;
  11061. }
  11062. }
  11063. });
  11064. }
  11065. });
  11066. }
  11067. break;
  11068. }
  11069. }
  11070. JingleSession.prototype.accept = function () {
  11071. var self = this;
  11072. this.state = 'active';
  11073. var pranswer = this.peerconnection.localDescription;
  11074. if (!pranswer || pranswer.type != 'pranswer') {
  11075. return;
  11076. }
  11077. console.log('going from pranswer to answer');
  11078. if (this.usetrickle) {
  11079. // remove candidates already sent from session-accept
  11080. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11081. for (var i = 0; i < lines.length; i++) {
  11082. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11083. }
  11084. }
  11085. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11086. // FIXME: change any inactive to sendrecv or whatever they were originally
  11087. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11088. }
  11089. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  11090. var prsdp = new SDP(pranswer.sdp);
  11091. var accept = $iq({to: this.peerjid,
  11092. type: 'set'})
  11093. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11094. action: 'session-accept',
  11095. initiator: this.initiator,
  11096. responder: this.responder,
  11097. sid: this.sid });
  11098. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11099. var sdp = this.peerconnection.localDescription.sdp;
  11100. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11101. // FIXME: change any inactive to sendrecv or whatever they were originally
  11102. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11103. }
  11104. var self = this;
  11105. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11106. function () {
  11107. //console.log('setLocalDescription success');
  11108. self.setLocalDescription();
  11109. self.connection.sendIQ(accept,
  11110. function () {
  11111. var ack = {};
  11112. ack.source = 'answer';
  11113. $(document).trigger('ack.jingle', [self.sid, ack]);
  11114. },
  11115. function (stanza) {
  11116. var error = ($(stanza).find('error').length) ? {
  11117. code: $(stanza).find('error').attr('code'),
  11118. reason: $(stanza).find('error :first')[0].tagName
  11119. }:{};
  11120. error.source = 'answer';
  11121. JingleSession.onJingleError(self.sid, error);
  11122. },
  11123. 10000);
  11124. },
  11125. function (e) {
  11126. console.error('setLocalDescription failed', e);
  11127. }
  11128. );
  11129. };
  11130. JingleSession.prototype.terminate = function (reason) {
  11131. this.state = 'ended';
  11132. this.reason = reason;
  11133. this.peerconnection.close();
  11134. if (this.statsinterval !== null) {
  11135. window.clearInterval(this.statsinterval);
  11136. this.statsinterval = null;
  11137. }
  11138. };
  11139. JingleSession.prototype.active = function () {
  11140. return this.state == 'active';
  11141. };
  11142. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11143. var self = this;
  11144. if (candidate && !this.lasticecandidate) {
  11145. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11146. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11147. if (!(ice && jcand)) {
  11148. console.error('failed to get ice && jcand');
  11149. return;
  11150. }
  11151. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11152. if (jcand.type === 'srflx') {
  11153. this.hadstuncandidate = true;
  11154. } else if (jcand.type === 'relay') {
  11155. this.hadturncandidate = true;
  11156. }
  11157. if (this.usetrickle) {
  11158. if (this.usedrip) {
  11159. if (this.drip_container.length === 0) {
  11160. // start 20ms callout
  11161. window.setTimeout(function () {
  11162. if (self.drip_container.length === 0) return;
  11163. self.sendIceCandidates(self.drip_container);
  11164. self.drip_container = [];
  11165. }, 20);
  11166. }
  11167. this.drip_container.push(candidate);
  11168. return;
  11169. } else {
  11170. self.sendIceCandidate([candidate]);
  11171. }
  11172. }
  11173. } else {
  11174. //console.log('sendIceCandidate: last candidate.');
  11175. if (!this.usetrickle) {
  11176. //console.log('should send full offer now...');
  11177. var init = $iq({to: this.peerjid,
  11178. type: 'set'})
  11179. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11180. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11181. initiator: this.initiator,
  11182. sid: this.sid});
  11183. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11184. var self = this;
  11185. var sendJingle = function (ssrc) {
  11186. if(!ssrc)
  11187. ssrc = {};
  11188. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  11189. self.connection.sendIQ(init,
  11190. function () {
  11191. //console.log('session initiate ack');
  11192. var ack = {};
  11193. ack.source = 'offer';
  11194. $(document).trigger('ack.jingle', [self.sid, ack]);
  11195. },
  11196. function (stanza) {
  11197. self.state = 'error';
  11198. self.peerconnection.close();
  11199. var error = ($(stanza).find('error').length) ? {
  11200. code: $(stanza).find('error').attr('code'),
  11201. reason: $(stanza).find('error :first')[0].tagName,
  11202. }:{};
  11203. error.source = 'offer';
  11204. JingleSession.onJingleError(self.sid, error);
  11205. },
  11206. 10000);
  11207. }
  11208. sendJingle();
  11209. }
  11210. this.lasticecandidate = true;
  11211. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11212. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11213. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11214. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11215. }
  11216. }
  11217. };
  11218. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11219. console.log('sendIceCandidates', candidates);
  11220. var cand = $iq({to: this.peerjid, type: 'set'})
  11221. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11222. action: 'transport-info',
  11223. initiator: this.initiator,
  11224. sid: this.sid});
  11225. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11226. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11227. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11228. if (cands.length > 0) {
  11229. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11230. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11231. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11232. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11233. }).c('transport', ice);
  11234. for (var i = 0; i < cands.length; i++) {
  11235. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11236. }
  11237. // add fingerprint
  11238. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11239. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11240. tmp.required = true;
  11241. cand.c(
  11242. 'fingerprint',
  11243. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11244. .t(tmp.fingerprint);
  11245. delete tmp.fingerprint;
  11246. cand.attrs(tmp);
  11247. cand.up();
  11248. }
  11249. cand.up(); // transport
  11250. cand.up(); // content
  11251. }
  11252. }
  11253. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11254. //console.log('was this the last candidate', this.lasticecandidate);
  11255. this.connection.sendIQ(cand,
  11256. function () {
  11257. var ack = {};
  11258. ack.source = 'transportinfo';
  11259. $(document).trigger('ack.jingle', [this.sid, ack]);
  11260. },
  11261. function (stanza) {
  11262. var error = ($(stanza).find('error').length) ? {
  11263. code: $(stanza).find('error').attr('code'),
  11264. reason: $(stanza).find('error :first')[0].tagName,
  11265. }:{};
  11266. error.source = 'transportinfo';
  11267. JingleSession.onJingleError(this.sid, error);
  11268. },
  11269. 10000);
  11270. };
  11271. JingleSession.prototype.sendOffer = function () {
  11272. //console.log('sendOffer...');
  11273. var self = this;
  11274. this.peerconnection.createOffer(function (sdp) {
  11275. self.createdOffer(sdp);
  11276. },
  11277. function (e) {
  11278. console.error('createOffer failed', e);
  11279. },
  11280. this.media_constraints
  11281. );
  11282. };
  11283. JingleSession.prototype.createdOffer = function (sdp) {
  11284. //console.log('createdOffer', sdp);
  11285. var self = this;
  11286. this.localSDP = new SDP(sdp.sdp);
  11287. //this.localSDP.mangle();
  11288. var sendJingle = function () {
  11289. var init = $iq({to: this.peerjid,
  11290. type: 'set'})
  11291. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11292. action: 'session-initiate',
  11293. initiator: this.initiator,
  11294. sid: this.sid});
  11295. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11296. self.connection.sendIQ(init,
  11297. function () {
  11298. var ack = {};
  11299. ack.source = 'offer';
  11300. $(document).trigger('ack.jingle', [self.sid, ack]);
  11301. },
  11302. function (stanza) {
  11303. self.state = 'error';
  11304. self.peerconnection.close();
  11305. var error = ($(stanza).find('error').length) ? {
  11306. code: $(stanza).find('error').attr('code'),
  11307. reason: $(stanza).find('error :first')[0].tagName,
  11308. }:{};
  11309. error.source = 'offer';
  11310. JingleSession.onJingleError(self.sid, error);
  11311. },
  11312. 10000);
  11313. }
  11314. sdp.sdp = this.localSDP.raw;
  11315. this.peerconnection.setLocalDescription(sdp,
  11316. function () {
  11317. if(self.usetrickle)
  11318. {
  11319. sendJingle();
  11320. }
  11321. self.setLocalDescription();
  11322. //console.log('setLocalDescription success');
  11323. },
  11324. function (e) {
  11325. console.error('setLocalDescription failed', e);
  11326. }
  11327. );
  11328. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11329. for (var i = 0; i < cands.length; i++) {
  11330. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11331. if (cand.type == 'srflx') {
  11332. this.hadstuncandidate = true;
  11333. } else if (cand.type == 'relay') {
  11334. this.hadturncandidate = true;
  11335. }
  11336. }
  11337. };
  11338. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11339. //console.log('setting remote description... ', desctype);
  11340. this.remoteSDP = new SDP('');
  11341. this.remoteSDP.fromJingle(elem);
  11342. if (this.peerconnection.remoteDescription !== null) {
  11343. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11344. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11345. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11346. for (var i = 0; i < pranswer.media.length; i++) {
  11347. // make sure we have ice ufrag and pwd
  11348. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11349. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11350. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11351. } else {
  11352. console.warn('no ice ufrag?');
  11353. }
  11354. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11355. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11356. } else {
  11357. console.warn('no ice pwd?');
  11358. }
  11359. }
  11360. // copy over candidates
  11361. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11362. for (var j = 0; j < lines.length; j++) {
  11363. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11364. }
  11365. }
  11366. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11367. }
  11368. }
  11369. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11370. this.peerconnection.setRemoteDescription(remotedesc,
  11371. function () {
  11372. //console.log('setRemoteDescription success');
  11373. },
  11374. function (e) {
  11375. console.error('setRemoteDescription error', e);
  11376. JingleSession.onJingleFatalError(self, e);
  11377. }
  11378. );
  11379. };
  11380. JingleSession.prototype.addIceCandidate = function (elem) {
  11381. var self = this;
  11382. if (this.peerconnection.signalingState == 'closed') {
  11383. return;
  11384. }
  11385. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11386. console.log('trickle ice candidate arriving before session accept...');
  11387. // create a PRANSWER for setRemoteDescription
  11388. if (!this.remoteSDP) {
  11389. var cobbled = 'v=0\r\n' +
  11390. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11391. 's=-\r\n' +
  11392. 't=0 0\r\n';
  11393. // first, take some things from the local description
  11394. for (var i = 0; i < this.localSDP.media.length; i++) {
  11395. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11396. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11397. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11398. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11399. }
  11400. cobbled += 'a=inactive\r\n';
  11401. }
  11402. this.remoteSDP = new SDP(cobbled);
  11403. }
  11404. // then add things like ice and dtls from remote candidate
  11405. elem.each(function () {
  11406. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11407. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11408. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11409. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11410. var tmp = $(this).find('transport');
  11411. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11412. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11413. tmp = $(this).find('transport>fingerprint');
  11414. if (tmp.length) {
  11415. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11416. } else {
  11417. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11418. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11419. }
  11420. break;
  11421. }
  11422. }
  11423. }
  11424. });
  11425. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11426. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11427. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11428. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11429. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11430. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11431. }).length == this.remoteSDP.media.length;
  11432. if (iscomplete) {
  11433. console.log('setting pranswer');
  11434. try {
  11435. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11436. function() {
  11437. },
  11438. function(e) {
  11439. console.log('setRemoteDescription pranswer failed', e.toString());
  11440. });
  11441. } catch (e) {
  11442. console.error('setting pranswer failed', e);
  11443. }
  11444. } else {
  11445. //console.log('not yet setting pranswer');
  11446. }
  11447. }
  11448. // operate on each content element
  11449. elem.each(function () {
  11450. // would love to deactivate this, but firefox still requires it
  11451. var idx = -1;
  11452. var i;
  11453. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11454. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11455. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11456. idx = i;
  11457. break;
  11458. }
  11459. }
  11460. if (idx == -1) { // fall back to localdescription
  11461. for (i = 0; i < self.localSDP.media.length; i++) {
  11462. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11463. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11464. idx = i;
  11465. break;
  11466. }
  11467. }
  11468. }
  11469. var name = $(this).attr('name');
  11470. // TODO: check ice-pwd and ice-ufrag?
  11471. $(this).find('transport>candidate').each(function () {
  11472. var line, candidate;
  11473. line = SDPUtil.candidateFromJingle(this);
  11474. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11475. sdpMid: name,
  11476. candidate: line});
  11477. try {
  11478. self.peerconnection.addIceCandidate(candidate);
  11479. } catch (e) {
  11480. console.error('addIceCandidate failed', e.toString(), line);
  11481. }
  11482. });
  11483. });
  11484. };
  11485. JingleSession.prototype.sendAnswer = function (provisional) {
  11486. //console.log('createAnswer', provisional);
  11487. var self = this;
  11488. this.peerconnection.createAnswer(
  11489. function (sdp) {
  11490. self.createdAnswer(sdp, provisional);
  11491. },
  11492. function (e) {
  11493. console.error('createAnswer failed', e);
  11494. },
  11495. this.media_constraints
  11496. );
  11497. };
  11498. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11499. //console.log('createAnswer callback');
  11500. var self = this;
  11501. this.localSDP = new SDP(sdp.sdp);
  11502. //this.localSDP.mangle();
  11503. this.usepranswer = provisional === true;
  11504. if (this.usetrickle) {
  11505. if (this.usepranswer) {
  11506. sdp.type = 'pranswer';
  11507. for (var i = 0; i < this.localSDP.media.length; i++) {
  11508. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11509. }
  11510. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11511. }
  11512. }
  11513. var self = this;
  11514. var sendJingle = function (ssrcs) {
  11515. var accept = $iq({to: self.peerjid,
  11516. type: 'set'})
  11517. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11518. action: 'session-accept',
  11519. initiator: self.initiator,
  11520. responder: self.responder,
  11521. sid: self.sid });
  11522. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11523. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11524. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11525. self.connection.sendIQ(accept,
  11526. function () {
  11527. var ack = {};
  11528. ack.source = 'answer';
  11529. $(document).trigger('ack.jingle', [self.sid, ack]);
  11530. },
  11531. function (stanza) {
  11532. var error = ($(stanza).find('error').length) ? {
  11533. code: $(stanza).find('error').attr('code'),
  11534. reason: $(stanza).find('error :first')[0].tagName,
  11535. }:{};
  11536. error.source = 'answer';
  11537. JingleSession.onJingleError(self.sid, error);
  11538. },
  11539. 10000);
  11540. }
  11541. sdp.sdp = this.localSDP.raw;
  11542. this.peerconnection.setLocalDescription(sdp,
  11543. function () {
  11544. //console.log('setLocalDescription success');
  11545. if (self.usetrickle && !self.usepranswer) {
  11546. sendJingle();
  11547. }
  11548. self.setLocalDescription();
  11549. },
  11550. function (e) {
  11551. console.error('setLocalDescription failed', e);
  11552. }
  11553. );
  11554. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11555. for (var j = 0; j < cands.length; j++) {
  11556. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11557. if (cand.type == 'srflx') {
  11558. this.hadstuncandidate = true;
  11559. } else if (cand.type == 'relay') {
  11560. this.hadturncandidate = true;
  11561. }
  11562. }
  11563. };
  11564. JingleSession.prototype.sendTerminate = function (reason, text) {
  11565. var self = this,
  11566. term = $iq({to: this.peerjid,
  11567. type: 'set'})
  11568. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11569. action: 'session-terminate',
  11570. initiator: this.initiator,
  11571. sid: this.sid})
  11572. .c('reason')
  11573. .c(reason || 'success');
  11574. if (text) {
  11575. term.up().c('text').t(text);
  11576. }
  11577. this.connection.sendIQ(term,
  11578. function () {
  11579. self.peerconnection.close();
  11580. self.peerconnection = null;
  11581. self.terminate();
  11582. var ack = {};
  11583. ack.source = 'terminate';
  11584. $(document).trigger('ack.jingle', [self.sid, ack]);
  11585. },
  11586. function (stanza) {
  11587. var error = ($(stanza).find('error').length) ? {
  11588. code: $(stanza).find('error').attr('code'),
  11589. reason: $(stanza).find('error :first')[0].tagName,
  11590. }:{};
  11591. $(document).trigger('ack.jingle', [self.sid, error]);
  11592. },
  11593. 10000);
  11594. if (this.statsinterval !== null) {
  11595. window.clearInterval(this.statsinterval);
  11596. this.statsinterval = null;
  11597. }
  11598. };
  11599. JingleSession.prototype.addSource = function (elem, fromJid) {
  11600. var self = this;
  11601. // FIXME: dirty waiting
  11602. if (!this.peerconnection.localDescription)
  11603. {
  11604. console.warn("addSource - localDescription not ready yet")
  11605. setTimeout(function()
  11606. {
  11607. self.addSource(elem, fromJid);
  11608. },
  11609. 200
  11610. );
  11611. return;
  11612. }
  11613. console.log('addssrc', new Date().getTime());
  11614. console.log('ice', this.peerconnection.iceConnectionState);
  11615. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11616. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11617. $(elem).each(function (idx, content) {
  11618. var name = $(content).attr('name');
  11619. var lines = '';
  11620. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11621. var semantics = this.getAttribute('semantics');
  11622. var ssrcs = $(this).find('>source').map(function () {
  11623. return this.getAttribute('ssrc');
  11624. }).get();
  11625. if (ssrcs.length != 0) {
  11626. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11627. }
  11628. });
  11629. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11630. tmp.each(function () {
  11631. var ssrc = $(this).attr('ssrc');
  11632. if(mySdp.containsSSRC(ssrc)){
  11633. /**
  11634. * This happens when multiple participants change their streams at the same time and
  11635. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11636. * addssrc are scheduled for update IQ. See
  11637. */
  11638. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11639. return;
  11640. }
  11641. $(this).find('>parameter').each(function () {
  11642. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11643. if ($(this).attr('value') && $(this).attr('value').length)
  11644. lines += ':' + $(this).attr('value');
  11645. lines += '\r\n';
  11646. });
  11647. });
  11648. sdp.media.forEach(function(media, idx) {
  11649. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11650. return;
  11651. sdp.media[idx] += lines;
  11652. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11653. self.addssrc[idx] += lines;
  11654. });
  11655. sdp.raw = sdp.session + sdp.media.join('');
  11656. });
  11657. this.modifySourcesQueue.push(function() {
  11658. // When a source is added and if this is FF, a new channel is allocated
  11659. // for receiving the added source. We need to diffuse the SSRC of this
  11660. // new recvonly channel to the rest of the peers.
  11661. console.log('modify sources done');
  11662. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11663. console.log("SDPs", mySdp, newSdp);
  11664. self.notifyMySSRCUpdate(mySdp, newSdp);
  11665. });
  11666. };
  11667. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11668. var self = this;
  11669. // FIXME: dirty waiting
  11670. if (!this.peerconnection.localDescription)
  11671. {
  11672. console.warn("removeSource - localDescription not ready yet")
  11673. setTimeout(function()
  11674. {
  11675. self.removeSource(elem, fromJid);
  11676. },
  11677. 200
  11678. );
  11679. return;
  11680. }
  11681. console.log('removessrc', new Date().getTime());
  11682. console.log('ice', this.peerconnection.iceConnectionState);
  11683. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11684. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11685. $(elem).each(function (idx, content) {
  11686. var name = $(content).attr('name');
  11687. var lines = '';
  11688. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11689. var semantics = this.getAttribute('semantics');
  11690. var ssrcs = $(this).find('>source').map(function () {
  11691. return this.getAttribute('ssrc');
  11692. }).get();
  11693. if (ssrcs.length != 0) {
  11694. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11695. }
  11696. });
  11697. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11698. tmp.each(function () {
  11699. var ssrc = $(this).attr('ssrc');
  11700. // This should never happen, but can be useful for bug detection
  11701. if(mySdp.containsSSRC(ssrc)){
  11702. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11703. return;
  11704. }
  11705. $(this).find('>parameter').each(function () {
  11706. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11707. if ($(this).attr('value') && $(this).attr('value').length)
  11708. lines += ':' + $(this).attr('value');
  11709. lines += '\r\n';
  11710. });
  11711. });
  11712. sdp.media.forEach(function(media, idx) {
  11713. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11714. return;
  11715. sdp.media[idx] += lines;
  11716. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11717. self.removessrc[idx] += lines;
  11718. });
  11719. sdp.raw = sdp.session + sdp.media.join('');
  11720. });
  11721. this.modifySourcesQueue.push(function() {
  11722. // When a source is removed and if this is FF, the recvonly channel that
  11723. // receives the remote stream is deactivated . We need to diffuse the
  11724. // recvonly SSRC removal to the rest of the peers.
  11725. console.log('modify sources done');
  11726. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11727. console.log("SDPs", mySdp, newSdp);
  11728. self.notifyMySSRCUpdate(mySdp, newSdp);
  11729. });
  11730. };
  11731. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  11732. var self = this;
  11733. if (this.peerconnection.signalingState == 'closed') return;
  11734. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11735. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11736. this.setLocalDescription();
  11737. if(successCallback){
  11738. successCallback();
  11739. }
  11740. queueCallback();
  11741. return;
  11742. }
  11743. // Reset switch streams flag
  11744. this.switchstreams = false;
  11745. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11746. // add sources
  11747. this.addssrc.forEach(function(lines, idx) {
  11748. sdp.media[idx] += lines;
  11749. });
  11750. this.addssrc = [];
  11751. // remove sources
  11752. this.removessrc.forEach(function(lines, idx) {
  11753. lines = lines.split('\r\n');
  11754. lines.pop(); // remove empty last element;
  11755. lines.forEach(function(line) {
  11756. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11757. });
  11758. });
  11759. this.removessrc = [];
  11760. // FIXME:
  11761. // this was a hack for the situation when only one peer exists
  11762. // in the conference.
  11763. // check if still required and remove
  11764. if (sdp.media[0])
  11765. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11766. if (sdp.media[1])
  11767. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11768. sdp.raw = sdp.session + sdp.media.join('');
  11769. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11770. function() {
  11771. if(self.signalingState == 'closed') {
  11772. console.error("createAnswer attempt on closed state");
  11773. queueCallback("createAnswer attempt on closed state");
  11774. return;
  11775. }
  11776. self.peerconnection.createAnswer(
  11777. function(modifiedAnswer) {
  11778. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11779. if (self.pendingop !== null) {
  11780. var sdp = new SDP(modifiedAnswer.sdp);
  11781. if (sdp.media.length > 1) {
  11782. switch(self.pendingop) {
  11783. case 'mute':
  11784. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11785. break;
  11786. case 'unmute':
  11787. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11788. break;
  11789. }
  11790. sdp.raw = sdp.session + sdp.media.join('');
  11791. modifiedAnswer.sdp = sdp.raw;
  11792. }
  11793. self.pendingop = null;
  11794. }
  11795. // FIXME: pushing down an answer while ice connection state
  11796. // is still checking is bad...
  11797. //console.log(self.peerconnection.iceConnectionState);
  11798. // trying to work around another chrome bug
  11799. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11800. self.peerconnection.setLocalDescription(modifiedAnswer,
  11801. function() {
  11802. //console.log('modified setLocalDescription ok');
  11803. self.setLocalDescription();
  11804. if(successCallback){
  11805. successCallback();
  11806. }
  11807. queueCallback();
  11808. },
  11809. function(error) {
  11810. console.error('modified setLocalDescription failed', error);
  11811. queueCallback(error);
  11812. }
  11813. );
  11814. },
  11815. function(error) {
  11816. console.error('modified answer failed', error);
  11817. queueCallback(error);
  11818. }
  11819. );
  11820. },
  11821. function(error) {
  11822. console.error('modify failed', error);
  11823. queueCallback(error);
  11824. }
  11825. );
  11826. };
  11827. /**
  11828. * Switches video streams.
  11829. * @param new_stream new stream that will be used as video of this session.
  11830. * @param oldStream old video stream of this session.
  11831. * @param success_callback callback executed after successful stream switch.
  11832. */
  11833. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  11834. var self = this;
  11835. // Remember SDP to figure out added/removed SSRCs
  11836. var oldSdp = null;
  11837. if(self.peerconnection) {
  11838. if(self.peerconnection.localDescription) {
  11839. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11840. }
  11841. self.peerconnection.removeStream(oldStream, true);
  11842. if(new_stream)
  11843. self.peerconnection.addStream(new_stream);
  11844. }
  11845. if(!isAudio)
  11846. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11847. // Conference is not active
  11848. if(!oldSdp || !self.peerconnection) {
  11849. success_callback();
  11850. return;
  11851. }
  11852. self.switchstreams = true;
  11853. self.modifySourcesQueue.push(function() {
  11854. console.log('modify sources done');
  11855. success_callback();
  11856. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11857. console.log("SDPs", oldSdp, newSdp);
  11858. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11859. });
  11860. };
  11861. /**
  11862. * Figures out added/removed ssrcs and send update IQs.
  11863. * @param old_sdp SDP object for old description.
  11864. * @param new_sdp SDP object for new description.
  11865. */
  11866. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11867. if (!(this.peerconnection.signalingState == 'stable' &&
  11868. this.peerconnection.iceConnectionState == 'connected')){
  11869. console.log("Too early to send updates");
  11870. return;
  11871. }
  11872. // send source-remove IQ.
  11873. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11874. var remove = $iq({to: this.peerjid, type: 'set'})
  11875. .c('jingle', {
  11876. xmlns: 'urn:xmpp:jingle:1',
  11877. action: 'source-remove',
  11878. initiator: this.initiator,
  11879. sid: this.sid
  11880. }
  11881. );
  11882. var removed = sdpDiffer.toJingle(remove);
  11883. if (removed) {
  11884. this.connection.sendIQ(remove,
  11885. function (res) {
  11886. console.info('got remove result', res);
  11887. },
  11888. function (err) {
  11889. console.error('got remove error', err);
  11890. }
  11891. );
  11892. } else {
  11893. console.log('removal not necessary');
  11894. }
  11895. // send source-add IQ.
  11896. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11897. var add = $iq({to: this.peerjid, type: 'set'})
  11898. .c('jingle', {
  11899. xmlns: 'urn:xmpp:jingle:1',
  11900. action: 'source-add',
  11901. initiator: this.initiator,
  11902. sid: this.sid
  11903. }
  11904. );
  11905. var added = sdpDiffer.toJingle(add);
  11906. if (added) {
  11907. this.connection.sendIQ(add,
  11908. function (res) {
  11909. console.info('got add result', res);
  11910. },
  11911. function (err) {
  11912. console.error('got add error', err);
  11913. }
  11914. );
  11915. } else {
  11916. console.log('addition not necessary');
  11917. }
  11918. };
  11919. /**
  11920. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11921. *
  11922. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11923. * tracks; otherwise, <tt>false</tt>
  11924. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11925. * tracks have been enabled/disabled. The function may, optionally, return
  11926. * another function which is to be invoked after the whole mute/unmute operation
  11927. * has completed successfully.
  11928. * @param options an object which specifies optional arguments such as the
  11929. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11930. * specifies whether the method was initiated in response to a user command (in
  11931. * contrast to an automatic decision made by the application logic)
  11932. */
  11933. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11934. var byUser;
  11935. if (options) {
  11936. byUser = options.byUser;
  11937. if (typeof byUser === 'undefined') {
  11938. byUser = true;
  11939. }
  11940. } else {
  11941. byUser = true;
  11942. }
  11943. // The user's command to mute the (local) video takes precedence over any
  11944. // automatic decision made by the application logic.
  11945. if (byUser) {
  11946. this.videoMuteByUser = mute;
  11947. } else if (this.videoMuteByUser) {
  11948. return;
  11949. }
  11950. this.hardMuteVideo(mute);
  11951. var self = this;
  11952. var oldSdp = null;
  11953. if(self.peerconnection) {
  11954. if(self.peerconnection.localDescription) {
  11955. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11956. }
  11957. }
  11958. this.modifySourcesQueue.push(function() {
  11959. console.log('modify sources done');
  11960. callback(mute);
  11961. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11962. console.log("SDPs", oldSdp, newSdp);
  11963. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11964. });
  11965. };
  11966. JingleSession.prototype.hardMuteVideo = function (muted) {
  11967. this.pendingop = muted ? 'mute' : 'unmute';
  11968. };
  11969. JingleSession.prototype.sendMute = function (muted, content) {
  11970. var info = $iq({to: this.peerjid,
  11971. type: 'set'})
  11972. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11973. action: 'session-info',
  11974. initiator: this.initiator,
  11975. sid: this.sid });
  11976. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11977. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11978. if (content) {
  11979. info.attrs({'name': content});
  11980. }
  11981. this.connection.send(info);
  11982. };
  11983. JingleSession.prototype.sendRinging = function () {
  11984. var info = $iq({to: this.peerjid,
  11985. type: 'set'})
  11986. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11987. action: 'session-info',
  11988. initiator: this.initiator,
  11989. sid: this.sid });
  11990. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11991. this.connection.send(info);
  11992. };
  11993. JingleSession.prototype.getStats = function (interval) {
  11994. var self = this;
  11995. var recv = {audio: 0, video: 0};
  11996. var lost = {audio: 0, video: 0};
  11997. var lastrecv = {audio: 0, video: 0};
  11998. var lastlost = {audio: 0, video: 0};
  11999. var loss = {audio: 0, video: 0};
  12000. var delta = {audio: 0, video: 0};
  12001. this.statsinterval = window.setInterval(function () {
  12002. if (self && self.peerconnection && self.peerconnection.getStats) {
  12003. self.peerconnection.getStats(function (stats) {
  12004. var results = stats.result();
  12005. // TODO: there are so much statistics you can get from this..
  12006. for (var i = 0; i < results.length; ++i) {
  12007. if (results[i].type == 'ssrc') {
  12008. var packetsrecv = results[i].stat('packetsReceived');
  12009. var packetslost = results[i].stat('packetsLost');
  12010. if (packetsrecv && packetslost) {
  12011. packetsrecv = parseInt(packetsrecv, 10);
  12012. packetslost = parseInt(packetslost, 10);
  12013. if (results[i].stat('googFrameRateReceived')) {
  12014. lastlost.video = lost.video;
  12015. lastrecv.video = recv.video;
  12016. recv.video = packetsrecv;
  12017. lost.video = packetslost;
  12018. } else {
  12019. lastlost.audio = lost.audio;
  12020. lastrecv.audio = recv.audio;
  12021. recv.audio = packetsrecv;
  12022. lost.audio = packetslost;
  12023. }
  12024. }
  12025. }
  12026. }
  12027. delta.audio = recv.audio - lastrecv.audio;
  12028. delta.video = recv.video - lastrecv.video;
  12029. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12030. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12031. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12032. });
  12033. }
  12034. }, interval || 3000);
  12035. return this.statsinterval;
  12036. };
  12037. JingleSession.onJingleError = function (session, error)
  12038. {
  12039. console.error("Jingle error", error);
  12040. }
  12041. JingleSession.onJingleFatalError = function (session, error)
  12042. {
  12043. this.service.sessionTerminated = true;
  12044. this.connection.emuc.doLeave();
  12045. APP.UI.messageHandler.showError("dialog.sorry",
  12046. "dialog.internalError");
  12047. }
  12048. JingleSession.prototype.setLocalDescription = function () {
  12049. // put our ssrcs into presence so other clients can identify our stream
  12050. var newssrcs = [];
  12051. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  12052. media.forEach(function (media) {
  12053. if(Object.keys(media.sources).length > 0) {
  12054. // TODO(gp) maybe exclude FID streams?
  12055. Object.keys(media.sources).forEach(function (ssrc) {
  12056. newssrcs.push({
  12057. 'ssrc': ssrc,
  12058. 'type': media.type,
  12059. 'direction': media.direction
  12060. });
  12061. });
  12062. }
  12063. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  12064. {
  12065. newssrcs.push({
  12066. 'ssrc': this.localStreamsSSRC[media.type],
  12067. 'type': media.type,
  12068. 'direction': media.direction
  12069. });
  12070. }
  12071. });
  12072. console.log('new ssrcs', newssrcs);
  12073. // Have to clear presence map to get rid of removed streams
  12074. this.connection.emuc.clearPresenceMedia();
  12075. if (newssrcs.length > 0) {
  12076. for (var i = 1; i <= newssrcs.length; i ++) {
  12077. // Change video type to screen
  12078. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  12079. newssrcs[i-1].type = 'screen';
  12080. }
  12081. this.connection.emuc.addMediaToPresence(i,
  12082. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  12083. }
  12084. this.connection.emuc.sendPresence();
  12085. }
  12086. }
  12087. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12088. function sendKeyframe(pc) {
  12089. console.log('sendkeyframe', pc.iceConnectionState);
  12090. if (pc.iceConnectionState !== 'connected') return; // safe...
  12091. pc.setRemoteDescription(
  12092. pc.remoteDescription,
  12093. function () {
  12094. pc.createAnswer(
  12095. function (modifiedAnswer) {
  12096. pc.setLocalDescription(
  12097. modifiedAnswer,
  12098. function () {
  12099. // noop
  12100. },
  12101. function (error) {
  12102. console.log('triggerKeyframe setLocalDescription failed', error);
  12103. APP.UI.messageHandler.showError();
  12104. }
  12105. );
  12106. },
  12107. function (error) {
  12108. console.log('triggerKeyframe createAnswer failed', error);
  12109. APP.UI.messageHandler.showError();
  12110. }
  12111. );
  12112. },
  12113. function (error) {
  12114. console.log('triggerKeyframe setRemoteDescription failed', error);
  12115. APP.UI.messageHandler.showError();
  12116. }
  12117. );
  12118. }
  12119. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12120. var self = this;
  12121. var thessrc;
  12122. var ssrc2jid = this.connection.emuc.ssrc2jid;
  12123. // look up an associated JID for a stream id
  12124. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  12125. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12126. var ssrclines
  12127. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12128. ssrclines = ssrclines.filter(function (line) {
  12129. // NOTE(gp) previously we filtered on the mslabel, but that property
  12130. // is not always present.
  12131. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12132. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  12133. });
  12134. if (ssrclines.length) {
  12135. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12136. // We signal our streams (through Jingle to the focus) before we set
  12137. // our presence (through which peers associate remote streams to
  12138. // jids). So, it might arrive that a remote stream is added but
  12139. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  12140. // successfully set. Here we wait for up to a second for the
  12141. // presence to arrive.
  12142. if (!ssrc2jid[thessrc]) {
  12143. if (typeof times === 'undefined')
  12144. {
  12145. times = 0;
  12146. }
  12147. if (times > 10)
  12148. {
  12149. console.warning('Waiting for jid timed out', thessrc);
  12150. }
  12151. else
  12152. {
  12153. setTimeout(function(d) {
  12154. return function() {
  12155. self.remoteStreamAdded(d, times++);
  12156. }
  12157. }(data), 250);
  12158. }
  12159. return;
  12160. }
  12161. // ok to overwrite the one from focus? might save work in colibri.js
  12162. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  12163. if (ssrc2jid[thessrc]) {
  12164. data.peerjid = ssrc2jid[thessrc];
  12165. }
  12166. }
  12167. }
  12168. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12169. var isVideo = data.stream.getVideoTracks().length > 0;
  12170. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12171. if (isVideo &&
  12172. data.peerjid && this.peerjid === data.peerjid &&
  12173. data.stream.getVideoTracks().length === 0 &&
  12174. APP.RTC.localVideo.getTracks().length > 0) {
  12175. window.setTimeout(function () {
  12176. sendKeyframe(self.peerconnection);
  12177. }, 3000);
  12178. }
  12179. }
  12180. module.exports = JingleSession;
  12181. },{"../../service/RTC/RTCBrowserType":95,"./SDP":50,"./SDPDiffer":51,"./SDPUtil":52,"./TraceablePeerConnection":53,"async":63}],50:[function(require,module,exports){
  12182. /* jshint -W117 */
  12183. var SDPUtil = require("./SDPUtil");
  12184. // SDP STUFF
  12185. function SDP(sdp) {
  12186. this.media = sdp.split('\r\nm=');
  12187. for (var i = 1; i < this.media.length; i++) {
  12188. this.media[i] = 'm=' + this.media[i];
  12189. if (i != this.media.length - 1) {
  12190. this.media[i] += '\r\n';
  12191. }
  12192. }
  12193. this.session = this.media.shift() + '\r\n';
  12194. this.raw = this.session + this.media.join('');
  12195. }
  12196. /**
  12197. * Returns map of MediaChannel mapped per channel idx.
  12198. */
  12199. SDP.prototype.getMediaSsrcMap = function() {
  12200. var self = this;
  12201. var media_ssrcs = {};
  12202. var tmp;
  12203. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12204. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12205. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12206. var media = {
  12207. mediaindex: mediaindex,
  12208. mid: mid,
  12209. ssrcs: {},
  12210. ssrcGroups: []
  12211. };
  12212. media_ssrcs[mediaindex] = media;
  12213. tmp.forEach(function (line) {
  12214. var linessrc = line.substring(7).split(' ')[0];
  12215. // allocate new ChannelSsrc
  12216. if(!media.ssrcs[linessrc]) {
  12217. media.ssrcs[linessrc] = {
  12218. ssrc: linessrc,
  12219. lines: []
  12220. };
  12221. }
  12222. media.ssrcs[linessrc].lines.push(line);
  12223. });
  12224. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12225. tmp.forEach(function(line){
  12226. var semantics = line.substr(0, idx).substr(13);
  12227. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12228. if (ssrcs.length != 0) {
  12229. media.ssrcGroups.push({
  12230. semantics: semantics,
  12231. ssrcs: ssrcs
  12232. });
  12233. }
  12234. });
  12235. }
  12236. return media_ssrcs;
  12237. };
  12238. /**
  12239. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12240. * @param ssrc the ssrc to check.
  12241. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12242. */
  12243. SDP.prototype.containsSSRC = function(ssrc) {
  12244. var medias = this.getMediaSsrcMap();
  12245. var contains = false;
  12246. Object.keys(medias).forEach(function(mediaindex){
  12247. var media = medias[mediaindex];
  12248. //console.log("Check", channel, ssrc);
  12249. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12250. contains = true;
  12251. }
  12252. });
  12253. return contains;
  12254. };
  12255. // remove iSAC and CN from SDP
  12256. SDP.prototype.mangle = function () {
  12257. var i, j, mline, lines, rtpmap, newdesc;
  12258. for (i = 0; i < this.media.length; i++) {
  12259. lines = this.media[i].split('\r\n');
  12260. lines.pop(); // remove empty last element
  12261. mline = SDPUtil.parse_mline(lines.shift());
  12262. if (mline.media != 'audio')
  12263. continue;
  12264. newdesc = '';
  12265. mline.fmt.length = 0;
  12266. for (j = 0; j < lines.length; j++) {
  12267. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12268. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12269. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12270. continue;
  12271. mline.fmt.push(rtpmap.id);
  12272. newdesc += lines[j] + '\r\n';
  12273. } else {
  12274. newdesc += lines[j] + '\r\n';
  12275. }
  12276. }
  12277. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12278. this.media[i] += newdesc;
  12279. }
  12280. this.raw = this.session + this.media.join('');
  12281. };
  12282. // remove lines matching prefix from session section
  12283. SDP.prototype.removeSessionLines = function(prefix) {
  12284. var self = this;
  12285. var lines = SDPUtil.find_lines(this.session, prefix);
  12286. lines.forEach(function(line) {
  12287. self.session = self.session.replace(line + '\r\n', '');
  12288. });
  12289. this.raw = this.session + this.media.join('');
  12290. return lines;
  12291. }
  12292. // remove lines matching prefix from a media section specified by mediaindex
  12293. // TODO: non-numeric mediaindex could match mid
  12294. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12295. var self = this;
  12296. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12297. lines.forEach(function(line) {
  12298. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12299. });
  12300. this.raw = this.session + this.media.join('');
  12301. return lines;
  12302. }
  12303. // add content's to a jingle element
  12304. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  12305. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12306. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12307. var self = this;
  12308. // new bundle plan
  12309. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12310. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12311. for (i = 0; i < lines.length; i++) {
  12312. tmp = lines[i].split(' ');
  12313. var semantics = tmp.shift().substr(8);
  12314. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12315. for (j = 0; j < tmp.length; j++) {
  12316. elem.c('content', {name: tmp[j]}).up();
  12317. }
  12318. elem.up();
  12319. }
  12320. }
  12321. for (i = 0; i < this.media.length; i++) {
  12322. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12323. if (!(mline.media === 'audio' ||
  12324. mline.media === 'video' ||
  12325. mline.media === 'application'))
  12326. {
  12327. continue;
  12328. }
  12329. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12330. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12331. } else {
  12332. if(ssrcs && ssrcs[mline.media])
  12333. {
  12334. ssrc = ssrcs[mline.media];
  12335. }
  12336. else
  12337. ssrc = false;
  12338. }
  12339. elem.c('content', {creator: thecreator, name: mline.media});
  12340. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12341. // prefer identifier from a=mid if present
  12342. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12343. elem.attrs({ name: mid });
  12344. }
  12345. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12346. {
  12347. elem.c('description',
  12348. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12349. media: mline.media });
  12350. if (ssrc) {
  12351. elem.attrs({ssrc: ssrc});
  12352. }
  12353. for (j = 0; j < mline.fmt.length; j++) {
  12354. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12355. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12356. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12357. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12358. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12359. for (k = 0; k < tmp.length; k++) {
  12360. elem.c('parameter', tmp[k]).up();
  12361. }
  12362. }
  12363. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12364. elem.up();
  12365. }
  12366. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12367. elem.c('encryption', {required: 1});
  12368. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12369. crypto.forEach(function(line) {
  12370. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12371. });
  12372. elem.up(); // end of encryption
  12373. }
  12374. if (ssrc) {
  12375. // new style mapping
  12376. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12377. // FIXME: group by ssrc and support multiple different ssrcs
  12378. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12379. if(ssrclines.length > 0) {
  12380. ssrclines.forEach(function (line) {
  12381. idx = line.indexOf(' ');
  12382. var linessrc = line.substr(0, idx).substr(7);
  12383. if (linessrc != ssrc) {
  12384. elem.up();
  12385. ssrc = linessrc;
  12386. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12387. }
  12388. var kv = line.substr(idx + 1);
  12389. elem.c('parameter');
  12390. if (kv.indexOf(':') == -1) {
  12391. elem.attrs({ name: kv });
  12392. } else {
  12393. elem.attrs({ name: kv.split(':', 2)[0] });
  12394. elem.attrs({ value: kv.split(':', 2)[1] });
  12395. }
  12396. elem.up();
  12397. });
  12398. elem.up();
  12399. }
  12400. else
  12401. {
  12402. elem.up();
  12403. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12404. elem.c('parameter');
  12405. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12406. elem.up();
  12407. var msid = null;
  12408. if(mline.media == "audio")
  12409. {
  12410. msid = APP.RTC.localAudio.getId();
  12411. }
  12412. else
  12413. {
  12414. msid = APP.RTC.localVideo.getId();
  12415. }
  12416. if(msid != null)
  12417. {
  12418. msid = msid.replace(/[\{,\}]/g,"");
  12419. elem.c('parameter');
  12420. elem.attrs({name: "msid", value:msid});
  12421. elem.up();
  12422. elem.c('parameter');
  12423. elem.attrs({name: "mslabel", value:msid});
  12424. elem.up();
  12425. elem.c('parameter');
  12426. elem.attrs({name: "label", value:msid});
  12427. elem.up();
  12428. elem.up();
  12429. }
  12430. }
  12431. // XEP-0339 handle ssrc-group attributes
  12432. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12433. ssrc_group_lines.forEach(function(line) {
  12434. idx = line.indexOf(' ');
  12435. var semantics = line.substr(0, idx).substr(13);
  12436. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12437. if (ssrcs.length != 0) {
  12438. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12439. ssrcs.forEach(function(ssrc) {
  12440. elem.c('source', { ssrc: ssrc })
  12441. .up();
  12442. });
  12443. elem.up();
  12444. }
  12445. });
  12446. }
  12447. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12448. elem.c('rtcp-mux').up();
  12449. }
  12450. // XEP-0293 -- map a=rtcp-fb:*
  12451. this.RtcpFbToJingle(i, elem, '*');
  12452. // XEP-0294
  12453. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12454. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12455. for (j = 0; j < lines.length; j++) {
  12456. tmp = SDPUtil.parse_extmap(lines[j]);
  12457. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12458. uri: tmp.uri,
  12459. id: tmp.value });
  12460. if (tmp.hasOwnProperty('direction')) {
  12461. switch (tmp.direction) {
  12462. case 'sendonly':
  12463. elem.attrs({senders: 'responder'});
  12464. break;
  12465. case 'recvonly':
  12466. elem.attrs({senders: 'initiator'});
  12467. break;
  12468. case 'sendrecv':
  12469. elem.attrs({senders: 'both'});
  12470. break;
  12471. case 'inactive':
  12472. elem.attrs({senders: 'none'});
  12473. break;
  12474. }
  12475. }
  12476. // TODO: handle params
  12477. elem.up();
  12478. }
  12479. }
  12480. elem.up(); // end of description
  12481. }
  12482. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12483. this.TransportToJingle(i, elem);
  12484. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12485. elem.attrs({senders: 'both'});
  12486. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12487. elem.attrs({senders: 'initiator'});
  12488. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12489. elem.attrs({senders: 'responder'});
  12490. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12491. elem.attrs({senders: 'none'});
  12492. }
  12493. if (mline.port == '0') {
  12494. // estos hack to reject an m-line
  12495. elem.attrs({senders: 'rejected'});
  12496. }
  12497. elem.up(); // end of content
  12498. }
  12499. elem.up();
  12500. return elem;
  12501. };
  12502. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12503. var i = mediaindex;
  12504. var tmp;
  12505. var self = this;
  12506. elem.c('transport');
  12507. // XEP-0343 DTLS/SCTP
  12508. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12509. {
  12510. var sctpmap = SDPUtil.find_line(
  12511. this.media[i], 'a=sctpmap:', self.session);
  12512. if (sctpmap)
  12513. {
  12514. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12515. elem.c('sctpmap',
  12516. {
  12517. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12518. number: sctpAttrs[0], /* SCTP port */
  12519. protocol: sctpAttrs[1], /* protocol */
  12520. });
  12521. // Optional stream count attribute
  12522. if (sctpAttrs.length > 2)
  12523. elem.attrs({ streams: sctpAttrs[2]});
  12524. elem.up();
  12525. }
  12526. }
  12527. // XEP-0320
  12528. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12529. fingerprints.forEach(function(line) {
  12530. tmp = SDPUtil.parse_fingerprint(line);
  12531. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12532. elem.c('fingerprint').t(tmp.fingerprint);
  12533. delete tmp.fingerprint;
  12534. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12535. if (line) {
  12536. tmp.setup = line.substr(8);
  12537. }
  12538. elem.attrs(tmp);
  12539. elem.up(); // end of fingerprint
  12540. });
  12541. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12542. if (tmp) {
  12543. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12544. elem.attrs(tmp);
  12545. // XEP-0176
  12546. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12547. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12548. lines.forEach(function (line) {
  12549. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12550. });
  12551. }
  12552. }
  12553. elem.up(); // end of transport
  12554. }
  12555. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12556. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12557. lines.forEach(function (line) {
  12558. var tmp = SDPUtil.parse_rtcpfb(line);
  12559. if (tmp.type == 'trr-int') {
  12560. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12561. elem.up();
  12562. } else {
  12563. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12564. if (tmp.params.length > 0) {
  12565. elem.attrs({'subtype': tmp.params[0]});
  12566. }
  12567. elem.up();
  12568. }
  12569. });
  12570. };
  12571. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12572. var media = '';
  12573. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12574. if (tmp.length) {
  12575. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12576. if (tmp.attr('value')) {
  12577. media += tmp.attr('value');
  12578. } else {
  12579. media += '0';
  12580. }
  12581. media += '\r\n';
  12582. }
  12583. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12584. tmp.each(function () {
  12585. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12586. if ($(this).attr('subtype')) {
  12587. media += ' ' + $(this).attr('subtype');
  12588. }
  12589. media += '\r\n';
  12590. });
  12591. return media;
  12592. };
  12593. // construct an SDP from a jingle stanza
  12594. SDP.prototype.fromJingle = function (jingle) {
  12595. var self = this;
  12596. this.raw = 'v=0\r\n' +
  12597. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12598. 's=-\r\n' +
  12599. 't=0 0\r\n';
  12600. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12601. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12602. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12603. var contents = $(group).find('>content').map(function (idx, content) {
  12604. return content.getAttribute('name');
  12605. }).get();
  12606. if (contents.length > 0) {
  12607. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12608. }
  12609. });
  12610. }
  12611. this.session = this.raw;
  12612. jingle.find('>content').each(function () {
  12613. var m = self.jingle2media($(this));
  12614. self.media.push(m);
  12615. });
  12616. // reconstruct msid-semantic -- apparently not necessary
  12617. /*
  12618. var msid = SDPUtil.parse_ssrc(this.raw);
  12619. if (msid.hasOwnProperty('mslabel')) {
  12620. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12621. }
  12622. */
  12623. this.raw = this.session + this.media.join('');
  12624. };
  12625. // translate a jingle content element into an an SDP media part
  12626. SDP.prototype.jingle2media = function (content) {
  12627. var media = '',
  12628. desc = content.find('description'),
  12629. ssrc = desc.attr('ssrc'),
  12630. self = this,
  12631. tmp;
  12632. var sctp = content.find(
  12633. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12634. tmp = { media: desc.attr('media') };
  12635. tmp.port = '1';
  12636. if (content.attr('senders') == 'rejected') {
  12637. // estos hack to reject an m-line.
  12638. tmp.port = '0';
  12639. }
  12640. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12641. if (sctp.length)
  12642. tmp.proto = 'DTLS/SCTP';
  12643. else
  12644. tmp.proto = 'RTP/SAVPF';
  12645. } else {
  12646. tmp.proto = 'RTP/AVPF';
  12647. }
  12648. if (!sctp.length)
  12649. {
  12650. tmp.fmt = desc.find('payload-type').map(
  12651. function () { return this.getAttribute('id'); }).get();
  12652. media += SDPUtil.build_mline(tmp) + '\r\n';
  12653. }
  12654. else
  12655. {
  12656. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12657. media += 'a=sctpmap:' + sctp.attr('number') +
  12658. ' ' + sctp.attr('protocol');
  12659. var streamCount = sctp.attr('streams');
  12660. if (streamCount)
  12661. media += ' ' + streamCount + '\r\n';
  12662. else
  12663. media += '\r\n';
  12664. }
  12665. media += 'c=IN IP4 0.0.0.0\r\n';
  12666. if (!sctp.length)
  12667. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12668. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12669. if (tmp.length) {
  12670. if (tmp.attr('ufrag')) {
  12671. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12672. }
  12673. if (tmp.attr('pwd')) {
  12674. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12675. }
  12676. tmp.find('>fingerprint').each(function () {
  12677. // FIXME: check namespace at some point
  12678. media += 'a=fingerprint:' + this.getAttribute('hash');
  12679. media += ' ' + $(this).text();
  12680. media += '\r\n';
  12681. if (this.getAttribute('setup')) {
  12682. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12683. }
  12684. });
  12685. }
  12686. switch (content.attr('senders')) {
  12687. case 'initiator':
  12688. media += 'a=sendonly\r\n';
  12689. break;
  12690. case 'responder':
  12691. media += 'a=recvonly\r\n';
  12692. break;
  12693. case 'none':
  12694. media += 'a=inactive\r\n';
  12695. break;
  12696. case 'both':
  12697. media += 'a=sendrecv\r\n';
  12698. break;
  12699. }
  12700. media += 'a=mid:' + content.attr('name') + '\r\n';
  12701. // <description><rtcp-mux/></description>
  12702. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12703. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12704. if (desc.find('rtcp-mux').length) {
  12705. media += 'a=rtcp-mux\r\n';
  12706. }
  12707. if (desc.find('encryption').length) {
  12708. desc.find('encryption>crypto').each(function () {
  12709. media += 'a=crypto:' + this.getAttribute('tag');
  12710. media += ' ' + this.getAttribute('crypto-suite');
  12711. media += ' ' + this.getAttribute('key-params');
  12712. if (this.getAttribute('session-params')) {
  12713. media += ' ' + this.getAttribute('session-params');
  12714. }
  12715. media += '\r\n';
  12716. });
  12717. }
  12718. desc.find('payload-type').each(function () {
  12719. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12720. if ($(this).find('>parameter').length) {
  12721. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12722. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12723. media += '\r\n';
  12724. }
  12725. // xep-0293
  12726. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12727. });
  12728. // xep-0293
  12729. media += self.RtcpFbFromJingle(desc, '*');
  12730. // xep-0294
  12731. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12732. tmp.each(function () {
  12733. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12734. });
  12735. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12736. media += SDPUtil.candidateFromJingle(this);
  12737. });
  12738. // XEP-0339 handle ssrc-group attributes
  12739. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12740. var semantics = this.getAttribute('semantics');
  12741. var ssrcs = $(this).find('>source').map(function() {
  12742. return this.getAttribute('ssrc');
  12743. }).get();
  12744. if (ssrcs.length != 0) {
  12745. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12746. }
  12747. });
  12748. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12749. tmp.each(function () {
  12750. var ssrc = this.getAttribute('ssrc');
  12751. $(this).find('>parameter').each(function () {
  12752. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12753. if (this.getAttribute('value') && this.getAttribute('value').length)
  12754. media += ':' + this.getAttribute('value');
  12755. media += '\r\n';
  12756. });
  12757. });
  12758. return media;
  12759. };
  12760. module.exports = SDP;
  12761. },{"./SDPUtil":52}],51:[function(require,module,exports){
  12762. function SDPDiffer(mySDP, otherSDP) {
  12763. this.mySDP = mySDP;
  12764. this.otherSDP = otherSDP;
  12765. }
  12766. /**
  12767. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12768. * @param otherSdp the other SDP to check ssrc with.
  12769. */
  12770. SDPDiffer.prototype.getNewMedia = function() {
  12771. // this could be useful in Array.prototype.
  12772. function arrayEquals(array) {
  12773. // if the other array is a falsy value, return
  12774. if (!array)
  12775. return false;
  12776. // compare lengths - can save a lot of time
  12777. if (this.length != array.length)
  12778. return false;
  12779. for (var i = 0, l=this.length; i < l; i++) {
  12780. // Check if we have nested arrays
  12781. if (this[i] instanceof Array && array[i] instanceof Array) {
  12782. // recurse into the nested arrays
  12783. if (!this[i].equals(array[i]))
  12784. return false;
  12785. }
  12786. else if (this[i] != array[i]) {
  12787. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12788. return false;
  12789. }
  12790. }
  12791. return true;
  12792. }
  12793. var myMedias = this.mySDP.getMediaSsrcMap();
  12794. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12795. var newMedia = {};
  12796. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12797. var myMedia = myMedias[othersMediaIdx];
  12798. var othersMedia = othersMedias[othersMediaIdx];
  12799. if(!myMedia && othersMedia) {
  12800. // Add whole channel
  12801. newMedia[othersMediaIdx] = othersMedia;
  12802. return;
  12803. }
  12804. // Look for new ssrcs accross the channel
  12805. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12806. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12807. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12808. if(!newMedia[othersMediaIdx]){
  12809. newMedia[othersMediaIdx] = {
  12810. mediaindex: othersMedia.mediaindex,
  12811. mid: othersMedia.mid,
  12812. ssrcs: {},
  12813. ssrcGroups: []
  12814. };
  12815. }
  12816. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12817. }
  12818. });
  12819. // Look for new ssrc groups across the channels
  12820. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12821. // try to match the other ssrc-group with an ssrc-group of ours
  12822. var matched = false;
  12823. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12824. var mySsrcGroup = myMedia.ssrcGroups[i];
  12825. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12826. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12827. matched = true;
  12828. break;
  12829. }
  12830. }
  12831. if (!matched) {
  12832. // Allocate channel if we've found an ssrc-group that doesn't
  12833. // exist in our channel
  12834. if(!newMedia[othersMediaIdx]){
  12835. newMedia[othersMediaIdx] = {
  12836. mediaindex: othersMedia.mediaindex,
  12837. mid: othersMedia.mid,
  12838. ssrcs: {},
  12839. ssrcGroups: []
  12840. };
  12841. }
  12842. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12843. }
  12844. });
  12845. });
  12846. return newMedia;
  12847. };
  12848. /**
  12849. * Sends SSRC update IQ.
  12850. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12851. * @param sid session identifier that will be put into the IQ.
  12852. * @param initiator initiator identifier.
  12853. * @param toJid destination Jid
  12854. * @param isAdd indicates if this is remove or add operation.
  12855. */
  12856. SDPDiffer.prototype.toJingle = function(modify) {
  12857. var sdpMediaSsrcs = this.getNewMedia();
  12858. var self = this;
  12859. // FIXME: only announce video ssrcs since we mix audio and dont need
  12860. // the audio ssrcs therefore
  12861. var modified = false;
  12862. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12863. modified = true;
  12864. var media = sdpMediaSsrcs[mediaindex];
  12865. modify.c('content', {name: media.mid});
  12866. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12867. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12868. // generate sources from lines
  12869. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12870. var mediaSsrc = media.ssrcs[ssrcNum];
  12871. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12872. modify.attrs({ssrc: mediaSsrc.ssrc});
  12873. // iterate over ssrc lines
  12874. mediaSsrc.lines.forEach(function (line) {
  12875. var idx = line.indexOf(' ');
  12876. var kv = line.substr(idx + 1);
  12877. modify.c('parameter');
  12878. if (kv.indexOf(':') == -1) {
  12879. modify.attrs({ name: kv });
  12880. } else {
  12881. modify.attrs({ name: kv.split(':', 2)[0] });
  12882. modify.attrs({ value: kv.split(':', 2)[1] });
  12883. }
  12884. modify.up(); // end of parameter
  12885. });
  12886. modify.up(); // end of source
  12887. });
  12888. // generate source groups from lines
  12889. media.ssrcGroups.forEach(function(ssrcGroup) {
  12890. if (ssrcGroup.ssrcs.length != 0) {
  12891. modify.c('ssrc-group', {
  12892. semantics: ssrcGroup.semantics,
  12893. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12894. });
  12895. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12896. modify.c('source', { ssrc: ssrc })
  12897. .up(); // end of source
  12898. });
  12899. modify.up(); // end of ssrc-group
  12900. }
  12901. });
  12902. modify.up(); // end of description
  12903. modify.up(); // end of content
  12904. });
  12905. return modified;
  12906. };
  12907. module.exports = SDPDiffer;
  12908. },{}],52:[function(require,module,exports){
  12909. SDPUtil = {
  12910. iceparams: function (mediadesc, sessiondesc) {
  12911. var data = null;
  12912. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12913. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12914. data = {
  12915. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12916. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12917. };
  12918. }
  12919. return data;
  12920. },
  12921. parse_iceufrag: function (line) {
  12922. return line.substring(12);
  12923. },
  12924. build_iceufrag: function (frag) {
  12925. return 'a=ice-ufrag:' + frag;
  12926. },
  12927. parse_icepwd: function (line) {
  12928. return line.substring(10);
  12929. },
  12930. build_icepwd: function (pwd) {
  12931. return 'a=ice-pwd:' + pwd;
  12932. },
  12933. parse_mid: function (line) {
  12934. return line.substring(6);
  12935. },
  12936. parse_mline: function (line) {
  12937. var parts = line.substring(2).split(' '),
  12938. data = {};
  12939. data.media = parts.shift();
  12940. data.port = parts.shift();
  12941. data.proto = parts.shift();
  12942. if (parts[parts.length - 1] === '') { // trailing whitespace
  12943. parts.pop();
  12944. }
  12945. data.fmt = parts;
  12946. return data;
  12947. },
  12948. build_mline: function (mline) {
  12949. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12950. },
  12951. parse_rtpmap: function (line) {
  12952. var parts = line.substring(9).split(' '),
  12953. data = {};
  12954. data.id = parts.shift();
  12955. parts = parts[0].split('/');
  12956. data.name = parts.shift();
  12957. data.clockrate = parts.shift();
  12958. data.channels = parts.length ? parts.shift() : '1';
  12959. return data;
  12960. },
  12961. /**
  12962. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12963. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12964. * @returns [SCTP port number, protocol, streams]
  12965. */
  12966. parse_sctpmap: function (line)
  12967. {
  12968. var parts = line.substring(10).split(' ');
  12969. var sctpPort = parts[0];
  12970. var protocol = parts[1];
  12971. // Stream count is optional
  12972. var streamCount = parts.length > 2 ? parts[2] : null;
  12973. return [sctpPort, protocol, streamCount];// SCTP port
  12974. },
  12975. build_rtpmap: function (el) {
  12976. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12977. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12978. line += '/' + el.getAttribute('channels');
  12979. }
  12980. return line;
  12981. },
  12982. parse_crypto: function (line) {
  12983. var parts = line.substring(9).split(' '),
  12984. data = {};
  12985. data.tag = parts.shift();
  12986. data['crypto-suite'] = parts.shift();
  12987. data['key-params'] = parts.shift();
  12988. if (parts.length) {
  12989. data['session-params'] = parts.join(' ');
  12990. }
  12991. return data;
  12992. },
  12993. parse_fingerprint: function (line) { // RFC 4572
  12994. var parts = line.substring(14).split(' '),
  12995. data = {};
  12996. data.hash = parts.shift();
  12997. data.fingerprint = parts.shift();
  12998. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12999. return data;
  13000. },
  13001. parse_fmtp: function (line) {
  13002. var parts = line.split(' '),
  13003. i, key, value,
  13004. data = [];
  13005. parts.shift();
  13006. parts = parts.join(' ').split(';');
  13007. for (i = 0; i < parts.length; i++) {
  13008. key = parts[i].split('=')[0];
  13009. while (key.length && key[0] == ' ') {
  13010. key = key.substring(1);
  13011. }
  13012. value = parts[i].split('=')[1];
  13013. if (key && value) {
  13014. data.push({name: key, value: value});
  13015. } else if (key) {
  13016. // rfc 4733 (DTMF) style stuff
  13017. data.push({name: '', value: key});
  13018. }
  13019. }
  13020. return data;
  13021. },
  13022. parse_icecandidate: function (line) {
  13023. var candidate = {},
  13024. elems = line.split(' ');
  13025. candidate.foundation = elems[0].substring(12);
  13026. candidate.component = elems[1];
  13027. candidate.protocol = elems[2].toLowerCase();
  13028. candidate.priority = elems[3];
  13029. candidate.ip = elems[4];
  13030. candidate.port = elems[5];
  13031. // elems[6] => "typ"
  13032. candidate.type = elems[7];
  13033. candidate.generation = 0; // default value, may be overwritten below
  13034. for (var i = 8; i < elems.length; i += 2) {
  13035. switch (elems[i]) {
  13036. case 'raddr':
  13037. candidate['rel-addr'] = elems[i + 1];
  13038. break;
  13039. case 'rport':
  13040. candidate['rel-port'] = elems[i + 1];
  13041. break;
  13042. case 'generation':
  13043. candidate.generation = elems[i + 1];
  13044. break;
  13045. case 'tcptype':
  13046. candidate.tcptype = elems[i + 1];
  13047. break;
  13048. default: // TODO
  13049. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13050. }
  13051. }
  13052. candidate.network = '1';
  13053. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13054. return candidate;
  13055. },
  13056. build_icecandidate: function (cand) {
  13057. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13058. line += ' ';
  13059. switch (cand.type) {
  13060. case 'srflx':
  13061. case 'prflx':
  13062. case 'relay':
  13063. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13064. line += 'raddr';
  13065. line += ' ';
  13066. line += cand['rel-addr'];
  13067. line += ' ';
  13068. line += 'rport';
  13069. line += ' ';
  13070. line += cand['rel-port'];
  13071. line += ' ';
  13072. }
  13073. break;
  13074. }
  13075. if (cand.hasOwnAttribute('tcptype')) {
  13076. line += 'tcptype';
  13077. line += ' ';
  13078. line += cand.tcptype;
  13079. line += ' ';
  13080. }
  13081. line += 'generation';
  13082. line += ' ';
  13083. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13084. return line;
  13085. },
  13086. parse_ssrc: function (desc) {
  13087. // proprietary mapping of a=ssrc lines
  13088. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13089. // and parse according to that
  13090. var lines = desc.split('\r\n'),
  13091. data = {};
  13092. for (var i = 0; i < lines.length; i++) {
  13093. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13094. var idx = lines[i].indexOf(' ');
  13095. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13096. }
  13097. }
  13098. return data;
  13099. },
  13100. parse_rtcpfb: function (line) {
  13101. var parts = line.substr(10).split(' ');
  13102. var data = {};
  13103. data.pt = parts.shift();
  13104. data.type = parts.shift();
  13105. data.params = parts;
  13106. return data;
  13107. },
  13108. parse_extmap: function (line) {
  13109. var parts = line.substr(9).split(' ');
  13110. var data = {};
  13111. data.value = parts.shift();
  13112. if (data.value.indexOf('/') != -1) {
  13113. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13114. data.value = data.value.substr(0, data.value.indexOf('/'));
  13115. } else {
  13116. data.direction = 'both';
  13117. }
  13118. data.uri = parts.shift();
  13119. data.params = parts;
  13120. return data;
  13121. },
  13122. find_line: function (haystack, needle, sessionpart) {
  13123. var lines = haystack.split('\r\n');
  13124. for (var i = 0; i < lines.length; i++) {
  13125. if (lines[i].substring(0, needle.length) == needle) {
  13126. return lines[i];
  13127. }
  13128. }
  13129. if (!sessionpart) {
  13130. return false;
  13131. }
  13132. // search session part
  13133. lines = sessionpart.split('\r\n');
  13134. for (var j = 0; j < lines.length; j++) {
  13135. if (lines[j].substring(0, needle.length) == needle) {
  13136. return lines[j];
  13137. }
  13138. }
  13139. return false;
  13140. },
  13141. find_lines: function (haystack, needle, sessionpart) {
  13142. var lines = haystack.split('\r\n'),
  13143. needles = [];
  13144. for (var i = 0; i < lines.length; i++) {
  13145. if (lines[i].substring(0, needle.length) == needle)
  13146. needles.push(lines[i]);
  13147. }
  13148. if (needles.length || !sessionpart) {
  13149. return needles;
  13150. }
  13151. // search session part
  13152. lines = sessionpart.split('\r\n');
  13153. for (var j = 0; j < lines.length; j++) {
  13154. if (lines[j].substring(0, needle.length) == needle) {
  13155. needles.push(lines[j]);
  13156. }
  13157. }
  13158. return needles;
  13159. },
  13160. candidateToJingle: function (line) {
  13161. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13162. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13163. if (line.indexOf('candidate:') === 0) {
  13164. line = 'a=' + line;
  13165. } else if (line.substring(0, 12) != 'a=candidate:') {
  13166. console.log('parseCandidate called with a line that is not a candidate line');
  13167. console.log(line);
  13168. return null;
  13169. }
  13170. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13171. line = line.substring(0, line.length - 2);
  13172. var candidate = {},
  13173. elems = line.split(' '),
  13174. i;
  13175. if (elems[6] != 'typ') {
  13176. console.log('did not find typ in the right place');
  13177. console.log(line);
  13178. return null;
  13179. }
  13180. candidate.foundation = elems[0].substring(12);
  13181. candidate.component = elems[1];
  13182. candidate.protocol = elems[2].toLowerCase();
  13183. candidate.priority = elems[3];
  13184. candidate.ip = elems[4];
  13185. candidate.port = elems[5];
  13186. // elems[6] => "typ"
  13187. candidate.type = elems[7];
  13188. candidate.generation = '0'; // default, may be overwritten below
  13189. for (i = 8; i < elems.length; i += 2) {
  13190. switch (elems[i]) {
  13191. case 'raddr':
  13192. candidate['rel-addr'] = elems[i + 1];
  13193. break;
  13194. case 'rport':
  13195. candidate['rel-port'] = elems[i + 1];
  13196. break;
  13197. case 'generation':
  13198. candidate.generation = elems[i + 1];
  13199. break;
  13200. case 'tcptype':
  13201. candidate.tcptype = elems[i + 1];
  13202. break;
  13203. default: // TODO
  13204. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13205. }
  13206. }
  13207. candidate.network = '1';
  13208. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13209. return candidate;
  13210. },
  13211. candidateFromJingle: function (cand) {
  13212. var line = 'a=candidate:';
  13213. line += cand.getAttribute('foundation');
  13214. line += ' ';
  13215. line += cand.getAttribute('component');
  13216. line += ' ';
  13217. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13218. line += ' ';
  13219. line += cand.getAttribute('priority');
  13220. line += ' ';
  13221. line += cand.getAttribute('ip');
  13222. line += ' ';
  13223. line += cand.getAttribute('port');
  13224. line += ' ';
  13225. line += 'typ';
  13226. line += ' ' + cand.getAttribute('type');
  13227. line += ' ';
  13228. switch (cand.getAttribute('type')) {
  13229. case 'srflx':
  13230. case 'prflx':
  13231. case 'relay':
  13232. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13233. line += 'raddr';
  13234. line += ' ';
  13235. line += cand.getAttribute('rel-addr');
  13236. line += ' ';
  13237. line += 'rport';
  13238. line += ' ';
  13239. line += cand.getAttribute('rel-port');
  13240. line += ' ';
  13241. }
  13242. break;
  13243. }
  13244. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13245. line += 'tcptype';
  13246. line += ' ';
  13247. line += cand.getAttribute('tcptype');
  13248. line += ' ';
  13249. }
  13250. line += 'generation';
  13251. line += ' ';
  13252. line += cand.getAttribute('generation') || '0';
  13253. return line + '\r\n';
  13254. }
  13255. };
  13256. module.exports = SDPUtil;
  13257. },{}],53:[function(require,module,exports){
  13258. function TraceablePeerConnection(ice_config, constraints) {
  13259. var self = this;
  13260. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  13261. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  13262. this.updateLog = [];
  13263. this.stats = {};
  13264. this.statsinterval = null;
  13265. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13266. var Interop = require('sdp-interop').Interop;
  13267. this.interop = new Interop();
  13268. // override as desired
  13269. this.trace = function (what, info) {
  13270. //console.warn('WTRACE', what, info);
  13271. self.updateLog.push({
  13272. time: new Date(),
  13273. type: what,
  13274. value: info || ""
  13275. });
  13276. };
  13277. this.onicecandidate = null;
  13278. this.peerconnection.onicecandidate = function (event) {
  13279. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13280. if (self.onicecandidate !== null) {
  13281. self.onicecandidate(event);
  13282. }
  13283. };
  13284. this.onaddstream = null;
  13285. this.peerconnection.onaddstream = function (event) {
  13286. self.trace('onaddstream', event.stream.id);
  13287. if (self.onaddstream !== null) {
  13288. self.onaddstream(event);
  13289. }
  13290. };
  13291. this.onremovestream = null;
  13292. this.peerconnection.onremovestream = function (event) {
  13293. self.trace('onremovestream', event.stream.id);
  13294. if (self.onremovestream !== null) {
  13295. self.onremovestream(event);
  13296. }
  13297. };
  13298. this.onsignalingstatechange = null;
  13299. this.peerconnection.onsignalingstatechange = function (event) {
  13300. self.trace('onsignalingstatechange', self.signalingState);
  13301. if (self.onsignalingstatechange !== null) {
  13302. self.onsignalingstatechange(event);
  13303. }
  13304. };
  13305. this.oniceconnectionstatechange = null;
  13306. this.peerconnection.oniceconnectionstatechange = function (event) {
  13307. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13308. if (self.oniceconnectionstatechange !== null) {
  13309. self.oniceconnectionstatechange(event);
  13310. }
  13311. };
  13312. this.onnegotiationneeded = null;
  13313. this.peerconnection.onnegotiationneeded = function (event) {
  13314. self.trace('onnegotiationneeded');
  13315. if (self.onnegotiationneeded !== null) {
  13316. self.onnegotiationneeded(event);
  13317. }
  13318. };
  13319. self.ondatachannel = null;
  13320. this.peerconnection.ondatachannel = function (event) {
  13321. self.trace('ondatachannel', event);
  13322. if (self.ondatachannel !== null) {
  13323. self.ondatachannel(event);
  13324. }
  13325. };
  13326. if (!navigator.mozGetUserMedia && this.maxstats) {
  13327. this.statsinterval = window.setInterval(function() {
  13328. self.peerconnection.getStats(function(stats) {
  13329. var results = stats.result();
  13330. for (var i = 0; i < results.length; ++i) {
  13331. //console.log(results[i].type, results[i].id, results[i].names())
  13332. var now = new Date();
  13333. results[i].names().forEach(function (name) {
  13334. var id = results[i].id + '-' + name;
  13335. if (!self.stats[id]) {
  13336. self.stats[id] = {
  13337. startTime: now,
  13338. endTime: now,
  13339. values: [],
  13340. times: []
  13341. };
  13342. }
  13343. self.stats[id].values.push(results[i].stat(name));
  13344. self.stats[id].times.push(now.getTime());
  13345. if (self.stats[id].values.length > self.maxstats) {
  13346. self.stats[id].values.shift();
  13347. self.stats[id].times.shift();
  13348. }
  13349. self.stats[id].endTime = now;
  13350. });
  13351. }
  13352. });
  13353. }, 1000);
  13354. }
  13355. };
  13356. dumpSDP = function(description) {
  13357. if (typeof description === 'undefined' || description == null) {
  13358. return '';
  13359. }
  13360. return 'type: ' + description.type + '\r\n' + description.sdp;
  13361. };
  13362. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13363. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13364. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13365. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13366. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  13367. // if we're running on FF, transform to Plan B first.
  13368. var desc = this.peerconnection.localDescription;
  13369. if (navigator.mozGetUserMedia) {
  13370. desc = this.interop.toPlanB(desc);
  13371. } else {
  13372. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  13373. }
  13374. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13375. return desc;
  13376. });
  13377. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13378. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13379. // if we're running on FF, transform to Plan B first.
  13380. var desc = this.peerconnection.remoteDescription;
  13381. if (navigator.mozGetUserMedia) {
  13382. desc = this.interop.toPlanB(desc);
  13383. } else {
  13384. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13385. }
  13386. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13387. return desc;
  13388. });
  13389. }
  13390. TraceablePeerConnection.prototype.addStream = function (stream) {
  13391. this.trace('addStream', stream.id);
  13392. APP.simulcast.resetSender();
  13393. try
  13394. {
  13395. this.peerconnection.addStream(stream);
  13396. }
  13397. catch (e)
  13398. {
  13399. console.error(e);
  13400. return;
  13401. }
  13402. };
  13403. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13404. this.trace('removeStream', stream.id);
  13405. APP.simulcast.resetSender();
  13406. if(stopStreams) {
  13407. stream.getAudioTracks().forEach(function (track) {
  13408. track.stop();
  13409. });
  13410. stream.getVideoTracks().forEach(function (track) {
  13411. track.stop();
  13412. });
  13413. }
  13414. try {
  13415. // FF doesn't support this yet.
  13416. this.peerconnection.removeStream(stream);
  13417. } catch (e) {
  13418. console.error(e);
  13419. }
  13420. };
  13421. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13422. this.trace('createDataChannel', label, opts);
  13423. return this.peerconnection.createDataChannel(label, opts);
  13424. };
  13425. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13426. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13427. // if we're running on FF, transform to Plan A first.
  13428. if (navigator.mozGetUserMedia) {
  13429. description = this.interop.toUnifiedPlan(description);
  13430. } else {
  13431. description = APP.simulcast.transformLocalDescription(description);
  13432. }
  13433. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13434. var self = this;
  13435. this.peerconnection.setLocalDescription(description,
  13436. function () {
  13437. self.trace('setLocalDescriptionOnSuccess');
  13438. successCallback();
  13439. },
  13440. function (err) {
  13441. self.trace('setLocalDescriptionOnFailure', err);
  13442. failureCallback(err);
  13443. }
  13444. );
  13445. /*
  13446. if (this.statsinterval === null && this.maxstats > 0) {
  13447. // start gathering stats
  13448. }
  13449. */
  13450. };
  13451. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13452. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13453. // if we're running on FF, transform to Plan A first.
  13454. if (navigator.mozGetUserMedia) {
  13455. description = this.interop.toUnifiedPlan(description);
  13456. }
  13457. else {
  13458. description = APP.simulcast.transformRemoteDescription(description);
  13459. }
  13460. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13461. var self = this;
  13462. this.peerconnection.setRemoteDescription(description,
  13463. function () {
  13464. self.trace('setRemoteDescriptionOnSuccess');
  13465. successCallback();
  13466. },
  13467. function (err) {
  13468. self.trace('setRemoteDescriptionOnFailure', err);
  13469. failureCallback(err);
  13470. }
  13471. );
  13472. /*
  13473. if (this.statsinterval === null && this.maxstats > 0) {
  13474. // start gathering stats
  13475. }
  13476. */
  13477. };
  13478. TraceablePeerConnection.prototype.close = function () {
  13479. this.trace('stop');
  13480. if (this.statsinterval !== null) {
  13481. window.clearInterval(this.statsinterval);
  13482. this.statsinterval = null;
  13483. }
  13484. this.peerconnection.close();
  13485. };
  13486. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13487. var self = this;
  13488. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13489. this.peerconnection.createOffer(
  13490. function (offer) {
  13491. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13492. // if we're running on FF, transform to Plan B first.
  13493. if (navigator.mozGetUserMedia) {
  13494. offer = self.interop.toPlanB(offer);
  13495. }
  13496. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13497. successCallback(offer);
  13498. },
  13499. function(err) {
  13500. self.trace('createOfferOnFailure', err);
  13501. failureCallback(err);
  13502. },
  13503. constraints
  13504. );
  13505. };
  13506. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13507. var self = this;
  13508. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13509. this.peerconnection.createAnswer(
  13510. function (answer) {
  13511. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13512. // if we're running on FF, transform to Plan A first.
  13513. if (navigator.mozGetUserMedia) {
  13514. answer = self.interop.toPlanB(answer);
  13515. } else {
  13516. answer = APP.simulcast.transformAnswer(answer);
  13517. }
  13518. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13519. successCallback(answer);
  13520. },
  13521. function(err) {
  13522. self.trace('createAnswerOnFailure', err);
  13523. failureCallback(err);
  13524. },
  13525. constraints
  13526. );
  13527. };
  13528. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13529. var self = this;
  13530. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13531. this.peerconnection.addIceCandidate(candidate);
  13532. /* maybe later
  13533. this.peerconnection.addIceCandidate(candidate,
  13534. function () {
  13535. self.trace('addIceCandidateOnSuccess');
  13536. successCallback();
  13537. },
  13538. function (err) {
  13539. self.trace('addIceCandidateOnFailure', err);
  13540. failureCallback(err);
  13541. }
  13542. );
  13543. */
  13544. };
  13545. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13546. if (navigator.mozGetUserMedia) {
  13547. // ignore for now...
  13548. if(!errback)
  13549. errback = function () {
  13550. }
  13551. this.peerconnection.getStats(null,callback,errback);
  13552. } else {
  13553. this.peerconnection.getStats(callback);
  13554. }
  13555. };
  13556. module.exports = TraceablePeerConnection;
  13557. },{"sdp-interop":87}],54:[function(require,module,exports){
  13558. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13559. roomName, sessionTerminated, Strophe, Util */
  13560. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13561. var Settings = require("../settings/Settings");
  13562. var AuthenticationEvents
  13563. = require("../../service/authentication/AuthenticationEvents");
  13564. /**
  13565. * Contains logic responsible for enabling/disabling functionality available
  13566. * only to moderator users.
  13567. */
  13568. var connection = null;
  13569. var focusUserJid;
  13570. function createExpBackoffTimer(step) {
  13571. var count = 1;
  13572. return function (reset) {
  13573. // Reset call
  13574. if (reset) {
  13575. count = 1;
  13576. return;
  13577. }
  13578. // Calculate next timeout
  13579. var timeout = Math.pow(2, count - 1);
  13580. count += 1;
  13581. return timeout * step;
  13582. };
  13583. }
  13584. var getNextTimeout = createExpBackoffTimer(1000);
  13585. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13586. // External authentication stuff
  13587. var externalAuthEnabled = false;
  13588. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13589. // it will be enabled automatically if focus detects the component through
  13590. // service discovery.
  13591. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13592. var eventEmitter = null;
  13593. var Moderator = {
  13594. isModerator: function () {
  13595. return connection && connection.emuc.isModerator();
  13596. },
  13597. isPeerModerator: function (peerJid) {
  13598. return connection &&
  13599. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13600. },
  13601. isExternalAuthEnabled: function () {
  13602. return externalAuthEnabled;
  13603. },
  13604. isSipGatewayEnabled: function () {
  13605. return sipGatewayEnabled;
  13606. },
  13607. setConnection: function (con) {
  13608. connection = con;
  13609. },
  13610. init: function (xmpp, emitter) {
  13611. this.xmppService = xmpp;
  13612. eventEmitter = emitter;
  13613. // Message listener that talks to POPUP window
  13614. function listener(event) {
  13615. if (event.data && event.data.sessionId) {
  13616. if (event.origin !== window.location.origin) {
  13617. console.warn(
  13618. "Ignoring sessionId from different origin: " + event.origin);
  13619. return;
  13620. }
  13621. localStorage.setItem('sessionId', event.data.sessionId);
  13622. // After popup is closed we will authenticate
  13623. }
  13624. }
  13625. // Register
  13626. if (window.addEventListener) {
  13627. window.addEventListener("message", listener, false);
  13628. } else {
  13629. window.attachEvent("onmessage", listener);
  13630. }
  13631. },
  13632. onMucMemberLeft: function (jid) {
  13633. console.info("Someone left is it focus ? " + jid);
  13634. var resource = Strophe.getResourceFromJid(jid);
  13635. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13636. console.info(
  13637. "Focus has left the room - leaving conference");
  13638. //hangUp();
  13639. // We'd rather reload to have everything re-initialized
  13640. // FIXME: show some message before reload
  13641. location.reload();
  13642. }
  13643. },
  13644. setFocusUserJid: function (focusJid) {
  13645. if (!focusUserJid) {
  13646. focusUserJid = focusJid;
  13647. console.info("Focus jid set to: " + focusUserJid);
  13648. }
  13649. },
  13650. getFocusUserJid: function () {
  13651. return focusUserJid;
  13652. },
  13653. getFocusComponent: function () {
  13654. // Get focus component address
  13655. var focusComponent = config.hosts.focus;
  13656. // If not specified use default: 'focus.domain'
  13657. if (!focusComponent) {
  13658. focusComponent = 'focus.' + config.hosts.domain;
  13659. }
  13660. return focusComponent;
  13661. },
  13662. createConferenceIq: function (roomName) {
  13663. // Generate create conference IQ
  13664. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13665. // Session Id used for authentication
  13666. var sessionId = localStorage.getItem('sessionId');
  13667. var machineUID = Settings.getSettings().uid;
  13668. console.info(
  13669. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13670. elem.c('conference', {
  13671. xmlns: 'http://jitsi.org/protocol/focus',
  13672. room: roomName,
  13673. 'machine-uid': machineUID
  13674. });
  13675. if (sessionId) {
  13676. elem.attrs({ 'session-id': sessionId});
  13677. }
  13678. if (config.hosts.bridge !== undefined) {
  13679. elem.c(
  13680. 'property',
  13681. { name: 'bridge', value: config.hosts.bridge})
  13682. .up();
  13683. }
  13684. // Tell the focus we have Jigasi configured
  13685. if (config.hosts.call_control !== undefined) {
  13686. elem.c(
  13687. 'property',
  13688. { name: 'call_control', value: config.hosts.call_control})
  13689. .up();
  13690. }
  13691. if (config.channelLastN !== undefined) {
  13692. elem.c(
  13693. 'property',
  13694. { name: 'channelLastN', value: config.channelLastN})
  13695. .up();
  13696. }
  13697. if (config.adaptiveLastN !== undefined) {
  13698. elem.c(
  13699. 'property',
  13700. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13701. .up();
  13702. }
  13703. if (config.adaptiveSimulcast !== undefined) {
  13704. elem.c(
  13705. 'property',
  13706. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13707. .up();
  13708. }
  13709. if (config.openSctp !== undefined) {
  13710. elem.c(
  13711. 'property',
  13712. { name: 'openSctp', value: config.openSctp})
  13713. .up();
  13714. }
  13715. if(config.startAudioMuted !== undefined)
  13716. {
  13717. elem.c(
  13718. 'property',
  13719. { name: 'startAudioMuted', value: config.startAudioMuted})
  13720. .up();
  13721. }
  13722. if(config.startVideoMuted !== undefined)
  13723. {
  13724. elem.c(
  13725. 'property',
  13726. { name: 'startVideoMuted', value: config.startVideoMuted})
  13727. .up();
  13728. }
  13729. elem.up();
  13730. return elem;
  13731. },
  13732. parseSessionId: function (resultIq) {
  13733. var sessionId = $(resultIq).find('conference').attr('session-id');
  13734. if (sessionId) {
  13735. console.info('Received sessionId: ' + sessionId);
  13736. localStorage.setItem('sessionId', sessionId);
  13737. }
  13738. },
  13739. parseConfigOptions: function (resultIq) {
  13740. Moderator.setFocusUserJid(
  13741. $(resultIq).find('conference').attr('focusjid'));
  13742. var authenticationEnabled
  13743. = $(resultIq).find(
  13744. '>conference>property' +
  13745. '[name=\'authentication\'][value=\'true\']').length > 0;
  13746. console.info("Authentication enabled: " + authenticationEnabled);
  13747. externalAuthEnabled
  13748. = $(resultIq).find(
  13749. '>conference>property' +
  13750. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13751. console.info('External authentication enabled: ' + externalAuthEnabled);
  13752. if (!externalAuthEnabled) {
  13753. // We expect to receive sessionId in 'internal' authentication mode
  13754. Moderator.parseSessionId(resultIq);
  13755. }
  13756. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13757. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13758. authenticationEnabled, authIdentity);
  13759. // Check if focus has auto-detected Jigasi component(this will be also
  13760. // included if we have passed our host from the config)
  13761. if ($(resultIq).find(
  13762. '>conference>property' +
  13763. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13764. sipGatewayEnabled = true;
  13765. }
  13766. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13767. },
  13768. // FIXME: we need to show the fact that we're waiting for the focus
  13769. // to the user(or that focus is not available)
  13770. allocateConferenceFocus: function (roomName, callback) {
  13771. // Try to use focus user JID from the config
  13772. Moderator.setFocusUserJid(config.focusUserJid);
  13773. // Send create conference IQ
  13774. var iq = Moderator.createConferenceIq(roomName);
  13775. var self = this;
  13776. connection.sendIQ(
  13777. iq,
  13778. function (result) {
  13779. // Setup config options
  13780. Moderator.parseConfigOptions(result);
  13781. if ('true' === $(result).find('conference').attr('ready')) {
  13782. // Reset both timers
  13783. getNextTimeout(true);
  13784. getNextErrorTimeout(true);
  13785. // Exec callback
  13786. callback();
  13787. } else {
  13788. var waitMs = getNextTimeout();
  13789. console.info("Waiting for the focus... " + waitMs);
  13790. // Reset error timeout
  13791. getNextErrorTimeout(true);
  13792. window.setTimeout(
  13793. function () {
  13794. Moderator.allocateConferenceFocus(
  13795. roomName, callback);
  13796. }, waitMs);
  13797. }
  13798. },
  13799. function (error) {
  13800. // Invalid session ? remove and try again
  13801. // without session ID to get a new one
  13802. var invalidSession
  13803. = $(error).find('>error>session-invalid').length;
  13804. if (invalidSession) {
  13805. console.info("Session expired! - removing");
  13806. localStorage.removeItem("sessionId");
  13807. }
  13808. if ($(error).find('>error>graceful-shutdown').length) {
  13809. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13810. return;
  13811. }
  13812. // Check for error returned by the reservation system
  13813. var reservationErr = $(error).find('>error>reservation-error');
  13814. if (reservationErr.length) {
  13815. // Trigger error event
  13816. var errorCode = reservationErr.attr('error-code');
  13817. var errorMsg;
  13818. if ($(error).find('>error>text')) {
  13819. errorMsg = $(error).find('>error>text').text();
  13820. }
  13821. eventEmitter.emit(
  13822. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13823. return;
  13824. }
  13825. // Not authorized to create new room
  13826. if ($(error).find('>error>not-authorized').length) {
  13827. console.warn("Unauthorized to start the conference", error);
  13828. var toDomain
  13829. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13830. if (toDomain !== config.hosts.anonymousdomain) {
  13831. // FIXME: "is external" should come either from
  13832. // the focus or config.js
  13833. externalAuthEnabled = true;
  13834. }
  13835. eventEmitter.emit(
  13836. XMPPEvents.AUTHENTICATION_REQUIRED,
  13837. function () {
  13838. Moderator.allocateConferenceFocus(
  13839. roomName, callback);
  13840. });
  13841. return;
  13842. }
  13843. var waitMs = getNextErrorTimeout();
  13844. console.error("Focus error, retry after " + waitMs, error);
  13845. // Show message
  13846. var focusComponent = Moderator.getFocusComponent();
  13847. var retrySec = waitMs / 1000;
  13848. // FIXME: message is duplicated ?
  13849. // Do not show in case of session invalid
  13850. // which means just a retry
  13851. if (!invalidSession) {
  13852. APP.UI.messageHandler.notify(
  13853. null, "notify.focus",
  13854. 'disconnected', "notify.focusFail",
  13855. {component: focusComponent, ms: retrySec});
  13856. }
  13857. // Reset response timeout
  13858. getNextTimeout(true);
  13859. window.setTimeout(
  13860. function () {
  13861. Moderator.allocateConferenceFocus(roomName, callback);
  13862. }, waitMs);
  13863. }
  13864. );
  13865. },
  13866. getLoginUrl: function (roomName, urlCallback) {
  13867. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13868. iq.c('login-url', {
  13869. xmlns: 'http://jitsi.org/protocol/focus',
  13870. room: roomName,
  13871. 'machine-uid': Settings.getSettings().uid
  13872. });
  13873. connection.sendIQ(
  13874. iq,
  13875. function (result) {
  13876. var url = $(result).find('login-url').attr('url');
  13877. url = url = decodeURIComponent(url);
  13878. if (url) {
  13879. console.info("Got auth url: " + url);
  13880. urlCallback(url);
  13881. } else {
  13882. console.error(
  13883. "Failed to get auth url from the focus", result);
  13884. }
  13885. },
  13886. function (error) {
  13887. console.error("Get auth url error", error);
  13888. }
  13889. );
  13890. },
  13891. getPopupLoginUrl: function (roomName, urlCallback) {
  13892. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13893. iq.c('login-url', {
  13894. xmlns: 'http://jitsi.org/protocol/focus',
  13895. room: roomName,
  13896. 'machine-uid': Settings.getSettings().uid,
  13897. popup: true
  13898. });
  13899. connection.sendIQ(
  13900. iq,
  13901. function (result) {
  13902. var url = $(result).find('login-url').attr('url');
  13903. url = url = decodeURIComponent(url);
  13904. if (url) {
  13905. console.info("Got POPUP auth url: " + url);
  13906. urlCallback(url);
  13907. } else {
  13908. console.error(
  13909. "Failed to get POPUP auth url from the focus", result);
  13910. }
  13911. },
  13912. function (error) {
  13913. console.error('Get POPUP auth url error', error);
  13914. }
  13915. );
  13916. },
  13917. logout: function (callback) {
  13918. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13919. var sessionId = localStorage.getItem('sessionId');
  13920. if (!sessionId) {
  13921. callback();
  13922. return;
  13923. }
  13924. iq.c('logout', {
  13925. xmlns: 'http://jitsi.org/protocol/focus',
  13926. 'session-id': sessionId
  13927. });
  13928. connection.sendIQ(
  13929. iq,
  13930. function (result) {
  13931. var logoutUrl = $(result).find('logout').attr('logout-url');
  13932. if (logoutUrl) {
  13933. logoutUrl = decodeURIComponent(logoutUrl);
  13934. }
  13935. console.info("Log out OK, url: " + logoutUrl, result);
  13936. localStorage.removeItem('sessionId');
  13937. callback(logoutUrl);
  13938. },
  13939. function (error) {
  13940. console.error("Logout error", error);
  13941. }
  13942. );
  13943. }
  13944. };
  13945. module.exports = Moderator;
  13946. },{"../../service/authentication/AuthenticationEvents":100,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":39}],55:[function(require,module,exports){
  13947. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13948. Toolbar, Util */
  13949. var Moderator = require("./moderator");
  13950. var recordingToken = null;
  13951. var recordingEnabled;
  13952. /**
  13953. * Whether to use a jirecon component for recording, or use the videobridge
  13954. * through COLIBRI.
  13955. */
  13956. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13957. /**
  13958. * The ID of the jirecon recording session. Jirecon generates it when we
  13959. * initially start recording, and it needs to be used in subsequent requests
  13960. * to jirecon.
  13961. */
  13962. var jireconRid = null;
  13963. function setRecordingToken(token) {
  13964. recordingToken = token;
  13965. }
  13966. function setRecording(state, token, callback, connection) {
  13967. if (useJirecon){
  13968. setRecordingJirecon(state, token, callback, connection);
  13969. } else {
  13970. setRecordingColibri(state, token, callback, connection);
  13971. }
  13972. }
  13973. function setRecordingJirecon(state, token, callback, connection) {
  13974. if (state == recordingEnabled){
  13975. return;
  13976. }
  13977. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13978. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13979. action: state ? 'start' : 'stop',
  13980. mucjid: connection.emuc.roomjid});
  13981. if (!state){
  13982. iq.attrs({rid: jireconRid});
  13983. }
  13984. console.log('Start recording');
  13985. connection.sendIQ(
  13986. iq,
  13987. function (result) {
  13988. // TODO wait for an IQ with the real status, since this is
  13989. // provisional?
  13990. jireconRid = $(result).find('recording').attr('rid');
  13991. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13992. '(jirecon)' + result);
  13993. recordingEnabled = state;
  13994. if (!state){
  13995. jireconRid = null;
  13996. }
  13997. callback(state);
  13998. },
  13999. function (error) {
  14000. console.log('Failed to start recording, error: ', error);
  14001. callback(recordingEnabled);
  14002. });
  14003. }
  14004. // Sends a COLIBRI message which enables or disables (according to 'state')
  14005. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14006. // with the new recording state, according to the IQ.
  14007. function setRecordingColibri(state, token, callback, connection) {
  14008. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14009. elem.c('conference', {
  14010. xmlns: 'http://jitsi.org/protocol/colibri'
  14011. });
  14012. elem.c('recording', {state: state, token: token});
  14013. connection.sendIQ(elem,
  14014. function (result) {
  14015. console.log('Set recording "', state, '". Result:', result);
  14016. var recordingElem = $(result).find('>conference>recording');
  14017. var newState = ('true' === recordingElem.attr('state'));
  14018. recordingEnabled = newState;
  14019. callback(newState);
  14020. },
  14021. function (error) {
  14022. console.warn(error);
  14023. callback(recordingEnabled);
  14024. }
  14025. );
  14026. }
  14027. var Recording = {
  14028. toggleRecording: function (tokenEmptyCallback,
  14029. startingCallback, startedCallback, connection) {
  14030. if (!Moderator.isModerator()) {
  14031. console.log(
  14032. 'non-focus, or conference not yet organized:' +
  14033. ' not enabling recording');
  14034. return;
  14035. }
  14036. var self = this;
  14037. // Jirecon does not (currently) support a token.
  14038. if (!recordingToken && !useJirecon) {
  14039. tokenEmptyCallback(function (value) {
  14040. setRecordingToken(value);
  14041. self.toggleRecording(tokenEmptyCallback,
  14042. startingCallback, startedCallback, connection);
  14043. });
  14044. return;
  14045. }
  14046. var oldState = recordingEnabled;
  14047. startingCallback(!oldState);
  14048. setRecording(!oldState,
  14049. recordingToken,
  14050. function (state) {
  14051. console.log("New recording state: ", state);
  14052. if (state === oldState) {
  14053. // FIXME: new focus:
  14054. // this will not work when moderator changes
  14055. // during active session. Then it will assume that
  14056. // recording status has changed to true, but it might have
  14057. // been already true(and we only received actual status from
  14058. // the focus).
  14059. //
  14060. // SO we start with status null, so that it is initialized
  14061. // here and will fail only after second click, so if invalid
  14062. // token was used we have to press the button twice before
  14063. // current status will be fetched and token will be reset.
  14064. //
  14065. // Reliable way would be to return authentication error.
  14066. // Or status update when moderator connects.
  14067. // Or we have to stop recording session when current
  14068. // moderator leaves the room.
  14069. // Failed to change, reset the token because it might
  14070. // have been wrong
  14071. setRecordingToken(null);
  14072. }
  14073. startedCallback(state);
  14074. },
  14075. connection
  14076. );
  14077. }
  14078. }
  14079. module.exports = Recording;
  14080. },{"./moderator":54}],56:[function(require,module,exports){
  14081. /* jshint -W117 */
  14082. /* a simple MUC connection plugin
  14083. * can only handle a single MUC room
  14084. */
  14085. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14086. var Moderator = require("./moderator");
  14087. var JingleSession = require("./JingleSession");
  14088. var bridgeIsDown = false;
  14089. module.exports = function(XMPP, eventEmitter) {
  14090. Strophe.addConnectionPlugin('emuc', {
  14091. connection: null,
  14092. roomjid: null,
  14093. myroomjid: null,
  14094. members: {},
  14095. list_members: [], // so we can elect a new focus
  14096. presMap: {},
  14097. preziMap: {},
  14098. joined: false,
  14099. isOwner: false,
  14100. role: null,
  14101. focusMucJid: null,
  14102. ssrc2jid: {},
  14103. init: function (conn) {
  14104. this.connection = conn;
  14105. },
  14106. initPresenceMap: function (myroomjid) {
  14107. this.presMap['to'] = myroomjid;
  14108. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14109. if(APP.RTC.localAudio.isMuted())
  14110. {
  14111. this.addAudioInfoToPresence(true);
  14112. }
  14113. if(APP.RTC.localVideo.isMuted())
  14114. {
  14115. this.addVideoInfoToPresence(true);
  14116. }
  14117. },
  14118. doJoin: function (jid, password) {
  14119. this.myroomjid = jid;
  14120. console.info("Joined MUC as " + this.myroomjid);
  14121. this.initPresenceMap(this.myroomjid);
  14122. if (!this.roomjid) {
  14123. this.roomjid = Strophe.getBareJidFromJid(jid);
  14124. // add handlers (just once)
  14125. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14126. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14127. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14128. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14129. }
  14130. if (password !== undefined) {
  14131. this.presMap['password'] = password;
  14132. }
  14133. this.sendPresence();
  14134. },
  14135. doLeave: function () {
  14136. console.log("do leave", this.myroomjid);
  14137. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14138. this.presMap.length = 0;
  14139. this.connection.send(pres);
  14140. },
  14141. createNonAnonymousRoom: function () {
  14142. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14143. var getForm = $iq({type: 'get', to: this.roomjid})
  14144. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14145. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14146. var self = this;
  14147. this.connection.sendIQ(getForm, function (form) {
  14148. if (!$(form).find(
  14149. '>query>x[xmlns="jabber:x:data"]' +
  14150. '>field[var="muc#roomconfig_whois"]').length) {
  14151. console.error('non-anonymous rooms not supported');
  14152. return;
  14153. }
  14154. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14155. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14156. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14157. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14158. .c('value')
  14159. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14160. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14161. .c('value').t('anyone').up().up();
  14162. self.connection.sendIQ(formSubmit);
  14163. }, function (error) {
  14164. console.error("Error getting room configuration form");
  14165. });
  14166. },
  14167. onPresence: function (pres) {
  14168. var from = pres.getAttribute('from');
  14169. // What is this for? A workaround for something?
  14170. if (pres.getAttribute('type')) {
  14171. return true;
  14172. }
  14173. // Parse etherpad tag.
  14174. var etherpad = $(pres).find('>etherpad');
  14175. if (etherpad.length) {
  14176. if (config.etherpad_base && !Moderator.isModerator()) {
  14177. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14178. }
  14179. }
  14180. // Parse prezi tag.
  14181. var presentation = $(pres).find('>prezi');
  14182. if (presentation.length) {
  14183. var url = presentation.attr('url');
  14184. var current = presentation.find('>current').text();
  14185. console.log('presentation info received from', from, url);
  14186. if (this.preziMap[from] == null) {
  14187. this.preziMap[from] = url;
  14188. $(document).trigger('presentationadded.muc', [from, url, current]);
  14189. }
  14190. else {
  14191. $(document).trigger('gotoslide.muc', [from, url, current]);
  14192. }
  14193. }
  14194. else if (this.preziMap[from] != null) {
  14195. var url = this.preziMap[from];
  14196. delete this.preziMap[from];
  14197. $(document).trigger('presentationremoved.muc', [from, url]);
  14198. }
  14199. // Parse audio info tag.
  14200. var audioMuted = $(pres).find('>audiomuted');
  14201. if (audioMuted.length) {
  14202. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  14203. }
  14204. // Parse video info tag.
  14205. var videoMuted = $(pres).find('>videomuted');
  14206. if (videoMuted.length) {
  14207. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  14208. }
  14209. var startMuted = $(pres).find('>startmuted');
  14210. if (startMuted.length)
  14211. {
  14212. eventEmitter.emit(XMPPEvents.START_MUTED,
  14213. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14214. }
  14215. var devices = $(pres).find('>devices');
  14216. if(devices.length)
  14217. {
  14218. var audio = devices.find('>audio');
  14219. var video = devices.find('>video');
  14220. var devicesValues = {audio: false, video: false};
  14221. if(audio.length && audio.text() === "true")
  14222. {
  14223. devicesValues.audio = true;
  14224. }
  14225. if(video.length && video.text() === "true")
  14226. {
  14227. devicesValues.video = true;
  14228. }
  14229. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14230. Strophe.getResourceFromJid(from), devicesValues);
  14231. }
  14232. var stats = $(pres).find('>stats');
  14233. if (stats.length) {
  14234. var statsObj = {};
  14235. Strophe.forEachChild(stats[0], "stat", function (el) {
  14236. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14237. });
  14238. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14239. }
  14240. // Parse status.
  14241. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14242. this.isOwner = true;
  14243. this.createNonAnonymousRoom();
  14244. }
  14245. // Parse roles.
  14246. var member = {};
  14247. member.show = $(pres).find('>show').text();
  14248. member.status = $(pres).find('>status').text();
  14249. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14250. member.affiliation = tmp.attr('affiliation');
  14251. member.role = tmp.attr('role');
  14252. // Focus recognition
  14253. member.jid = tmp.attr('jid');
  14254. member.isFocus = false;
  14255. if (member.jid
  14256. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14257. member.isFocus = true;
  14258. }
  14259. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14260. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14261. if (from == this.myroomjid) {
  14262. if (member.affiliation == 'owner') this.isOwner = true;
  14263. if (this.role !== member.role) {
  14264. this.role = member.role;
  14265. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14266. from, member, pres, Moderator.isModerator());
  14267. }
  14268. if (!this.joined) {
  14269. this.joined = true;
  14270. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14271. this.list_members.push(from);
  14272. }
  14273. } else if (this.members[from] === undefined) {
  14274. // new participant
  14275. this.members[from] = member;
  14276. this.list_members.push(from);
  14277. console.log('entered', from, member);
  14278. if (member.isFocus) {
  14279. this.focusMucJid = from;
  14280. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14281. }
  14282. else {
  14283. var id = $(pres).find('>userId').text();
  14284. var email = $(pres).find('>email');
  14285. if (email.length > 0) {
  14286. id = email.text();
  14287. }
  14288. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14289. }
  14290. } else {
  14291. // Presence update for existing participant
  14292. // Watch role change:
  14293. if (this.members[from].role != member.role) {
  14294. this.members[from].role = member.role;
  14295. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14296. member.role, member.displayName);
  14297. }
  14298. }
  14299. // Always trigger presence to update bindings
  14300. this.parsePresence(from, member, pres);
  14301. // Trigger status message update
  14302. if (member.status) {
  14303. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14304. }
  14305. return true;
  14306. },
  14307. onPresenceUnavailable: function (pres) {
  14308. var from = pres.getAttribute('from');
  14309. // room destroyed ?
  14310. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14311. '>destroy').length) {
  14312. var reason;
  14313. var reasonSelect = $(pres).find(
  14314. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14315. '>destroy>reason');
  14316. if (reasonSelect.length) {
  14317. reason = reasonSelect.text();
  14318. }
  14319. XMPP.disposeConference(false);
  14320. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14321. return true;
  14322. }
  14323. // Status code 110 indicates that this notification is "self-presence".
  14324. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14325. delete this.members[from];
  14326. this.list_members.splice(this.list_members.indexOf(from), 1);
  14327. this.onParticipantLeft(from);
  14328. }
  14329. // If the status code is 110 this means we're leaving and we would like
  14330. // to remove everyone else from our view, so we trigger the event.
  14331. else if (this.list_members.length > 1) {
  14332. for (var i = 0; i < this.list_members.length; i++) {
  14333. var member = this.list_members[i];
  14334. delete this.members[i];
  14335. this.list_members.splice(i, 1);
  14336. this.onParticipantLeft(member);
  14337. }
  14338. }
  14339. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14340. $(document).trigger('kicked.muc', [from]);
  14341. if (this.myroomjid === from) {
  14342. XMPP.disposeConference(false);
  14343. eventEmitter.emit(XMPPEvents.KICKED);
  14344. }
  14345. }
  14346. return true;
  14347. },
  14348. onPresenceError: function (pres) {
  14349. var from = pres.getAttribute('from');
  14350. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14351. console.log('on password required', from);
  14352. var self = this;
  14353. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14354. self.doJoin(from, value);
  14355. });
  14356. } else if ($(pres).find(
  14357. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14358. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14359. if (toDomain === config.hosts.anonymousdomain) {
  14360. // enter the room by replying with 'not-authorized'. This would
  14361. // result in reconnection from authorized domain.
  14362. // We're either missing Jicofo/Prosody config for anonymous
  14363. // domains or something is wrong.
  14364. // XMPP.promptLogin();
  14365. APP.UI.messageHandler.openReportDialog(null,
  14366. "dialog.joinError", pres);
  14367. } else {
  14368. console.warn('onPresError ', pres);
  14369. APP.UI.messageHandler.openReportDialog(null,
  14370. "dialog.connectError",
  14371. pres);
  14372. }
  14373. } else {
  14374. console.warn('onPresError ', pres);
  14375. APP.UI.messageHandler.openReportDialog(null,
  14376. "dialog.connectError",
  14377. pres);
  14378. }
  14379. return true;
  14380. },
  14381. sendMessage: function (body, nickname) {
  14382. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14383. msg.c('body', body).up();
  14384. if (nickname) {
  14385. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14386. }
  14387. this.connection.send(msg);
  14388. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14389. },
  14390. setSubject: function (subject) {
  14391. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14392. msg.c('subject', subject);
  14393. this.connection.send(msg);
  14394. console.log("topic changed to " + subject);
  14395. },
  14396. onMessage: function (msg) {
  14397. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14398. var from = msg.getAttribute('from');
  14399. var nick =
  14400. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14401. .text() ||
  14402. Strophe.getResourceFromJid(from);
  14403. var txt = $(msg).find('>body').text();
  14404. var type = msg.getAttribute("type");
  14405. if (type == "error") {
  14406. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14407. $(msg).find('>text').text(), txt);
  14408. return true;
  14409. }
  14410. var subject = $(msg).find('>subject');
  14411. if (subject.length) {
  14412. var subjectText = subject.text();
  14413. if (subjectText || subjectText == "") {
  14414. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14415. console.log("Subject is changed to " + subjectText);
  14416. }
  14417. }
  14418. if (txt) {
  14419. console.log('chat', nick, txt);
  14420. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14421. from, nick, txt, this.myroomjid);
  14422. }
  14423. return true;
  14424. },
  14425. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14426. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14427. var ob = this;
  14428. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14429. function (res) {
  14430. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14431. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14432. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14433. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14434. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14435. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14436. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14437. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14438. ob.connection.sendIQ(formsubmit,
  14439. onSuccess,
  14440. onError);
  14441. } else {
  14442. onNotSupported();
  14443. }
  14444. }, onError);
  14445. },
  14446. kick: function (jid) {
  14447. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14448. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14449. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14450. .c('reason').t('You have been kicked.').up().up().up();
  14451. this.connection.sendIQ(
  14452. kickIQ,
  14453. function (result) {
  14454. console.log('Kick participant with jid: ', jid, result);
  14455. },
  14456. function (error) {
  14457. console.log('Kick participant error: ', error);
  14458. });
  14459. },
  14460. sendPresence: function () {
  14461. if (!this.presMap['to']) {
  14462. // Too early to send presence - not initialized
  14463. return;
  14464. }
  14465. var pres = $pres({to: this.presMap['to'] });
  14466. pres.c('x', {xmlns: this.presMap['xns']});
  14467. if (this.presMap['password']) {
  14468. pres.c('password').t(this.presMap['password']).up();
  14469. }
  14470. pres.up();
  14471. // Send XEP-0115 'c' stanza that contains our capabilities info
  14472. if (this.connection.caps) {
  14473. this.connection.caps.node = config.clientNode;
  14474. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14475. }
  14476. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14477. .t(navigator.userAgent).up();
  14478. if (this.presMap['bridgeIsDown']) {
  14479. pres.c('bridgeIsDown').up();
  14480. }
  14481. if (this.presMap['email']) {
  14482. pres.c('email').t(this.presMap['email']).up();
  14483. }
  14484. if (this.presMap['userId']) {
  14485. pres.c('userId').t(this.presMap['userId']).up();
  14486. }
  14487. if (this.presMap['displayName']) {
  14488. // XEP-0172
  14489. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14490. .t(this.presMap['displayName']).up();
  14491. }
  14492. if(this.presMap["devices"])
  14493. {
  14494. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14495. .c('video').t(this.presMap['devices'].video).up().up();
  14496. }
  14497. if (this.presMap['audions']) {
  14498. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14499. .t(this.presMap['audiomuted']).up();
  14500. }
  14501. if (this.presMap['videons']) {
  14502. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14503. .t(this.presMap['videomuted']).up();
  14504. }
  14505. if (this.presMap['statsns']) {
  14506. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14507. for (var stat in this.presMap["stats"])
  14508. if (this.presMap["stats"][stat] != null)
  14509. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14510. pres.up();
  14511. }
  14512. if (this.presMap['prezins']) {
  14513. pres.c('prezi',
  14514. {xmlns: this.presMap['prezins'],
  14515. 'url': this.presMap['preziurl']})
  14516. .c('current').t(this.presMap['prezicurrent']).up().up();
  14517. }
  14518. if (this.presMap['etherpadns']) {
  14519. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14520. .t(this.presMap['etherpadname']).up();
  14521. }
  14522. if (this.presMap['medians']) {
  14523. pres.c('media', {xmlns: this.presMap['medians']});
  14524. var sourceNumber = 0;
  14525. Object.keys(this.presMap).forEach(function (key) {
  14526. if (key.indexOf('source') >= 0) {
  14527. sourceNumber++;
  14528. }
  14529. });
  14530. if (sourceNumber > 0)
  14531. for (var i = 1; i <= sourceNumber / 3; i++) {
  14532. pres.c('source',
  14533. {type: this.presMap['source' + i + '_type'],
  14534. ssrc: this.presMap['source' + i + '_ssrc'],
  14535. direction: this.presMap['source' + i + '_direction']
  14536. || 'sendrecv' }
  14537. ).up();
  14538. }
  14539. pres.up();
  14540. }
  14541. if(this.presMap["startMuted"] !== undefined)
  14542. {
  14543. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  14544. video: this.presMap["startMuted"].video,
  14545. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  14546. delete this.presMap["startMuted"];
  14547. }
  14548. pres.up();
  14549. this.connection.send(pres);
  14550. },
  14551. addDisplayNameToPresence: function (displayName) {
  14552. this.presMap['displayName'] = displayName;
  14553. },
  14554. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14555. if (!this.presMap['medians'])
  14556. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14557. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14558. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14559. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14560. },
  14561. addDevicesToPresence: function (devices) {
  14562. this.presMap['devices'] = devices;
  14563. },
  14564. clearPresenceMedia: function () {
  14565. var self = this;
  14566. Object.keys(this.presMap).forEach(function (key) {
  14567. if (key.indexOf('source') != -1) {
  14568. delete self.presMap[key];
  14569. }
  14570. });
  14571. },
  14572. addPreziToPresence: function (url, currentSlide) {
  14573. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14574. this.presMap['preziurl'] = url;
  14575. this.presMap['prezicurrent'] = currentSlide;
  14576. },
  14577. removePreziFromPresence: function () {
  14578. delete this.presMap['prezins'];
  14579. delete this.presMap['preziurl'];
  14580. delete this.presMap['prezicurrent'];
  14581. },
  14582. addCurrentSlideToPresence: function (currentSlide) {
  14583. this.presMap['prezicurrent'] = currentSlide;
  14584. },
  14585. getPrezi: function (roomjid) {
  14586. return this.preziMap[roomjid];
  14587. },
  14588. addEtherpadToPresence: function (etherpadName) {
  14589. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14590. this.presMap['etherpadname'] = etherpadName;
  14591. },
  14592. addAudioInfoToPresence: function (isMuted) {
  14593. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14594. this.presMap['audiomuted'] = isMuted.toString();
  14595. },
  14596. addVideoInfoToPresence: function (isMuted) {
  14597. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14598. this.presMap['videomuted'] = isMuted.toString();
  14599. },
  14600. addConnectionInfoToPresence: function (stats) {
  14601. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14602. this.presMap['stats'] = stats;
  14603. },
  14604. findJidFromResource: function (resourceJid) {
  14605. if (resourceJid &&
  14606. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14607. return this.myroomjid;
  14608. }
  14609. var peerJid = null;
  14610. Object.keys(this.members).some(function (jid) {
  14611. peerJid = jid;
  14612. return Strophe.getResourceFromJid(jid) === resourceJid;
  14613. });
  14614. return peerJid;
  14615. },
  14616. addBridgeIsDownToPresence: function () {
  14617. this.presMap['bridgeIsDown'] = true;
  14618. },
  14619. addEmailToPresence: function (email) {
  14620. this.presMap['email'] = email;
  14621. },
  14622. addUserIdToPresence: function (userId) {
  14623. this.presMap['userId'] = userId;
  14624. },
  14625. addStartMutedToPresence: function (audio, video) {
  14626. this.presMap["startMuted"] = {audio: audio, video: video};
  14627. },
  14628. isModerator: function () {
  14629. return this.role === 'moderator';
  14630. },
  14631. getMemberRole: function (peerJid) {
  14632. if (this.members[peerJid]) {
  14633. return this.members[peerJid].role;
  14634. }
  14635. return null;
  14636. },
  14637. onParticipantLeft: function (jid) {
  14638. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  14639. this.connection.jingle.terminateByJid(jid);
  14640. if (this.getPrezi(jid)) {
  14641. $(document).trigger('presentationremoved.muc',
  14642. [jid, this.getPrezi(jid)]);
  14643. }
  14644. Moderator.onMucMemberLeft(jid);
  14645. },
  14646. parsePresence: function (from, memeber, pres) {
  14647. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14648. bridgeIsDown = true;
  14649. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14650. }
  14651. if(memeber.isFocus)
  14652. return;
  14653. var self = this;
  14654. // Remove old ssrcs coming from the jid
  14655. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14656. if (self.ssrc2jid[ssrc] == from) {
  14657. delete self.ssrc2jid[ssrc];
  14658. }
  14659. });
  14660. var changedStreams = [];
  14661. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14662. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14663. var ssrcV = ssrc.getAttribute('ssrc');
  14664. self.ssrc2jid[ssrcV] = from;
  14665. var type = ssrc.getAttribute('type');
  14666. var direction = ssrc.getAttribute('direction');
  14667. changedStreams.push({type: type, direction: direction});
  14668. });
  14669. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  14670. var displayName = !config.displayJids
  14671. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14672. if (displayName && displayName.length > 0)
  14673. {
  14674. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14675. }
  14676. var id = $(pres).find('>userID').text();
  14677. var email = $(pres).find('>email');
  14678. if(email.length > 0) {
  14679. id = email.text();
  14680. }
  14681. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14682. }
  14683. });
  14684. };
  14685. },{"../../service/xmpp/XMPPEvents":105,"./JingleSession":49,"./moderator":54}],57:[function(require,module,exports){
  14686. /* jshint -W117 */
  14687. var JingleSession = require("./JingleSession");
  14688. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14689. module.exports = function(XMPP, eventEmitter)
  14690. {
  14691. function CallIncomingJingle(sid, connection) {
  14692. var sess = connection.jingle.sessions[sid];
  14693. // TODO: do we check activecall == null?
  14694. connection.jingle.activecall = sess;
  14695. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14696. // TODO: check affiliation and/or role
  14697. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14698. sess.usedrip = true; // not-so-naive trickle ice
  14699. sess.sendAnswer();
  14700. sess.accept();
  14701. };
  14702. Strophe.addConnectionPlugin('jingle', {
  14703. connection: null,
  14704. sessions: {},
  14705. jid2session: {},
  14706. ice_config: {iceServers: []},
  14707. pc_constraints: {},
  14708. activecall: null,
  14709. media_constraints: {
  14710. mandatory: {
  14711. 'OfferToReceiveAudio': true,
  14712. 'OfferToReceiveVideo': true
  14713. }
  14714. // MozDontOfferDataChannel: true when this is firefox
  14715. },
  14716. init: function (conn) {
  14717. this.connection = conn;
  14718. if (this.connection.disco) {
  14719. // http://xmpp.org/extensions/xep-0167.html#support
  14720. // http://xmpp.org/extensions/xep-0176.html#support
  14721. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14722. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14723. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14724. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14725. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14726. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14727. // this is dealt with by SDP O/A so we don't need to annouce this
  14728. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14729. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14730. if (config.useRtcpMux) {
  14731. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14732. }
  14733. if (config.useBundle) {
  14734. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14735. }
  14736. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14737. }
  14738. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14739. },
  14740. onJingle: function (iq) {
  14741. var sid = $(iq).find('jingle').attr('sid');
  14742. var action = $(iq).find('jingle').attr('action');
  14743. var fromJid = iq.getAttribute('from');
  14744. // send ack first
  14745. var ack = $iq({type: 'result',
  14746. to: fromJid,
  14747. id: iq.getAttribute('id')
  14748. });
  14749. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14750. var sess = this.sessions[sid];
  14751. if ('session-initiate' != action) {
  14752. if (sess === null) {
  14753. ack.type = 'error';
  14754. ack.c('error', {type: 'cancel'})
  14755. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14756. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14757. this.connection.send(ack);
  14758. return true;
  14759. }
  14760. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14761. // local jid is not checked
  14762. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14763. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14764. ack.type = 'error';
  14765. ack.c('error', {type: 'cancel'})
  14766. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14767. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14768. this.connection.send(ack);
  14769. return true;
  14770. }
  14771. } else if (sess !== undefined) {
  14772. // existing session with same session id
  14773. // this might be out-of-order if the sess.peerjid is the same as from
  14774. ack.type = 'error';
  14775. ack.c('error', {type: 'cancel'})
  14776. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14777. console.warn('duplicate session id', sid);
  14778. this.connection.send(ack);
  14779. return true;
  14780. }
  14781. // FIXME: check for a defined action
  14782. this.connection.send(ack);
  14783. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14784. switch (action) {
  14785. case 'session-initiate':
  14786. var startMuted = $(iq).find('jingle>startmuted');
  14787. if(startMuted && startMuted.length > 0)
  14788. {
  14789. var audioMuted = startMuted.attr("audio");
  14790. var videoMuted = startMuted.attr("video");
  14791. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  14792. (videoMuted === "true"));
  14793. }
  14794. sess = new JingleSession(
  14795. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14796. this.connection, XMPP);
  14797. // configure session
  14798. sess.media_constraints = this.media_constraints;
  14799. sess.pc_constraints = this.pc_constraints;
  14800. sess.ice_config = this.ice_config;
  14801. sess.initiate(fromJid, false);
  14802. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14803. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14804. this.sessions[sess.sid] = sess;
  14805. this.jid2session[sess.peerjid] = sess;
  14806. // the callback should either
  14807. // .sendAnswer and .accept
  14808. // or .sendTerminate -- not necessarily synchronus
  14809. CallIncomingJingle(sess.sid, this.connection);
  14810. break;
  14811. case 'session-accept':
  14812. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14813. sess.accept();
  14814. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14815. break;
  14816. case 'session-terminate':
  14817. // If this is not the focus sending the terminate, we have
  14818. // nothing more to do here.
  14819. if (Object.keys(this.sessions).length < 1
  14820. || !(this.sessions[Object.keys(this.sessions)[0]]
  14821. instanceof JingleSession))
  14822. {
  14823. break;
  14824. }
  14825. console.log('terminating...', sess.sid);
  14826. sess.terminate();
  14827. this.terminate(sess.sid);
  14828. if ($(iq).find('>jingle>reason').length) {
  14829. $(document).trigger('callterminated.jingle', [
  14830. sess.sid,
  14831. sess.peerjid,
  14832. $(iq).find('>jingle>reason>:first')[0].tagName,
  14833. $(iq).find('>jingle>reason>text').text()
  14834. ]);
  14835. } else {
  14836. $(document).trigger('callterminated.jingle',
  14837. [sess.sid, sess.peerjid]);
  14838. }
  14839. break;
  14840. case 'transport-info':
  14841. sess.addIceCandidate($(iq).find('>jingle>content'));
  14842. break;
  14843. case 'session-info':
  14844. var affected;
  14845. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14846. $(document).trigger('ringing.jingle', [sess.sid]);
  14847. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14848. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14849. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14850. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14851. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14852. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14853. }
  14854. break;
  14855. case 'addsource': // FIXME: proprietary, un-jingleish
  14856. case 'source-add': // FIXME: proprietary
  14857. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14858. break;
  14859. case 'removesource': // FIXME: proprietary, un-jingleish
  14860. case 'source-remove': // FIXME: proprietary
  14861. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14862. break;
  14863. default:
  14864. console.warn('jingle action not implemented', action);
  14865. break;
  14866. }
  14867. return true;
  14868. },
  14869. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14870. var sess = new JingleSession(myjid || this.connection.jid,
  14871. Math.random().toString(36).substr(2, 12), // random string
  14872. this.connection, XMPP);
  14873. // configure session
  14874. sess.media_constraints = this.media_constraints;
  14875. sess.pc_constraints = this.pc_constraints;
  14876. sess.ice_config = this.ice_config;
  14877. sess.initiate(peerjid, true);
  14878. this.sessions[sess.sid] = sess;
  14879. this.jid2session[sess.peerjid] = sess;
  14880. sess.sendOffer();
  14881. return sess;
  14882. },
  14883. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14884. if (sid === null || sid === undefined) {
  14885. for (sid in this.sessions) {
  14886. if (this.sessions[sid].state != 'ended') {
  14887. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14888. this.sessions[sid].terminate();
  14889. }
  14890. delete this.jid2session[this.sessions[sid].peerjid];
  14891. delete this.sessions[sid];
  14892. }
  14893. } else if (this.sessions.hasOwnProperty(sid)) {
  14894. if (this.sessions[sid].state != 'ended') {
  14895. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14896. this.sessions[sid].terminate();
  14897. }
  14898. delete this.jid2session[this.sessions[sid].peerjid];
  14899. delete this.sessions[sid];
  14900. }
  14901. },
  14902. // Used to terminate a session when an unavailable presence is received.
  14903. terminateByJid: function (jid) {
  14904. if (this.jid2session.hasOwnProperty(jid)) {
  14905. var sess = this.jid2session[jid];
  14906. if (sess) {
  14907. sess.terminate();
  14908. console.log('peer went away silently', jid);
  14909. delete this.sessions[sess.sid];
  14910. delete this.jid2session[jid];
  14911. $(document).trigger('callterminated.jingle',
  14912. [sess.sid, jid], 'gone');
  14913. }
  14914. }
  14915. },
  14916. terminateRemoteByJid: function (jid, reason) {
  14917. if (this.jid2session.hasOwnProperty(jid)) {
  14918. var sess = this.jid2session[jid];
  14919. if (sess) {
  14920. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14921. sess.terminate();
  14922. console.log('terminate peer with jid', sess.sid, jid);
  14923. delete this.sessions[sess.sid];
  14924. delete this.jid2session[jid];
  14925. $(document).trigger('callterminated.jingle',
  14926. [sess.sid, jid, 'kicked']);
  14927. }
  14928. }
  14929. },
  14930. getStunAndTurnCredentials: function () {
  14931. // get stun and turn configuration from server via xep-0215
  14932. // uses time-limited credentials as described in
  14933. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14934. //
  14935. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14936. // for a prosody module which implements this
  14937. //
  14938. // currently, this doesn't work with updateIce and therefore credentials with a long
  14939. // validity have to be fetched before creating the peerconnection
  14940. // TODO: implement refresh via updateIce as described in
  14941. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14942. var self = this;
  14943. this.connection.sendIQ(
  14944. $iq({type: 'get', to: this.connection.domain})
  14945. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14946. function (res) {
  14947. var iceservers = [];
  14948. $(res).find('>services>service').each(function (idx, el) {
  14949. el = $(el);
  14950. var dict = {};
  14951. var type = el.attr('type');
  14952. switch (type) {
  14953. case 'stun':
  14954. dict.url = 'stun:' + el.attr('host');
  14955. if (el.attr('port')) {
  14956. dict.url += ':' + el.attr('port');
  14957. }
  14958. iceservers.push(dict);
  14959. break;
  14960. case 'turn':
  14961. case 'turns':
  14962. dict.url = type + ':';
  14963. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14964. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14965. dict.url += el.attr('username') + '@';
  14966. } else {
  14967. dict.username = el.attr('username'); // only works in M28
  14968. }
  14969. }
  14970. dict.url += el.attr('host');
  14971. if (el.attr('port') && el.attr('port') != '3478') {
  14972. dict.url += ':' + el.attr('port');
  14973. }
  14974. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14975. dict.url += '?transport=' + el.attr('transport');
  14976. }
  14977. if (el.attr('password')) {
  14978. dict.credential = el.attr('password');
  14979. }
  14980. iceservers.push(dict);
  14981. break;
  14982. }
  14983. });
  14984. self.ice_config.iceServers = iceservers;
  14985. },
  14986. function (err) {
  14987. console.warn('getting turn credentials failed', err);
  14988. console.warn('is mod_turncredentials or similar installed?');
  14989. }
  14990. );
  14991. // implement push?
  14992. },
  14993. /**
  14994. * Populates the log data
  14995. */
  14996. populateData: function () {
  14997. var data = {};
  14998. Object.keys(this.sessions).forEach(function (sid) {
  14999. var session = this.sessions[sid];
  15000. if (session.peerconnection && session.peerconnection.updateLog) {
  15001. // FIXME: should probably be a .dump call
  15002. data["jingle_" + session.sid] = {
  15003. updateLog: session.peerconnection.updateLog,
  15004. stats: session.peerconnection.stats,
  15005. url: window.location.href
  15006. };
  15007. }
  15008. });
  15009. return data;
  15010. }
  15011. });
  15012. };
  15013. },{"../../service/xmpp/XMPPEvents":105,"./JingleSession":49}],58:[function(require,module,exports){
  15014. /* global Strophe */
  15015. module.exports = function () {
  15016. Strophe.addConnectionPlugin('logger', {
  15017. // logs raw stanzas and makes them available for download as JSON
  15018. connection: null,
  15019. log: [],
  15020. init: function (conn) {
  15021. this.connection = conn;
  15022. this.connection.rawInput = this.log_incoming.bind(this);
  15023. this.connection.rawOutput = this.log_outgoing.bind(this);
  15024. },
  15025. log_incoming: function (stanza) {
  15026. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15027. },
  15028. log_outgoing: function (stanza) {
  15029. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15030. }
  15031. });
  15032. };
  15033. },{}],59:[function(require,module,exports){
  15034. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15035. setAudioMuted, Strophe */
  15036. /**
  15037. * Moderate connection plugin.
  15038. */
  15039. module.exports = function (XMPP) {
  15040. Strophe.addConnectionPlugin('moderate', {
  15041. connection: null,
  15042. init: function (conn) {
  15043. this.connection = conn;
  15044. this.connection.addHandler(this.onMute.bind(this),
  15045. 'http://jitsi.org/jitmeet/audio',
  15046. 'iq',
  15047. 'set',
  15048. null,
  15049. null);
  15050. },
  15051. setMute: function (jid, mute) {
  15052. console.info("set mute", mute);
  15053. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15054. .c('mute', {
  15055. xmlns: 'http://jitsi.org/jitmeet/audio',
  15056. jid: jid
  15057. })
  15058. .t(mute.toString())
  15059. .up();
  15060. this.connection.sendIQ(
  15061. iqToFocus,
  15062. function (result) {
  15063. console.log('set mute', result);
  15064. },
  15065. function (error) {
  15066. console.log('set mute error', error);
  15067. });
  15068. },
  15069. onMute: function (iq) {
  15070. var from = iq.getAttribute('from');
  15071. if (from !== this.connection.emuc.focusMucJid) {
  15072. console.warn("Ignored mute from non focus peer");
  15073. return false;
  15074. }
  15075. var mute = $(iq).find('mute');
  15076. if (mute.length) {
  15077. var doMuteAudio = mute.text() === "true";
  15078. APP.UI.setAudioMuted(doMuteAudio);
  15079. XMPP.forceMuted = doMuteAudio;
  15080. }
  15081. return true;
  15082. },
  15083. eject: function (jid) {
  15084. // We're not the focus, so can't terminate
  15085. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15086. this.connection.emuc.kick(jid);
  15087. }
  15088. });
  15089. }
  15090. },{}],60:[function(require,module,exports){
  15091. /* jshint -W117 */
  15092. module.exports = function() {
  15093. Strophe.addConnectionPlugin('rayo',
  15094. {
  15095. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15096. connection: null,
  15097. init: function (conn) {
  15098. this.connection = conn;
  15099. if (this.connection.disco) {
  15100. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15101. }
  15102. this.connection.addHandler(
  15103. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15104. },
  15105. onRayo: function (iq) {
  15106. console.info("Rayo IQ", iq);
  15107. },
  15108. dial: function (to, from, roomName, roomPass) {
  15109. var self = this;
  15110. var req = $iq(
  15111. {
  15112. type: 'set',
  15113. to: this.connection.emuc.focusMucJid
  15114. }
  15115. );
  15116. req.c('dial',
  15117. {
  15118. xmlns: this.RAYO_XMLNS,
  15119. to: to,
  15120. from: from
  15121. });
  15122. req.c('header',
  15123. {
  15124. name: 'JvbRoomName',
  15125. value: roomName
  15126. }).up();
  15127. if (roomPass !== null && roomPass.length) {
  15128. req.c('header',
  15129. {
  15130. name: 'JvbRoomPassword',
  15131. value: roomPass
  15132. }).up();
  15133. }
  15134. this.connection.sendIQ(
  15135. req,
  15136. function (result) {
  15137. console.info('Dial result ', result);
  15138. var resource = $(result).find('ref').attr('uri');
  15139. this.call_resource = resource.substr('xmpp:'.length);
  15140. console.info(
  15141. "Received call resource: " + this.call_resource);
  15142. },
  15143. function (error) {
  15144. console.info('Dial error ', error);
  15145. }
  15146. );
  15147. },
  15148. hang_up: function () {
  15149. if (!this.call_resource) {
  15150. console.warn("No call in progress");
  15151. return;
  15152. }
  15153. var self = this;
  15154. var req = $iq(
  15155. {
  15156. type: 'set',
  15157. to: this.call_resource
  15158. }
  15159. );
  15160. req.c('hangup',
  15161. {
  15162. xmlns: this.RAYO_XMLNS
  15163. });
  15164. this.connection.sendIQ(
  15165. req,
  15166. function (result) {
  15167. console.info('Hangup result ', result);
  15168. self.call_resource = null;
  15169. },
  15170. function (error) {
  15171. console.info('Hangup error ', error);
  15172. self.call_resource = null;
  15173. }
  15174. );
  15175. }
  15176. }
  15177. );
  15178. };
  15179. },{}],61:[function(require,module,exports){
  15180. /**
  15181. * Strophe logger implementation. Logs from level WARN and above.
  15182. */
  15183. module.exports = function () {
  15184. Strophe.log = function (level, msg) {
  15185. switch (level) {
  15186. case Strophe.LogLevel.WARN:
  15187. console.warn("Strophe: " + msg);
  15188. break;
  15189. case Strophe.LogLevel.ERROR:
  15190. case Strophe.LogLevel.FATAL:
  15191. console.error("Strophe: " + msg);
  15192. break;
  15193. }
  15194. };
  15195. Strophe.getStatusString = function (status) {
  15196. switch (status) {
  15197. case Strophe.Status.ERROR:
  15198. return "ERROR";
  15199. case Strophe.Status.CONNECTING:
  15200. return "CONNECTING";
  15201. case Strophe.Status.CONNFAIL:
  15202. return "CONNFAIL";
  15203. case Strophe.Status.AUTHENTICATING:
  15204. return "AUTHENTICATING";
  15205. case Strophe.Status.AUTHFAIL:
  15206. return "AUTHFAIL";
  15207. case Strophe.Status.CONNECTED:
  15208. return "CONNECTED";
  15209. case Strophe.Status.DISCONNECTED:
  15210. return "DISCONNECTED";
  15211. case Strophe.Status.DISCONNECTING:
  15212. return "DISCONNECTING";
  15213. case Strophe.Status.ATTACHED:
  15214. return "ATTACHED";
  15215. default:
  15216. return "unknown";
  15217. }
  15218. };
  15219. };
  15220. },{}],62:[function(require,module,exports){
  15221. /* global $, APP, config, Strophe*/
  15222. var Moderator = require("./moderator");
  15223. var EventEmitter = require("events");
  15224. var Recording = require("./recording");
  15225. var SDP = require("./SDP");
  15226. var Settings = require("../settings/Settings");
  15227. var Pako = require("pako");
  15228. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15229. var RTCEvents = require("../../service/RTC/RTCEvents");
  15230. var UIEvents = require("../../service/UI/UIEvents");
  15231. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15232. var retry = require('retry');
  15233. var eventEmitter = new EventEmitter();
  15234. var connection = null;
  15235. var authenticatedUser = false;
  15236. function connect(jid, password) {
  15237. var faultTolerantConnect = retry.operation({
  15238. retries: 3
  15239. });
  15240. // fault tolerant connect
  15241. faultTolerantConnect.attempt(function () {
  15242. connection = XMPP.createConnection();
  15243. Moderator.setConnection(connection);
  15244. if (connection.disco) {
  15245. // for chrome, add multistream cap
  15246. }
  15247. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15248. if (config.useIPv6) {
  15249. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15250. if (!connection.jingle.pc_constraints.optional)
  15251. connection.jingle.pc_constraints.optional = [];
  15252. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15253. }
  15254. // Include user info in MUC presence
  15255. var settings = Settings.getSettings();
  15256. if (settings.email) {
  15257. connection.emuc.addEmailToPresence(settings.email);
  15258. }
  15259. if (settings.uid) {
  15260. connection.emuc.addUserIdToPresence(settings.uid);
  15261. }
  15262. if (settings.displayName) {
  15263. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15264. }
  15265. // connection.connect() starts the connection process.
  15266. //
  15267. // As the connection process proceeds, the user supplied callback will
  15268. // be triggered multiple times with status updates. The callback should
  15269. // take two arguments - the status code and the error condition.
  15270. //
  15271. // The status code will be one of the values in the Strophe.Status
  15272. // constants. The error condition will be one of the conditions defined
  15273. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15274. //
  15275. // The Parameters wait, hold and route are optional and only relevant
  15276. // for BOSH connections. Please see XEP 124 for a more detailed
  15277. // explanation of the optional parameters.
  15278. //
  15279. // Connection status constants for use by the connection handler
  15280. // callback.
  15281. //
  15282. // Status.ERROR - An error has occurred (websockets specific)
  15283. // Status.CONNECTING - The connection is currently being made
  15284. // Status.CONNFAIL - The connection attempt failed
  15285. // Status.AUTHENTICATING - The connection is authenticating
  15286. // Status.AUTHFAIL - The authentication attempt failed
  15287. // Status.CONNECTED - The connection has succeeded
  15288. // Status.DISCONNECTED - The connection has been terminated
  15289. // Status.DISCONNECTING - The connection is currently being terminated
  15290. // Status.ATTACHED - The connection has been attached
  15291. var anonymousConnectionFailed = false;
  15292. var connectionFailed = false;
  15293. var lastErrorMsg;
  15294. connection.connect(jid, password, function (status, msg) {
  15295. console.log('Strophe status changed to',
  15296. Strophe.getStatusString(status), msg);
  15297. if (status === Strophe.Status.CONNECTED) {
  15298. if (config.useStunTurn) {
  15299. connection.jingle.getStunAndTurnCredentials();
  15300. }
  15301. console.info("My Jabber ID: " + connection.jid);
  15302. if (password)
  15303. authenticatedUser = true;
  15304. maybeDoJoin();
  15305. } else if (status === Strophe.Status.CONNFAIL) {
  15306. if (msg === 'x-strophe-bad-non-anon-jid') {
  15307. anonymousConnectionFailed = true;
  15308. } else {
  15309. connectionFailed = true;
  15310. }
  15311. lastErrorMsg = msg;
  15312. } else if (status === Strophe.Status.DISCONNECTED) {
  15313. if (anonymousConnectionFailed) {
  15314. // prompt user for username and password
  15315. XMPP.promptLogin();
  15316. } else {
  15317. // Strophe already has built-in HTTP/BOSH error handling and
  15318. // request retry logic. Requests are resent automatically
  15319. // until their error count reaches 5. Strophe.js disconnects
  15320. // if the error count is > 5. We are not replicating this
  15321. // here.
  15322. //
  15323. // The "problem" is that failed HTTP/BOSH requests don't
  15324. // trigger a callback with a status update, so when a
  15325. // callback with status Strophe.Status.DISCONNECTED arrives,
  15326. // we can't be sure if it's a graceful disconnect or if it's
  15327. // triggered by some HTTP/BOSH error.
  15328. //
  15329. // But that's a minor issue in Jitsi Meet as we never
  15330. // disconnect anyway, not even when the user closes the
  15331. // browser window (which is kind of wrong, but the point is
  15332. // that we should never ever get disconnected).
  15333. //
  15334. // On the other hand, failed connections due to XMPP layer
  15335. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15336. //
  15337. // Here we implement retry logic for failed connections due
  15338. // to XMPP layer errors and we display an error to the user
  15339. // if we get disconnected from the XMPP server permanently.
  15340. // If the connection failed, retry.
  15341. if (connectionFailed
  15342. && faultTolerantConnect.retry("connection-failed")) {
  15343. return;
  15344. }
  15345. // If we failed to connect to the XMPP server, fire an event
  15346. // to let all the interested module now about it.
  15347. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15348. msg ? msg : lastErrorMsg);
  15349. }
  15350. } else if (status === Strophe.Status.AUTHFAIL) {
  15351. // wrong password or username, prompt user
  15352. XMPP.promptLogin();
  15353. }
  15354. });
  15355. });
  15356. }
  15357. function maybeDoJoin() {
  15358. if (connection && connection.connected &&
  15359. Strophe.getResourceFromJid(connection.jid)
  15360. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15361. // .connected is true while connecting?
  15362. doJoin();
  15363. }
  15364. }
  15365. function doJoin() {
  15366. var roomName = APP.UI.generateRoomName();
  15367. Moderator.allocateConferenceFocus(
  15368. roomName, APP.UI.checkForNicknameAndJoin);
  15369. }
  15370. function initStrophePlugins()
  15371. {
  15372. require("./strophe.emuc")(XMPP, eventEmitter);
  15373. require("./strophe.jingle")(XMPP, eventEmitter);
  15374. require("./strophe.moderate")(XMPP);
  15375. require("./strophe.util")();
  15376. require("./strophe.rayo")();
  15377. require("./strophe.logger")();
  15378. }
  15379. function registerListeners() {
  15380. APP.RTC.addStreamListener(maybeDoJoin,
  15381. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15382. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15383. XMPP.addToPresence("devices", devices);
  15384. })
  15385. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15386. XMPP.addToPresence("displayName", nickname);
  15387. });
  15388. }
  15389. var unload = (function () {
  15390. var unloaded = false;
  15391. return function () {
  15392. if (unloaded) { return; }
  15393. unloaded = true;
  15394. if (connection && connection.connected) {
  15395. // ensure signout
  15396. $.ajax({
  15397. type: 'POST',
  15398. url: config.bosh,
  15399. async: false,
  15400. cache: false,
  15401. contentType: 'application/xml',
  15402. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15403. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15404. (connection.sid || connection._proto.sid) +
  15405. "' type='terminate'>" +
  15406. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15407. "</body>",
  15408. success: function (data) {
  15409. console.log('signed out');
  15410. console.log(data);
  15411. },
  15412. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15413. console.log('signout error',
  15414. textStatus + ' (' + errorThrown + ')');
  15415. }
  15416. });
  15417. }
  15418. XMPP.disposeConference(true);
  15419. };
  15420. })();
  15421. function setupEvents() {
  15422. // In recent versions of FF the 'beforeunload' event is not fired when the
  15423. // window or the tab is closed. It is only fired when we leave the page
  15424. // (change URL). If this participant doesn't unload properly, then it
  15425. // becomes a ghost for the rest of the participants that stay in the
  15426. // conference. Thankfully handling the 'unload' event in addition to the
  15427. // 'beforeunload' event seems to garante the execution of the 'unload'
  15428. // method at least once.
  15429. //
  15430. // The 'unload' method can safely be run multiple times, it will actually do
  15431. // something only the first time that it's run, so we're don't have to worry
  15432. // about browsers that fire both events.
  15433. $(window).bind('beforeunload', unload);
  15434. $(window).bind('unload', unload);
  15435. }
  15436. var XMPP = {
  15437. getConnection: function(){ return connection; },
  15438. sessionTerminated: false,
  15439. /**
  15440. * XMPP connection status
  15441. */
  15442. Status: Strophe.Status,
  15443. /**
  15444. * Remembers if we were muted by the focus.
  15445. * @type {boolean}
  15446. */
  15447. forceMuted: false,
  15448. start: function () {
  15449. setupEvents();
  15450. initStrophePlugins();
  15451. registerListeners();
  15452. Moderator.init(this, eventEmitter);
  15453. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15454. // Force authenticated domain if room is appended with '?login=true'
  15455. if (config.hosts.anonymousdomain &&
  15456. window.location.search.indexOf("login=true") !== -1) {
  15457. configDomain = config.hosts.domain;
  15458. }
  15459. var jid = configDomain || window.location.hostname;
  15460. connect(jid, null);
  15461. },
  15462. createConnection: function () {
  15463. var bosh = config.bosh || '/http-bind';
  15464. return new Strophe.Connection(bosh);
  15465. },
  15466. getStatusString: function (status) {
  15467. return Strophe.getStatusString(status);
  15468. },
  15469. promptLogin: function () {
  15470. // FIXME: re-use LoginDialog which supports retries
  15471. APP.UI.showLoginPopup(connect);
  15472. },
  15473. joinRoom: function(roomName, useNicks, nick)
  15474. {
  15475. var roomjid;
  15476. roomjid = roomName;
  15477. if (useNicks) {
  15478. if (nick) {
  15479. roomjid += '/' + nick;
  15480. } else {
  15481. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15482. }
  15483. } else {
  15484. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15485. if(!authenticatedUser)
  15486. tmpJid = tmpJid.substr(0, 8);
  15487. roomjid += '/' + tmpJid;
  15488. }
  15489. connection.emuc.doJoin(roomjid);
  15490. },
  15491. myJid: function () {
  15492. if(!connection)
  15493. return null;
  15494. return connection.emuc.myroomjid;
  15495. },
  15496. myResource: function () {
  15497. if(!connection || ! connection.emuc.myroomjid)
  15498. return null;
  15499. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15500. },
  15501. disposeConference: function (onUnload) {
  15502. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15503. var handler = connection.jingle.activecall;
  15504. if (handler && handler.peerconnection) {
  15505. // FIXME: probably removing streams is not required and close() should
  15506. // be enough
  15507. if (APP.RTC.localAudio) {
  15508. handler.peerconnection.removeStream(
  15509. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15510. }
  15511. if (APP.RTC.localVideo) {
  15512. handler.peerconnection.removeStream(
  15513. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15514. }
  15515. handler.peerconnection.close();
  15516. }
  15517. connection.jingle.activecall = null;
  15518. if(!onUnload)
  15519. {
  15520. this.sessionTerminated = true;
  15521. connection.emuc.doLeave();
  15522. }
  15523. },
  15524. addListener: function(type, listener)
  15525. {
  15526. eventEmitter.on(type, listener);
  15527. },
  15528. removeListener: function (type, listener) {
  15529. eventEmitter.removeListener(type, listener);
  15530. },
  15531. allocateConferenceFocus: function(roomName, callback) {
  15532. Moderator.allocateConferenceFocus(roomName, callback);
  15533. },
  15534. getLoginUrl: function (roomName, callback) {
  15535. Moderator.getLoginUrl(roomName, callback);
  15536. },
  15537. getPopupLoginUrl: function (roomName, callback) {
  15538. Moderator.getPopupLoginUrl(roomName, callback);
  15539. },
  15540. isModerator: function () {
  15541. return Moderator.isModerator();
  15542. },
  15543. isSipGatewayEnabled: function () {
  15544. return Moderator.isSipGatewayEnabled();
  15545. },
  15546. isExternalAuthEnabled: function () {
  15547. return Moderator.isExternalAuthEnabled();
  15548. },
  15549. switchStreams: function (stream, oldStream, callback, isAudio) {
  15550. if (connection && connection.jingle.activecall) {
  15551. // FIXME: will block switchInProgress on true value in case of exception
  15552. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  15553. } else {
  15554. // We are done immediately
  15555. console.warn("No conference handler or conference not started yet");
  15556. callback();
  15557. }
  15558. },
  15559. sendVideoInfoPresence: function (mute) {
  15560. if(!connection)
  15561. return;
  15562. connection.emuc.addVideoInfoToPresence(mute);
  15563. connection.emuc.sendPresence();
  15564. },
  15565. setVideoMute: function (mute, callback, options) {
  15566. if(!connection)
  15567. return;
  15568. var self = this;
  15569. var localCallback = function (mute) {
  15570. self.sendVideoInfoPresence(mute);
  15571. return callback(mute);
  15572. };
  15573. if(connection.jingle.activecall)
  15574. {
  15575. connection.jingle.activecall.setVideoMute(
  15576. mute, localCallback, options);
  15577. }
  15578. else {
  15579. localCallback(mute);
  15580. }
  15581. },
  15582. setAudioMute: function (mute, callback) {
  15583. if (!(connection && APP.RTC.localAudio)) {
  15584. return false;
  15585. }
  15586. if (this.forceMuted && !mute) {
  15587. console.info("Asking focus for unmute");
  15588. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15589. // FIXME: wait for result before resetting muted status
  15590. this.forceMuted = false;
  15591. }
  15592. if (mute == APP.RTC.localAudio.isMuted()) {
  15593. // Nothing to do
  15594. return true;
  15595. }
  15596. // It is not clear what is the right way to handle multiple tracks.
  15597. // So at least make sure that they are all muted or all unmuted and
  15598. // that we send presence just once.
  15599. APP.RTC.localAudio.setMute(!mute);
  15600. // isMuted is the opposite of audioEnabled
  15601. this.sendAudioInfoPresence(mute, callback);
  15602. return true;
  15603. },
  15604. sendAudioInfoPresence: function(mute, callback)
  15605. {
  15606. if(connection) {
  15607. connection.emuc.addAudioInfoToPresence(mute);
  15608. connection.emuc.sendPresence();
  15609. }
  15610. callback();
  15611. return true;
  15612. },
  15613. // Really mute video, i.e. dont even send black frames
  15614. muteVideo: function (pc, unmute) {
  15615. // FIXME: this probably needs another of those lovely state safeguards...
  15616. // which checks for iceconn == connected and sigstate == stable
  15617. pc.setRemoteDescription(pc.remoteDescription,
  15618. function () {
  15619. pc.createAnswer(
  15620. function (answer) {
  15621. var sdp = new SDP(answer.sdp);
  15622. if (sdp.media.length > 1) {
  15623. if (unmute)
  15624. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15625. else
  15626. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15627. sdp.raw = sdp.session + sdp.media.join('');
  15628. answer.sdp = sdp.raw;
  15629. }
  15630. pc.setLocalDescription(answer,
  15631. function () {
  15632. console.log('mute SLD ok');
  15633. },
  15634. function (error) {
  15635. console.log('mute SLD error');
  15636. APP.UI.messageHandler.showError("dialog.error",
  15637. "dialog.SLDFailure");
  15638. }
  15639. );
  15640. },
  15641. function (error) {
  15642. console.log(error);
  15643. APP.UI.messageHandler.showError();
  15644. }
  15645. );
  15646. },
  15647. function (error) {
  15648. console.log('muteVideo SRD error');
  15649. APP.UI.messageHandler.showError("dialog.error",
  15650. "dialog.SRDFailure");
  15651. }
  15652. );
  15653. },
  15654. toggleRecording: function (tokenEmptyCallback,
  15655. startingCallback, startedCallback) {
  15656. Recording.toggleRecording(tokenEmptyCallback,
  15657. startingCallback, startedCallback, connection);
  15658. },
  15659. addToPresence: function (name, value, dontSend) {
  15660. switch (name)
  15661. {
  15662. case "displayName":
  15663. connection.emuc.addDisplayNameToPresence(value);
  15664. break;
  15665. case "etherpad":
  15666. connection.emuc.addEtherpadToPresence(value);
  15667. break;
  15668. case "prezi":
  15669. connection.emuc.addPreziToPresence(value, 0);
  15670. break;
  15671. case "preziSlide":
  15672. connection.emuc.addCurrentSlideToPresence(value);
  15673. break;
  15674. case "connectionQuality":
  15675. connection.emuc.addConnectionInfoToPresence(value);
  15676. break;
  15677. case "email":
  15678. connection.emuc.addEmailToPresence(value);
  15679. break;
  15680. case "devices":
  15681. connection.emuc.addDevicesToPresence(value);
  15682. break;
  15683. case "startMuted":
  15684. if(!Moderator.isModerator())
  15685. return;
  15686. connection.emuc.addStartMutedToPresence(value[0],
  15687. value[1]);
  15688. break;
  15689. default :
  15690. console.log("Unknown tag for presence: " + name);
  15691. return;
  15692. }
  15693. if (!dontSend)
  15694. connection.emuc.sendPresence();
  15695. },
  15696. /**
  15697. * Sends 'data' as a log message to the focus. Returns true iff a message
  15698. * was sent.
  15699. * @param data
  15700. * @returns {boolean} true iff a message was sent.
  15701. */
  15702. sendLogs: function (data) {
  15703. if(!connection.emuc.focusMucJid)
  15704. return false;
  15705. var deflate = true;
  15706. var content = JSON.stringify(data);
  15707. if (deflate) {
  15708. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15709. }
  15710. content = Base64.encode(content);
  15711. // XEP-0337-ish
  15712. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15713. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15714. id: 'PeerConnectionStats'});
  15715. message.c('message').t(content).up();
  15716. if (deflate) {
  15717. message.c('tag', {name: "deflated", value: "true"}).up();
  15718. }
  15719. message.up();
  15720. connection.send(message);
  15721. return true;
  15722. },
  15723. populateData: function () {
  15724. var data = {};
  15725. if (connection.jingle) {
  15726. data = connection.jingle.populateData();
  15727. }
  15728. return data;
  15729. },
  15730. getLogger: function () {
  15731. if(connection.logger)
  15732. return connection.logger.log;
  15733. return null;
  15734. },
  15735. getPrezi: function () {
  15736. return connection.emuc.getPrezi(this.myJid());
  15737. },
  15738. removePreziFromPresence: function () {
  15739. connection.emuc.removePreziFromPresence();
  15740. connection.emuc.sendPresence();
  15741. },
  15742. sendChatMessage: function (message, nickname) {
  15743. connection.emuc.sendMessage(message, nickname);
  15744. },
  15745. setSubject: function (topic) {
  15746. connection.emuc.setSubject(topic);
  15747. },
  15748. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15749. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15750. },
  15751. dial: function (to, from, roomName,roomPass) {
  15752. connection.rayo.dial(to, from, roomName,roomPass);
  15753. },
  15754. setMute: function (jid, mute) {
  15755. connection.moderate.setMute(jid, mute);
  15756. },
  15757. eject: function (jid) {
  15758. connection.moderate.eject(jid);
  15759. },
  15760. logout: function (callback) {
  15761. Moderator.logout(callback);
  15762. },
  15763. findJidFromResource: function (resource) {
  15764. return connection.emuc.findJidFromResource(resource);
  15765. },
  15766. getMembers: function () {
  15767. return connection.emuc.members;
  15768. },
  15769. getJidFromSSRC: function (ssrc) {
  15770. if(!connection)
  15771. return null;
  15772. return connection.emuc.ssrc2jid[ssrc];
  15773. },
  15774. getMUCJoined: function () {
  15775. return connection.emuc.joined;
  15776. },
  15777. getSessions: function () {
  15778. return connection.jingle.sessions;
  15779. },
  15780. removeStream: function (stream) {
  15781. if(!connection || !connection.jingle.activecall ||
  15782. !connection.jingle.activecall.peerconnection)
  15783. return;
  15784. connection.jingle.activecall.peerconnection.removeStream(stream);
  15785. }
  15786. };
  15787. module.exports = XMPP;
  15788. },{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/UI/UIEvents":99,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":39,"./SDP":50,"./moderator":54,"./recording":55,"./strophe.emuc":56,"./strophe.jingle":57,"./strophe.logger":58,"./strophe.moderate":59,"./strophe.rayo":60,"./strophe.util":61,"events":65,"pako":67,"retry":83}],63:[function(require,module,exports){
  15789. (function (process){
  15790. /*!
  15791. * async
  15792. * https://github.com/caolan/async
  15793. *
  15794. * Copyright 2010-2014 Caolan McMahon
  15795. * Released under the MIT license
  15796. */
  15797. /*jshint onevar: false, indent:4 */
  15798. /*global setImmediate: false, setTimeout: false, console: false */
  15799. (function () {
  15800. var async = {};
  15801. // global on the server, window in the browser
  15802. var root, previous_async;
  15803. root = this;
  15804. if (root != null) {
  15805. previous_async = root.async;
  15806. }
  15807. async.noConflict = function () {
  15808. root.async = previous_async;
  15809. return async;
  15810. };
  15811. function only_once(fn) {
  15812. var called = false;
  15813. return function() {
  15814. if (called) throw new Error("Callback was already called.");
  15815. called = true;
  15816. fn.apply(root, arguments);
  15817. }
  15818. }
  15819. //// cross-browser compatiblity functions ////
  15820. var _toString = Object.prototype.toString;
  15821. var _isArray = Array.isArray || function (obj) {
  15822. return _toString.call(obj) === '[object Array]';
  15823. };
  15824. var _each = function (arr, iterator) {
  15825. if (arr.forEach) {
  15826. return arr.forEach(iterator);
  15827. }
  15828. for (var i = 0; i < arr.length; i += 1) {
  15829. iterator(arr[i], i, arr);
  15830. }
  15831. };
  15832. var _map = function (arr, iterator) {
  15833. if (arr.map) {
  15834. return arr.map(iterator);
  15835. }
  15836. var results = [];
  15837. _each(arr, function (x, i, a) {
  15838. results.push(iterator(x, i, a));
  15839. });
  15840. return results;
  15841. };
  15842. var _reduce = function (arr, iterator, memo) {
  15843. if (arr.reduce) {
  15844. return arr.reduce(iterator, memo);
  15845. }
  15846. _each(arr, function (x, i, a) {
  15847. memo = iterator(memo, x, i, a);
  15848. });
  15849. return memo;
  15850. };
  15851. var _keys = function (obj) {
  15852. if (Object.keys) {
  15853. return Object.keys(obj);
  15854. }
  15855. var keys = [];
  15856. for (var k in obj) {
  15857. if (obj.hasOwnProperty(k)) {
  15858. keys.push(k);
  15859. }
  15860. }
  15861. return keys;
  15862. };
  15863. //// exported async module functions ////
  15864. //// nextTick implementation with browser-compatible fallback ////
  15865. if (typeof process === 'undefined' || !(process.nextTick)) {
  15866. if (typeof setImmediate === 'function') {
  15867. async.nextTick = function (fn) {
  15868. // not a direct alias for IE10 compatibility
  15869. setImmediate(fn);
  15870. };
  15871. async.setImmediate = async.nextTick;
  15872. }
  15873. else {
  15874. async.nextTick = function (fn) {
  15875. setTimeout(fn, 0);
  15876. };
  15877. async.setImmediate = async.nextTick;
  15878. }
  15879. }
  15880. else {
  15881. async.nextTick = process.nextTick;
  15882. if (typeof setImmediate !== 'undefined') {
  15883. async.setImmediate = function (fn) {
  15884. // not a direct alias for IE10 compatibility
  15885. setImmediate(fn);
  15886. };
  15887. }
  15888. else {
  15889. async.setImmediate = async.nextTick;
  15890. }
  15891. }
  15892. async.each = function (arr, iterator, callback) {
  15893. callback = callback || function () {};
  15894. if (!arr.length) {
  15895. return callback();
  15896. }
  15897. var completed = 0;
  15898. _each(arr, function (x) {
  15899. iterator(x, only_once(done) );
  15900. });
  15901. function done(err) {
  15902. if (err) {
  15903. callback(err);
  15904. callback = function () {};
  15905. }
  15906. else {
  15907. completed += 1;
  15908. if (completed >= arr.length) {
  15909. callback();
  15910. }
  15911. }
  15912. }
  15913. };
  15914. async.forEach = async.each;
  15915. async.eachSeries = function (arr, iterator, callback) {
  15916. callback = callback || function () {};
  15917. if (!arr.length) {
  15918. return callback();
  15919. }
  15920. var completed = 0;
  15921. var iterate = function () {
  15922. iterator(arr[completed], function (err) {
  15923. if (err) {
  15924. callback(err);
  15925. callback = function () {};
  15926. }
  15927. else {
  15928. completed += 1;
  15929. if (completed >= arr.length) {
  15930. callback();
  15931. }
  15932. else {
  15933. iterate();
  15934. }
  15935. }
  15936. });
  15937. };
  15938. iterate();
  15939. };
  15940. async.forEachSeries = async.eachSeries;
  15941. async.eachLimit = function (arr, limit, iterator, callback) {
  15942. var fn = _eachLimit(limit);
  15943. fn.apply(null, [arr, iterator, callback]);
  15944. };
  15945. async.forEachLimit = async.eachLimit;
  15946. var _eachLimit = function (limit) {
  15947. return function (arr, iterator, callback) {
  15948. callback = callback || function () {};
  15949. if (!arr.length || limit <= 0) {
  15950. return callback();
  15951. }
  15952. var completed = 0;
  15953. var started = 0;
  15954. var running = 0;
  15955. (function replenish () {
  15956. if (completed >= arr.length) {
  15957. return callback();
  15958. }
  15959. while (running < limit && started < arr.length) {
  15960. started += 1;
  15961. running += 1;
  15962. iterator(arr[started - 1], function (err) {
  15963. if (err) {
  15964. callback(err);
  15965. callback = function () {};
  15966. }
  15967. else {
  15968. completed += 1;
  15969. running -= 1;
  15970. if (completed >= arr.length) {
  15971. callback();
  15972. }
  15973. else {
  15974. replenish();
  15975. }
  15976. }
  15977. });
  15978. }
  15979. })();
  15980. };
  15981. };
  15982. var doParallel = function (fn) {
  15983. return function () {
  15984. var args = Array.prototype.slice.call(arguments);
  15985. return fn.apply(null, [async.each].concat(args));
  15986. };
  15987. };
  15988. var doParallelLimit = function(limit, fn) {
  15989. return function () {
  15990. var args = Array.prototype.slice.call(arguments);
  15991. return fn.apply(null, [_eachLimit(limit)].concat(args));
  15992. };
  15993. };
  15994. var doSeries = function (fn) {
  15995. return function () {
  15996. var args = Array.prototype.slice.call(arguments);
  15997. return fn.apply(null, [async.eachSeries].concat(args));
  15998. };
  15999. };
  16000. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16001. arr = _map(arr, function (x, i) {
  16002. return {index: i, value: x};
  16003. });
  16004. if (!callback) {
  16005. eachfn(arr, function (x, callback) {
  16006. iterator(x.value, function (err) {
  16007. callback(err);
  16008. });
  16009. });
  16010. } else {
  16011. var results = [];
  16012. eachfn(arr, function (x, callback) {
  16013. iterator(x.value, function (err, v) {
  16014. results[x.index] = v;
  16015. callback(err);
  16016. });
  16017. }, function (err) {
  16018. callback(err, results);
  16019. });
  16020. }
  16021. };
  16022. async.map = doParallel(_asyncMap);
  16023. async.mapSeries = doSeries(_asyncMap);
  16024. async.mapLimit = function (arr, limit, iterator, callback) {
  16025. return _mapLimit(limit)(arr, iterator, callback);
  16026. };
  16027. var _mapLimit = function(limit) {
  16028. return doParallelLimit(limit, _asyncMap);
  16029. };
  16030. // reduce only has a series version, as doing reduce in parallel won't
  16031. // work in many situations.
  16032. async.reduce = function (arr, memo, iterator, callback) {
  16033. async.eachSeries(arr, function (x, callback) {
  16034. iterator(memo, x, function (err, v) {
  16035. memo = v;
  16036. callback(err);
  16037. });
  16038. }, function (err) {
  16039. callback(err, memo);
  16040. });
  16041. };
  16042. // inject alias
  16043. async.inject = async.reduce;
  16044. // foldl alias
  16045. async.foldl = async.reduce;
  16046. async.reduceRight = function (arr, memo, iterator, callback) {
  16047. var reversed = _map(arr, function (x) {
  16048. return x;
  16049. }).reverse();
  16050. async.reduce(reversed, memo, iterator, callback);
  16051. };
  16052. // foldr alias
  16053. async.foldr = async.reduceRight;
  16054. var _filter = function (eachfn, arr, iterator, callback) {
  16055. var results = [];
  16056. arr = _map(arr, function (x, i) {
  16057. return {index: i, value: x};
  16058. });
  16059. eachfn(arr, function (x, callback) {
  16060. iterator(x.value, function (v) {
  16061. if (v) {
  16062. results.push(x);
  16063. }
  16064. callback();
  16065. });
  16066. }, function (err) {
  16067. callback(_map(results.sort(function (a, b) {
  16068. return a.index - b.index;
  16069. }), function (x) {
  16070. return x.value;
  16071. }));
  16072. });
  16073. };
  16074. async.filter = doParallel(_filter);
  16075. async.filterSeries = doSeries(_filter);
  16076. // select alias
  16077. async.select = async.filter;
  16078. async.selectSeries = async.filterSeries;
  16079. var _reject = function (eachfn, arr, iterator, callback) {
  16080. var results = [];
  16081. arr = _map(arr, function (x, i) {
  16082. return {index: i, value: x};
  16083. });
  16084. eachfn(arr, function (x, callback) {
  16085. iterator(x.value, function (v) {
  16086. if (!v) {
  16087. results.push(x);
  16088. }
  16089. callback();
  16090. });
  16091. }, function (err) {
  16092. callback(_map(results.sort(function (a, b) {
  16093. return a.index - b.index;
  16094. }), function (x) {
  16095. return x.value;
  16096. }));
  16097. });
  16098. };
  16099. async.reject = doParallel(_reject);
  16100. async.rejectSeries = doSeries(_reject);
  16101. var _detect = function (eachfn, arr, iterator, main_callback) {
  16102. eachfn(arr, function (x, callback) {
  16103. iterator(x, function (result) {
  16104. if (result) {
  16105. main_callback(x);
  16106. main_callback = function () {};
  16107. }
  16108. else {
  16109. callback();
  16110. }
  16111. });
  16112. }, function (err) {
  16113. main_callback();
  16114. });
  16115. };
  16116. async.detect = doParallel(_detect);
  16117. async.detectSeries = doSeries(_detect);
  16118. async.some = function (arr, iterator, main_callback) {
  16119. async.each(arr, function (x, callback) {
  16120. iterator(x, function (v) {
  16121. if (v) {
  16122. main_callback(true);
  16123. main_callback = function () {};
  16124. }
  16125. callback();
  16126. });
  16127. }, function (err) {
  16128. main_callback(false);
  16129. });
  16130. };
  16131. // any alias
  16132. async.any = async.some;
  16133. async.every = function (arr, iterator, main_callback) {
  16134. async.each(arr, function (x, callback) {
  16135. iterator(x, function (v) {
  16136. if (!v) {
  16137. main_callback(false);
  16138. main_callback = function () {};
  16139. }
  16140. callback();
  16141. });
  16142. }, function (err) {
  16143. main_callback(true);
  16144. });
  16145. };
  16146. // all alias
  16147. async.all = async.every;
  16148. async.sortBy = function (arr, iterator, callback) {
  16149. async.map(arr, function (x, callback) {
  16150. iterator(x, function (err, criteria) {
  16151. if (err) {
  16152. callback(err);
  16153. }
  16154. else {
  16155. callback(null, {value: x, criteria: criteria});
  16156. }
  16157. });
  16158. }, function (err, results) {
  16159. if (err) {
  16160. return callback(err);
  16161. }
  16162. else {
  16163. var fn = function (left, right) {
  16164. var a = left.criteria, b = right.criteria;
  16165. return a < b ? -1 : a > b ? 1 : 0;
  16166. };
  16167. callback(null, _map(results.sort(fn), function (x) {
  16168. return x.value;
  16169. }));
  16170. }
  16171. });
  16172. };
  16173. async.auto = function (tasks, callback) {
  16174. callback = callback || function () {};
  16175. var keys = _keys(tasks);
  16176. var remainingTasks = keys.length
  16177. if (!remainingTasks) {
  16178. return callback();
  16179. }
  16180. var results = {};
  16181. var listeners = [];
  16182. var addListener = function (fn) {
  16183. listeners.unshift(fn);
  16184. };
  16185. var removeListener = function (fn) {
  16186. for (var i = 0; i < listeners.length; i += 1) {
  16187. if (listeners[i] === fn) {
  16188. listeners.splice(i, 1);
  16189. return;
  16190. }
  16191. }
  16192. };
  16193. var taskComplete = function () {
  16194. remainingTasks--
  16195. _each(listeners.slice(0), function (fn) {
  16196. fn();
  16197. });
  16198. };
  16199. addListener(function () {
  16200. if (!remainingTasks) {
  16201. var theCallback = callback;
  16202. // prevent final callback from calling itself if it errors
  16203. callback = function () {};
  16204. theCallback(null, results);
  16205. }
  16206. });
  16207. _each(keys, function (k) {
  16208. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16209. var taskCallback = function (err) {
  16210. var args = Array.prototype.slice.call(arguments, 1);
  16211. if (args.length <= 1) {
  16212. args = args[0];
  16213. }
  16214. if (err) {
  16215. var safeResults = {};
  16216. _each(_keys(results), function(rkey) {
  16217. safeResults[rkey] = results[rkey];
  16218. });
  16219. safeResults[k] = args;
  16220. callback(err, safeResults);
  16221. // stop subsequent errors hitting callback multiple times
  16222. callback = function () {};
  16223. }
  16224. else {
  16225. results[k] = args;
  16226. async.setImmediate(taskComplete);
  16227. }
  16228. };
  16229. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16230. var ready = function () {
  16231. return _reduce(requires, function (a, x) {
  16232. return (a && results.hasOwnProperty(x));
  16233. }, true) && !results.hasOwnProperty(k);
  16234. };
  16235. if (ready()) {
  16236. task[task.length - 1](taskCallback, results);
  16237. }
  16238. else {
  16239. var listener = function () {
  16240. if (ready()) {
  16241. removeListener(listener);
  16242. task[task.length - 1](taskCallback, results);
  16243. }
  16244. };
  16245. addListener(listener);
  16246. }
  16247. });
  16248. };
  16249. async.retry = function(times, task, callback) {
  16250. var DEFAULT_TIMES = 5;
  16251. var attempts = [];
  16252. // Use defaults if times not passed
  16253. if (typeof times === 'function') {
  16254. callback = task;
  16255. task = times;
  16256. times = DEFAULT_TIMES;
  16257. }
  16258. // Make sure times is a number
  16259. times = parseInt(times, 10) || DEFAULT_TIMES;
  16260. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16261. var retryAttempt = function(task, finalAttempt) {
  16262. return function(seriesCallback) {
  16263. task(function(err, result){
  16264. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16265. }, wrappedResults);
  16266. };
  16267. };
  16268. while (times) {
  16269. attempts.push(retryAttempt(task, !(times-=1)));
  16270. }
  16271. async.series(attempts, function(done, data){
  16272. data = data[data.length - 1];
  16273. (wrappedCallback || callback)(data.err, data.result);
  16274. });
  16275. }
  16276. // If a callback is passed, run this as a controll flow
  16277. return callback ? wrappedTask() : wrappedTask
  16278. };
  16279. async.waterfall = function (tasks, callback) {
  16280. callback = callback || function () {};
  16281. if (!_isArray(tasks)) {
  16282. var err = new Error('First argument to waterfall must be an array of functions');
  16283. return callback(err);
  16284. }
  16285. if (!tasks.length) {
  16286. return callback();
  16287. }
  16288. var wrapIterator = function (iterator) {
  16289. return function (err) {
  16290. if (err) {
  16291. callback.apply(null, arguments);
  16292. callback = function () {};
  16293. }
  16294. else {
  16295. var args = Array.prototype.slice.call(arguments, 1);
  16296. var next = iterator.next();
  16297. if (next) {
  16298. args.push(wrapIterator(next));
  16299. }
  16300. else {
  16301. args.push(callback);
  16302. }
  16303. async.setImmediate(function () {
  16304. iterator.apply(null, args);
  16305. });
  16306. }
  16307. };
  16308. };
  16309. wrapIterator(async.iterator(tasks))();
  16310. };
  16311. var _parallel = function(eachfn, tasks, callback) {
  16312. callback = callback || function () {};
  16313. if (_isArray(tasks)) {
  16314. eachfn.map(tasks, function (fn, callback) {
  16315. if (fn) {
  16316. fn(function (err) {
  16317. var args = Array.prototype.slice.call(arguments, 1);
  16318. if (args.length <= 1) {
  16319. args = args[0];
  16320. }
  16321. callback.call(null, err, args);
  16322. });
  16323. }
  16324. }, callback);
  16325. }
  16326. else {
  16327. var results = {};
  16328. eachfn.each(_keys(tasks), function (k, callback) {
  16329. tasks[k](function (err) {
  16330. var args = Array.prototype.slice.call(arguments, 1);
  16331. if (args.length <= 1) {
  16332. args = args[0];
  16333. }
  16334. results[k] = args;
  16335. callback(err);
  16336. });
  16337. }, function (err) {
  16338. callback(err, results);
  16339. });
  16340. }
  16341. };
  16342. async.parallel = function (tasks, callback) {
  16343. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16344. };
  16345. async.parallelLimit = function(tasks, limit, callback) {
  16346. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16347. };
  16348. async.series = function (tasks, callback) {
  16349. callback = callback || function () {};
  16350. if (_isArray(tasks)) {
  16351. async.mapSeries(tasks, function (fn, callback) {
  16352. if (fn) {
  16353. fn(function (err) {
  16354. var args = Array.prototype.slice.call(arguments, 1);
  16355. if (args.length <= 1) {
  16356. args = args[0];
  16357. }
  16358. callback.call(null, err, args);
  16359. });
  16360. }
  16361. }, callback);
  16362. }
  16363. else {
  16364. var results = {};
  16365. async.eachSeries(_keys(tasks), function (k, callback) {
  16366. tasks[k](function (err) {
  16367. var args = Array.prototype.slice.call(arguments, 1);
  16368. if (args.length <= 1) {
  16369. args = args[0];
  16370. }
  16371. results[k] = args;
  16372. callback(err);
  16373. });
  16374. }, function (err) {
  16375. callback(err, results);
  16376. });
  16377. }
  16378. };
  16379. async.iterator = function (tasks) {
  16380. var makeCallback = function (index) {
  16381. var fn = function () {
  16382. if (tasks.length) {
  16383. tasks[index].apply(null, arguments);
  16384. }
  16385. return fn.next();
  16386. };
  16387. fn.next = function () {
  16388. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16389. };
  16390. return fn;
  16391. };
  16392. return makeCallback(0);
  16393. };
  16394. async.apply = function (fn) {
  16395. var args = Array.prototype.slice.call(arguments, 1);
  16396. return function () {
  16397. return fn.apply(
  16398. null, args.concat(Array.prototype.slice.call(arguments))
  16399. );
  16400. };
  16401. };
  16402. var _concat = function (eachfn, arr, fn, callback) {
  16403. var r = [];
  16404. eachfn(arr, function (x, cb) {
  16405. fn(x, function (err, y) {
  16406. r = r.concat(y || []);
  16407. cb(err);
  16408. });
  16409. }, function (err) {
  16410. callback(err, r);
  16411. });
  16412. };
  16413. async.concat = doParallel(_concat);
  16414. async.concatSeries = doSeries(_concat);
  16415. async.whilst = function (test, iterator, callback) {
  16416. if (test()) {
  16417. iterator(function (err) {
  16418. if (err) {
  16419. return callback(err);
  16420. }
  16421. async.whilst(test, iterator, callback);
  16422. });
  16423. }
  16424. else {
  16425. callback();
  16426. }
  16427. };
  16428. async.doWhilst = function (iterator, test, callback) {
  16429. iterator(function (err) {
  16430. if (err) {
  16431. return callback(err);
  16432. }
  16433. var args = Array.prototype.slice.call(arguments, 1);
  16434. if (test.apply(null, args)) {
  16435. async.doWhilst(iterator, test, callback);
  16436. }
  16437. else {
  16438. callback();
  16439. }
  16440. });
  16441. };
  16442. async.until = function (test, iterator, callback) {
  16443. if (!test()) {
  16444. iterator(function (err) {
  16445. if (err) {
  16446. return callback(err);
  16447. }
  16448. async.until(test, iterator, callback);
  16449. });
  16450. }
  16451. else {
  16452. callback();
  16453. }
  16454. };
  16455. async.doUntil = function (iterator, test, callback) {
  16456. iterator(function (err) {
  16457. if (err) {
  16458. return callback(err);
  16459. }
  16460. var args = Array.prototype.slice.call(arguments, 1);
  16461. if (!test.apply(null, args)) {
  16462. async.doUntil(iterator, test, callback);
  16463. }
  16464. else {
  16465. callback();
  16466. }
  16467. });
  16468. };
  16469. async.queue = function (worker, concurrency) {
  16470. if (concurrency === undefined) {
  16471. concurrency = 1;
  16472. }
  16473. function _insert(q, data, pos, callback) {
  16474. if (!q.started){
  16475. q.started = true;
  16476. }
  16477. if (!_isArray(data)) {
  16478. data = [data];
  16479. }
  16480. if(data.length == 0) {
  16481. // call drain immediately if there are no tasks
  16482. return async.setImmediate(function() {
  16483. if (q.drain) {
  16484. q.drain();
  16485. }
  16486. });
  16487. }
  16488. _each(data, function(task) {
  16489. var item = {
  16490. data: task,
  16491. callback: typeof callback === 'function' ? callback : null
  16492. };
  16493. if (pos) {
  16494. q.tasks.unshift(item);
  16495. } else {
  16496. q.tasks.push(item);
  16497. }
  16498. if (q.saturated && q.tasks.length === q.concurrency) {
  16499. q.saturated();
  16500. }
  16501. async.setImmediate(q.process);
  16502. });
  16503. }
  16504. var workers = 0;
  16505. var q = {
  16506. tasks: [],
  16507. concurrency: concurrency,
  16508. saturated: null,
  16509. empty: null,
  16510. drain: null,
  16511. started: false,
  16512. paused: false,
  16513. push: function (data, callback) {
  16514. _insert(q, data, false, callback);
  16515. },
  16516. kill: function () {
  16517. q.drain = null;
  16518. q.tasks = [];
  16519. },
  16520. unshift: function (data, callback) {
  16521. _insert(q, data, true, callback);
  16522. },
  16523. process: function () {
  16524. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16525. var task = q.tasks.shift();
  16526. if (q.empty && q.tasks.length === 0) {
  16527. q.empty();
  16528. }
  16529. workers += 1;
  16530. var next = function () {
  16531. workers -= 1;
  16532. if (task.callback) {
  16533. task.callback.apply(task, arguments);
  16534. }
  16535. if (q.drain && q.tasks.length + workers === 0) {
  16536. q.drain();
  16537. }
  16538. q.process();
  16539. };
  16540. var cb = only_once(next);
  16541. worker(task.data, cb);
  16542. }
  16543. },
  16544. length: function () {
  16545. return q.tasks.length;
  16546. },
  16547. running: function () {
  16548. return workers;
  16549. },
  16550. idle: function() {
  16551. return q.tasks.length + workers === 0;
  16552. },
  16553. pause: function () {
  16554. if (q.paused === true) { return; }
  16555. q.paused = true;
  16556. q.process();
  16557. },
  16558. resume: function () {
  16559. if (q.paused === false) { return; }
  16560. q.paused = false;
  16561. q.process();
  16562. }
  16563. };
  16564. return q;
  16565. };
  16566. async.priorityQueue = function (worker, concurrency) {
  16567. function _compareTasks(a, b){
  16568. return a.priority - b.priority;
  16569. };
  16570. function _binarySearch(sequence, item, compare) {
  16571. var beg = -1,
  16572. end = sequence.length - 1;
  16573. while (beg < end) {
  16574. var mid = beg + ((end - beg + 1) >>> 1);
  16575. if (compare(item, sequence[mid]) >= 0) {
  16576. beg = mid;
  16577. } else {
  16578. end = mid - 1;
  16579. }
  16580. }
  16581. return beg;
  16582. }
  16583. function _insert(q, data, priority, callback) {
  16584. if (!q.started){
  16585. q.started = true;
  16586. }
  16587. if (!_isArray(data)) {
  16588. data = [data];
  16589. }
  16590. if(data.length == 0) {
  16591. // call drain immediately if there are no tasks
  16592. return async.setImmediate(function() {
  16593. if (q.drain) {
  16594. q.drain();
  16595. }
  16596. });
  16597. }
  16598. _each(data, function(task) {
  16599. var item = {
  16600. data: task,
  16601. priority: priority,
  16602. callback: typeof callback === 'function' ? callback : null
  16603. };
  16604. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  16605. if (q.saturated && q.tasks.length === q.concurrency) {
  16606. q.saturated();
  16607. }
  16608. async.setImmediate(q.process);
  16609. });
  16610. }
  16611. // Start with a normal queue
  16612. var q = async.queue(worker, concurrency);
  16613. // Override push to accept second parameter representing priority
  16614. q.push = function (data, priority, callback) {
  16615. _insert(q, data, priority, callback);
  16616. };
  16617. // Remove unshift function
  16618. delete q.unshift;
  16619. return q;
  16620. };
  16621. async.cargo = function (worker, payload) {
  16622. var working = false,
  16623. tasks = [];
  16624. var cargo = {
  16625. tasks: tasks,
  16626. payload: payload,
  16627. saturated: null,
  16628. empty: null,
  16629. drain: null,
  16630. drained: true,
  16631. push: function (data, callback) {
  16632. if (!_isArray(data)) {
  16633. data = [data];
  16634. }
  16635. _each(data, function(task) {
  16636. tasks.push({
  16637. data: task,
  16638. callback: typeof callback === 'function' ? callback : null
  16639. });
  16640. cargo.drained = false;
  16641. if (cargo.saturated && tasks.length === payload) {
  16642. cargo.saturated();
  16643. }
  16644. });
  16645. async.setImmediate(cargo.process);
  16646. },
  16647. process: function process() {
  16648. if (working) return;
  16649. if (tasks.length === 0) {
  16650. if(cargo.drain && !cargo.drained) cargo.drain();
  16651. cargo.drained = true;
  16652. return;
  16653. }
  16654. var ts = typeof payload === 'number'
  16655. ? tasks.splice(0, payload)
  16656. : tasks.splice(0, tasks.length);
  16657. var ds = _map(ts, function (task) {
  16658. return task.data;
  16659. });
  16660. if(cargo.empty) cargo.empty();
  16661. working = true;
  16662. worker(ds, function () {
  16663. working = false;
  16664. var args = arguments;
  16665. _each(ts, function (data) {
  16666. if (data.callback) {
  16667. data.callback.apply(null, args);
  16668. }
  16669. });
  16670. process();
  16671. });
  16672. },
  16673. length: function () {
  16674. return tasks.length;
  16675. },
  16676. running: function () {
  16677. return working;
  16678. }
  16679. };
  16680. return cargo;
  16681. };
  16682. var _console_fn = function (name) {
  16683. return function (fn) {
  16684. var args = Array.prototype.slice.call(arguments, 1);
  16685. fn.apply(null, args.concat([function (err) {
  16686. var args = Array.prototype.slice.call(arguments, 1);
  16687. if (typeof console !== 'undefined') {
  16688. if (err) {
  16689. if (console.error) {
  16690. console.error(err);
  16691. }
  16692. }
  16693. else if (console[name]) {
  16694. _each(args, function (x) {
  16695. console[name](x);
  16696. });
  16697. }
  16698. }
  16699. }]));
  16700. };
  16701. };
  16702. async.log = _console_fn('log');
  16703. async.dir = _console_fn('dir');
  16704. /*async.info = _console_fn('info');
  16705. async.warn = _console_fn('warn');
  16706. async.error = _console_fn('error');*/
  16707. async.memoize = function (fn, hasher) {
  16708. var memo = {};
  16709. var queues = {};
  16710. hasher = hasher || function (x) {
  16711. return x;
  16712. };
  16713. var memoized = function () {
  16714. var args = Array.prototype.slice.call(arguments);
  16715. var callback = args.pop();
  16716. var key = hasher.apply(null, args);
  16717. if (key in memo) {
  16718. async.nextTick(function () {
  16719. callback.apply(null, memo[key]);
  16720. });
  16721. }
  16722. else if (key in queues) {
  16723. queues[key].push(callback);
  16724. }
  16725. else {
  16726. queues[key] = [callback];
  16727. fn.apply(null, args.concat([function () {
  16728. memo[key] = arguments;
  16729. var q = queues[key];
  16730. delete queues[key];
  16731. for (var i = 0, l = q.length; i < l; i++) {
  16732. q[i].apply(null, arguments);
  16733. }
  16734. }]));
  16735. }
  16736. };
  16737. memoized.memo = memo;
  16738. memoized.unmemoized = fn;
  16739. return memoized;
  16740. };
  16741. async.unmemoize = function (fn) {
  16742. return function () {
  16743. return (fn.unmemoized || fn).apply(null, arguments);
  16744. };
  16745. };
  16746. async.times = function (count, iterator, callback) {
  16747. var counter = [];
  16748. for (var i = 0; i < count; i++) {
  16749. counter.push(i);
  16750. }
  16751. return async.map(counter, iterator, callback);
  16752. };
  16753. async.timesSeries = function (count, iterator, callback) {
  16754. var counter = [];
  16755. for (var i = 0; i < count; i++) {
  16756. counter.push(i);
  16757. }
  16758. return async.mapSeries(counter, iterator, callback);
  16759. };
  16760. async.seq = function (/* functions... */) {
  16761. var fns = arguments;
  16762. return function () {
  16763. var that = this;
  16764. var args = Array.prototype.slice.call(arguments);
  16765. var callback = args.pop();
  16766. async.reduce(fns, args, function (newargs, fn, cb) {
  16767. fn.apply(that, newargs.concat([function () {
  16768. var err = arguments[0];
  16769. var nextargs = Array.prototype.slice.call(arguments, 1);
  16770. cb(err, nextargs);
  16771. }]))
  16772. },
  16773. function (err, results) {
  16774. callback.apply(that, [err].concat(results));
  16775. });
  16776. };
  16777. };
  16778. async.compose = function (/* functions... */) {
  16779. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  16780. };
  16781. var _applyEach = function (eachfn, fns /*args...*/) {
  16782. var go = function () {
  16783. var that = this;
  16784. var args = Array.prototype.slice.call(arguments);
  16785. var callback = args.pop();
  16786. return eachfn(fns, function (fn, cb) {
  16787. fn.apply(that, args.concat([cb]));
  16788. },
  16789. callback);
  16790. };
  16791. if (arguments.length > 2) {
  16792. var args = Array.prototype.slice.call(arguments, 2);
  16793. return go.apply(this, args);
  16794. }
  16795. else {
  16796. return go;
  16797. }
  16798. };
  16799. async.applyEach = doParallel(_applyEach);
  16800. async.applyEachSeries = doSeries(_applyEach);
  16801. async.forever = function (fn, callback) {
  16802. function next(err) {
  16803. if (err) {
  16804. if (callback) {
  16805. return callback(err);
  16806. }
  16807. throw err;
  16808. }
  16809. fn(next);
  16810. }
  16811. next();
  16812. };
  16813. // Node.js
  16814. if (typeof module !== 'undefined' && module.exports) {
  16815. module.exports = async;
  16816. }
  16817. // AMD / RequireJS
  16818. else if (typeof define !== 'undefined' && define.amd) {
  16819. define([], function () {
  16820. return async;
  16821. });
  16822. }
  16823. // included directly via <script> tag
  16824. else {
  16825. root.async = async;
  16826. }
  16827. }());
  16828. }).call(this,require('_process'))
  16829. },{"_process":64}],64:[function(require,module,exports){
  16830. // shim for using process in browser
  16831. var process = module.exports = {};
  16832. var queue = [];
  16833. var draining = false;
  16834. var currentQueue;
  16835. var queueIndex = -1;
  16836. function cleanUpNextTick() {
  16837. draining = false;
  16838. if (currentQueue.length) {
  16839. queue = currentQueue.concat(queue);
  16840. } else {
  16841. queueIndex = -1;
  16842. }
  16843. if (queue.length) {
  16844. drainQueue();
  16845. }
  16846. }
  16847. function drainQueue() {
  16848. if (draining) {
  16849. return;
  16850. }
  16851. var timeout = setTimeout(cleanUpNextTick);
  16852. draining = true;
  16853. var len = queue.length;
  16854. while(len) {
  16855. currentQueue = queue;
  16856. queue = [];
  16857. while (++queueIndex < len) {
  16858. currentQueue[queueIndex].run();
  16859. }
  16860. queueIndex = -1;
  16861. len = queue.length;
  16862. }
  16863. currentQueue = null;
  16864. draining = false;
  16865. clearTimeout(timeout);
  16866. }
  16867. process.nextTick = function (fun) {
  16868. var args = new Array(arguments.length - 1);
  16869. if (arguments.length > 1) {
  16870. for (var i = 1; i < arguments.length; i++) {
  16871. args[i - 1] = arguments[i];
  16872. }
  16873. }
  16874. queue.push(new Item(fun, args));
  16875. if (!draining) {
  16876. setTimeout(drainQueue, 0);
  16877. }
  16878. };
  16879. // v8 likes predictible objects
  16880. function Item(fun, array) {
  16881. this.fun = fun;
  16882. this.array = array;
  16883. }
  16884. Item.prototype.run = function () {
  16885. this.fun.apply(null, this.array);
  16886. };
  16887. process.title = 'browser';
  16888. process.browser = true;
  16889. process.env = {};
  16890. process.argv = [];
  16891. process.version = ''; // empty string to avoid regexp issues
  16892. process.versions = {};
  16893. function noop() {}
  16894. process.on = noop;
  16895. process.addListener = noop;
  16896. process.once = noop;
  16897. process.off = noop;
  16898. process.removeListener = noop;
  16899. process.removeAllListeners = noop;
  16900. process.emit = noop;
  16901. process.binding = function (name) {
  16902. throw new Error('process.binding is not supported');
  16903. };
  16904. // TODO(shtylman)
  16905. process.cwd = function () { return '/' };
  16906. process.chdir = function (dir) {
  16907. throw new Error('process.chdir is not supported');
  16908. };
  16909. process.umask = function() { return 0; };
  16910. },{}],65:[function(require,module,exports){
  16911. // Copyright Joyent, Inc. and other Node contributors.
  16912. //
  16913. // Permission is hereby granted, free of charge, to any person obtaining a
  16914. // copy of this software and associated documentation files (the
  16915. // "Software"), to deal in the Software without restriction, including
  16916. // without limitation the rights to use, copy, modify, merge, publish,
  16917. // distribute, sublicense, and/or sell copies of the Software, and to permit
  16918. // persons to whom the Software is furnished to do so, subject to the
  16919. // following conditions:
  16920. //
  16921. // The above copyright notice and this permission notice shall be included
  16922. // in all copies or substantial portions of the Software.
  16923. //
  16924. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16925. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16926. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  16927. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  16928. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16929. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  16930. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  16931. function EventEmitter() {
  16932. this._events = this._events || {};
  16933. this._maxListeners = this._maxListeners || undefined;
  16934. }
  16935. module.exports = EventEmitter;
  16936. // Backwards-compat with node 0.10.x
  16937. EventEmitter.EventEmitter = EventEmitter;
  16938. EventEmitter.prototype._events = undefined;
  16939. EventEmitter.prototype._maxListeners = undefined;
  16940. // By default EventEmitters will print a warning if more than 10 listeners are
  16941. // added to it. This is a useful default which helps finding memory leaks.
  16942. EventEmitter.defaultMaxListeners = 10;
  16943. // Obviously not all Emitters should be limited to 10. This function allows
  16944. // that to be increased. Set to zero for unlimited.
  16945. EventEmitter.prototype.setMaxListeners = function(n) {
  16946. if (!isNumber(n) || n < 0 || isNaN(n))
  16947. throw TypeError('n must be a positive number');
  16948. this._maxListeners = n;
  16949. return this;
  16950. };
  16951. EventEmitter.prototype.emit = function(type) {
  16952. var er, handler, len, args, i, listeners;
  16953. if (!this._events)
  16954. this._events = {};
  16955. // If there is no 'error' event listener then throw.
  16956. if (type === 'error') {
  16957. if (!this._events.error ||
  16958. (isObject(this._events.error) && !this._events.error.length)) {
  16959. er = arguments[1];
  16960. if (er instanceof Error) {
  16961. throw er; // Unhandled 'error' event
  16962. }
  16963. throw TypeError('Uncaught, unspecified "error" event.');
  16964. }
  16965. }
  16966. handler = this._events[type];
  16967. if (isUndefined(handler))
  16968. return false;
  16969. if (isFunction(handler)) {
  16970. switch (arguments.length) {
  16971. // fast cases
  16972. case 1:
  16973. handler.call(this);
  16974. break;
  16975. case 2:
  16976. handler.call(this, arguments[1]);
  16977. break;
  16978. case 3:
  16979. handler.call(this, arguments[1], arguments[2]);
  16980. break;
  16981. // slower
  16982. default:
  16983. len = arguments.length;
  16984. args = new Array(len - 1);
  16985. for (i = 1; i < len; i++)
  16986. args[i - 1] = arguments[i];
  16987. handler.apply(this, args);
  16988. }
  16989. } else if (isObject(handler)) {
  16990. len = arguments.length;
  16991. args = new Array(len - 1);
  16992. for (i = 1; i < len; i++)
  16993. args[i - 1] = arguments[i];
  16994. listeners = handler.slice();
  16995. len = listeners.length;
  16996. for (i = 0; i < len; i++)
  16997. listeners[i].apply(this, args);
  16998. }
  16999. return true;
  17000. };
  17001. EventEmitter.prototype.addListener = function(type, listener) {
  17002. var m;
  17003. if (!isFunction(listener))
  17004. throw TypeError('listener must be a function');
  17005. if (!this._events)
  17006. this._events = {};
  17007. // To avoid recursion in the case that type === "newListener"! Before
  17008. // adding it to the listeners, first emit "newListener".
  17009. if (this._events.newListener)
  17010. this.emit('newListener', type,
  17011. isFunction(listener.listener) ?
  17012. listener.listener : listener);
  17013. if (!this._events[type])
  17014. // Optimize the case of one listener. Don't need the extra array object.
  17015. this._events[type] = listener;
  17016. else if (isObject(this._events[type]))
  17017. // If we've already got an array, just append.
  17018. this._events[type].push(listener);
  17019. else
  17020. // Adding the second element, need to change to array.
  17021. this._events[type] = [this._events[type], listener];
  17022. // Check for listener leak
  17023. if (isObject(this._events[type]) && !this._events[type].warned) {
  17024. var m;
  17025. if (!isUndefined(this._maxListeners)) {
  17026. m = this._maxListeners;
  17027. } else {
  17028. m = EventEmitter.defaultMaxListeners;
  17029. }
  17030. if (m && m > 0 && this._events[type].length > m) {
  17031. this._events[type].warned = true;
  17032. console.error('(node) warning: possible EventEmitter memory ' +
  17033. 'leak detected. %d listeners added. ' +
  17034. 'Use emitter.setMaxListeners() to increase limit.',
  17035. this._events[type].length);
  17036. if (typeof console.trace === 'function') {
  17037. // not supported in IE 10
  17038. console.trace();
  17039. }
  17040. }
  17041. }
  17042. return this;
  17043. };
  17044. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  17045. EventEmitter.prototype.once = function(type, listener) {
  17046. if (!isFunction(listener))
  17047. throw TypeError('listener must be a function');
  17048. var fired = false;
  17049. function g() {
  17050. this.removeListener(type, g);
  17051. if (!fired) {
  17052. fired = true;
  17053. listener.apply(this, arguments);
  17054. }
  17055. }
  17056. g.listener = listener;
  17057. this.on(type, g);
  17058. return this;
  17059. };
  17060. // emits a 'removeListener' event iff the listener was removed
  17061. EventEmitter.prototype.removeListener = function(type, listener) {
  17062. var list, position, length, i;
  17063. if (!isFunction(listener))
  17064. throw TypeError('listener must be a function');
  17065. if (!this._events || !this._events[type])
  17066. return this;
  17067. list = this._events[type];
  17068. length = list.length;
  17069. position = -1;
  17070. if (list === listener ||
  17071. (isFunction(list.listener) && list.listener === listener)) {
  17072. delete this._events[type];
  17073. if (this._events.removeListener)
  17074. this.emit('removeListener', type, listener);
  17075. } else if (isObject(list)) {
  17076. for (i = length; i-- > 0;) {
  17077. if (list[i] === listener ||
  17078. (list[i].listener && list[i].listener === listener)) {
  17079. position = i;
  17080. break;
  17081. }
  17082. }
  17083. if (position < 0)
  17084. return this;
  17085. if (list.length === 1) {
  17086. list.length = 0;
  17087. delete this._events[type];
  17088. } else {
  17089. list.splice(position, 1);
  17090. }
  17091. if (this._events.removeListener)
  17092. this.emit('removeListener', type, listener);
  17093. }
  17094. return this;
  17095. };
  17096. EventEmitter.prototype.removeAllListeners = function(type) {
  17097. var key, listeners;
  17098. if (!this._events)
  17099. return this;
  17100. // not listening for removeListener, no need to emit
  17101. if (!this._events.removeListener) {
  17102. if (arguments.length === 0)
  17103. this._events = {};
  17104. else if (this._events[type])
  17105. delete this._events[type];
  17106. return this;
  17107. }
  17108. // emit removeListener for all listeners on all events
  17109. if (arguments.length === 0) {
  17110. for (key in this._events) {
  17111. if (key === 'removeListener') continue;
  17112. this.removeAllListeners(key);
  17113. }
  17114. this.removeAllListeners('removeListener');
  17115. this._events = {};
  17116. return this;
  17117. }
  17118. listeners = this._events[type];
  17119. if (isFunction(listeners)) {
  17120. this.removeListener(type, listeners);
  17121. } else {
  17122. // LIFO order
  17123. while (listeners.length)
  17124. this.removeListener(type, listeners[listeners.length - 1]);
  17125. }
  17126. delete this._events[type];
  17127. return this;
  17128. };
  17129. EventEmitter.prototype.listeners = function(type) {
  17130. var ret;
  17131. if (!this._events || !this._events[type])
  17132. ret = [];
  17133. else if (isFunction(this._events[type]))
  17134. ret = [this._events[type]];
  17135. else
  17136. ret = this._events[type].slice();
  17137. return ret;
  17138. };
  17139. EventEmitter.listenerCount = function(emitter, type) {
  17140. var ret;
  17141. if (!emitter._events || !emitter._events[type])
  17142. ret = 0;
  17143. else if (isFunction(emitter._events[type]))
  17144. ret = 1;
  17145. else
  17146. ret = emitter._events[type].length;
  17147. return ret;
  17148. };
  17149. function isFunction(arg) {
  17150. return typeof arg === 'function';
  17151. }
  17152. function isNumber(arg) {
  17153. return typeof arg === 'number';
  17154. }
  17155. function isObject(arg) {
  17156. return typeof arg === 'object' && arg !== null;
  17157. }
  17158. function isUndefined(arg) {
  17159. return arg === void 0;
  17160. }
  17161. },{}],66:[function(require,module,exports){
  17162. // i18next, v1.7.7
  17163. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17164. // Distributed under MIT license
  17165. // http://i18next.com
  17166. (function() {
  17167. // add indexOf to non ECMA-262 standard compliant browsers
  17168. if (!Array.prototype.indexOf) {
  17169. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17170. "use strict";
  17171. if (this == null) {
  17172. throw new TypeError();
  17173. }
  17174. var t = Object(this);
  17175. var len = t.length >>> 0;
  17176. if (len === 0) {
  17177. return -1;
  17178. }
  17179. var n = 0;
  17180. if (arguments.length > 0) {
  17181. n = Number(arguments[1]);
  17182. if (n != n) { // shortcut for verifying if it's NaN
  17183. n = 0;
  17184. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17185. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17186. }
  17187. }
  17188. if (n >= len) {
  17189. return -1;
  17190. }
  17191. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17192. for (; k < len; k++) {
  17193. if (k in t && t[k] === searchElement) {
  17194. return k;
  17195. }
  17196. }
  17197. return -1;
  17198. }
  17199. }
  17200. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17201. if (!Array.prototype.lastIndexOf) {
  17202. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17203. "use strict";
  17204. if (this == null) {
  17205. throw new TypeError();
  17206. }
  17207. var t = Object(this);
  17208. var len = t.length >>> 0;
  17209. if (len === 0) {
  17210. return -1;
  17211. }
  17212. var n = len;
  17213. if (arguments.length > 1) {
  17214. n = Number(arguments[1]);
  17215. if (n != n) {
  17216. n = 0;
  17217. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17218. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17219. }
  17220. }
  17221. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17222. for (; k >= 0; k--) {
  17223. if (k in t && t[k] === searchElement) {
  17224. return k;
  17225. }
  17226. }
  17227. return -1;
  17228. };
  17229. }
  17230. // Add string trim for IE8.
  17231. if (typeof String.prototype.trim !== 'function') {
  17232. String.prototype.trim = function() {
  17233. return this.replace(/^\s+|\s+$/g, '');
  17234. }
  17235. }
  17236. var root = this
  17237. , $ = root.jQuery || root.Zepto
  17238. , i18n = {}
  17239. , resStore = {}
  17240. , currentLng
  17241. , replacementCounter = 0
  17242. , languages = []
  17243. , initialized = false
  17244. , sync = {};
  17245. // Export the i18next object for **CommonJS**.
  17246. // If we're not in CommonJS, add `i18n` to the
  17247. // global object or to jquery.
  17248. if (typeof module !== 'undefined' && module.exports) {
  17249. if (!$) {
  17250. try {
  17251. $ = require('jquery');
  17252. } catch(e) {
  17253. // just ignore
  17254. }
  17255. }
  17256. if ($) {
  17257. $.i18n = $.i18n || i18n;
  17258. }
  17259. module.exports = i18n;
  17260. } else {
  17261. if ($) {
  17262. $.i18n = $.i18n || i18n;
  17263. }
  17264. root.i18n = root.i18n || i18n;
  17265. }
  17266. sync = {
  17267. load: function(lngs, options, cb) {
  17268. if (options.useLocalStorage) {
  17269. sync._loadLocal(lngs, options, function(err, store) {
  17270. var missingLngs = [];
  17271. for (var i = 0, len = lngs.length; i < len; i++) {
  17272. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17273. }
  17274. if (missingLngs.length > 0) {
  17275. sync._fetch(missingLngs, options, function(err, fetched) {
  17276. f.extend(store, fetched);
  17277. sync._storeLocal(fetched);
  17278. cb(null, store);
  17279. });
  17280. } else {
  17281. cb(null, store);
  17282. }
  17283. });
  17284. } else {
  17285. sync._fetch(lngs, options, function(err, store){
  17286. cb(null, store);
  17287. });
  17288. }
  17289. },
  17290. _loadLocal: function(lngs, options, cb) {
  17291. var store = {}
  17292. , nowMS = new Date().getTime();
  17293. if(window.localStorage) {
  17294. var todo = lngs.length;
  17295. f.each(lngs, function(key, lng) {
  17296. var local = window.localStorage.getItem('res_' + lng);
  17297. if (local) {
  17298. local = JSON.parse(local);
  17299. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17300. store[lng] = local;
  17301. }
  17302. }
  17303. todo--; // wait for all done befor callback
  17304. if (todo === 0) cb(null, store);
  17305. });
  17306. }
  17307. },
  17308. _storeLocal: function(store) {
  17309. if(window.localStorage) {
  17310. for (var m in store) {
  17311. store[m].i18nStamp = new Date().getTime();
  17312. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17313. }
  17314. }
  17315. return;
  17316. },
  17317. _fetch: function(lngs, options, cb) {
  17318. var ns = options.ns
  17319. , store = {};
  17320. if (!options.dynamicLoad) {
  17321. var todo = ns.namespaces.length * lngs.length
  17322. , errors;
  17323. // load each file individual
  17324. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17325. f.each(lngs, function(lngIndex, lngValue) {
  17326. // Call this once our translation has returned.
  17327. var loadComplete = function(err, data) {
  17328. if (err) {
  17329. errors = errors || [];
  17330. errors.push(err);
  17331. }
  17332. store[lngValue] = store[lngValue] || {};
  17333. store[lngValue][nsValue] = data;
  17334. todo--; // wait for all done befor callback
  17335. if (todo === 0) cb(errors, store);
  17336. };
  17337. if(typeof options.customLoad == 'function'){
  17338. // Use the specified custom callback.
  17339. options.customLoad(lngValue, nsValue, options, loadComplete);
  17340. } else {
  17341. //~ // Use our inbuilt sync.
  17342. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17343. }
  17344. });
  17345. });
  17346. } else {
  17347. // Call this once our translation has returned.
  17348. var loadComplete = function(err, data) {
  17349. cb(null, data);
  17350. };
  17351. if(typeof options.customLoad == 'function'){
  17352. // Use the specified custom callback.
  17353. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17354. } else {
  17355. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17356. // load all needed stuff once
  17357. f.ajax({
  17358. url: url,
  17359. success: function(data, status, xhr) {
  17360. f.log('loaded: ' + url);
  17361. loadComplete(null, data);
  17362. },
  17363. error : function(xhr, status, error) {
  17364. f.log('failed loading: ' + url);
  17365. loadComplete('failed loading resource.json error: ' + error);
  17366. },
  17367. dataType: "json",
  17368. async : options.getAsync
  17369. });
  17370. }
  17371. }
  17372. },
  17373. _fetchOne: function(lng, ns, options, done) {
  17374. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17375. f.ajax({
  17376. url: url,
  17377. success: function(data, status, xhr) {
  17378. f.log('loaded: ' + url);
  17379. done(null, data);
  17380. },
  17381. error : function(xhr, status, error) {
  17382. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17383. // file loaded but invalid json, stop waste time !
  17384. f.error('There is a typo in: ' + url);
  17385. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17386. f.log('Does not exist: ' + url);
  17387. } else {
  17388. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17389. f.log(theStatus + ' when loading ' + url);
  17390. }
  17391. done(error, {});
  17392. },
  17393. dataType: "json",
  17394. async : options.getAsync
  17395. });
  17396. },
  17397. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17398. var payload = {};
  17399. payload[key] = defaultValue;
  17400. var urls = [];
  17401. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17402. for (var i = 0; i < o.fallbackLng.length; i++) {
  17403. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17404. }
  17405. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17406. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17407. } else if (o.sendMissingTo === 'all') {
  17408. for (var i = 0, l = lngs.length; i < l; i++) {
  17409. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17410. }
  17411. }
  17412. for (var y = 0, len = urls.length; y < len; y++) {
  17413. var item = urls[y];
  17414. f.ajax({
  17415. url: item.url,
  17416. type: o.sendType,
  17417. data: payload,
  17418. success: function(data, status, xhr) {
  17419. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17420. // add key to resStore
  17421. var keys = key.split('.');
  17422. var x = 0;
  17423. var value = resStore[item.lng][ns];
  17424. while (keys[x]) {
  17425. if (x === keys.length - 1) {
  17426. value = value[keys[x]] = defaultValue;
  17427. } else {
  17428. value = value[keys[x]] = value[keys[x]] || {};
  17429. }
  17430. x++;
  17431. }
  17432. },
  17433. error : function(xhr, status, error) {
  17434. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17435. },
  17436. dataType: "json",
  17437. async : o.postAsync
  17438. });
  17439. }
  17440. },
  17441. reload: reload
  17442. };
  17443. // defaults
  17444. var o = {
  17445. lng: undefined,
  17446. load: 'all',
  17447. preload: [],
  17448. lowerCaseLng: false,
  17449. returnObjectTrees: false,
  17450. fallbackLng: ['dev'],
  17451. fallbackNS: [],
  17452. detectLngQS: 'setLng',
  17453. detectLngFromLocalStorage: false,
  17454. ns: 'translation',
  17455. fallbackOnNull: true,
  17456. fallbackOnEmpty: false,
  17457. fallbackToDefaultNS: false,
  17458. nsseparator: ':',
  17459. keyseparator: '.',
  17460. selectorAttr: 'data-i18n',
  17461. debug: false,
  17462. resGetPath: 'locales/__lng__/__ns__.json',
  17463. resPostPath: 'locales/add/__lng__/__ns__',
  17464. getAsync: true,
  17465. postAsync: true,
  17466. resStore: undefined,
  17467. useLocalStorage: false,
  17468. localStorageExpirationTime: 7*24*60*60*1000,
  17469. dynamicLoad: false,
  17470. sendMissing: false,
  17471. sendMissingTo: 'fallback', // current | all
  17472. sendType: 'POST',
  17473. interpolationPrefix: '__',
  17474. interpolationSuffix: '__',
  17475. defaultVariables: false,
  17476. reusePrefix: '$t(',
  17477. reuseSuffix: ')',
  17478. pluralSuffix: '_plural',
  17479. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17480. contextNotFound: ['context_not_found', Math.random()].join(''),
  17481. escapeInterpolation: false,
  17482. indefiniteSuffix: '_indefinite',
  17483. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17484. setJqueryExt: true,
  17485. defaultValueFromContent: true,
  17486. useDataAttrOptions: false,
  17487. cookieExpirationTime: undefined,
  17488. useCookie: true,
  17489. cookieName: 'i18next',
  17490. cookieDomain: undefined,
  17491. objectTreeKeyHandler: undefined,
  17492. postProcess: undefined,
  17493. parseMissingKey: undefined,
  17494. missingKeyHandler: sync.postMissing,
  17495. shortcutFunction: 'sprintf' // or: defaultValue
  17496. };
  17497. function _extend(target, source) {
  17498. if (!source || typeof source === 'function') {
  17499. return target;
  17500. }
  17501. for (var attr in source) { target[attr] = source[attr]; }
  17502. return target;
  17503. }
  17504. function _deepExtend(target, source) {
  17505. for (var prop in source)
  17506. if (prop in target)
  17507. _deepExtend(target[prop], source[prop]);
  17508. else
  17509. target[prop] = source[prop];
  17510. return target;
  17511. }
  17512. function _each(object, callback, args) {
  17513. var name, i = 0,
  17514. length = object.length,
  17515. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17516. if (args) {
  17517. if (isObj) {
  17518. for (name in object) {
  17519. if (callback.apply(object[name], args) === false) {
  17520. break;
  17521. }
  17522. }
  17523. } else {
  17524. for ( ; i < length; ) {
  17525. if (callback.apply(object[i++], args) === false) {
  17526. break;
  17527. }
  17528. }
  17529. }
  17530. // A special, fast, case for the most common use of each
  17531. } else {
  17532. if (isObj) {
  17533. for (name in object) {
  17534. if (callback.call(object[name], name, object[name]) === false) {
  17535. break;
  17536. }
  17537. }
  17538. } else {
  17539. for ( ; i < length; ) {
  17540. if (callback.call(object[i], i, object[i++]) === false) {
  17541. break;
  17542. }
  17543. }
  17544. }
  17545. }
  17546. return object;
  17547. }
  17548. var _entityMap = {
  17549. "&": "&amp;",
  17550. "<": "&lt;",
  17551. ">": "&gt;",
  17552. '"': '&quot;',
  17553. "'": '&#39;',
  17554. "/": '&#x2F;'
  17555. };
  17556. function _escape(data) {
  17557. if (typeof data === 'string') {
  17558. return data.replace(/[&<>"'\/]/g, function (s) {
  17559. return _entityMap[s];
  17560. });
  17561. }else{
  17562. return data;
  17563. }
  17564. }
  17565. function _ajax(options) {
  17566. // v0.5.0 of https://github.com/goloroden/http.js
  17567. var getXhr = function (callback) {
  17568. // Use the native XHR object if the browser supports it.
  17569. if (window.XMLHttpRequest) {
  17570. return callback(null, new XMLHttpRequest());
  17571. } else if (window.ActiveXObject) {
  17572. // In Internet Explorer check for ActiveX versions of the XHR object.
  17573. try {
  17574. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17575. } catch (e) {
  17576. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17577. }
  17578. }
  17579. // If no XHR support was found, throw an error.
  17580. return callback(new Error());
  17581. };
  17582. var encodeUsingUrlEncoding = function (data) {
  17583. if(typeof data === 'string') {
  17584. return data;
  17585. }
  17586. var result = [];
  17587. for(var dataItem in data) {
  17588. if(data.hasOwnProperty(dataItem)) {
  17589. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17590. }
  17591. }
  17592. return result.join('&');
  17593. };
  17594. var utf8 = function (text) {
  17595. text = text.replace(/\r\n/g, '\n');
  17596. var result = '';
  17597. for(var i = 0; i < text.length; i++) {
  17598. var c = text.charCodeAt(i);
  17599. if(c < 128) {
  17600. result += String.fromCharCode(c);
  17601. } else if((c > 127) && (c < 2048)) {
  17602. result += String.fromCharCode((c >> 6) | 192);
  17603. result += String.fromCharCode((c & 63) | 128);
  17604. } else {
  17605. result += String.fromCharCode((c >> 12) | 224);
  17606. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17607. result += String.fromCharCode((c & 63) | 128);
  17608. }
  17609. }
  17610. return result;
  17611. };
  17612. var base64 = function (text) {
  17613. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17614. text = utf8(text);
  17615. var result = '',
  17616. chr1, chr2, chr3,
  17617. enc1, enc2, enc3, enc4,
  17618. i = 0;
  17619. do {
  17620. chr1 = text.charCodeAt(i++);
  17621. chr2 = text.charCodeAt(i++);
  17622. chr3 = text.charCodeAt(i++);
  17623. enc1 = chr1 >> 2;
  17624. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17625. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17626. enc4 = chr3 & 63;
  17627. if(isNaN(chr2)) {
  17628. enc3 = enc4 = 64;
  17629. } else if(isNaN(chr3)) {
  17630. enc4 = 64;
  17631. }
  17632. result +=
  17633. keyStr.charAt(enc1) +
  17634. keyStr.charAt(enc2) +
  17635. keyStr.charAt(enc3) +
  17636. keyStr.charAt(enc4);
  17637. chr1 = chr2 = chr3 = '';
  17638. enc1 = enc2 = enc3 = enc4 = '';
  17639. } while(i < text.length);
  17640. return result;
  17641. };
  17642. var mergeHeaders = function () {
  17643. // Use the first header object as base.
  17644. var result = arguments[0];
  17645. // Iterate through the remaining header objects and add them.
  17646. for(var i = 1; i < arguments.length; i++) {
  17647. var currentHeaders = arguments[i];
  17648. for(var header in currentHeaders) {
  17649. if(currentHeaders.hasOwnProperty(header)) {
  17650. result[header] = currentHeaders[header];
  17651. }
  17652. }
  17653. }
  17654. // Return the merged headers.
  17655. return result;
  17656. };
  17657. var ajax = function (method, url, options, callback) {
  17658. // Adjust parameters.
  17659. if(typeof options === 'function') {
  17660. callback = options;
  17661. options = {};
  17662. }
  17663. // Set default parameter values.
  17664. options.cache = options.cache || false;
  17665. options.data = options.data || {};
  17666. options.headers = options.headers || {};
  17667. options.jsonp = options.jsonp || false;
  17668. options.async = options.async === undefined ? true : options.async;
  17669. // Merge the various header objects.
  17670. var headers = mergeHeaders({
  17671. 'accept': '*/*',
  17672. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17673. }, ajax.headers, options.headers);
  17674. // Encode the data according to the content-type.
  17675. var payload;
  17676. if (headers['content-type'] === 'application/json') {
  17677. payload = JSON.stringify(options.data);
  17678. } else {
  17679. payload = encodeUsingUrlEncoding(options.data);
  17680. }
  17681. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17682. // if neccessary.
  17683. if(method === 'GET') {
  17684. // Setup the query string.
  17685. var queryString = [];
  17686. if(payload) {
  17687. queryString.push(payload);
  17688. payload = null;
  17689. }
  17690. // Handle caching.
  17691. if(!options.cache) {
  17692. queryString.push('_=' + (new Date()).getTime());
  17693. }
  17694. // If neccessary prepare the query string for a JSONP call.
  17695. if(options.jsonp) {
  17696. queryString.push('callback=' + options.jsonp);
  17697. queryString.push('jsonp=' + options.jsonp);
  17698. }
  17699. // Merge the query string and attach it to the url.
  17700. queryString = queryString.join('&');
  17701. if (queryString.length > 1) {
  17702. if (url.indexOf('?') > -1) {
  17703. url += '&' + queryString;
  17704. } else {
  17705. url += '?' + queryString;
  17706. }
  17707. }
  17708. // Make a JSONP call if neccessary.
  17709. if(options.jsonp) {
  17710. var head = document.getElementsByTagName('head')[0];
  17711. var script = document.createElement('script');
  17712. script.type = 'text/javascript';
  17713. script.src = url;
  17714. head.appendChild(script);
  17715. return;
  17716. }
  17717. }
  17718. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17719. getXhr(function (err, xhr) {
  17720. if(err) return callback(err);
  17721. // Open the request.
  17722. xhr.open(method, url, options.async);
  17723. // Set the request headers.
  17724. for(var header in headers) {
  17725. if(headers.hasOwnProperty(header)) {
  17726. xhr.setRequestHeader(header, headers[header]);
  17727. }
  17728. }
  17729. // Handle the request events.
  17730. xhr.onreadystatechange = function () {
  17731. if(xhr.readyState === 4) {
  17732. var data = xhr.responseText || '';
  17733. // If no callback is given, return.
  17734. if(!callback) {
  17735. return;
  17736. }
  17737. // Return an object that provides access to the data as text and JSON.
  17738. callback(xhr.status, {
  17739. text: function () {
  17740. return data;
  17741. },
  17742. json: function () {
  17743. try {
  17744. return JSON.parse(data)
  17745. } catch (e) {
  17746. f.error('Can not parse JSON. URL: ' + url);
  17747. return {};
  17748. }
  17749. }
  17750. });
  17751. }
  17752. };
  17753. // Actually send the XHR request.
  17754. xhr.send(payload);
  17755. });
  17756. };
  17757. // Define the external interface.
  17758. var http = {
  17759. authBasic: function (username, password) {
  17760. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17761. },
  17762. connect: function (url, options, callback) {
  17763. return ajax('CONNECT', url, options, callback);
  17764. },
  17765. del: function (url, options, callback) {
  17766. return ajax('DELETE', url, options, callback);
  17767. },
  17768. get: function (url, options, callback) {
  17769. return ajax('GET', url, options, callback);
  17770. },
  17771. head: function (url, options, callback) {
  17772. return ajax('HEAD', url, options, callback);
  17773. },
  17774. headers: function (headers) {
  17775. ajax.headers = headers || {};
  17776. },
  17777. isAllowed: function (url, verb, callback) {
  17778. this.options(url, function (status, data) {
  17779. callback(data.text().indexOf(verb) !== -1);
  17780. });
  17781. },
  17782. options: function (url, options, callback) {
  17783. return ajax('OPTIONS', url, options, callback);
  17784. },
  17785. patch: function (url, options, callback) {
  17786. return ajax('PATCH', url, options, callback);
  17787. },
  17788. post: function (url, options, callback) {
  17789. return ajax('POST', url, options, callback);
  17790. },
  17791. put: function (url, options, callback) {
  17792. return ajax('PUT', url, options, callback);
  17793. },
  17794. trace: function (url, options, callback) {
  17795. return ajax('TRACE', url, options, callback);
  17796. }
  17797. };
  17798. var methode = options.type ? options.type.toLowerCase() : 'get';
  17799. http[methode](options.url, options, function (status, data) {
  17800. // file: protocol always gives status code 0, so check for data
  17801. if (status === 200 || (status === 0 && data.text())) {
  17802. options.success(data.json(), status, null);
  17803. } else {
  17804. options.error(data.text(), status, null);
  17805. }
  17806. });
  17807. }
  17808. var _cookie = {
  17809. create: function(name,value,minutes,domain) {
  17810. var expires;
  17811. if (minutes) {
  17812. var date = new Date();
  17813. date.setTime(date.getTime()+(minutes*60*1000));
  17814. expires = "; expires="+date.toGMTString();
  17815. }
  17816. else expires = "";
  17817. domain = (domain)? "domain="+domain+";" : "";
  17818. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17819. },
  17820. read: function(name) {
  17821. var nameEQ = name + "=";
  17822. var ca = document.cookie.split(';');
  17823. for(var i=0;i < ca.length;i++) {
  17824. var c = ca[i];
  17825. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17826. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17827. }
  17828. return null;
  17829. },
  17830. remove: function(name) {
  17831. this.create(name,"",-1);
  17832. }
  17833. };
  17834. var cookie_noop = {
  17835. create: function(name,value,minutes,domain) {},
  17836. read: function(name) { return null; },
  17837. remove: function(name) {}
  17838. };
  17839. // move dependent functions to a container so that
  17840. // they can be overriden easier in no jquery environment (node.js)
  17841. var f = {
  17842. extend: $ ? $.extend : _extend,
  17843. deepExtend: _deepExtend,
  17844. each: $ ? $.each : _each,
  17845. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17846. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17847. detectLanguage: detectLanguage,
  17848. escape: _escape,
  17849. log: function(str) {
  17850. if (o.debug && typeof console !== "undefined") console.log(str);
  17851. },
  17852. error: function(str) {
  17853. if (typeof console !== "undefined") console.error(str);
  17854. },
  17855. getCountyIndexOfLng: function(lng) {
  17856. var lng_index = 0;
  17857. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17858. return lng_index;
  17859. },
  17860. toLanguages: function(lng) {
  17861. var log = this.log;
  17862. function applyCase(l) {
  17863. var ret = l;
  17864. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17865. var parts = l.split('-');
  17866. ret = o.lowerCaseLng ?
  17867. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17868. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17869. } else {
  17870. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17871. }
  17872. return ret;
  17873. }
  17874. var languages = [];
  17875. var whitelist = o.lngWhitelist || false;
  17876. var addLanguage = function(language){
  17877. //reject langs not whitelisted
  17878. if(!whitelist || whitelist.indexOf(language) > -1){
  17879. languages.push(language);
  17880. }else{
  17881. log('rejecting non-whitelisted language: ' + language);
  17882. }
  17883. };
  17884. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  17885. var parts = lng.split('-');
  17886. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  17887. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  17888. } else {
  17889. addLanguage(applyCase(lng));
  17890. }
  17891. for (var i = 0; i < o.fallbackLng.length; i++) {
  17892. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  17893. }
  17894. return languages;
  17895. },
  17896. regexEscape: function(str) {
  17897. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  17898. },
  17899. regexReplacementEscape: function(strOrFn) {
  17900. if (typeof strOrFn === 'string') {
  17901. return strOrFn.replace(/\$/g, "$$$$");
  17902. } else {
  17903. return strOrFn;
  17904. }
  17905. },
  17906. localStorage: {
  17907. setItem: function(key, value) {
  17908. if (window.localStorage) {
  17909. try {
  17910. window.localStorage.setItem(key, value);
  17911. } catch (e) {
  17912. f.log('failed to set value for key "' + key + '" to localStorage.');
  17913. }
  17914. }
  17915. }
  17916. }
  17917. };
  17918. function init(options, cb) {
  17919. if (typeof options === 'function') {
  17920. cb = options;
  17921. options = {};
  17922. }
  17923. options = options || {};
  17924. // override defaults with passed in options
  17925. f.extend(o, options);
  17926. delete o.fixLng; /* passed in each time */
  17927. // override functions: .log(), .detectLanguage(), etc
  17928. if (o.functions) {
  17929. delete o.functions;
  17930. f.extend(f, options.functions);
  17931. }
  17932. // create namespace object if namespace is passed in as string
  17933. if (typeof o.ns == 'string') {
  17934. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  17935. }
  17936. // fallback namespaces
  17937. if (typeof o.fallbackNS == 'string') {
  17938. o.fallbackNS = [o.fallbackNS];
  17939. }
  17940. // fallback languages
  17941. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  17942. o.fallbackLng = [o.fallbackLng];
  17943. }
  17944. // escape prefix/suffix
  17945. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  17946. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  17947. if (!o.lng) o.lng = f.detectLanguage();
  17948. languages = f.toLanguages(o.lng);
  17949. currentLng = languages[0];
  17950. f.log('currentLng set to: ' + currentLng);
  17951. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  17952. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  17953. }
  17954. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  17955. f.localStorage.setItem('i18next_lng', currentLng);
  17956. }
  17957. var lngTranslate = translate;
  17958. if (options.fixLng) {
  17959. lngTranslate = function(key, options) {
  17960. options = options || {};
  17961. options.lng = options.lng || lngTranslate.lng;
  17962. return translate(key, options);
  17963. };
  17964. lngTranslate.lng = currentLng;
  17965. }
  17966. pluralExtensions.setCurrentLng(currentLng);
  17967. // add JQuery extensions
  17968. if ($ && o.setJqueryExt) addJqueryFunct();
  17969. // jQuery deferred
  17970. var deferred;
  17971. if ($ && $.Deferred) {
  17972. deferred = $.Deferred();
  17973. }
  17974. // return immidiatly if res are passed in
  17975. if (o.resStore) {
  17976. resStore = o.resStore;
  17977. initialized = true;
  17978. if (cb) cb(lngTranslate);
  17979. if (deferred) deferred.resolve(lngTranslate);
  17980. if (deferred) return deferred.promise();
  17981. return;
  17982. }
  17983. // languages to load
  17984. var lngsToLoad = f.toLanguages(o.lng);
  17985. if (typeof o.preload === 'string') o.preload = [o.preload];
  17986. for (var i = 0, l = o.preload.length; i < l; i++) {
  17987. var pres = f.toLanguages(o.preload[i]);
  17988. for (var y = 0, len = pres.length; y < len; y++) {
  17989. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17990. lngsToLoad.push(pres[y]);
  17991. }
  17992. }
  17993. }
  17994. // else load them
  17995. i18n.sync.load(lngsToLoad, o, function(err, store) {
  17996. resStore = store;
  17997. initialized = true;
  17998. if (cb) cb(lngTranslate);
  17999. if (deferred) deferred.resolve(lngTranslate);
  18000. });
  18001. if (deferred) return deferred.promise();
  18002. }
  18003. function preload(lngs, cb) {
  18004. if (typeof lngs === 'string') lngs = [lngs];
  18005. for (var i = 0, l = lngs.length; i < l; i++) {
  18006. if (o.preload.indexOf(lngs[i]) < 0) {
  18007. o.preload.push(lngs[i]);
  18008. }
  18009. }
  18010. return init(cb);
  18011. }
  18012. function addResourceBundle(lng, ns, resources, deep) {
  18013. if (typeof ns !== 'string') {
  18014. resources = ns;
  18015. ns = o.ns.defaultNs;
  18016. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18017. o.ns.namespaces.push(ns);
  18018. }
  18019. resStore[lng] = resStore[lng] || {};
  18020. resStore[lng][ns] = resStore[lng][ns] || {};
  18021. if (deep) {
  18022. f.deepExtend(resStore[lng][ns], resources);
  18023. } else {
  18024. f.extend(resStore[lng][ns], resources);
  18025. }
  18026. }
  18027. function hasResourceBundle(lng, ns) {
  18028. if (typeof ns !== 'string') {
  18029. ns = o.ns.defaultNs;
  18030. }
  18031. resStore[lng] = resStore[lng] || {};
  18032. var res = resStore[lng][ns] || {};
  18033. var hasValues = false;
  18034. for(var prop in res) {
  18035. if (res.hasOwnProperty(prop)) {
  18036. hasValues = true;
  18037. }
  18038. }
  18039. return hasValues;
  18040. }
  18041. function removeResourceBundle(lng, ns) {
  18042. if (typeof ns !== 'string') {
  18043. ns = o.ns.defaultNs;
  18044. }
  18045. resStore[lng] = resStore[lng] || {};
  18046. resStore[lng][ns] = {};
  18047. }
  18048. function addResource(lng, ns, key, value) {
  18049. if (typeof ns !== 'string') {
  18050. resource = ns;
  18051. ns = o.ns.defaultNs;
  18052. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18053. o.ns.namespaces.push(ns);
  18054. }
  18055. resStore[lng] = resStore[lng] || {};
  18056. resStore[lng][ns] = resStore[lng][ns] || {};
  18057. var keys = key.split(o.keyseparator);
  18058. var x = 0;
  18059. var node = resStore[lng][ns];
  18060. var origRef = node;
  18061. while (keys[x]) {
  18062. if (x == keys.length - 1)
  18063. node[keys[x]] = value;
  18064. else {
  18065. if (node[keys[x]] == null)
  18066. node[keys[x]] = {};
  18067. node = node[keys[x]];
  18068. }
  18069. x++;
  18070. }
  18071. }
  18072. function addResources(lng, ns, resources) {
  18073. if (typeof ns !== 'string') {
  18074. resource = ns;
  18075. ns = o.ns.defaultNs;
  18076. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18077. o.ns.namespaces.push(ns);
  18078. }
  18079. for (var m in resources) {
  18080. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18081. }
  18082. }
  18083. function setDefaultNamespace(ns) {
  18084. o.ns.defaultNs = ns;
  18085. }
  18086. function loadNamespace(namespace, cb) {
  18087. loadNamespaces([namespace], cb);
  18088. }
  18089. function loadNamespaces(namespaces, cb) {
  18090. var opts = {
  18091. dynamicLoad: o.dynamicLoad,
  18092. resGetPath: o.resGetPath,
  18093. getAsync: o.getAsync,
  18094. customLoad: o.customLoad,
  18095. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18096. };
  18097. // languages to load
  18098. var lngsToLoad = f.toLanguages(o.lng);
  18099. if (typeof o.preload === 'string') o.preload = [o.preload];
  18100. for (var i = 0, l = o.preload.length; i < l; i++) {
  18101. var pres = f.toLanguages(o.preload[i]);
  18102. for (var y = 0, len = pres.length; y < len; y++) {
  18103. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18104. lngsToLoad.push(pres[y]);
  18105. }
  18106. }
  18107. }
  18108. // check if we have to load
  18109. var lngNeedLoad = [];
  18110. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18111. var needLoad = false;
  18112. var resSet = resStore[lngsToLoad[a]];
  18113. if (resSet) {
  18114. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18115. if (!resSet[namespaces[b]]) needLoad = true;
  18116. }
  18117. } else {
  18118. needLoad = true;
  18119. }
  18120. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18121. }
  18122. if (lngNeedLoad.length) {
  18123. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18124. var todo = namespaces.length * lngNeedLoad.length;
  18125. // load each file individual
  18126. f.each(namespaces, function(nsIndex, nsValue) {
  18127. // append namespace to namespace array
  18128. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18129. o.ns.namespaces.push(nsValue);
  18130. }
  18131. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18132. resStore[lngValue] = resStore[lngValue] || {};
  18133. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18134. todo--; // wait for all done befor callback
  18135. if (todo === 0 && cb) {
  18136. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18137. cb();
  18138. }
  18139. });
  18140. });
  18141. });
  18142. } else {
  18143. if (cb) cb();
  18144. }
  18145. }
  18146. function setLng(lng, options, cb) {
  18147. if (typeof options === 'function') {
  18148. cb = options;
  18149. options = {};
  18150. } else if (!options) {
  18151. options = {};
  18152. }
  18153. options.lng = lng;
  18154. return init(options, cb);
  18155. }
  18156. function lng() {
  18157. return currentLng;
  18158. }
  18159. function reload(cb) {
  18160. resStore = {};
  18161. setLng(currentLng, cb);
  18162. }
  18163. function addJqueryFunct() {
  18164. // $.t shortcut
  18165. $.t = $.t || translate;
  18166. function parse(ele, key, options) {
  18167. if (key.length === 0) return;
  18168. var attr = 'text';
  18169. if (key.indexOf('[') === 0) {
  18170. var parts = key.split(']');
  18171. key = parts[1];
  18172. attr = parts[0].substr(1, parts[0].length-1);
  18173. }
  18174. if (key.indexOf(';') === key.length-1) {
  18175. key = key.substr(0, key.length-2);
  18176. }
  18177. var optionsToUse;
  18178. if (attr === 'html') {
  18179. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18180. ele.html($.t(key, optionsToUse));
  18181. } else if (attr === 'text') {
  18182. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18183. ele.text($.t(key, optionsToUse));
  18184. } else if (attr === 'prepend') {
  18185. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18186. ele.prepend($.t(key, optionsToUse));
  18187. } else if (attr === 'append') {
  18188. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18189. ele.append($.t(key, optionsToUse));
  18190. } else if (attr.indexOf("data-") === 0) {
  18191. var dataAttr = attr.substr(("data-").length);
  18192. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18193. var translated = $.t(key, optionsToUse);
  18194. //we change into the data cache
  18195. ele.data(dataAttr, translated);
  18196. //we change into the dom
  18197. ele.attr(attr, translated);
  18198. } else {
  18199. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18200. ele.attr(attr, $.t(key, optionsToUse));
  18201. }
  18202. }
  18203. function localize(ele, options) {
  18204. var key = ele.attr(o.selectorAttr);
  18205. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18206. if (!key) return;
  18207. var target = ele
  18208. , targetSelector = ele.data("i18n-target");
  18209. if (targetSelector) {
  18210. target = ele.find(targetSelector) || ele;
  18211. }
  18212. if (!options && o.useDataAttrOptions === true) {
  18213. options = ele.data("i18n-options");
  18214. }
  18215. options = options || {};
  18216. if (key.indexOf(';') >= 0) {
  18217. var keys = key.split(';');
  18218. $.each(keys, function(m, k) {
  18219. if (k !== '') parse(target, k, options);
  18220. });
  18221. } else {
  18222. parse(target, key, options);
  18223. }
  18224. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18225. }
  18226. // fn
  18227. $.fn.i18n = function (options) {
  18228. return this.each(function() {
  18229. // localize element itself
  18230. localize($(this), options);
  18231. // localize childs
  18232. var elements = $(this).find('[' + o.selectorAttr + ']');
  18233. elements.each(function() {
  18234. localize($(this), options);
  18235. });
  18236. });
  18237. };
  18238. }
  18239. function applyReplacement(str, replacementHash, nestedKey, options) {
  18240. if (!str) return str;
  18241. options = options || replacementHash; // first call uses replacement hash combined with options
  18242. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18243. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18244. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18245. , unEscapingSuffix = 'HTML'+suffix;
  18246. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18247. f.each(hash, function(key, value) {
  18248. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18249. if (typeof value === 'object' && value !== null) {
  18250. str = applyReplacement(str, value, nextKey, options);
  18251. } else {
  18252. if (options.escapeInterpolation || o.escapeInterpolation) {
  18253. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18254. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18255. } else {
  18256. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18257. }
  18258. // str = options.escapeInterpolation;
  18259. }
  18260. });
  18261. return str;
  18262. }
  18263. // append it to functions
  18264. f.applyReplacement = applyReplacement;
  18265. function applyReuse(translated, options) {
  18266. var comma = ',';
  18267. var options_open = '{';
  18268. var options_close = '}';
  18269. var opts = f.extend({}, options);
  18270. delete opts.postProcess;
  18271. while (translated.indexOf(o.reusePrefix) != -1) {
  18272. replacementCounter++;
  18273. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18274. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18275. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18276. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18277. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18278. if (index_of_end_of_closing <= index_of_opening) {
  18279. f.error('there is an missing closing in following translation value', translated);
  18280. return '';
  18281. }
  18282. if (token_without_symbols.indexOf(comma) != -1) {
  18283. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18284. 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) {
  18285. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18286. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18287. try {
  18288. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18289. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18290. } catch (e) {
  18291. }
  18292. }
  18293. }
  18294. var translated_token = _translate(token_without_symbols, opts);
  18295. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18296. }
  18297. return translated;
  18298. }
  18299. function hasContext(options) {
  18300. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18301. }
  18302. function needsPlural(options, lng) {
  18303. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18304. }
  18305. function needsIndefiniteArticle(options) {
  18306. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18307. }
  18308. function exists(key, options) {
  18309. options = options || {};
  18310. var notFound = _getDefaultValue(key, options)
  18311. , found = _find(key, options);
  18312. return found !== undefined || found === notFound;
  18313. }
  18314. function translate(key, options) {
  18315. options = options || {};
  18316. if (!initialized) {
  18317. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18318. return options.defaultValue || '';
  18319. };
  18320. replacementCounter = 0;
  18321. return _translate.apply(null, arguments);
  18322. }
  18323. function _getDefaultValue(key, options) {
  18324. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18325. }
  18326. function _injectSprintfProcessor() {
  18327. var values = [];
  18328. // mh: build array from second argument onwards
  18329. for (var i = 1; i < arguments.length; i++) {
  18330. values.push(arguments[i]);
  18331. }
  18332. return {
  18333. postProcess: 'sprintf',
  18334. sprintf: values
  18335. };
  18336. }
  18337. function _translate(potentialKeys, options) {
  18338. if (options && typeof options !== 'object') {
  18339. if (o.shortcutFunction === 'sprintf') {
  18340. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18341. options = _injectSprintfProcessor.apply(null, arguments);
  18342. } else if (o.shortcutFunction === 'defaultValue') {
  18343. options = {
  18344. defaultValue: options
  18345. }
  18346. }
  18347. } else {
  18348. options = options || {};
  18349. }
  18350. if (typeof o.defaultVariables === 'object') {
  18351. options = f.extend({}, o.defaultVariables, options);
  18352. }
  18353. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18354. if (typeof potentialKeys === 'string') {
  18355. potentialKeys = [potentialKeys];
  18356. }
  18357. var key = potentialKeys[0];
  18358. if (potentialKeys.length > 1) {
  18359. for (var i = 0; i < potentialKeys.length; i++) {
  18360. key = potentialKeys[i];
  18361. if (exists(key, options)) {
  18362. break;
  18363. }
  18364. }
  18365. }
  18366. var notFound = _getDefaultValue(key, options)
  18367. , found = _find(key, options)
  18368. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18369. , ns = options.ns || o.ns.defaultNs
  18370. , parts;
  18371. // split ns and key
  18372. if (key.indexOf(o.nsseparator) > -1) {
  18373. parts = key.split(o.nsseparator);
  18374. ns = parts[0];
  18375. key = parts[1];
  18376. }
  18377. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18378. if (options.lng) {
  18379. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18380. } else {
  18381. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18382. }
  18383. }
  18384. var postProcessor = options.postProcess || o.postProcess;
  18385. if (found !== undefined && postProcessor) {
  18386. if (postProcessors[postProcessor]) {
  18387. found = postProcessors[postProcessor](found, key, options);
  18388. }
  18389. }
  18390. // process notFound if function exists
  18391. var splitNotFound = notFound;
  18392. if (notFound.indexOf(o.nsseparator) > -1) {
  18393. parts = notFound.split(o.nsseparator);
  18394. splitNotFound = parts[1];
  18395. }
  18396. if (splitNotFound === key && o.parseMissingKey) {
  18397. notFound = o.parseMissingKey(notFound);
  18398. }
  18399. if (found === undefined) {
  18400. notFound = applyReplacement(notFound, options);
  18401. notFound = applyReuse(notFound, options);
  18402. if (postProcessor && postProcessors[postProcessor]) {
  18403. var val = _getDefaultValue(key, options);
  18404. found = postProcessors[postProcessor](val, key, options);
  18405. }
  18406. }
  18407. return (found !== undefined) ? found : notFound;
  18408. }
  18409. function _find(key, options) {
  18410. options = options || {};
  18411. var optionWithoutCount, translated
  18412. , notFound = _getDefaultValue(key, options)
  18413. , lngs = languages;
  18414. if (!resStore) { return notFound; } // no resStore to translate from
  18415. // CI mode
  18416. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18417. // passed in lng
  18418. if (options.lngs) lngs = options.lngs;
  18419. if (options.lng) {
  18420. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18421. if (!resStore[lngs[0]]) {
  18422. var oldAsync = o.getAsync;
  18423. o.getAsync = false;
  18424. i18n.sync.load(lngs, o, function(err, store) {
  18425. f.extend(resStore, store);
  18426. o.getAsync = oldAsync;
  18427. });
  18428. }
  18429. }
  18430. var ns = options.ns || o.ns.defaultNs;
  18431. if (key.indexOf(o.nsseparator) > -1) {
  18432. var parts = key.split(o.nsseparator);
  18433. ns = parts[0];
  18434. key = parts[1];
  18435. }
  18436. if (hasContext(options)) {
  18437. optionWithoutCount = f.extend({}, options);
  18438. delete optionWithoutCount.context;
  18439. optionWithoutCount.defaultValue = o.contextNotFound;
  18440. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18441. translated = translate(contextKey, optionWithoutCount);
  18442. if (translated != o.contextNotFound) {
  18443. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18444. } // else continue translation with original/nonContext key
  18445. }
  18446. if (needsPlural(options, lngs[0])) {
  18447. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18448. delete optionWithoutCount.count;
  18449. delete optionWithoutCount.lng;
  18450. optionWithoutCount.defaultValue = o.pluralNotFound;
  18451. var pluralKey;
  18452. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18453. pluralKey = ns + o.nsseparator + key;
  18454. } else {
  18455. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18456. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18457. if (pluralExtension >= 0) {
  18458. pluralKey = pluralKey + '_' + pluralExtension;
  18459. } else if (pluralExtension === 1) {
  18460. pluralKey = ns + o.nsseparator + key; // singular
  18461. }
  18462. }
  18463. translated = translate(pluralKey, optionWithoutCount);
  18464. if (translated != o.pluralNotFound) {
  18465. return applyReplacement(translated, {
  18466. count: options.count,
  18467. interpolationPrefix: options.interpolationPrefix,
  18468. interpolationSuffix: options.interpolationSuffix
  18469. }); // apply replacement for count only
  18470. } else if (lngs.length > 1) {
  18471. // remove failed lng
  18472. var clone = lngs.slice();
  18473. clone.shift();
  18474. options = f.extend(options, { lngs: clone });
  18475. delete options.lng;
  18476. // retry with fallbacks
  18477. translated = translate(ns + o.nsseparator + key, options);
  18478. if (translated != o.pluralNotFound) return translated;
  18479. } else {
  18480. return translated;
  18481. }
  18482. }
  18483. if (needsIndefiniteArticle(options)) {
  18484. var optionsWithoutIndef = f.extend({}, options);
  18485. delete optionsWithoutIndef.indefinite_article;
  18486. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18487. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18488. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18489. translated = translate(indefiniteKey, optionsWithoutIndef);
  18490. if (translated != o.indefiniteNotFound) {
  18491. return translated;
  18492. }
  18493. }
  18494. var found;
  18495. var keys = key.split(o.keyseparator);
  18496. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18497. if (found !== undefined) break;
  18498. var l = lngs[i];
  18499. var x = 0;
  18500. var value = resStore[l] && resStore[l][ns];
  18501. while (keys[x]) {
  18502. value = value && value[keys[x]];
  18503. x++;
  18504. }
  18505. if (value !== undefined) {
  18506. var valueType = Object.prototype.toString.apply(value);
  18507. if (typeof value === 'string') {
  18508. value = applyReplacement(value, options);
  18509. value = applyReuse(value, options);
  18510. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18511. value = value.join('\n');
  18512. value = applyReplacement(value, options);
  18513. value = applyReuse(value, options);
  18514. } else if (value === null && o.fallbackOnNull === true) {
  18515. value = undefined;
  18516. } else if (value !== null) {
  18517. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18518. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18519. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18520. } else {
  18521. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18522. 'returned an object instead of string.';
  18523. f.log(value);
  18524. }
  18525. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18526. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18527. f.each(value, function(m) {
  18528. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18529. });
  18530. value = copy;
  18531. }
  18532. }
  18533. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18534. value = undefined;
  18535. found = value;
  18536. }
  18537. }
  18538. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18539. // set flag for fallback lookup - avoid recursion
  18540. options.isFallbackLookup = true;
  18541. if (o.fallbackNS.length) {
  18542. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18543. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18544. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18545. /* compare value without namespace */
  18546. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18547. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18548. if (foundValue !== notFoundValue) break;
  18549. }
  18550. }
  18551. } else {
  18552. found = _find(key, options); // fallback to default NS
  18553. }
  18554. options.isFallbackLookup = false;
  18555. }
  18556. return found;
  18557. }
  18558. function detectLanguage() {
  18559. var detectedLng;
  18560. var whitelist = o.lngWhitelist || [];
  18561. var userLngChoices = [];
  18562. // get from qs
  18563. var qsParm = [];
  18564. if (typeof window !== 'undefined') {
  18565. (function() {
  18566. var query = window.location.search.substring(1);
  18567. var params = query.split('&');
  18568. for (var i=0; i<params.length; i++) {
  18569. var pos = params[i].indexOf('=');
  18570. if (pos > 0) {
  18571. var key = params[i].substring(0,pos);
  18572. if (key == o.detectLngQS) {
  18573. userLngChoices.push(params[i].substring(pos+1));
  18574. }
  18575. }
  18576. }
  18577. })();
  18578. }
  18579. // get from cookie
  18580. if (o.useCookie && typeof document !== 'undefined') {
  18581. var c = f.cookie.read(o.cookieName);
  18582. if (c) userLngChoices.push(c);
  18583. }
  18584. // get from localStorage
  18585. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18586. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18587. }
  18588. // get from navigator
  18589. if (typeof navigator !== 'undefined') {
  18590. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18591. for (var i=0;i<navigator.languages.length;i++) {
  18592. userLngChoices.push(navigator.languages[i]);
  18593. }
  18594. }
  18595. if (navigator.userLanguage) {
  18596. userLngChoices.push(navigator.userLanguage);
  18597. }
  18598. if (navigator.language) {
  18599. userLngChoices.push(navigator.language);
  18600. }
  18601. }
  18602. (function() {
  18603. for (var i=0;i<userLngChoices.length;i++) {
  18604. var lng = userLngChoices[i];
  18605. if (lng.indexOf('-') > -1) {
  18606. var parts = lng.split('-');
  18607. lng = o.lowerCaseLng ?
  18608. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18609. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18610. }
  18611. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18612. detectedLng = lng;
  18613. break;
  18614. }
  18615. }
  18616. })();
  18617. //fallback
  18618. if (!detectedLng){
  18619. detectedLng = o.fallbackLng[0];
  18620. }
  18621. return detectedLng;
  18622. }
  18623. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18624. /* [code, name, numbers, pluralsType] */
  18625. var _rules = [
  18626. ["ach", "Acholi", [1,2], 1],
  18627. ["af", "Afrikaans",[1,2], 2],
  18628. ["ak", "Akan", [1,2], 1],
  18629. ["am", "Amharic", [1,2], 1],
  18630. ["an", "Aragonese",[1,2], 2],
  18631. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18632. ["arn", "Mapudungun",[1,2], 1],
  18633. ["ast", "Asturian", [1,2], 2],
  18634. ["ay", "Aymará", [1], 3],
  18635. ["az", "Azerbaijani",[1,2],2],
  18636. ["be", "Belarusian",[1,2,5],4],
  18637. ["bg", "Bulgarian",[1,2], 2],
  18638. ["bn", "Bengali", [1,2], 2],
  18639. ["bo", "Tibetan", [1], 3],
  18640. ["br", "Breton", [1,2], 1],
  18641. ["bs", "Bosnian", [1,2,5],4],
  18642. ["ca", "Catalan", [1,2], 2],
  18643. ["cgg", "Chiga", [1], 3],
  18644. ["cs", "Czech", [1,2,5],6],
  18645. ["csb", "Kashubian",[1,2,5],7],
  18646. ["cy", "Welsh", [1,2,3,8],8],
  18647. ["da", "Danish", [1,2], 2],
  18648. ["de", "German", [1,2], 2],
  18649. ["dev", "Development Fallback", [1,2], 2],
  18650. ["dz", "Dzongkha", [1], 3],
  18651. ["el", "Greek", [1,2], 2],
  18652. ["en", "English", [1,2], 2],
  18653. ["eo", "Esperanto",[1,2], 2],
  18654. ["es", "Spanish", [1,2], 2],
  18655. ["es_ar","Argentinean Spanish", [1,2], 2],
  18656. ["et", "Estonian", [1,2], 2],
  18657. ["eu", "Basque", [1,2], 2],
  18658. ["fa", "Persian", [1], 3],
  18659. ["fi", "Finnish", [1,2], 2],
  18660. ["fil", "Filipino", [1,2], 1],
  18661. ["fo", "Faroese", [1,2], 2],
  18662. ["fr", "French", [1,2], 9],
  18663. ["fur", "Friulian", [1,2], 2],
  18664. ["fy", "Frisian", [1,2], 2],
  18665. ["ga", "Irish", [1,2,3,7,11],10],
  18666. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18667. ["gl", "Galician", [1,2], 2],
  18668. ["gu", "Gujarati", [1,2], 2],
  18669. ["gun", "Gun", [1,2], 1],
  18670. ["ha", "Hausa", [1,2], 2],
  18671. ["he", "Hebrew", [1,2], 2],
  18672. ["hi", "Hindi", [1,2], 2],
  18673. ["hr", "Croatian", [1,2,5],4],
  18674. ["hu", "Hungarian",[1,2], 2],
  18675. ["hy", "Armenian", [1,2], 2],
  18676. ["ia", "Interlingua",[1,2],2],
  18677. ["id", "Indonesian",[1], 3],
  18678. ["is", "Icelandic",[1,2], 12],
  18679. ["it", "Italian", [1,2], 2],
  18680. ["ja", "Japanese", [1], 3],
  18681. ["jbo", "Lojban", [1], 3],
  18682. ["jv", "Javanese", [0,1], 13],
  18683. ["ka", "Georgian", [1], 3],
  18684. ["kk", "Kazakh", [1], 3],
  18685. ["km", "Khmer", [1], 3],
  18686. ["kn", "Kannada", [1,2], 2],
  18687. ["ko", "Korean", [1], 3],
  18688. ["ku", "Kurdish", [1,2], 2],
  18689. ["kw", "Cornish", [1,2,3,4],14],
  18690. ["ky", "Kyrgyz", [1], 3],
  18691. ["lb", "Letzeburgesch",[1,2],2],
  18692. ["ln", "Lingala", [1,2], 1],
  18693. ["lo", "Lao", [1], 3],
  18694. ["lt", "Lithuanian",[1,2,10],15],
  18695. ["lv", "Latvian", [1,2,0],16],
  18696. ["mai", "Maithili", [1,2], 2],
  18697. ["mfe", "Mauritian Creole",[1,2],1],
  18698. ["mg", "Malagasy", [1,2], 1],
  18699. ["mi", "Maori", [1,2], 1],
  18700. ["mk", "Macedonian",[1,2],17],
  18701. ["ml", "Malayalam",[1,2], 2],
  18702. ["mn", "Mongolian",[1,2], 2],
  18703. ["mnk", "Mandinka", [0,1,2],18],
  18704. ["mr", "Marathi", [1,2], 2],
  18705. ["ms", "Malay", [1], 3],
  18706. ["mt", "Maltese", [1,2,11,20],19],
  18707. ["nah", "Nahuatl", [1,2], 2],
  18708. ["nap", "Neapolitan",[1,2], 2],
  18709. ["nb", "Norwegian Bokmal",[1,2],2],
  18710. ["ne", "Nepali", [1,2], 2],
  18711. ["nl", "Dutch", [1,2], 2],
  18712. ["nn", "Norwegian Nynorsk",[1,2],2],
  18713. ["no", "Norwegian",[1,2], 2],
  18714. ["nso", "Northern Sotho",[1,2],2],
  18715. ["oc", "Occitan", [1,2], 1],
  18716. ["or", "Oriya", [2,1], 2],
  18717. ["pa", "Punjabi", [1,2], 2],
  18718. ["pap", "Papiamento",[1,2], 2],
  18719. ["pl", "Polish", [1,2,5],7],
  18720. ["pms", "Piemontese",[1,2], 2],
  18721. ["ps", "Pashto", [1,2], 2],
  18722. ["pt", "Portuguese",[1,2], 2],
  18723. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18724. ["rm", "Romansh", [1,2], 2],
  18725. ["ro", "Romanian", [1,2,20],20],
  18726. ["ru", "Russian", [1,2,5],4],
  18727. ["sah", "Yakut", [1], 3],
  18728. ["sco", "Scots", [1,2], 2],
  18729. ["se", "Northern Sami",[1,2], 2],
  18730. ["si", "Sinhala", [1,2], 2],
  18731. ["sk", "Slovak", [1,2,5],6],
  18732. ["sl", "Slovenian",[5,1,2,3],21],
  18733. ["so", "Somali", [1,2], 2],
  18734. ["son", "Songhay", [1,2], 2],
  18735. ["sq", "Albanian", [1,2], 2],
  18736. ["sr", "Serbian", [1,2,5],4],
  18737. ["su", "Sundanese",[1], 3],
  18738. ["sv", "Swedish", [1,2], 2],
  18739. ["sw", "Swahili", [1,2], 2],
  18740. ["ta", "Tamil", [1,2], 2],
  18741. ["te", "Telugu", [1,2], 2],
  18742. ["tg", "Tajik", [1,2], 1],
  18743. ["th", "Thai", [1], 3],
  18744. ["ti", "Tigrinya", [1,2], 1],
  18745. ["tk", "Turkmen", [1,2], 2],
  18746. ["tr", "Turkish", [1,2], 1],
  18747. ["tt", "Tatar", [1], 3],
  18748. ["ug", "Uyghur", [1], 3],
  18749. ["uk", "Ukrainian",[1,2,5],4],
  18750. ["ur", "Urdu", [1,2], 2],
  18751. ["uz", "Uzbek", [1,2], 1],
  18752. ["vi", "Vietnamese",[1], 3],
  18753. ["wa", "Walloon", [1,2], 1],
  18754. ["wo", "Wolof", [1], 3],
  18755. ["yo", "Yoruba", [1,2], 2],
  18756. ["zh", "Chinese", [1], 3]
  18757. ];
  18758. var _rulesPluralsTypes = {
  18759. 1: function(n) {return Number(n > 1);},
  18760. 2: function(n) {return Number(n != 1);},
  18761. 3: function(n) {return 0;},
  18762. 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);},
  18763. 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);},
  18764. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18765. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18766. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18767. 9: function(n) {return Number(n >= 2);},
  18768. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18769. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18770. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18771. 13: function(n) {return Number(n !== 0);},
  18772. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18773. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18774. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18775. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18776. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18777. 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);},
  18778. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18779. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18780. };
  18781. var pluralExtensions = {
  18782. rules: (function () {
  18783. var l, rules = {};
  18784. for (l=_rules.length; l-- ;) {
  18785. rules[_rules[l][0]] = {
  18786. name: _rules[l][1],
  18787. numbers: _rules[l][2],
  18788. plurals: _rulesPluralsTypes[_rules[l][3]]
  18789. }
  18790. }
  18791. return rules;
  18792. }()),
  18793. // you can add your own pluralExtensions
  18794. addRule: function(lng, obj) {
  18795. pluralExtensions.rules[lng] = obj;
  18796. },
  18797. setCurrentLng: function(lng) {
  18798. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18799. var parts = lng.split('-');
  18800. pluralExtensions.currentRule = {
  18801. lng: lng,
  18802. rule: pluralExtensions.rules[parts[0]]
  18803. };
  18804. }
  18805. },
  18806. needsPlural: function(lng, count) {
  18807. var parts = lng.split('-');
  18808. var ext;
  18809. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18810. ext = pluralExtensions.currentRule.rule;
  18811. } else {
  18812. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18813. }
  18814. if (ext && ext.numbers.length <= 1) {
  18815. return false;
  18816. } else {
  18817. return this.get(lng, count) !== 1;
  18818. }
  18819. },
  18820. get: function(lng, count) {
  18821. var parts = lng.split('-');
  18822. function getResult(l, c) {
  18823. var ext;
  18824. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18825. ext = pluralExtensions.currentRule.rule;
  18826. } else {
  18827. ext = pluralExtensions.rules[l];
  18828. }
  18829. if (ext) {
  18830. var i;
  18831. if (ext.noAbs) {
  18832. i = ext.plurals(c);
  18833. } else {
  18834. i = ext.plurals(Math.abs(c));
  18835. }
  18836. var number = ext.numbers[i];
  18837. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18838. if (number === 2) {
  18839. number = -1; // regular plural
  18840. } else if (number === 1) {
  18841. number = 1; // singular
  18842. }
  18843. }//console.log(count + '-' + number);
  18844. return number;
  18845. } else {
  18846. return c === 1 ? '1' : '-1';
  18847. }
  18848. }
  18849. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18850. }
  18851. };
  18852. var postProcessors = {};
  18853. var addPostProcessor = function(name, fc) {
  18854. postProcessors[name] = fc;
  18855. };
  18856. // sprintf support
  18857. var sprintf = (function() {
  18858. function get_type(variable) {
  18859. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18860. }
  18861. function str_repeat(input, multiplier) {
  18862. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18863. return output.join('');
  18864. }
  18865. var str_format = function() {
  18866. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18867. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18868. }
  18869. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18870. };
  18871. str_format.format = function(parse_tree, argv) {
  18872. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18873. for (i = 0; i < tree_length; i++) {
  18874. node_type = get_type(parse_tree[i]);
  18875. if (node_type === 'string') {
  18876. output.push(parse_tree[i]);
  18877. }
  18878. else if (node_type === 'array') {
  18879. match = parse_tree[i]; // convenience purposes only
  18880. if (match[2]) { // keyword argument
  18881. arg = argv[cursor];
  18882. for (k = 0; k < match[2].length; k++) {
  18883. if (!arg.hasOwnProperty(match[2][k])) {
  18884. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  18885. }
  18886. arg = arg[match[2][k]];
  18887. }
  18888. }
  18889. else if (match[1]) { // positional argument (explicit)
  18890. arg = argv[match[1]];
  18891. }
  18892. else { // positional argument (implicit)
  18893. arg = argv[cursor++];
  18894. }
  18895. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  18896. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  18897. }
  18898. switch (match[8]) {
  18899. case 'b': arg = arg.toString(2); break;
  18900. case 'c': arg = String.fromCharCode(arg); break;
  18901. case 'd': arg = parseInt(arg, 10); break;
  18902. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  18903. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  18904. case 'o': arg = arg.toString(8); break;
  18905. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  18906. case 'u': arg = Math.abs(arg); break;
  18907. case 'x': arg = arg.toString(16); break;
  18908. case 'X': arg = arg.toString(16).toUpperCase(); break;
  18909. }
  18910. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  18911. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  18912. pad_length = match[6] - String(arg).length;
  18913. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  18914. output.push(match[5] ? arg + pad : pad + arg);
  18915. }
  18916. }
  18917. return output.join('');
  18918. };
  18919. str_format.cache = {};
  18920. str_format.parse = function(fmt) {
  18921. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  18922. while (_fmt) {
  18923. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  18924. parse_tree.push(match[0]);
  18925. }
  18926. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  18927. parse_tree.push('%');
  18928. }
  18929. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  18930. if (match[2]) {
  18931. arg_names |= 1;
  18932. var field_list = [], replacement_field = match[2], field_match = [];
  18933. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18934. field_list.push(field_match[1]);
  18935. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  18936. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18937. field_list.push(field_match[1]);
  18938. }
  18939. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  18940. field_list.push(field_match[1]);
  18941. }
  18942. else {
  18943. throw('[sprintf] huh?');
  18944. }
  18945. }
  18946. }
  18947. else {
  18948. throw('[sprintf] huh?');
  18949. }
  18950. match[2] = field_list;
  18951. }
  18952. else {
  18953. arg_names |= 2;
  18954. }
  18955. if (arg_names === 3) {
  18956. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  18957. }
  18958. parse_tree.push(match);
  18959. }
  18960. else {
  18961. throw('[sprintf] huh?');
  18962. }
  18963. _fmt = _fmt.substring(match[0].length);
  18964. }
  18965. return parse_tree;
  18966. };
  18967. return str_format;
  18968. })();
  18969. var vsprintf = function(fmt, argv) {
  18970. argv.unshift(fmt);
  18971. return sprintf.apply(null, argv);
  18972. };
  18973. addPostProcessor("sprintf", function(val, key, opts) {
  18974. if (!opts.sprintf) return val;
  18975. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  18976. return vsprintf(val, opts.sprintf);
  18977. } else if (typeof opts.sprintf === 'object') {
  18978. return sprintf(val, opts.sprintf);
  18979. }
  18980. return val;
  18981. });
  18982. // public api interface
  18983. i18n.init = init;
  18984. i18n.setLng = setLng;
  18985. i18n.preload = preload;
  18986. i18n.addResourceBundle = addResourceBundle;
  18987. i18n.hasResourceBundle = hasResourceBundle;
  18988. i18n.addResource = addResource;
  18989. i18n.addResources = addResources;
  18990. i18n.removeResourceBundle = removeResourceBundle;
  18991. i18n.loadNamespace = loadNamespace;
  18992. i18n.loadNamespaces = loadNamespaces;
  18993. i18n.setDefaultNamespace = setDefaultNamespace;
  18994. i18n.t = translate;
  18995. i18n.translate = translate;
  18996. i18n.exists = exists;
  18997. i18n.detectLanguage = f.detectLanguage;
  18998. i18n.pluralExtensions = pluralExtensions;
  18999. i18n.sync = sync;
  19000. i18n.functions = f;
  19001. i18n.lng = lng;
  19002. i18n.addPostProcessor = addPostProcessor;
  19003. i18n.options = o;
  19004. })();
  19005. },{"jquery":"jquery"}],67:[function(require,module,exports){
  19006. // Top level file is just a mixin of submodules & constants
  19007. 'use strict';
  19008. var assign = require('./lib/utils/common').assign;
  19009. var deflate = require('./lib/deflate');
  19010. var inflate = require('./lib/inflate');
  19011. var constants = require('./lib/zlib/constants');
  19012. var pako = {};
  19013. assign(pako, deflate, inflate, constants);
  19014. module.exports = pako;
  19015. },{"./lib/deflate":68,"./lib/inflate":69,"./lib/utils/common":70,"./lib/zlib/constants":73}],68:[function(require,module,exports){
  19016. 'use strict';
  19017. var zlib_deflate = require('./zlib/deflate.js');
  19018. var utils = require('./utils/common');
  19019. var strings = require('./utils/strings');
  19020. var msg = require('./zlib/messages');
  19021. var zstream = require('./zlib/zstream');
  19022. var toString = Object.prototype.toString;
  19023. /* Public constants ==========================================================*/
  19024. /* ===========================================================================*/
  19025. var Z_NO_FLUSH = 0;
  19026. var Z_FINISH = 4;
  19027. var Z_OK = 0;
  19028. var Z_STREAM_END = 1;
  19029. var Z_DEFAULT_COMPRESSION = -1;
  19030. var Z_DEFAULT_STRATEGY = 0;
  19031. var Z_DEFLATED = 8;
  19032. /* ===========================================================================*/
  19033. /**
  19034. * class Deflate
  19035. *
  19036. * Generic JS-style wrapper for zlib calls. If you don't need
  19037. * streaming behaviour - use more simple functions: [[deflate]],
  19038. * [[deflateRaw]] and [[gzip]].
  19039. **/
  19040. /* internal
  19041. * Deflate.chunks -> Array
  19042. *
  19043. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19044. **/
  19045. /**
  19046. * Deflate.result -> Uint8Array|Array
  19047. *
  19048. * Compressed result, generated by default [[Deflate#onData]]
  19049. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19050. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  19051. **/
  19052. /**
  19053. * Deflate.err -> Number
  19054. *
  19055. * Error code after deflate finished. 0 (Z_OK) on success.
  19056. * You will not need it in real life, because deflate errors
  19057. * are possible only on wrong options or bad `onData` / `onEnd`
  19058. * custom handlers.
  19059. **/
  19060. /**
  19061. * Deflate.msg -> String
  19062. *
  19063. * Error message, if [[Deflate.err]] != 0
  19064. **/
  19065. /**
  19066. * new Deflate(options)
  19067. * - options (Object): zlib deflate options.
  19068. *
  19069. * Creates new deflator instance with specified params. Throws exception
  19070. * on bad params. Supported options:
  19071. *
  19072. * - `level`
  19073. * - `windowBits`
  19074. * - `memLevel`
  19075. * - `strategy`
  19076. *
  19077. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19078. * for more information on these.
  19079. *
  19080. * Additional options, for internal needs:
  19081. *
  19082. * - `chunkSize` - size of generated data chunks (16K by default)
  19083. * - `raw` (Boolean) - do raw deflate
  19084. * - `gzip` (Boolean) - create gzip wrapper
  19085. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19086. * (each char code [0..255])
  19087. * - `header` (Object) - custom header for gzip
  19088. * - `text` (Boolean) - true if compressed data believed to be text
  19089. * - `time` (Number) - modification time, unix timestamp
  19090. * - `os` (Number) - operation system code
  19091. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19092. * - `name` (String) - file name (binary string)
  19093. * - `comment` (String) - comment (binary string)
  19094. * - `hcrc` (Boolean) - true if header crc should be added
  19095. *
  19096. * ##### Example:
  19097. *
  19098. * ```javascript
  19099. * var pako = require('pako')
  19100. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19101. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19102. *
  19103. * var deflate = new pako.Deflate({ level: 3});
  19104. *
  19105. * deflate.push(chunk1, false);
  19106. * deflate.push(chunk2, true); // true -> last chunk
  19107. *
  19108. * if (deflate.err) { throw new Error(deflate.err); }
  19109. *
  19110. * console.log(deflate.result);
  19111. * ```
  19112. **/
  19113. var Deflate = function(options) {
  19114. this.options = utils.assign({
  19115. level: Z_DEFAULT_COMPRESSION,
  19116. method: Z_DEFLATED,
  19117. chunkSize: 16384,
  19118. windowBits: 15,
  19119. memLevel: 8,
  19120. strategy: Z_DEFAULT_STRATEGY,
  19121. to: ''
  19122. }, options || {});
  19123. var opt = this.options;
  19124. if (opt.raw && (opt.windowBits > 0)) {
  19125. opt.windowBits = -opt.windowBits;
  19126. }
  19127. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19128. opt.windowBits += 16;
  19129. }
  19130. this.err = 0; // error code, if happens (0 = Z_OK)
  19131. this.msg = ''; // error message
  19132. this.ended = false; // used to avoid multiple onEnd() calls
  19133. this.chunks = []; // chunks of compressed data
  19134. this.strm = new zstream();
  19135. this.strm.avail_out = 0;
  19136. var status = zlib_deflate.deflateInit2(
  19137. this.strm,
  19138. opt.level,
  19139. opt.method,
  19140. opt.windowBits,
  19141. opt.memLevel,
  19142. opt.strategy
  19143. );
  19144. if (status !== Z_OK) {
  19145. throw new Error(msg[status]);
  19146. }
  19147. if (opt.header) {
  19148. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19149. }
  19150. };
  19151. /**
  19152. * Deflate#push(data[, mode]) -> Boolean
  19153. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19154. * converted to utf8 byte sequence.
  19155. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19156. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19157. *
  19158. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19159. * new compressed chunks. Returns `true` on success. The last data block must have
  19160. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  19161. * [[Deflate#onEnd]].
  19162. *
  19163. * On fail call [[Deflate#onEnd]] with error code and return false.
  19164. *
  19165. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19166. * array format is detected automatically). Also, don't skip last param and always
  19167. * use the same type in your code (boolean or number). That will improve JS speed.
  19168. *
  19169. * For regular `Array`-s make sure all elements are [0..255].
  19170. *
  19171. * ##### Example
  19172. *
  19173. * ```javascript
  19174. * push(chunk, false); // push one of data chunks
  19175. * ...
  19176. * push(chunk, true); // push last chunk
  19177. * ```
  19178. **/
  19179. Deflate.prototype.push = function(data, mode) {
  19180. var strm = this.strm;
  19181. var chunkSize = this.options.chunkSize;
  19182. var status, _mode;
  19183. if (this.ended) { return false; }
  19184. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19185. // Convert data if needed
  19186. if (typeof data === 'string') {
  19187. // If we need to compress text, change encoding to utf8.
  19188. strm.input = strings.string2buf(data);
  19189. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19190. strm.input = new Uint8Array(data);
  19191. } else {
  19192. strm.input = data;
  19193. }
  19194. strm.next_in = 0;
  19195. strm.avail_in = strm.input.length;
  19196. do {
  19197. if (strm.avail_out === 0) {
  19198. strm.output = new utils.Buf8(chunkSize);
  19199. strm.next_out = 0;
  19200. strm.avail_out = chunkSize;
  19201. }
  19202. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19203. if (status !== Z_STREAM_END && status !== Z_OK) {
  19204. this.onEnd(status);
  19205. this.ended = true;
  19206. return false;
  19207. }
  19208. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  19209. if (this.options.to === 'string') {
  19210. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19211. } else {
  19212. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19213. }
  19214. }
  19215. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19216. // Finalize on the last chunk.
  19217. if (_mode === Z_FINISH) {
  19218. status = zlib_deflate.deflateEnd(this.strm);
  19219. this.onEnd(status);
  19220. this.ended = true;
  19221. return status === Z_OK;
  19222. }
  19223. return true;
  19224. };
  19225. /**
  19226. * Deflate#onData(chunk) -> Void
  19227. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19228. * on js engine support. When string output requested, each chunk
  19229. * will be string.
  19230. *
  19231. * By default, stores data blocks in `chunks[]` property and glue
  19232. * those in `onEnd`. Override this handler, if you need another behaviour.
  19233. **/
  19234. Deflate.prototype.onData = function(chunk) {
  19235. this.chunks.push(chunk);
  19236. };
  19237. /**
  19238. * Deflate#onEnd(status) -> Void
  19239. * - status (Number): deflate status. 0 (Z_OK) on success,
  19240. * other if not.
  19241. *
  19242. * Called once after you tell deflate that input stream complete
  19243. * or error happenned. By default - join collected chunks,
  19244. * free memory and fill `results` / `err` properties.
  19245. **/
  19246. Deflate.prototype.onEnd = function(status) {
  19247. // On success - join
  19248. if (status === Z_OK) {
  19249. if (this.options.to === 'string') {
  19250. this.result = this.chunks.join('');
  19251. } else {
  19252. this.result = utils.flattenChunks(this.chunks);
  19253. }
  19254. }
  19255. this.chunks = [];
  19256. this.err = status;
  19257. this.msg = this.strm.msg;
  19258. };
  19259. /**
  19260. * deflate(data[, options]) -> Uint8Array|Array|String
  19261. * - data (Uint8Array|Array|String): input data to compress.
  19262. * - options (Object): zlib deflate options.
  19263. *
  19264. * Compress `data` with deflate alrorythm and `options`.
  19265. *
  19266. * Supported options are:
  19267. *
  19268. * - level
  19269. * - windowBits
  19270. * - memLevel
  19271. * - strategy
  19272. *
  19273. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19274. * for more information on these.
  19275. *
  19276. * Sugar (options):
  19277. *
  19278. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19279. * negative windowBits implicitly.
  19280. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19281. * (each char code [0..255])
  19282. *
  19283. * ##### Example:
  19284. *
  19285. * ```javascript
  19286. * var pako = require('pako')
  19287. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19288. *
  19289. * console.log(pako.deflate(data));
  19290. * ```
  19291. **/
  19292. function deflate(input, options) {
  19293. var deflator = new Deflate(options);
  19294. deflator.push(input, true);
  19295. // That will never happens, if you don't cheat with options :)
  19296. if (deflator.err) { throw deflator.msg; }
  19297. return deflator.result;
  19298. }
  19299. /**
  19300. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19301. * - data (Uint8Array|Array|String): input data to compress.
  19302. * - options (Object): zlib deflate options.
  19303. *
  19304. * The same as [[deflate]], but creates raw data, without wrapper
  19305. * (header and adler32 crc).
  19306. **/
  19307. function deflateRaw(input, options) {
  19308. options = options || {};
  19309. options.raw = true;
  19310. return deflate(input, options);
  19311. }
  19312. /**
  19313. * gzip(data[, options]) -> Uint8Array|Array|String
  19314. * - data (Uint8Array|Array|String): input data to compress.
  19315. * - options (Object): zlib deflate options.
  19316. *
  19317. * The same as [[deflate]], but create gzip wrapper instead of
  19318. * deflate one.
  19319. **/
  19320. function gzip(input, options) {
  19321. options = options || {};
  19322. options.gzip = true;
  19323. return deflate(input, options);
  19324. }
  19325. exports.Deflate = Deflate;
  19326. exports.deflate = deflate;
  19327. exports.deflateRaw = deflateRaw;
  19328. exports.gzip = gzip;
  19329. },{"./utils/common":70,"./utils/strings":71,"./zlib/deflate.js":75,"./zlib/messages":80,"./zlib/zstream":82}],69:[function(require,module,exports){
  19330. 'use strict';
  19331. var zlib_inflate = require('./zlib/inflate.js');
  19332. var utils = require('./utils/common');
  19333. var strings = require('./utils/strings');
  19334. var c = require('./zlib/constants');
  19335. var msg = require('./zlib/messages');
  19336. var zstream = require('./zlib/zstream');
  19337. var gzheader = require('./zlib/gzheader');
  19338. var toString = Object.prototype.toString;
  19339. /**
  19340. * class Inflate
  19341. *
  19342. * Generic JS-style wrapper for zlib calls. If you don't need
  19343. * streaming behaviour - use more simple functions: [[inflate]]
  19344. * and [[inflateRaw]].
  19345. **/
  19346. /* internal
  19347. * inflate.chunks -> Array
  19348. *
  19349. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19350. **/
  19351. /**
  19352. * Inflate.result -> Uint8Array|Array|String
  19353. *
  19354. * Uncompressed result, generated by default [[Inflate#onData]]
  19355. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19356. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  19357. **/
  19358. /**
  19359. * Inflate.err -> Number
  19360. *
  19361. * Error code after inflate finished. 0 (Z_OK) on success.
  19362. * Should be checked if broken data possible.
  19363. **/
  19364. /**
  19365. * Inflate.msg -> String
  19366. *
  19367. * Error message, if [[Inflate.err]] != 0
  19368. **/
  19369. /**
  19370. * new Inflate(options)
  19371. * - options (Object): zlib inflate options.
  19372. *
  19373. * Creates new inflator instance with specified params. Throws exception
  19374. * on bad params. Supported options:
  19375. *
  19376. * - `windowBits`
  19377. *
  19378. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19379. * for more information on these.
  19380. *
  19381. * Additional options, for internal needs:
  19382. *
  19383. * - `chunkSize` - size of generated data chunks (16K by default)
  19384. * - `raw` (Boolean) - do raw inflate
  19385. * - `to` (String) - if equal to 'string', then result will be converted
  19386. * from utf8 to utf16 (javascript) string. When string output requested,
  19387. * chunk length can differ from `chunkSize`, depending on content.
  19388. *
  19389. * By default, when no options set, autodetect deflate/gzip data format via
  19390. * wrapper header.
  19391. *
  19392. * ##### Example:
  19393. *
  19394. * ```javascript
  19395. * var pako = require('pako')
  19396. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19397. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19398. *
  19399. * var inflate = new pako.Inflate({ level: 3});
  19400. *
  19401. * inflate.push(chunk1, false);
  19402. * inflate.push(chunk2, true); // true -> last chunk
  19403. *
  19404. * if (inflate.err) { throw new Error(inflate.err); }
  19405. *
  19406. * console.log(inflate.result);
  19407. * ```
  19408. **/
  19409. var Inflate = function(options) {
  19410. this.options = utils.assign({
  19411. chunkSize: 16384,
  19412. windowBits: 0,
  19413. to: ''
  19414. }, options || {});
  19415. var opt = this.options;
  19416. // Force window size for `raw` data, if not set directly,
  19417. // because we have no header for autodetect.
  19418. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19419. opt.windowBits = -opt.windowBits;
  19420. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19421. }
  19422. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19423. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19424. !(options && options.windowBits)) {
  19425. opt.windowBits += 32;
  19426. }
  19427. // Gzip header has no info about windows size, we can do autodetect only
  19428. // for deflate. So, if window size not set, force it to max when gzip possible
  19429. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19430. // bit 3 (16) -> gzipped data
  19431. // bit 4 (32) -> autodetect gzip/deflate
  19432. if ((opt.windowBits & 15) === 0) {
  19433. opt.windowBits |= 15;
  19434. }
  19435. }
  19436. this.err = 0; // error code, if happens (0 = Z_OK)
  19437. this.msg = ''; // error message
  19438. this.ended = false; // used to avoid multiple onEnd() calls
  19439. this.chunks = []; // chunks of compressed data
  19440. this.strm = new zstream();
  19441. this.strm.avail_out = 0;
  19442. var status = zlib_inflate.inflateInit2(
  19443. this.strm,
  19444. opt.windowBits
  19445. );
  19446. if (status !== c.Z_OK) {
  19447. throw new Error(msg[status]);
  19448. }
  19449. this.header = new gzheader();
  19450. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19451. };
  19452. /**
  19453. * Inflate#push(data[, mode]) -> Boolean
  19454. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19455. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19456. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19457. *
  19458. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19459. * new output chunks. Returns `true` on success. The last data block must have
  19460. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  19461. * [[Inflate#onEnd]].
  19462. *
  19463. * On fail call [[Inflate#onEnd]] with error code and return false.
  19464. *
  19465. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19466. * format is detected automatically). Also, don't skip last param and always
  19467. * use the same type in your code (boolean or number). That will improve JS speed.
  19468. *
  19469. * For regular `Array`-s make sure all elements are [0..255].
  19470. *
  19471. * ##### Example
  19472. *
  19473. * ```javascript
  19474. * push(chunk, false); // push one of data chunks
  19475. * ...
  19476. * push(chunk, true); // push last chunk
  19477. * ```
  19478. **/
  19479. Inflate.prototype.push = function(data, mode) {
  19480. var strm = this.strm;
  19481. var chunkSize = this.options.chunkSize;
  19482. var status, _mode;
  19483. var next_out_utf8, tail, utf8str;
  19484. if (this.ended) { return false; }
  19485. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19486. // Convert data if needed
  19487. if (typeof data === 'string') {
  19488. // Only binary strings can be decompressed on practice
  19489. strm.input = strings.binstring2buf(data);
  19490. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19491. strm.input = new Uint8Array(data);
  19492. } else {
  19493. strm.input = data;
  19494. }
  19495. strm.next_in = 0;
  19496. strm.avail_in = strm.input.length;
  19497. do {
  19498. if (strm.avail_out === 0) {
  19499. strm.output = new utils.Buf8(chunkSize);
  19500. strm.next_out = 0;
  19501. strm.avail_out = chunkSize;
  19502. }
  19503. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19504. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19505. this.onEnd(status);
  19506. this.ended = true;
  19507. return false;
  19508. }
  19509. if (strm.next_out) {
  19510. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  19511. if (this.options.to === 'string') {
  19512. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19513. tail = strm.next_out - next_out_utf8;
  19514. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19515. // move tail
  19516. strm.next_out = tail;
  19517. strm.avail_out = chunkSize - tail;
  19518. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19519. this.onData(utf8str);
  19520. } else {
  19521. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19522. }
  19523. }
  19524. }
  19525. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19526. if (status === c.Z_STREAM_END) {
  19527. _mode = c.Z_FINISH;
  19528. }
  19529. // Finalize on the last chunk.
  19530. if (_mode === c.Z_FINISH) {
  19531. status = zlib_inflate.inflateEnd(this.strm);
  19532. this.onEnd(status);
  19533. this.ended = true;
  19534. return status === c.Z_OK;
  19535. }
  19536. return true;
  19537. };
  19538. /**
  19539. * Inflate#onData(chunk) -> Void
  19540. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19541. * on js engine support. When string output requested, each chunk
  19542. * will be string.
  19543. *
  19544. * By default, stores data blocks in `chunks[]` property and glue
  19545. * those in `onEnd`. Override this handler, if you need another behaviour.
  19546. **/
  19547. Inflate.prototype.onData = function(chunk) {
  19548. this.chunks.push(chunk);
  19549. };
  19550. /**
  19551. * Inflate#onEnd(status) -> Void
  19552. * - status (Number): inflate status. 0 (Z_OK) on success,
  19553. * other if not.
  19554. *
  19555. * Called once after you tell inflate that input stream complete
  19556. * or error happenned. By default - join collected chunks,
  19557. * free memory and fill `results` / `err` properties.
  19558. **/
  19559. Inflate.prototype.onEnd = function(status) {
  19560. // On success - join
  19561. if (status === c.Z_OK) {
  19562. if (this.options.to === 'string') {
  19563. // Glue & convert here, until we teach pako to send
  19564. // utf8 alligned strings to onData
  19565. this.result = this.chunks.join('');
  19566. } else {
  19567. this.result = utils.flattenChunks(this.chunks);
  19568. }
  19569. }
  19570. this.chunks = [];
  19571. this.err = status;
  19572. this.msg = this.strm.msg;
  19573. };
  19574. /**
  19575. * inflate(data[, options]) -> Uint8Array|Array|String
  19576. * - data (Uint8Array|Array|String): input data to decompress.
  19577. * - options (Object): zlib inflate options.
  19578. *
  19579. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19580. * format via wrapper header by default. That's why we don't provide
  19581. * separate `ungzip` method.
  19582. *
  19583. * Supported options are:
  19584. *
  19585. * - windowBits
  19586. *
  19587. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19588. * for more information.
  19589. *
  19590. * Sugar (options):
  19591. *
  19592. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19593. * negative windowBits implicitly.
  19594. * - `to` (String) - if equal to 'string', then result will be converted
  19595. * from utf8 to utf16 (javascript) string. When string output requested,
  19596. * chunk length can differ from `chunkSize`, depending on content.
  19597. *
  19598. *
  19599. * ##### Example:
  19600. *
  19601. * ```javascript
  19602. * var pako = require('pako')
  19603. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19604. * , output;
  19605. *
  19606. * try {
  19607. * output = pako.inflate(input);
  19608. * } catch (err)
  19609. * console.log(err);
  19610. * }
  19611. * ```
  19612. **/
  19613. function inflate(input, options) {
  19614. var inflator = new Inflate(options);
  19615. inflator.push(input, true);
  19616. // That will never happens, if you don't cheat with options :)
  19617. if (inflator.err) { throw inflator.msg; }
  19618. return inflator.result;
  19619. }
  19620. /**
  19621. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19622. * - data (Uint8Array|Array|String): input data to decompress.
  19623. * - options (Object): zlib inflate options.
  19624. *
  19625. * The same as [[inflate]], but creates raw data, without wrapper
  19626. * (header and adler32 crc).
  19627. **/
  19628. function inflateRaw(input, options) {
  19629. options = options || {};
  19630. options.raw = true;
  19631. return inflate(input, options);
  19632. }
  19633. /**
  19634. * ungzip(data[, options]) -> Uint8Array|Array|String
  19635. * - data (Uint8Array|Array|String): input data to decompress.
  19636. * - options (Object): zlib inflate options.
  19637. *
  19638. * Just shortcut to [[inflate]], because it autodetects format
  19639. * by header.content. Done for convenience.
  19640. **/
  19641. exports.Inflate = Inflate;
  19642. exports.inflate = inflate;
  19643. exports.inflateRaw = inflateRaw;
  19644. exports.ungzip = inflate;
  19645. },{"./utils/common":70,"./utils/strings":71,"./zlib/constants":73,"./zlib/gzheader":76,"./zlib/inflate.js":78,"./zlib/messages":80,"./zlib/zstream":82}],70:[function(require,module,exports){
  19646. 'use strict';
  19647. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19648. (typeof Uint16Array !== 'undefined') &&
  19649. (typeof Int32Array !== 'undefined');
  19650. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19651. var sources = Array.prototype.slice.call(arguments, 1);
  19652. while (sources.length) {
  19653. var source = sources.shift();
  19654. if (!source) { continue; }
  19655. if (typeof(source) !== 'object') {
  19656. throw new TypeError(source + 'must be non-object');
  19657. }
  19658. for (var p in source) {
  19659. if (source.hasOwnProperty(p)) {
  19660. obj[p] = source[p];
  19661. }
  19662. }
  19663. }
  19664. return obj;
  19665. };
  19666. // reduce buffer size, avoiding mem copy
  19667. exports.shrinkBuf = function (buf, size) {
  19668. if (buf.length === size) { return buf; }
  19669. if (buf.subarray) { return buf.subarray(0, size); }
  19670. buf.length = size;
  19671. return buf;
  19672. };
  19673. var fnTyped = {
  19674. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19675. if (src.subarray && dest.subarray) {
  19676. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19677. return;
  19678. }
  19679. // Fallback to ordinary array
  19680. for(var i=0; i<len; i++) {
  19681. dest[dest_offs + i] = src[src_offs + i];
  19682. }
  19683. },
  19684. // Join array of chunks to single array.
  19685. flattenChunks: function(chunks) {
  19686. var i, l, len, pos, chunk, result;
  19687. // calculate data length
  19688. len = 0;
  19689. for (i=0, l=chunks.length; i<l; i++) {
  19690. len += chunks[i].length;
  19691. }
  19692. // join chunks
  19693. result = new Uint8Array(len);
  19694. pos = 0;
  19695. for (i=0, l=chunks.length; i<l; i++) {
  19696. chunk = chunks[i];
  19697. result.set(chunk, pos);
  19698. pos += chunk.length;
  19699. }
  19700. return result;
  19701. }
  19702. };
  19703. var fnUntyped = {
  19704. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19705. for(var i=0; i<len; i++) {
  19706. dest[dest_offs + i] = src[src_offs + i];
  19707. }
  19708. },
  19709. // Join array of chunks to single array.
  19710. flattenChunks: function(chunks) {
  19711. return [].concat.apply([], chunks);
  19712. }
  19713. };
  19714. // Enable/Disable typed arrays use, for testing
  19715. //
  19716. exports.setTyped = function (on) {
  19717. if (on) {
  19718. exports.Buf8 = Uint8Array;
  19719. exports.Buf16 = Uint16Array;
  19720. exports.Buf32 = Int32Array;
  19721. exports.assign(exports, fnTyped);
  19722. } else {
  19723. exports.Buf8 = Array;
  19724. exports.Buf16 = Array;
  19725. exports.Buf32 = Array;
  19726. exports.assign(exports, fnUntyped);
  19727. }
  19728. };
  19729. exports.setTyped(TYPED_OK);
  19730. },{}],71:[function(require,module,exports){
  19731. // String encode/decode helpers
  19732. 'use strict';
  19733. var utils = require('./common');
  19734. // Quick check if we can use fast array to bin string conversion
  19735. //
  19736. // - apply(Array) can fail on Android 2.2
  19737. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19738. //
  19739. var STR_APPLY_OK = true;
  19740. var STR_APPLY_UIA_OK = true;
  19741. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19742. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19743. // Table with utf8 lengths (calculated by first byte of sequence)
  19744. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19745. // because max possible codepoint is 0x10ffff
  19746. var _utf8len = new utils.Buf8(256);
  19747. for (var i=0; i<256; i++) {
  19748. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  19749. }
  19750. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19751. // convert string to array (typed, when possible)
  19752. exports.string2buf = function (str) {
  19753. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19754. // count binary size
  19755. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19756. c = str.charCodeAt(m_pos);
  19757. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19758. c2 = str.charCodeAt(m_pos+1);
  19759. if ((c2 & 0xfc00) === 0xdc00) {
  19760. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19761. m_pos++;
  19762. }
  19763. }
  19764. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19765. }
  19766. // allocate buffer
  19767. buf = new utils.Buf8(buf_len);
  19768. // convert
  19769. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19770. c = str.charCodeAt(m_pos);
  19771. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19772. c2 = str.charCodeAt(m_pos+1);
  19773. if ((c2 & 0xfc00) === 0xdc00) {
  19774. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19775. m_pos++;
  19776. }
  19777. }
  19778. if (c < 0x80) {
  19779. /* one byte */
  19780. buf[i++] = c;
  19781. } else if (c < 0x800) {
  19782. /* two bytes */
  19783. buf[i++] = 0xC0 | (c >>> 6);
  19784. buf[i++] = 0x80 | (c & 0x3f);
  19785. } else if (c < 0x10000) {
  19786. /* three bytes */
  19787. buf[i++] = 0xE0 | (c >>> 12);
  19788. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19789. buf[i++] = 0x80 | (c & 0x3f);
  19790. } else {
  19791. /* four bytes */
  19792. buf[i++] = 0xf0 | (c >>> 18);
  19793. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19794. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19795. buf[i++] = 0x80 | (c & 0x3f);
  19796. }
  19797. }
  19798. return buf;
  19799. };
  19800. // Helper (used in 2 places)
  19801. function buf2binstring(buf, len) {
  19802. // use fallback for big arrays to avoid stack overflow
  19803. if (len < 65537) {
  19804. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19805. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19806. }
  19807. }
  19808. var result = '';
  19809. for(var i=0; i < len; i++) {
  19810. result += String.fromCharCode(buf[i]);
  19811. }
  19812. return result;
  19813. }
  19814. // Convert byte array to binary string
  19815. exports.buf2binstring = function(buf) {
  19816. return buf2binstring(buf, buf.length);
  19817. };
  19818. // Convert binary string (typed, when possible)
  19819. exports.binstring2buf = function(str) {
  19820. var buf = new utils.Buf8(str.length);
  19821. for(var i=0, len=buf.length; i < len; i++) {
  19822. buf[i] = str.charCodeAt(i);
  19823. }
  19824. return buf;
  19825. };
  19826. // convert array to string
  19827. exports.buf2string = function (buf, max) {
  19828. var i, out, c, c_len;
  19829. var len = max || buf.length;
  19830. // Reserve max possible length (2 words per char)
  19831. // NB: by unknown reasons, Array is significantly faster for
  19832. // String.fromCharCode.apply than Uint16Array.
  19833. var utf16buf = new Array(len*2);
  19834. for (out=0, i=0; i<len;) {
  19835. c = buf[i++];
  19836. // quick process ascii
  19837. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19838. c_len = _utf8len[c];
  19839. // skip 5 & 6 byte codes
  19840. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19841. // apply mask on first byte
  19842. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19843. // join the rest
  19844. while (c_len > 1 && i < len) {
  19845. c = (c << 6) | (buf[i++] & 0x3f);
  19846. c_len--;
  19847. }
  19848. // terminated by end of string?
  19849. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19850. if (c < 0x10000) {
  19851. utf16buf[out++] = c;
  19852. } else {
  19853. c -= 0x10000;
  19854. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19855. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19856. }
  19857. }
  19858. return buf2binstring(utf16buf, out);
  19859. };
  19860. // Calculate max possible position in utf8 buffer,
  19861. // that will not break sequence. If that's not possible
  19862. // - (very small limits) return max size as is.
  19863. //
  19864. // buf[] - utf8 bytes array
  19865. // max - length limit (mandatory);
  19866. exports.utf8border = function(buf, max) {
  19867. var pos;
  19868. max = max || buf.length;
  19869. if (max > buf.length) { max = buf.length; }
  19870. // go back from last position, until start of sequence found
  19871. pos = max-1;
  19872. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  19873. // Fuckup - very small and broken sequence,
  19874. // return max, because we should return something anyway.
  19875. if (pos < 0) { return max; }
  19876. // If we came to start of buffer - that means vuffer is too small,
  19877. // return max too.
  19878. if (pos === 0) { return max; }
  19879. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  19880. };
  19881. },{"./common":70}],72:[function(require,module,exports){
  19882. 'use strict';
  19883. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  19884. // It doesn't worth to make additional optimizationa as in original.
  19885. // Small size is preferable.
  19886. function adler32(adler, buf, len, pos) {
  19887. var s1 = (adler & 0xffff) |0
  19888. , s2 = ((adler >>> 16) & 0xffff) |0
  19889. , n = 0;
  19890. while (len !== 0) {
  19891. // Set limit ~ twice less than 5552, to keep
  19892. // s2 in 31-bits, because we force signed ints.
  19893. // in other case %= will fail.
  19894. n = len > 2000 ? 2000 : len;
  19895. len -= n;
  19896. do {
  19897. s1 = (s1 + buf[pos++]) |0;
  19898. s2 = (s2 + s1) |0;
  19899. } while (--n);
  19900. s1 %= 65521;
  19901. s2 %= 65521;
  19902. }
  19903. return (s1 | (s2 << 16)) |0;
  19904. }
  19905. module.exports = adler32;
  19906. },{}],73:[function(require,module,exports){
  19907. module.exports = {
  19908. /* Allowed flush values; see deflate() and inflate() below for details */
  19909. Z_NO_FLUSH: 0,
  19910. Z_PARTIAL_FLUSH: 1,
  19911. Z_SYNC_FLUSH: 2,
  19912. Z_FULL_FLUSH: 3,
  19913. Z_FINISH: 4,
  19914. Z_BLOCK: 5,
  19915. Z_TREES: 6,
  19916. /* Return codes for the compression/decompression functions. Negative values
  19917. * are errors, positive values are used for special but normal events.
  19918. */
  19919. Z_OK: 0,
  19920. Z_STREAM_END: 1,
  19921. Z_NEED_DICT: 2,
  19922. Z_ERRNO: -1,
  19923. Z_STREAM_ERROR: -2,
  19924. Z_DATA_ERROR: -3,
  19925. //Z_MEM_ERROR: -4,
  19926. Z_BUF_ERROR: -5,
  19927. //Z_VERSION_ERROR: -6,
  19928. /* compression levels */
  19929. Z_NO_COMPRESSION: 0,
  19930. Z_BEST_SPEED: 1,
  19931. Z_BEST_COMPRESSION: 9,
  19932. Z_DEFAULT_COMPRESSION: -1,
  19933. Z_FILTERED: 1,
  19934. Z_HUFFMAN_ONLY: 2,
  19935. Z_RLE: 3,
  19936. Z_FIXED: 4,
  19937. Z_DEFAULT_STRATEGY: 0,
  19938. /* Possible values of the data_type field (though see inflate()) */
  19939. Z_BINARY: 0,
  19940. Z_TEXT: 1,
  19941. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  19942. Z_UNKNOWN: 2,
  19943. /* The deflate compression method */
  19944. Z_DEFLATED: 8
  19945. //Z_NULL: null // Use -1 or null inline, depending on var type
  19946. };
  19947. },{}],74:[function(require,module,exports){
  19948. 'use strict';
  19949. // Note: we can't get significant speed boost here.
  19950. // So write code to minimize size - no pregenerated tables
  19951. // and array tools dependencies.
  19952. // Use ordinary array, since untyped makes no boost here
  19953. function makeTable() {
  19954. var c, table = [];
  19955. for(var n =0; n < 256; n++){
  19956. c = n;
  19957. for(var k =0; k < 8; k++){
  19958. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  19959. }
  19960. table[n] = c;
  19961. }
  19962. return table;
  19963. }
  19964. // Create table on load. Just 255 signed longs. Not a problem.
  19965. var crcTable = makeTable();
  19966. function crc32(crc, buf, len, pos) {
  19967. var t = crcTable
  19968. , end = pos + len;
  19969. crc = crc ^ (-1);
  19970. for (var i = pos; i < end; i++ ) {
  19971. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  19972. }
  19973. return (crc ^ (-1)); // >>> 0;
  19974. }
  19975. module.exports = crc32;
  19976. },{}],75:[function(require,module,exports){
  19977. 'use strict';
  19978. var utils = require('../utils/common');
  19979. var trees = require('./trees');
  19980. var adler32 = require('./adler32');
  19981. var crc32 = require('./crc32');
  19982. var msg = require('./messages');
  19983. /* Public constants ==========================================================*/
  19984. /* ===========================================================================*/
  19985. /* Allowed flush values; see deflate() and inflate() below for details */
  19986. var Z_NO_FLUSH = 0;
  19987. var Z_PARTIAL_FLUSH = 1;
  19988. //var Z_SYNC_FLUSH = 2;
  19989. var Z_FULL_FLUSH = 3;
  19990. var Z_FINISH = 4;
  19991. var Z_BLOCK = 5;
  19992. //var Z_TREES = 6;
  19993. /* Return codes for the compression/decompression functions. Negative values
  19994. * are errors, positive values are used for special but normal events.
  19995. */
  19996. var Z_OK = 0;
  19997. var Z_STREAM_END = 1;
  19998. //var Z_NEED_DICT = 2;
  19999. //var Z_ERRNO = -1;
  20000. var Z_STREAM_ERROR = -2;
  20001. var Z_DATA_ERROR = -3;
  20002. //var Z_MEM_ERROR = -4;
  20003. var Z_BUF_ERROR = -5;
  20004. //var Z_VERSION_ERROR = -6;
  20005. /* compression levels */
  20006. //var Z_NO_COMPRESSION = 0;
  20007. //var Z_BEST_SPEED = 1;
  20008. //var Z_BEST_COMPRESSION = 9;
  20009. var Z_DEFAULT_COMPRESSION = -1;
  20010. var Z_FILTERED = 1;
  20011. var Z_HUFFMAN_ONLY = 2;
  20012. var Z_RLE = 3;
  20013. var Z_FIXED = 4;
  20014. var Z_DEFAULT_STRATEGY = 0;
  20015. /* Possible values of the data_type field (though see inflate()) */
  20016. //var Z_BINARY = 0;
  20017. //var Z_TEXT = 1;
  20018. //var Z_ASCII = 1; // = Z_TEXT
  20019. var Z_UNKNOWN = 2;
  20020. /* The deflate compression method */
  20021. var Z_DEFLATED = 8;
  20022. /*============================================================================*/
  20023. var MAX_MEM_LEVEL = 9;
  20024. /* Maximum value for memLevel in deflateInit2 */
  20025. var MAX_WBITS = 15;
  20026. /* 32K LZ77 window */
  20027. var DEF_MEM_LEVEL = 8;
  20028. var LENGTH_CODES = 29;
  20029. /* number of length codes, not counting the special END_BLOCK code */
  20030. var LITERALS = 256;
  20031. /* number of literal bytes 0..255 */
  20032. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20033. /* number of Literal or Length codes, including the END_BLOCK code */
  20034. var D_CODES = 30;
  20035. /* number of distance codes */
  20036. var BL_CODES = 19;
  20037. /* number of codes used to transfer the bit lengths */
  20038. var HEAP_SIZE = 2*L_CODES + 1;
  20039. /* maximum heap size */
  20040. var MAX_BITS = 15;
  20041. /* All codes must not exceed MAX_BITS bits */
  20042. var MIN_MATCH = 3;
  20043. var MAX_MATCH = 258;
  20044. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20045. var PRESET_DICT = 0x20;
  20046. var INIT_STATE = 42;
  20047. var EXTRA_STATE = 69;
  20048. var NAME_STATE = 73;
  20049. var COMMENT_STATE = 91;
  20050. var HCRC_STATE = 103;
  20051. var BUSY_STATE = 113;
  20052. var FINISH_STATE = 666;
  20053. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20054. var BS_BLOCK_DONE = 2; /* block flush performed */
  20055. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20056. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20057. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20058. function err(strm, errorCode) {
  20059. strm.msg = msg[errorCode];
  20060. return errorCode;
  20061. }
  20062. function rank(f) {
  20063. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20064. }
  20065. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20066. /* =========================================================================
  20067. * Flush as much pending output as possible. All deflate() output goes
  20068. * through this function so some applications may wish to modify it
  20069. * to avoid allocating a large strm->output buffer and copying into it.
  20070. * (See also read_buf()).
  20071. */
  20072. function flush_pending(strm) {
  20073. var s = strm.state;
  20074. //_tr_flush_bits(s);
  20075. var len = s.pending;
  20076. if (len > strm.avail_out) {
  20077. len = strm.avail_out;
  20078. }
  20079. if (len === 0) { return; }
  20080. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20081. strm.next_out += len;
  20082. s.pending_out += len;
  20083. strm.total_out += len;
  20084. strm.avail_out -= len;
  20085. s.pending -= len;
  20086. if (s.pending === 0) {
  20087. s.pending_out = 0;
  20088. }
  20089. }
  20090. function flush_block_only (s, last) {
  20091. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20092. s.block_start = s.strstart;
  20093. flush_pending(s.strm);
  20094. }
  20095. function put_byte(s, b) {
  20096. s.pending_buf[s.pending++] = b;
  20097. }
  20098. /* =========================================================================
  20099. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20100. * IN assertion: the stream state is correct and there is enough room in
  20101. * pending_buf.
  20102. */
  20103. function putShortMSB(s, b) {
  20104. // put_byte(s, (Byte)(b >> 8));
  20105. // put_byte(s, (Byte)(b & 0xff));
  20106. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20107. s.pending_buf[s.pending++] = b & 0xff;
  20108. }
  20109. /* ===========================================================================
  20110. * Read a new buffer from the current input stream, update the adler32
  20111. * and total number of bytes read. All deflate() input goes through
  20112. * this function so some applications may wish to modify it to avoid
  20113. * allocating a large strm->input buffer and copying from it.
  20114. * (See also flush_pending()).
  20115. */
  20116. function read_buf(strm, buf, start, size) {
  20117. var len = strm.avail_in;
  20118. if (len > size) { len = size; }
  20119. if (len === 0) { return 0; }
  20120. strm.avail_in -= len;
  20121. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20122. if (strm.state.wrap === 1) {
  20123. strm.adler = adler32(strm.adler, buf, len, start);
  20124. }
  20125. else if (strm.state.wrap === 2) {
  20126. strm.adler = crc32(strm.adler, buf, len, start);
  20127. }
  20128. strm.next_in += len;
  20129. strm.total_in += len;
  20130. return len;
  20131. }
  20132. /* ===========================================================================
  20133. * Set match_start to the longest match starting at the given string and
  20134. * return its length. Matches shorter or equal to prev_length are discarded,
  20135. * in which case the result is equal to prev_length and match_start is
  20136. * garbage.
  20137. * IN assertions: cur_match is the head of the hash chain for the current
  20138. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20139. * OUT assertion: the match length is not greater than s->lookahead.
  20140. */
  20141. function longest_match(s, cur_match) {
  20142. var chain_length = s.max_chain_length; /* max hash chain length */
  20143. var scan = s.strstart; /* current string */
  20144. var match; /* matched string */
  20145. var len; /* length of current match */
  20146. var best_len = s.prev_length; /* best match length so far */
  20147. var nice_match = s.nice_match; /* stop if match long enough */
  20148. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20149. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20150. var _win = s.window; // shortcut
  20151. var wmask = s.w_mask;
  20152. var prev = s.prev;
  20153. /* Stop when cur_match becomes <= limit. To simplify the code,
  20154. * we prevent matches with the string of window index 0.
  20155. */
  20156. var strend = s.strstart + MAX_MATCH;
  20157. var scan_end1 = _win[scan + best_len - 1];
  20158. var scan_end = _win[scan + best_len];
  20159. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20160. * It is easy to get rid of this optimization if necessary.
  20161. */
  20162. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20163. /* Do not waste too much time if we already have a good match: */
  20164. if (s.prev_length >= s.good_match) {
  20165. chain_length >>= 2;
  20166. }
  20167. /* Do not look for matches beyond the end of the input. This is necessary
  20168. * to make deflate deterministic.
  20169. */
  20170. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20171. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20172. do {
  20173. // Assert(cur_match < s->strstart, "no future");
  20174. match = cur_match;
  20175. /* Skip to next match if the match length cannot increase
  20176. * or if the match length is less than 2. Note that the checks below
  20177. * for insufficient lookahead only occur occasionally for performance
  20178. * reasons. Therefore uninitialized memory will be accessed, and
  20179. * conditional jumps will be made that depend on those values.
  20180. * However the length of the match is limited to the lookahead, so
  20181. * the output of deflate is not affected by the uninitialized values.
  20182. */
  20183. if (_win[match + best_len] !== scan_end ||
  20184. _win[match + best_len - 1] !== scan_end1 ||
  20185. _win[match] !== _win[scan] ||
  20186. _win[++match] !== _win[scan + 1]) {
  20187. continue;
  20188. }
  20189. /* The check at best_len-1 can be removed because it will be made
  20190. * again later. (This heuristic is not always a win.)
  20191. * It is not necessary to compare scan[2] and match[2] since they
  20192. * are always equal when the other bytes match, given that
  20193. * the hash keys are equal and that HASH_BITS >= 8.
  20194. */
  20195. scan += 2;
  20196. match++;
  20197. // Assert(*scan == *match, "match[2]?");
  20198. /* We check for insufficient lookahead only every 8th comparison;
  20199. * the 256th check will be made at strstart+258.
  20200. */
  20201. do {
  20202. /*jshint noempty:false*/
  20203. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20204. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20205. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20206. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20207. scan < strend);
  20208. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20209. len = MAX_MATCH - (strend - scan);
  20210. scan = strend - MAX_MATCH;
  20211. if (len > best_len) {
  20212. s.match_start = cur_match;
  20213. best_len = len;
  20214. if (len >= nice_match) {
  20215. break;
  20216. }
  20217. scan_end1 = _win[scan + best_len - 1];
  20218. scan_end = _win[scan + best_len];
  20219. }
  20220. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20221. if (best_len <= s.lookahead) {
  20222. return best_len;
  20223. }
  20224. return s.lookahead;
  20225. }
  20226. /* ===========================================================================
  20227. * Fill the window when the lookahead becomes insufficient.
  20228. * Updates strstart and lookahead.
  20229. *
  20230. * IN assertion: lookahead < MIN_LOOKAHEAD
  20231. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20232. * At least one byte has been read, or avail_in == 0; reads are
  20233. * performed for at least two bytes (required for the zip translate_eol
  20234. * option -- not supported here).
  20235. */
  20236. function fill_window(s) {
  20237. var _w_size = s.w_size;
  20238. var p, n, m, more, str;
  20239. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20240. do {
  20241. more = s.window_size - s.lookahead - s.strstart;
  20242. // JS ints have 32 bit, block below not needed
  20243. /* Deal with !@#$% 64K limit: */
  20244. //if (sizeof(int) <= 2) {
  20245. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20246. // more = wsize;
  20247. //
  20248. // } else if (more == (unsigned)(-1)) {
  20249. // /* Very unlikely, but possible on 16 bit machine if
  20250. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20251. // */
  20252. // more--;
  20253. // }
  20254. //}
  20255. /* If the window is almost full and there is insufficient lookahead,
  20256. * move the upper half to the lower one to make room in the upper half.
  20257. */
  20258. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20259. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20260. s.match_start -= _w_size;
  20261. s.strstart -= _w_size;
  20262. /* we now have strstart >= MAX_DIST */
  20263. s.block_start -= _w_size;
  20264. /* Slide the hash table (could be avoided with 32 bit values
  20265. at the expense of memory usage). We slide even when level == 0
  20266. to keep the hash table consistent if we switch back to level > 0
  20267. later. (Using level 0 permanently is not an optimal usage of
  20268. zlib, so we don't care about this pathological case.)
  20269. */
  20270. n = s.hash_size;
  20271. p = n;
  20272. do {
  20273. m = s.head[--p];
  20274. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20275. } while (--n);
  20276. n = _w_size;
  20277. p = n;
  20278. do {
  20279. m = s.prev[--p];
  20280. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20281. /* If n is not on any hash chain, prev[n] is garbage but
  20282. * its value will never be used.
  20283. */
  20284. } while (--n);
  20285. more += _w_size;
  20286. }
  20287. if (s.strm.avail_in === 0) {
  20288. break;
  20289. }
  20290. /* If there was no sliding:
  20291. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20292. * more == window_size - lookahead - strstart
  20293. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20294. * => more >= window_size - 2*WSIZE + 2
  20295. * In the BIG_MEM or MMAP case (not yet supported),
  20296. * window_size == input_size + MIN_LOOKAHEAD &&
  20297. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20298. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20299. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20300. */
  20301. //Assert(more >= 2, "more < 2");
  20302. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20303. s.lookahead += n;
  20304. /* Initialize the hash value now that we have some input: */
  20305. if (s.lookahead + s.insert >= MIN_MATCH) {
  20306. str = s.strstart - s.insert;
  20307. s.ins_h = s.window[str];
  20308. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20309. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20310. //#if MIN_MATCH != 3
  20311. // Call update_hash() MIN_MATCH-3 more times
  20312. //#endif
  20313. while (s.insert) {
  20314. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20315. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20316. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20317. s.head[s.ins_h] = str;
  20318. str++;
  20319. s.insert--;
  20320. if (s.lookahead + s.insert < MIN_MATCH) {
  20321. break;
  20322. }
  20323. }
  20324. }
  20325. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20326. * but this is not important since only literal bytes will be emitted.
  20327. */
  20328. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20329. /* If the WIN_INIT bytes after the end of the current data have never been
  20330. * written, then zero those bytes in order to avoid memory check reports of
  20331. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20332. * the longest match routines. Update the high water mark for the next
  20333. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20334. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20335. */
  20336. // if (s.high_water < s.window_size) {
  20337. // var curr = s.strstart + s.lookahead;
  20338. // var init = 0;
  20339. //
  20340. // if (s.high_water < curr) {
  20341. // /* Previous high water mark below current data -- zero WIN_INIT
  20342. // * bytes or up to end of window, whichever is less.
  20343. // */
  20344. // init = s.window_size - curr;
  20345. // if (init > WIN_INIT)
  20346. // init = WIN_INIT;
  20347. // zmemzero(s->window + curr, (unsigned)init);
  20348. // s->high_water = curr + init;
  20349. // }
  20350. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20351. // /* High water mark at or above current data, but below current data
  20352. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20353. // * to end of window, whichever is less.
  20354. // */
  20355. // init = (ulg)curr + WIN_INIT - s->high_water;
  20356. // if (init > s->window_size - s->high_water)
  20357. // init = s->window_size - s->high_water;
  20358. // zmemzero(s->window + s->high_water, (unsigned)init);
  20359. // s->high_water += init;
  20360. // }
  20361. // }
  20362. //
  20363. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20364. // "not enough room for search");
  20365. }
  20366. /* ===========================================================================
  20367. * Copy without compression as much as possible from the input stream, return
  20368. * the current block state.
  20369. * This function does not insert new strings in the dictionary since
  20370. * uncompressible data is probably not useful. This function is used
  20371. * only for the level=0 compression option.
  20372. * NOTE: this function should be optimized to avoid extra copying from
  20373. * window to pending_buf.
  20374. */
  20375. function deflate_stored(s, flush) {
  20376. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20377. * to pending_buf_size, and each stored block has a 5 byte header:
  20378. */
  20379. var max_block_size = 0xffff;
  20380. if (max_block_size > s.pending_buf_size - 5) {
  20381. max_block_size = s.pending_buf_size - 5;
  20382. }
  20383. /* Copy as much as possible from input to output: */
  20384. for (;;) {
  20385. /* Fill the window as much as possible: */
  20386. if (s.lookahead <= 1) {
  20387. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20388. // s->block_start >= (long)s->w_size, "slide too late");
  20389. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20390. // s.block_start >= s.w_size)) {
  20391. // throw new Error("slide too late");
  20392. // }
  20393. fill_window(s);
  20394. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20395. return BS_NEED_MORE;
  20396. }
  20397. if (s.lookahead === 0) {
  20398. break;
  20399. }
  20400. /* flush the current block */
  20401. }
  20402. //Assert(s->block_start >= 0L, "block gone");
  20403. // if (s.block_start < 0) throw new Error("block gone");
  20404. s.strstart += s.lookahead;
  20405. s.lookahead = 0;
  20406. /* Emit a stored block if pending_buf will be full: */
  20407. var max_start = s.block_start + max_block_size;
  20408. if (s.strstart === 0 || s.strstart >= max_start) {
  20409. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20410. s.lookahead = s.strstart - max_start;
  20411. s.strstart = max_start;
  20412. /*** FLUSH_BLOCK(s, 0); ***/
  20413. flush_block_only(s, false);
  20414. if (s.strm.avail_out === 0) {
  20415. return BS_NEED_MORE;
  20416. }
  20417. /***/
  20418. }
  20419. /* Flush if we may have to slide, otherwise block_start may become
  20420. * negative and the data will be gone:
  20421. */
  20422. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20423. /*** FLUSH_BLOCK(s, 0); ***/
  20424. flush_block_only(s, false);
  20425. if (s.strm.avail_out === 0) {
  20426. return BS_NEED_MORE;
  20427. }
  20428. /***/
  20429. }
  20430. }
  20431. s.insert = 0;
  20432. if (flush === Z_FINISH) {
  20433. /*** FLUSH_BLOCK(s, 1); ***/
  20434. flush_block_only(s, true);
  20435. if (s.strm.avail_out === 0) {
  20436. return BS_FINISH_STARTED;
  20437. }
  20438. /***/
  20439. return BS_FINISH_DONE;
  20440. }
  20441. if (s.strstart > s.block_start) {
  20442. /*** FLUSH_BLOCK(s, 0); ***/
  20443. flush_block_only(s, false);
  20444. if (s.strm.avail_out === 0) {
  20445. return BS_NEED_MORE;
  20446. }
  20447. /***/
  20448. }
  20449. return BS_NEED_MORE;
  20450. }
  20451. /* ===========================================================================
  20452. * Compress as much as possible from the input stream, return the current
  20453. * block state.
  20454. * This function does not perform lazy evaluation of matches and inserts
  20455. * new strings in the dictionary only for unmatched strings or for short
  20456. * matches. It is used only for the fast compression options.
  20457. */
  20458. function deflate_fast(s, flush) {
  20459. var hash_head; /* head of the hash chain */
  20460. var bflush; /* set if current block must be flushed */
  20461. for (;;) {
  20462. /* Make sure that we always have enough lookahead, except
  20463. * at the end of the input file. We need MAX_MATCH bytes
  20464. * for the next match, plus MIN_MATCH bytes to insert the
  20465. * string following the next match.
  20466. */
  20467. if (s.lookahead < MIN_LOOKAHEAD) {
  20468. fill_window(s);
  20469. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20470. return BS_NEED_MORE;
  20471. }
  20472. if (s.lookahead === 0) {
  20473. break; /* flush the current block */
  20474. }
  20475. }
  20476. /* Insert the string window[strstart .. strstart+2] in the
  20477. * dictionary, and set hash_head to the head of the hash chain:
  20478. */
  20479. hash_head = 0/*NIL*/;
  20480. if (s.lookahead >= MIN_MATCH) {
  20481. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20482. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20483. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20484. s.head[s.ins_h] = s.strstart;
  20485. /***/
  20486. }
  20487. /* Find the longest match, discarding those <= prev_length.
  20488. * At this point we have always match_length < MIN_MATCH
  20489. */
  20490. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20491. /* To simplify the code, we prevent matches with the string
  20492. * of window index 0 (in particular we have to avoid a match
  20493. * of the string with itself at the start of the input file).
  20494. */
  20495. s.match_length = longest_match(s, hash_head);
  20496. /* longest_match() sets match_start */
  20497. }
  20498. if (s.match_length >= MIN_MATCH) {
  20499. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20500. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20501. s.match_length - MIN_MATCH, bflush); ***/
  20502. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20503. s.lookahead -= s.match_length;
  20504. /* Insert new strings in the hash table only if the match length
  20505. * is not too large. This saves time but degrades compression.
  20506. */
  20507. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20508. s.match_length--; /* string at strstart already in table */
  20509. do {
  20510. s.strstart++;
  20511. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20512. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20513. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20514. s.head[s.ins_h] = s.strstart;
  20515. /***/
  20516. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20517. * always MIN_MATCH bytes ahead.
  20518. */
  20519. } while (--s.match_length !== 0);
  20520. s.strstart++;
  20521. } else
  20522. {
  20523. s.strstart += s.match_length;
  20524. s.match_length = 0;
  20525. s.ins_h = s.window[s.strstart];
  20526. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20527. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20528. //#if MIN_MATCH != 3
  20529. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20530. //#endif
  20531. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20532. * matter since it will be recomputed at next deflate call.
  20533. */
  20534. }
  20535. } else {
  20536. /* No match, output a literal byte */
  20537. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20538. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20539. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20540. s.lookahead--;
  20541. s.strstart++;
  20542. }
  20543. if (bflush) {
  20544. /*** FLUSH_BLOCK(s, 0); ***/
  20545. flush_block_only(s, false);
  20546. if (s.strm.avail_out === 0) {
  20547. return BS_NEED_MORE;
  20548. }
  20549. /***/
  20550. }
  20551. }
  20552. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20553. if (flush === Z_FINISH) {
  20554. /*** FLUSH_BLOCK(s, 1); ***/
  20555. flush_block_only(s, true);
  20556. if (s.strm.avail_out === 0) {
  20557. return BS_FINISH_STARTED;
  20558. }
  20559. /***/
  20560. return BS_FINISH_DONE;
  20561. }
  20562. if (s.last_lit) {
  20563. /*** FLUSH_BLOCK(s, 0); ***/
  20564. flush_block_only(s, false);
  20565. if (s.strm.avail_out === 0) {
  20566. return BS_NEED_MORE;
  20567. }
  20568. /***/
  20569. }
  20570. return BS_BLOCK_DONE;
  20571. }
  20572. /* ===========================================================================
  20573. * Same as above, but achieves better compression. We use a lazy
  20574. * evaluation for matches: a match is finally adopted only if there is
  20575. * no better match at the next window position.
  20576. */
  20577. function deflate_slow(s, flush) {
  20578. var hash_head; /* head of hash chain */
  20579. var bflush; /* set if current block must be flushed */
  20580. var max_insert;
  20581. /* Process the input block. */
  20582. for (;;) {
  20583. /* Make sure that we always have enough lookahead, except
  20584. * at the end of the input file. We need MAX_MATCH bytes
  20585. * for the next match, plus MIN_MATCH bytes to insert the
  20586. * string following the next match.
  20587. */
  20588. if (s.lookahead < MIN_LOOKAHEAD) {
  20589. fill_window(s);
  20590. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20591. return BS_NEED_MORE;
  20592. }
  20593. if (s.lookahead === 0) { break; } /* flush the current block */
  20594. }
  20595. /* Insert the string window[strstart .. strstart+2] in the
  20596. * dictionary, and set hash_head to the head of the hash chain:
  20597. */
  20598. hash_head = 0/*NIL*/;
  20599. if (s.lookahead >= MIN_MATCH) {
  20600. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20601. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20602. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20603. s.head[s.ins_h] = s.strstart;
  20604. /***/
  20605. }
  20606. /* Find the longest match, discarding those <= prev_length.
  20607. */
  20608. s.prev_length = s.match_length;
  20609. s.prev_match = s.match_start;
  20610. s.match_length = MIN_MATCH-1;
  20611. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20612. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20613. /* To simplify the code, we prevent matches with the string
  20614. * of window index 0 (in particular we have to avoid a match
  20615. * of the string with itself at the start of the input file).
  20616. */
  20617. s.match_length = longest_match(s, hash_head);
  20618. /* longest_match() sets match_start */
  20619. if (s.match_length <= 5 &&
  20620. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20621. /* If prev_match is also MIN_MATCH, match_start is garbage
  20622. * but we will ignore the current match anyway.
  20623. */
  20624. s.match_length = MIN_MATCH-1;
  20625. }
  20626. }
  20627. /* If there was a match at the previous step and the current
  20628. * match is not better, output the previous match:
  20629. */
  20630. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20631. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20632. /* Do not insert strings in hash table beyond this. */
  20633. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20634. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20635. s.prev_length - MIN_MATCH, bflush);***/
  20636. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20637. /* Insert in hash table all strings up to the end of the match.
  20638. * strstart-1 and strstart are already inserted. If there is not
  20639. * enough lookahead, the last two strings are not inserted in
  20640. * the hash table.
  20641. */
  20642. s.lookahead -= s.prev_length-1;
  20643. s.prev_length -= 2;
  20644. do {
  20645. if (++s.strstart <= max_insert) {
  20646. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20647. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20648. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20649. s.head[s.ins_h] = s.strstart;
  20650. /***/
  20651. }
  20652. } while (--s.prev_length !== 0);
  20653. s.match_available = 0;
  20654. s.match_length = MIN_MATCH-1;
  20655. s.strstart++;
  20656. if (bflush) {
  20657. /*** FLUSH_BLOCK(s, 0); ***/
  20658. flush_block_only(s, false);
  20659. if (s.strm.avail_out === 0) {
  20660. return BS_NEED_MORE;
  20661. }
  20662. /***/
  20663. }
  20664. } else if (s.match_available) {
  20665. /* If there was no match at the previous position, output a
  20666. * single literal. If there was a match but the current match
  20667. * is longer, truncate the previous match to a single literal.
  20668. */
  20669. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20670. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20671. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20672. if (bflush) {
  20673. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20674. flush_block_only(s, false);
  20675. /***/
  20676. }
  20677. s.strstart++;
  20678. s.lookahead--;
  20679. if (s.strm.avail_out === 0) {
  20680. return BS_NEED_MORE;
  20681. }
  20682. } else {
  20683. /* There is no previous match to compare with, wait for
  20684. * the next step to decide.
  20685. */
  20686. s.match_available = 1;
  20687. s.strstart++;
  20688. s.lookahead--;
  20689. }
  20690. }
  20691. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20692. if (s.match_available) {
  20693. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20694. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20695. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20696. s.match_available = 0;
  20697. }
  20698. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20699. if (flush === Z_FINISH) {
  20700. /*** FLUSH_BLOCK(s, 1); ***/
  20701. flush_block_only(s, true);
  20702. if (s.strm.avail_out === 0) {
  20703. return BS_FINISH_STARTED;
  20704. }
  20705. /***/
  20706. return BS_FINISH_DONE;
  20707. }
  20708. if (s.last_lit) {
  20709. /*** FLUSH_BLOCK(s, 0); ***/
  20710. flush_block_only(s, false);
  20711. if (s.strm.avail_out === 0) {
  20712. return BS_NEED_MORE;
  20713. }
  20714. /***/
  20715. }
  20716. return BS_BLOCK_DONE;
  20717. }
  20718. /* ===========================================================================
  20719. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20720. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20721. * deflate switches away from Z_RLE.)
  20722. */
  20723. function deflate_rle(s, flush) {
  20724. var bflush; /* set if current block must be flushed */
  20725. var prev; /* byte at distance one to match */
  20726. var scan, strend; /* scan goes up to strend for length of run */
  20727. var _win = s.window;
  20728. for (;;) {
  20729. /* Make sure that we always have enough lookahead, except
  20730. * at the end of the input file. We need MAX_MATCH bytes
  20731. * for the longest run, plus one for the unrolled loop.
  20732. */
  20733. if (s.lookahead <= MAX_MATCH) {
  20734. fill_window(s);
  20735. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20736. return BS_NEED_MORE;
  20737. }
  20738. if (s.lookahead === 0) { break; } /* flush the current block */
  20739. }
  20740. /* See how many times the previous byte repeats */
  20741. s.match_length = 0;
  20742. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20743. scan = s.strstart - 1;
  20744. prev = _win[scan];
  20745. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20746. strend = s.strstart + MAX_MATCH;
  20747. do {
  20748. /*jshint noempty:false*/
  20749. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20750. prev === _win[++scan] && prev === _win[++scan] &&
  20751. prev === _win[++scan] && prev === _win[++scan] &&
  20752. prev === _win[++scan] && prev === _win[++scan] &&
  20753. scan < strend);
  20754. s.match_length = MAX_MATCH - (strend - scan);
  20755. if (s.match_length > s.lookahead) {
  20756. s.match_length = s.lookahead;
  20757. }
  20758. }
  20759. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20760. }
  20761. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20762. if (s.match_length >= MIN_MATCH) {
  20763. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20764. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20765. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20766. s.lookahead -= s.match_length;
  20767. s.strstart += s.match_length;
  20768. s.match_length = 0;
  20769. } else {
  20770. /* No match, output a literal byte */
  20771. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20772. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20773. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20774. s.lookahead--;
  20775. s.strstart++;
  20776. }
  20777. if (bflush) {
  20778. /*** FLUSH_BLOCK(s, 0); ***/
  20779. flush_block_only(s, false);
  20780. if (s.strm.avail_out === 0) {
  20781. return BS_NEED_MORE;
  20782. }
  20783. /***/
  20784. }
  20785. }
  20786. s.insert = 0;
  20787. if (flush === Z_FINISH) {
  20788. /*** FLUSH_BLOCK(s, 1); ***/
  20789. flush_block_only(s, true);
  20790. if (s.strm.avail_out === 0) {
  20791. return BS_FINISH_STARTED;
  20792. }
  20793. /***/
  20794. return BS_FINISH_DONE;
  20795. }
  20796. if (s.last_lit) {
  20797. /*** FLUSH_BLOCK(s, 0); ***/
  20798. flush_block_only(s, false);
  20799. if (s.strm.avail_out === 0) {
  20800. return BS_NEED_MORE;
  20801. }
  20802. /***/
  20803. }
  20804. return BS_BLOCK_DONE;
  20805. }
  20806. /* ===========================================================================
  20807. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20808. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20809. */
  20810. function deflate_huff(s, flush) {
  20811. var bflush; /* set if current block must be flushed */
  20812. for (;;) {
  20813. /* Make sure that we have a literal to write. */
  20814. if (s.lookahead === 0) {
  20815. fill_window(s);
  20816. if (s.lookahead === 0) {
  20817. if (flush === Z_NO_FLUSH) {
  20818. return BS_NEED_MORE;
  20819. }
  20820. break; /* flush the current block */
  20821. }
  20822. }
  20823. /* Output a literal byte */
  20824. s.match_length = 0;
  20825. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20826. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20827. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20828. s.lookahead--;
  20829. s.strstart++;
  20830. if (bflush) {
  20831. /*** FLUSH_BLOCK(s, 0); ***/
  20832. flush_block_only(s, false);
  20833. if (s.strm.avail_out === 0) {
  20834. return BS_NEED_MORE;
  20835. }
  20836. /***/
  20837. }
  20838. }
  20839. s.insert = 0;
  20840. if (flush === Z_FINISH) {
  20841. /*** FLUSH_BLOCK(s, 1); ***/
  20842. flush_block_only(s, true);
  20843. if (s.strm.avail_out === 0) {
  20844. return BS_FINISH_STARTED;
  20845. }
  20846. /***/
  20847. return BS_FINISH_DONE;
  20848. }
  20849. if (s.last_lit) {
  20850. /*** FLUSH_BLOCK(s, 0); ***/
  20851. flush_block_only(s, false);
  20852. if (s.strm.avail_out === 0) {
  20853. return BS_NEED_MORE;
  20854. }
  20855. /***/
  20856. }
  20857. return BS_BLOCK_DONE;
  20858. }
  20859. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20860. * the desired pack level (0..9). The values given below have been tuned to
  20861. * exclude worst case performance for pathological files. Better values may be
  20862. * found for specific files.
  20863. */
  20864. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20865. this.good_length = good_length;
  20866. this.max_lazy = max_lazy;
  20867. this.nice_length = nice_length;
  20868. this.max_chain = max_chain;
  20869. this.func = func;
  20870. };
  20871. var configuration_table;
  20872. configuration_table = [
  20873. /* good lazy nice chain */
  20874. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  20875. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  20876. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  20877. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  20878. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  20879. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  20880. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  20881. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  20882. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  20883. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  20884. ];
  20885. /* ===========================================================================
  20886. * Initialize the "longest match" routines for a new zlib stream
  20887. */
  20888. function lm_init(s) {
  20889. s.window_size = 2 * s.w_size;
  20890. /*** CLEAR_HASH(s); ***/
  20891. zero(s.head); // Fill with NIL (= 0);
  20892. /* Set the default configuration parameters:
  20893. */
  20894. s.max_lazy_match = configuration_table[s.level].max_lazy;
  20895. s.good_match = configuration_table[s.level].good_length;
  20896. s.nice_match = configuration_table[s.level].nice_length;
  20897. s.max_chain_length = configuration_table[s.level].max_chain;
  20898. s.strstart = 0;
  20899. s.block_start = 0;
  20900. s.lookahead = 0;
  20901. s.insert = 0;
  20902. s.match_length = s.prev_length = MIN_MATCH - 1;
  20903. s.match_available = 0;
  20904. s.ins_h = 0;
  20905. }
  20906. function DeflateState() {
  20907. this.strm = null; /* pointer back to this zlib stream */
  20908. this.status = 0; /* as the name implies */
  20909. this.pending_buf = null; /* output still pending */
  20910. this.pending_buf_size = 0; /* size of pending_buf */
  20911. this.pending_out = 0; /* next pending byte to output to the stream */
  20912. this.pending = 0; /* nb of bytes in the pending buffer */
  20913. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20914. this.gzhead = null; /* gzip header information to write */
  20915. this.gzindex = 0; /* where in extra, name, or comment */
  20916. this.method = Z_DEFLATED; /* can only be DEFLATED */
  20917. this.last_flush = -1; /* value of flush param for previous deflate call */
  20918. this.w_size = 0; /* LZ77 window size (32K by default) */
  20919. this.w_bits = 0; /* log2(w_size) (8..16) */
  20920. this.w_mask = 0; /* w_size - 1 */
  20921. this.window = null;
  20922. /* Sliding window. Input bytes are read into the second half of the window,
  20923. * and move to the first half later to keep a dictionary of at least wSize
  20924. * bytes. With this organization, matches are limited to a distance of
  20925. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  20926. * performed with a length multiple of the block size.
  20927. */
  20928. this.window_size = 0;
  20929. /* Actual size of window: 2*wSize, except when the user input buffer
  20930. * is directly used as sliding window.
  20931. */
  20932. this.prev = null;
  20933. /* Link to older string with same hash index. To limit the size of this
  20934. * array to 64K, this link is maintained only for the last 32K strings.
  20935. * An index in this array is thus a window index modulo 32K.
  20936. */
  20937. this.head = null; /* Heads of the hash chains or NIL. */
  20938. this.ins_h = 0; /* hash index of string to be inserted */
  20939. this.hash_size = 0; /* number of elements in hash table */
  20940. this.hash_bits = 0; /* log2(hash_size) */
  20941. this.hash_mask = 0; /* hash_size-1 */
  20942. this.hash_shift = 0;
  20943. /* Number of bits by which ins_h must be shifted at each input
  20944. * step. It must be such that after MIN_MATCH steps, the oldest
  20945. * byte no longer takes part in the hash key, that is:
  20946. * hash_shift * MIN_MATCH >= hash_bits
  20947. */
  20948. this.block_start = 0;
  20949. /* Window position at the beginning of the current output block. Gets
  20950. * negative when the window is moved backwards.
  20951. */
  20952. this.match_length = 0; /* length of best match */
  20953. this.prev_match = 0; /* previous match */
  20954. this.match_available = 0; /* set if previous match exists */
  20955. this.strstart = 0; /* start of string to insert */
  20956. this.match_start = 0; /* start of matching string */
  20957. this.lookahead = 0; /* number of valid bytes ahead in window */
  20958. this.prev_length = 0;
  20959. /* Length of the best match at previous step. Matches not greater than this
  20960. * are discarded. This is used in the lazy match evaluation.
  20961. */
  20962. this.max_chain_length = 0;
  20963. /* To speed up deflation, hash chains are never searched beyond this
  20964. * length. A higher limit improves compression ratio but degrades the
  20965. * speed.
  20966. */
  20967. this.max_lazy_match = 0;
  20968. /* Attempt to find a better match only when the current match is strictly
  20969. * smaller than this value. This mechanism is used only for compression
  20970. * levels >= 4.
  20971. */
  20972. // That's alias to max_lazy_match, don't use directly
  20973. //this.max_insert_length = 0;
  20974. /* Insert new strings in the hash table only if the match length is not
  20975. * greater than this length. This saves time but degrades compression.
  20976. * max_insert_length is used only for compression levels <= 3.
  20977. */
  20978. this.level = 0; /* compression level (1..9) */
  20979. this.strategy = 0; /* favor or force Huffman coding*/
  20980. this.good_match = 0;
  20981. /* Use a faster search when the previous match is longer than this */
  20982. this.nice_match = 0; /* Stop searching when current match exceeds this */
  20983. /* used by trees.c: */
  20984. /* Didn't use ct_data typedef below to suppress compiler warning */
  20985. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  20986. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  20987. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  20988. // Use flat array of DOUBLE size, with interleaved fata,
  20989. // because JS does not support effective
  20990. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  20991. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  20992. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  20993. zero(this.dyn_ltree);
  20994. zero(this.dyn_dtree);
  20995. zero(this.bl_tree);
  20996. this.l_desc = null; /* desc. for literal tree */
  20997. this.d_desc = null; /* desc. for distance tree */
  20998. this.bl_desc = null; /* desc. for bit length tree */
  20999. //ush bl_count[MAX_BITS+1];
  21000. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21001. /* number of codes at each bit length for an optimal tree */
  21002. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21003. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21004. zero(this.heap);
  21005. this.heap_len = 0; /* number of elements in the heap */
  21006. this.heap_max = 0; /* element of largest frequency */
  21007. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21008. * The same heap array is used to build all trees.
  21009. */
  21010. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21011. zero(this.depth);
  21012. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21013. */
  21014. this.l_buf = 0; /* buffer index for literals or lengths */
  21015. this.lit_bufsize = 0;
  21016. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21017. * limiting lit_bufsize to 64K:
  21018. * - frequencies can be kept in 16 bit counters
  21019. * - if compression is not successful for the first block, all input
  21020. * data is still in the window so we can still emit a stored block even
  21021. * when input comes from standard input. (This can also be done for
  21022. * all blocks if lit_bufsize is not greater than 32K.)
  21023. * - if compression is not successful for a file smaller than 64K, we can
  21024. * even emit a stored file instead of a stored block (saving 5 bytes).
  21025. * This is applicable only for zip (not gzip or zlib).
  21026. * - creating new Huffman trees less frequently may not provide fast
  21027. * adaptation to changes in the input data statistics. (Take for
  21028. * example a binary file with poorly compressible code followed by
  21029. * a highly compressible string table.) Smaller buffer sizes give
  21030. * fast adaptation but have of course the overhead of transmitting
  21031. * trees more frequently.
  21032. * - I can't count above 4
  21033. */
  21034. this.last_lit = 0; /* running index in l_buf */
  21035. this.d_buf = 0;
  21036. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21037. * the same number of elements. To use different lengths, an extra flag
  21038. * array would be necessary.
  21039. */
  21040. this.opt_len = 0; /* bit length of current block with optimal trees */
  21041. this.static_len = 0; /* bit length of current block with static trees */
  21042. this.matches = 0; /* number of string matches in current block */
  21043. this.insert = 0; /* bytes at end of window left to insert */
  21044. this.bi_buf = 0;
  21045. /* Output buffer. bits are inserted starting at the bottom (least
  21046. * significant bits).
  21047. */
  21048. this.bi_valid = 0;
  21049. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21050. * are always zero.
  21051. */
  21052. // Used for window memory init. We safely ignore it for JS. That makes
  21053. // sense only for pointers and memory check tools.
  21054. //this.high_water = 0;
  21055. /* High water mark offset in window for initialized bytes -- bytes above
  21056. * this are set to zero in order to avoid memory check warnings when
  21057. * longest match routines access bytes past the input. This is then
  21058. * updated to the new high water mark.
  21059. */
  21060. }
  21061. function deflateResetKeep(strm) {
  21062. var s;
  21063. if (!strm || !strm.state) {
  21064. return err(strm, Z_STREAM_ERROR);
  21065. }
  21066. strm.total_in = strm.total_out = 0;
  21067. strm.data_type = Z_UNKNOWN;
  21068. s = strm.state;
  21069. s.pending = 0;
  21070. s.pending_out = 0;
  21071. if (s.wrap < 0) {
  21072. s.wrap = -s.wrap;
  21073. /* was made negative by deflate(..., Z_FINISH); */
  21074. }
  21075. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21076. strm.adler = (s.wrap === 2) ?
  21077. 0 // crc32(0, Z_NULL, 0)
  21078. :
  21079. 1; // adler32(0, Z_NULL, 0)
  21080. s.last_flush = Z_NO_FLUSH;
  21081. trees._tr_init(s);
  21082. return Z_OK;
  21083. }
  21084. function deflateReset(strm) {
  21085. var ret = deflateResetKeep(strm);
  21086. if (ret === Z_OK) {
  21087. lm_init(strm.state);
  21088. }
  21089. return ret;
  21090. }
  21091. function deflateSetHeader(strm, head) {
  21092. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21093. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21094. strm.state.gzhead = head;
  21095. return Z_OK;
  21096. }
  21097. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21098. if (!strm) { // === Z_NULL
  21099. return Z_STREAM_ERROR;
  21100. }
  21101. var wrap = 1;
  21102. if (level === Z_DEFAULT_COMPRESSION) {
  21103. level = 6;
  21104. }
  21105. if (windowBits < 0) { /* suppress zlib wrapper */
  21106. wrap = 0;
  21107. windowBits = -windowBits;
  21108. }
  21109. else if (windowBits > 15) {
  21110. wrap = 2; /* write gzip wrapper instead */
  21111. windowBits -= 16;
  21112. }
  21113. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21114. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21115. strategy < 0 || strategy > Z_FIXED) {
  21116. return err(strm, Z_STREAM_ERROR);
  21117. }
  21118. if (windowBits === 8) {
  21119. windowBits = 9;
  21120. }
  21121. /* until 256-byte window bug fixed */
  21122. var s = new DeflateState();
  21123. strm.state = s;
  21124. s.strm = strm;
  21125. s.wrap = wrap;
  21126. s.gzhead = null;
  21127. s.w_bits = windowBits;
  21128. s.w_size = 1 << s.w_bits;
  21129. s.w_mask = s.w_size - 1;
  21130. s.hash_bits = memLevel + 7;
  21131. s.hash_size = 1 << s.hash_bits;
  21132. s.hash_mask = s.hash_size - 1;
  21133. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21134. s.window = new utils.Buf8(s.w_size * 2);
  21135. s.head = new utils.Buf16(s.hash_size);
  21136. s.prev = new utils.Buf16(s.w_size);
  21137. // Don't need mem init magic for JS.
  21138. //s.high_water = 0; /* nothing written to s->window yet */
  21139. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21140. s.pending_buf_size = s.lit_bufsize * 4;
  21141. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21142. s.d_buf = s.lit_bufsize >> 1;
  21143. s.l_buf = (1 + 2) * s.lit_bufsize;
  21144. s.level = level;
  21145. s.strategy = strategy;
  21146. s.method = method;
  21147. return deflateReset(strm);
  21148. }
  21149. function deflateInit(strm, level) {
  21150. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21151. }
  21152. function deflate(strm, flush) {
  21153. var old_flush, s;
  21154. var beg, val; // for gzip header write only
  21155. if (!strm || !strm.state ||
  21156. flush > Z_BLOCK || flush < 0) {
  21157. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21158. }
  21159. s = strm.state;
  21160. if (!strm.output ||
  21161. (!strm.input && strm.avail_in !== 0) ||
  21162. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21163. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21164. }
  21165. s.strm = strm; /* just in case */
  21166. old_flush = s.last_flush;
  21167. s.last_flush = flush;
  21168. /* Write the header */
  21169. if (s.status === INIT_STATE) {
  21170. if (s.wrap === 2) { // GZIP header
  21171. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21172. put_byte(s, 31);
  21173. put_byte(s, 139);
  21174. put_byte(s, 8);
  21175. if (!s.gzhead) { // s->gzhead == Z_NULL
  21176. put_byte(s, 0);
  21177. put_byte(s, 0);
  21178. put_byte(s, 0);
  21179. put_byte(s, 0);
  21180. put_byte(s, 0);
  21181. put_byte(s, s.level === 9 ? 2 :
  21182. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21183. 4 : 0));
  21184. put_byte(s, OS_CODE);
  21185. s.status = BUSY_STATE;
  21186. }
  21187. else {
  21188. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21189. (s.gzhead.hcrc ? 2 : 0) +
  21190. (!s.gzhead.extra ? 0 : 4) +
  21191. (!s.gzhead.name ? 0 : 8) +
  21192. (!s.gzhead.comment ? 0 : 16)
  21193. );
  21194. put_byte(s, s.gzhead.time & 0xff);
  21195. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21196. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21197. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21198. put_byte(s, s.level === 9 ? 2 :
  21199. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21200. 4 : 0));
  21201. put_byte(s, s.gzhead.os & 0xff);
  21202. if (s.gzhead.extra && s.gzhead.extra.length) {
  21203. put_byte(s, s.gzhead.extra.length & 0xff);
  21204. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21205. }
  21206. if (s.gzhead.hcrc) {
  21207. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21208. }
  21209. s.gzindex = 0;
  21210. s.status = EXTRA_STATE;
  21211. }
  21212. }
  21213. else // DEFLATE header
  21214. {
  21215. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21216. var level_flags = -1;
  21217. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21218. level_flags = 0;
  21219. } else if (s.level < 6) {
  21220. level_flags = 1;
  21221. } else if (s.level === 6) {
  21222. level_flags = 2;
  21223. } else {
  21224. level_flags = 3;
  21225. }
  21226. header |= (level_flags << 6);
  21227. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21228. header += 31 - (header % 31);
  21229. s.status = BUSY_STATE;
  21230. putShortMSB(s, header);
  21231. /* Save the adler32 of the preset dictionary: */
  21232. if (s.strstart !== 0) {
  21233. putShortMSB(s, strm.adler >>> 16);
  21234. putShortMSB(s, strm.adler & 0xffff);
  21235. }
  21236. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21237. }
  21238. }
  21239. //#ifdef GZIP
  21240. if (s.status === EXTRA_STATE) {
  21241. if (s.gzhead.extra/* != Z_NULL*/) {
  21242. beg = s.pending; /* start of bytes to update crc */
  21243. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21244. if (s.pending === s.pending_buf_size) {
  21245. if (s.gzhead.hcrc && s.pending > beg) {
  21246. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21247. }
  21248. flush_pending(strm);
  21249. beg = s.pending;
  21250. if (s.pending === s.pending_buf_size) {
  21251. break;
  21252. }
  21253. }
  21254. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21255. s.gzindex++;
  21256. }
  21257. if (s.gzhead.hcrc && s.pending > beg) {
  21258. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21259. }
  21260. if (s.gzindex === s.gzhead.extra.length) {
  21261. s.gzindex = 0;
  21262. s.status = NAME_STATE;
  21263. }
  21264. }
  21265. else {
  21266. s.status = NAME_STATE;
  21267. }
  21268. }
  21269. if (s.status === NAME_STATE) {
  21270. if (s.gzhead.name/* != Z_NULL*/) {
  21271. beg = s.pending; /* start of bytes to update crc */
  21272. //int val;
  21273. do {
  21274. if (s.pending === s.pending_buf_size) {
  21275. if (s.gzhead.hcrc && s.pending > beg) {
  21276. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21277. }
  21278. flush_pending(strm);
  21279. beg = s.pending;
  21280. if (s.pending === s.pending_buf_size) {
  21281. val = 1;
  21282. break;
  21283. }
  21284. }
  21285. // JS specific: little magic to add zero terminator to end of string
  21286. if (s.gzindex < s.gzhead.name.length) {
  21287. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21288. } else {
  21289. val = 0;
  21290. }
  21291. put_byte(s, val);
  21292. } while (val !== 0);
  21293. if (s.gzhead.hcrc && s.pending > beg){
  21294. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21295. }
  21296. if (val === 0) {
  21297. s.gzindex = 0;
  21298. s.status = COMMENT_STATE;
  21299. }
  21300. }
  21301. else {
  21302. s.status = COMMENT_STATE;
  21303. }
  21304. }
  21305. if (s.status === COMMENT_STATE) {
  21306. if (s.gzhead.comment/* != Z_NULL*/) {
  21307. beg = s.pending; /* start of bytes to update crc */
  21308. //int val;
  21309. do {
  21310. if (s.pending === s.pending_buf_size) {
  21311. if (s.gzhead.hcrc && s.pending > beg) {
  21312. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21313. }
  21314. flush_pending(strm);
  21315. beg = s.pending;
  21316. if (s.pending === s.pending_buf_size) {
  21317. val = 1;
  21318. break;
  21319. }
  21320. }
  21321. // JS specific: little magic to add zero terminator to end of string
  21322. if (s.gzindex < s.gzhead.comment.length) {
  21323. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21324. } else {
  21325. val = 0;
  21326. }
  21327. put_byte(s, val);
  21328. } while (val !== 0);
  21329. if (s.gzhead.hcrc && s.pending > beg) {
  21330. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21331. }
  21332. if (val === 0) {
  21333. s.status = HCRC_STATE;
  21334. }
  21335. }
  21336. else {
  21337. s.status = HCRC_STATE;
  21338. }
  21339. }
  21340. if (s.status === HCRC_STATE) {
  21341. if (s.gzhead.hcrc) {
  21342. if (s.pending + 2 > s.pending_buf_size) {
  21343. flush_pending(strm);
  21344. }
  21345. if (s.pending + 2 <= s.pending_buf_size) {
  21346. put_byte(s, strm.adler & 0xff);
  21347. put_byte(s, (strm.adler >> 8) & 0xff);
  21348. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21349. s.status = BUSY_STATE;
  21350. }
  21351. }
  21352. else {
  21353. s.status = BUSY_STATE;
  21354. }
  21355. }
  21356. //#endif
  21357. /* Flush as much pending output as possible */
  21358. if (s.pending !== 0) {
  21359. flush_pending(strm);
  21360. if (strm.avail_out === 0) {
  21361. /* Since avail_out is 0, deflate will be called again with
  21362. * more output space, but possibly with both pending and
  21363. * avail_in equal to zero. There won't be anything to do,
  21364. * but this is not an error situation so make sure we
  21365. * return OK instead of BUF_ERROR at next call of deflate:
  21366. */
  21367. s.last_flush = -1;
  21368. return Z_OK;
  21369. }
  21370. /* Make sure there is something to do and avoid duplicate consecutive
  21371. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21372. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21373. */
  21374. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21375. flush !== Z_FINISH) {
  21376. return err(strm, Z_BUF_ERROR);
  21377. }
  21378. /* User must not provide more input after the first FINISH: */
  21379. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21380. return err(strm, Z_BUF_ERROR);
  21381. }
  21382. /* Start a new block or continue the current one.
  21383. */
  21384. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21385. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21386. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21387. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21388. configuration_table[s.level].func(s, flush));
  21389. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21390. s.status = FINISH_STATE;
  21391. }
  21392. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21393. if (strm.avail_out === 0) {
  21394. s.last_flush = -1;
  21395. /* avoid BUF_ERROR next call, see above */
  21396. }
  21397. return Z_OK;
  21398. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21399. * of deflate should use the same flush parameter to make sure
  21400. * that the flush is complete. So we don't have to output an
  21401. * empty block here, this will be done at next call. This also
  21402. * ensures that for a very small output buffer, we emit at most
  21403. * one empty block.
  21404. */
  21405. }
  21406. if (bstate === BS_BLOCK_DONE) {
  21407. if (flush === Z_PARTIAL_FLUSH) {
  21408. trees._tr_align(s);
  21409. }
  21410. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21411. trees._tr_stored_block(s, 0, 0, false);
  21412. /* For a full flush, this empty block will be recognized
  21413. * as a special marker by inflate_sync().
  21414. */
  21415. if (flush === Z_FULL_FLUSH) {
  21416. /*** CLEAR_HASH(s); ***/ /* forget history */
  21417. zero(s.head); // Fill with NIL (= 0);
  21418. if (s.lookahead === 0) {
  21419. s.strstart = 0;
  21420. s.block_start = 0;
  21421. s.insert = 0;
  21422. }
  21423. }
  21424. }
  21425. flush_pending(strm);
  21426. if (strm.avail_out === 0) {
  21427. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21428. return Z_OK;
  21429. }
  21430. }
  21431. }
  21432. //Assert(strm->avail_out > 0, "bug2");
  21433. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21434. if (flush !== Z_FINISH) { return Z_OK; }
  21435. if (s.wrap <= 0) { return Z_STREAM_END; }
  21436. /* Write the trailer */
  21437. if (s.wrap === 2) {
  21438. put_byte(s, strm.adler & 0xff);
  21439. put_byte(s, (strm.adler >> 8) & 0xff);
  21440. put_byte(s, (strm.adler >> 16) & 0xff);
  21441. put_byte(s, (strm.adler >> 24) & 0xff);
  21442. put_byte(s, strm.total_in & 0xff);
  21443. put_byte(s, (strm.total_in >> 8) & 0xff);
  21444. put_byte(s, (strm.total_in >> 16) & 0xff);
  21445. put_byte(s, (strm.total_in >> 24) & 0xff);
  21446. }
  21447. else
  21448. {
  21449. putShortMSB(s, strm.adler >>> 16);
  21450. putShortMSB(s, strm.adler & 0xffff);
  21451. }
  21452. flush_pending(strm);
  21453. /* If avail_out is zero, the application will call deflate again
  21454. * to flush the rest.
  21455. */
  21456. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21457. /* write the trailer only once! */
  21458. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21459. }
  21460. function deflateEnd(strm) {
  21461. var status;
  21462. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21463. return Z_STREAM_ERROR;
  21464. }
  21465. status = strm.state.status;
  21466. if (status !== INIT_STATE &&
  21467. status !== EXTRA_STATE &&
  21468. status !== NAME_STATE &&
  21469. status !== COMMENT_STATE &&
  21470. status !== HCRC_STATE &&
  21471. status !== BUSY_STATE &&
  21472. status !== FINISH_STATE
  21473. ) {
  21474. return err(strm, Z_STREAM_ERROR);
  21475. }
  21476. strm.state = null;
  21477. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21478. }
  21479. /* =========================================================================
  21480. * Copy the source state to the destination state
  21481. */
  21482. //function deflateCopy(dest, source) {
  21483. //
  21484. //}
  21485. exports.deflateInit = deflateInit;
  21486. exports.deflateInit2 = deflateInit2;
  21487. exports.deflateReset = deflateReset;
  21488. exports.deflateResetKeep = deflateResetKeep;
  21489. exports.deflateSetHeader = deflateSetHeader;
  21490. exports.deflate = deflate;
  21491. exports.deflateEnd = deflateEnd;
  21492. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21493. /* Not implemented
  21494. exports.deflateBound = deflateBound;
  21495. exports.deflateCopy = deflateCopy;
  21496. exports.deflateSetDictionary = deflateSetDictionary;
  21497. exports.deflateParams = deflateParams;
  21498. exports.deflatePending = deflatePending;
  21499. exports.deflatePrime = deflatePrime;
  21500. exports.deflateTune = deflateTune;
  21501. */
  21502. },{"../utils/common":70,"./adler32":72,"./crc32":74,"./messages":80,"./trees":81}],76:[function(require,module,exports){
  21503. 'use strict';
  21504. function GZheader() {
  21505. /* true if compressed data believed to be text */
  21506. this.text = 0;
  21507. /* modification time */
  21508. this.time = 0;
  21509. /* extra flags (not used when writing a gzip file) */
  21510. this.xflags = 0;
  21511. /* operating system */
  21512. this.os = 0;
  21513. /* pointer to extra field or Z_NULL if none */
  21514. this.extra = null;
  21515. /* extra field length (valid if extra != Z_NULL) */
  21516. this.extra_len = 0; // Actually, we don't need it in JS,
  21517. // but leave for few code modifications
  21518. //
  21519. // Setup limits is not necessary because in js we should not preallocate memory
  21520. // for inflate use constant limit in 65536 bytes
  21521. //
  21522. /* space at extra (only when reading header) */
  21523. // this.extra_max = 0;
  21524. /* pointer to zero-terminated file name or Z_NULL */
  21525. this.name = '';
  21526. /* space at name (only when reading header) */
  21527. // this.name_max = 0;
  21528. /* pointer to zero-terminated comment or Z_NULL */
  21529. this.comment = '';
  21530. /* space at comment (only when reading header) */
  21531. // this.comm_max = 0;
  21532. /* true if there was or will be a header crc */
  21533. this.hcrc = 0;
  21534. /* true when done reading gzip header (not used when writing a gzip file) */
  21535. this.done = false;
  21536. }
  21537. module.exports = GZheader;
  21538. },{}],77:[function(require,module,exports){
  21539. 'use strict';
  21540. // See state defs from inflate.js
  21541. var BAD = 30; /* got a data error -- remain here until reset */
  21542. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21543. /*
  21544. Decode literal, length, and distance codes and write out the resulting
  21545. literal and match bytes until either not enough input or output is
  21546. available, an end-of-block is encountered, or a data error is encountered.
  21547. When large enough input and output buffers are supplied to inflate(), for
  21548. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21549. inflate execution time is spent in this routine.
  21550. Entry assumptions:
  21551. state.mode === LEN
  21552. strm.avail_in >= 6
  21553. strm.avail_out >= 258
  21554. start >= strm.avail_out
  21555. state.bits < 8
  21556. On return, state.mode is one of:
  21557. LEN -- ran out of enough output space or enough available input
  21558. TYPE -- reached end of block code, inflate() to interpret next block
  21559. BAD -- error in block data
  21560. Notes:
  21561. - The maximum input bits used by a length/distance pair is 15 bits for the
  21562. length code, 5 bits for the length extra, 15 bits for the distance code,
  21563. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21564. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21565. checking for available input while decoding.
  21566. - The maximum bytes that a single length/distance pair can output is 258
  21567. bytes, which is the maximum length that can be coded. inflate_fast()
  21568. requires strm.avail_out >= 258 for each loop to avoid checking for
  21569. output space.
  21570. */
  21571. module.exports = function inflate_fast(strm, start) {
  21572. var state;
  21573. var _in; /* local strm.input */
  21574. var last; /* have enough input while in < last */
  21575. var _out; /* local strm.output */
  21576. var beg; /* inflate()'s initial strm.output */
  21577. var end; /* while out < end, enough space available */
  21578. //#ifdef INFLATE_STRICT
  21579. var dmax; /* maximum distance from zlib header */
  21580. //#endif
  21581. var wsize; /* window size or zero if not using window */
  21582. var whave; /* valid bytes in the window */
  21583. var wnext; /* window write index */
  21584. var window; /* allocated sliding window, if wsize != 0 */
  21585. var hold; /* local strm.hold */
  21586. var bits; /* local strm.bits */
  21587. var lcode; /* local strm.lencode */
  21588. var dcode; /* local strm.distcode */
  21589. var lmask; /* mask for first level of length codes */
  21590. var dmask; /* mask for first level of distance codes */
  21591. var here; /* retrieved table entry */
  21592. var op; /* code bits, operation, extra bits, or */
  21593. /* window position, window bytes to copy */
  21594. var len; /* match length, unused bytes */
  21595. var dist; /* match distance */
  21596. var from; /* where to copy match from */
  21597. var from_source;
  21598. var input, output; // JS specific, because we have no pointers
  21599. /* copy state to local variables */
  21600. state = strm.state;
  21601. //here = state.here;
  21602. _in = strm.next_in;
  21603. input = strm.input;
  21604. last = _in + (strm.avail_in - 5);
  21605. _out = strm.next_out;
  21606. output = strm.output;
  21607. beg = _out - (start - strm.avail_out);
  21608. end = _out + (strm.avail_out - 257);
  21609. //#ifdef INFLATE_STRICT
  21610. dmax = state.dmax;
  21611. //#endif
  21612. wsize = state.wsize;
  21613. whave = state.whave;
  21614. wnext = state.wnext;
  21615. window = state.window;
  21616. hold = state.hold;
  21617. bits = state.bits;
  21618. lcode = state.lencode;
  21619. dcode = state.distcode;
  21620. lmask = (1 << state.lenbits) - 1;
  21621. dmask = (1 << state.distbits) - 1;
  21622. /* decode literals and length/distances until end-of-block or not enough
  21623. input data or output space */
  21624. top:
  21625. do {
  21626. if (bits < 15) {
  21627. hold += input[_in++] << bits;
  21628. bits += 8;
  21629. hold += input[_in++] << bits;
  21630. bits += 8;
  21631. }
  21632. here = lcode[hold & lmask];
  21633. dolen:
  21634. for (;;) { // Goto emulation
  21635. op = here >>> 24/*here.bits*/;
  21636. hold >>>= op;
  21637. bits -= op;
  21638. op = (here >>> 16) & 0xff/*here.op*/;
  21639. if (op === 0) { /* literal */
  21640. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21641. // "inflate: literal '%c'\n" :
  21642. // "inflate: literal 0x%02x\n", here.val));
  21643. output[_out++] = here & 0xffff/*here.val*/;
  21644. }
  21645. else if (op & 16) { /* length base */
  21646. len = here & 0xffff/*here.val*/;
  21647. op &= 15; /* number of extra bits */
  21648. if (op) {
  21649. if (bits < op) {
  21650. hold += input[_in++] << bits;
  21651. bits += 8;
  21652. }
  21653. len += hold & ((1 << op) - 1);
  21654. hold >>>= op;
  21655. bits -= op;
  21656. }
  21657. //Tracevv((stderr, "inflate: length %u\n", len));
  21658. if (bits < 15) {
  21659. hold += input[_in++] << bits;
  21660. bits += 8;
  21661. hold += input[_in++] << bits;
  21662. bits += 8;
  21663. }
  21664. here = dcode[hold & dmask];
  21665. dodist:
  21666. for (;;) { // goto emulation
  21667. op = here >>> 24/*here.bits*/;
  21668. hold >>>= op;
  21669. bits -= op;
  21670. op = (here >>> 16) & 0xff/*here.op*/;
  21671. if (op & 16) { /* distance base */
  21672. dist = here & 0xffff/*here.val*/;
  21673. op &= 15; /* number of extra bits */
  21674. if (bits < op) {
  21675. hold += input[_in++] << bits;
  21676. bits += 8;
  21677. if (bits < op) {
  21678. hold += input[_in++] << bits;
  21679. bits += 8;
  21680. }
  21681. }
  21682. dist += hold & ((1 << op) - 1);
  21683. //#ifdef INFLATE_STRICT
  21684. if (dist > dmax) {
  21685. strm.msg = 'invalid distance too far back';
  21686. state.mode = BAD;
  21687. break top;
  21688. }
  21689. //#endif
  21690. hold >>>= op;
  21691. bits -= op;
  21692. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21693. op = _out - beg; /* max distance in output */
  21694. if (dist > op) { /* see if copy from window */
  21695. op = dist - op; /* distance back in window */
  21696. if (op > whave) {
  21697. if (state.sane) {
  21698. strm.msg = 'invalid distance too far back';
  21699. state.mode = BAD;
  21700. break top;
  21701. }
  21702. // (!) This block is disabled in zlib defailts,
  21703. // don't enable it for binary compatibility
  21704. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21705. // if (len <= op - whave) {
  21706. // do {
  21707. // output[_out++] = 0;
  21708. // } while (--len);
  21709. // continue top;
  21710. // }
  21711. // len -= op - whave;
  21712. // do {
  21713. // output[_out++] = 0;
  21714. // } while (--op > whave);
  21715. // if (op === 0) {
  21716. // from = _out - dist;
  21717. // do {
  21718. // output[_out++] = output[from++];
  21719. // } while (--len);
  21720. // continue top;
  21721. // }
  21722. //#endif
  21723. }
  21724. from = 0; // window index
  21725. from_source = window;
  21726. if (wnext === 0) { /* very common case */
  21727. from += wsize - op;
  21728. if (op < len) { /* some from window */
  21729. len -= op;
  21730. do {
  21731. output[_out++] = window[from++];
  21732. } while (--op);
  21733. from = _out - dist; /* rest from output */
  21734. from_source = output;
  21735. }
  21736. }
  21737. else if (wnext < op) { /* wrap around window */
  21738. from += wsize + wnext - op;
  21739. op -= wnext;
  21740. if (op < len) { /* some from end of window */
  21741. len -= op;
  21742. do {
  21743. output[_out++] = window[from++];
  21744. } while (--op);
  21745. from = 0;
  21746. if (wnext < len) { /* some from start of window */
  21747. op = wnext;
  21748. len -= op;
  21749. do {
  21750. output[_out++] = window[from++];
  21751. } while (--op);
  21752. from = _out - dist; /* rest from output */
  21753. from_source = output;
  21754. }
  21755. }
  21756. }
  21757. else { /* contiguous in window */
  21758. from += wnext - op;
  21759. if (op < len) { /* some from window */
  21760. len -= op;
  21761. do {
  21762. output[_out++] = window[from++];
  21763. } while (--op);
  21764. from = _out - dist; /* rest from output */
  21765. from_source = output;
  21766. }
  21767. }
  21768. while (len > 2) {
  21769. output[_out++] = from_source[from++];
  21770. output[_out++] = from_source[from++];
  21771. output[_out++] = from_source[from++];
  21772. len -= 3;
  21773. }
  21774. if (len) {
  21775. output[_out++] = from_source[from++];
  21776. if (len > 1) {
  21777. output[_out++] = from_source[from++];
  21778. }
  21779. }
  21780. }
  21781. else {
  21782. from = _out - dist; /* copy direct from output */
  21783. do { /* minimum length is three */
  21784. output[_out++] = output[from++];
  21785. output[_out++] = output[from++];
  21786. output[_out++] = output[from++];
  21787. len -= 3;
  21788. } while (len > 2);
  21789. if (len) {
  21790. output[_out++] = output[from++];
  21791. if (len > 1) {
  21792. output[_out++] = output[from++];
  21793. }
  21794. }
  21795. }
  21796. }
  21797. else if ((op & 64) === 0) { /* 2nd level distance code */
  21798. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21799. continue dodist;
  21800. }
  21801. else {
  21802. strm.msg = 'invalid distance code';
  21803. state.mode = BAD;
  21804. break top;
  21805. }
  21806. break; // need to emulate goto via "continue"
  21807. }
  21808. }
  21809. else if ((op & 64) === 0) { /* 2nd level length code */
  21810. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21811. continue dolen;
  21812. }
  21813. else if (op & 32) { /* end-of-block */
  21814. //Tracevv((stderr, "inflate: end of block\n"));
  21815. state.mode = TYPE;
  21816. break top;
  21817. }
  21818. else {
  21819. strm.msg = 'invalid literal/length code';
  21820. state.mode = BAD;
  21821. break top;
  21822. }
  21823. break; // need to emulate goto via "continue"
  21824. }
  21825. } while (_in < last && _out < end);
  21826. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21827. len = bits >> 3;
  21828. _in -= len;
  21829. bits -= len << 3;
  21830. hold &= (1 << bits) - 1;
  21831. /* update state and return */
  21832. strm.next_in = _in;
  21833. strm.next_out = _out;
  21834. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21835. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21836. state.hold = hold;
  21837. state.bits = bits;
  21838. return;
  21839. };
  21840. },{}],78:[function(require,module,exports){
  21841. 'use strict';
  21842. var utils = require('../utils/common');
  21843. var adler32 = require('./adler32');
  21844. var crc32 = require('./crc32');
  21845. var inflate_fast = require('./inffast');
  21846. var inflate_table = require('./inftrees');
  21847. var CODES = 0;
  21848. var LENS = 1;
  21849. var DISTS = 2;
  21850. /* Public constants ==========================================================*/
  21851. /* ===========================================================================*/
  21852. /* Allowed flush values; see deflate() and inflate() below for details */
  21853. //var Z_NO_FLUSH = 0;
  21854. //var Z_PARTIAL_FLUSH = 1;
  21855. //var Z_SYNC_FLUSH = 2;
  21856. //var Z_FULL_FLUSH = 3;
  21857. var Z_FINISH = 4;
  21858. var Z_BLOCK = 5;
  21859. var Z_TREES = 6;
  21860. /* Return codes for the compression/decompression functions. Negative values
  21861. * are errors, positive values are used for special but normal events.
  21862. */
  21863. var Z_OK = 0;
  21864. var Z_STREAM_END = 1;
  21865. var Z_NEED_DICT = 2;
  21866. //var Z_ERRNO = -1;
  21867. var Z_STREAM_ERROR = -2;
  21868. var Z_DATA_ERROR = -3;
  21869. var Z_MEM_ERROR = -4;
  21870. var Z_BUF_ERROR = -5;
  21871. //var Z_VERSION_ERROR = -6;
  21872. /* The deflate compression method */
  21873. var Z_DEFLATED = 8;
  21874. /* STATES ====================================================================*/
  21875. /* ===========================================================================*/
  21876. var HEAD = 1; /* i: waiting for magic header */
  21877. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  21878. var TIME = 3; /* i: waiting for modification time (gzip) */
  21879. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  21880. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  21881. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  21882. var NAME = 7; /* i: waiting for end of file name (gzip) */
  21883. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  21884. var HCRC = 9; /* i: waiting for header crc (gzip) */
  21885. var DICTID = 10; /* i: waiting for dictionary check value */
  21886. var DICT = 11; /* waiting for inflateSetDictionary() call */
  21887. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21888. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  21889. var STORED = 14; /* i: waiting for stored size (length and complement) */
  21890. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  21891. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  21892. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  21893. var LENLENS = 18; /* i: waiting for code length code lengths */
  21894. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  21895. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  21896. var LEN = 21; /* i: waiting for length/lit/eob code */
  21897. var LENEXT = 22; /* i: waiting for length extra bits */
  21898. var DIST = 23; /* i: waiting for distance code */
  21899. var DISTEXT = 24; /* i: waiting for distance extra bits */
  21900. var MATCH = 25; /* o: waiting for output space to copy string */
  21901. var LIT = 26; /* o: waiting for output space to write literal */
  21902. var CHECK = 27; /* i: waiting for 32-bit check value */
  21903. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  21904. var DONE = 29; /* finished check, done -- remain here until reset */
  21905. var BAD = 30; /* got a data error -- remain here until reset */
  21906. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  21907. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  21908. /* ===========================================================================*/
  21909. var ENOUGH_LENS = 852;
  21910. var ENOUGH_DISTS = 592;
  21911. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21912. var MAX_WBITS = 15;
  21913. /* 32K LZ77 window */
  21914. var DEF_WBITS = MAX_WBITS;
  21915. function ZSWAP32(q) {
  21916. return (((q >>> 24) & 0xff) +
  21917. ((q >>> 8) & 0xff00) +
  21918. ((q & 0xff00) << 8) +
  21919. ((q & 0xff) << 24));
  21920. }
  21921. function InflateState() {
  21922. this.mode = 0; /* current inflate mode */
  21923. this.last = false; /* true if processing last block */
  21924. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21925. this.havedict = false; /* true if dictionary provided */
  21926. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  21927. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  21928. this.check = 0; /* protected copy of check value */
  21929. this.total = 0; /* protected copy of output count */
  21930. // TODO: may be {}
  21931. this.head = null; /* where to save gzip header information */
  21932. /* sliding window */
  21933. this.wbits = 0; /* log base 2 of requested window size */
  21934. this.wsize = 0; /* window size or zero if not using window */
  21935. this.whave = 0; /* valid bytes in the window */
  21936. this.wnext = 0; /* window write index */
  21937. this.window = null; /* allocated sliding window, if needed */
  21938. /* bit accumulator */
  21939. this.hold = 0; /* input bit accumulator */
  21940. this.bits = 0; /* number of bits in "in" */
  21941. /* for string and stored block copying */
  21942. this.length = 0; /* literal or length of data to copy */
  21943. this.offset = 0; /* distance back to copy string from */
  21944. /* for table and code decoding */
  21945. this.extra = 0; /* extra bits needed */
  21946. /* fixed and dynamic code tables */
  21947. this.lencode = null; /* starting table for length/literal codes */
  21948. this.distcode = null; /* starting table for distance codes */
  21949. this.lenbits = 0; /* index bits for lencode */
  21950. this.distbits = 0; /* index bits for distcode */
  21951. /* dynamic table building */
  21952. this.ncode = 0; /* number of code length code lengths */
  21953. this.nlen = 0; /* number of length code lengths */
  21954. this.ndist = 0; /* number of distance code lengths */
  21955. this.have = 0; /* number of code lengths in lens[] */
  21956. this.next = null; /* next available space in codes[] */
  21957. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  21958. this.work = new utils.Buf16(288); /* work area for code table building */
  21959. /*
  21960. because we don't have pointers in js, we use lencode and distcode directly
  21961. as buffers so we don't need codes
  21962. */
  21963. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  21964. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  21965. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  21966. this.sane = 0; /* if false, allow invalid distance too far */
  21967. this.back = 0; /* bits back of last unprocessed length/lit */
  21968. this.was = 0; /* initial length of match */
  21969. }
  21970. function inflateResetKeep(strm) {
  21971. var state;
  21972. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21973. state = strm.state;
  21974. strm.total_in = strm.total_out = state.total = 0;
  21975. strm.msg = ''; /*Z_NULL*/
  21976. if (state.wrap) { /* to support ill-conceived Java test suite */
  21977. strm.adler = state.wrap & 1;
  21978. }
  21979. state.mode = HEAD;
  21980. state.last = 0;
  21981. state.havedict = 0;
  21982. state.dmax = 32768;
  21983. state.head = null/*Z_NULL*/;
  21984. state.hold = 0;
  21985. state.bits = 0;
  21986. //state.lencode = state.distcode = state.next = state.codes;
  21987. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  21988. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  21989. state.sane = 1;
  21990. state.back = -1;
  21991. //Tracev((stderr, "inflate: reset\n"));
  21992. return Z_OK;
  21993. }
  21994. function inflateReset(strm) {
  21995. var state;
  21996. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21997. state = strm.state;
  21998. state.wsize = 0;
  21999. state.whave = 0;
  22000. state.wnext = 0;
  22001. return inflateResetKeep(strm);
  22002. }
  22003. function inflateReset2(strm, windowBits) {
  22004. var wrap;
  22005. var state;
  22006. /* get the state */
  22007. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22008. state = strm.state;
  22009. /* extract wrap request from windowBits parameter */
  22010. if (windowBits < 0) {
  22011. wrap = 0;
  22012. windowBits = -windowBits;
  22013. }
  22014. else {
  22015. wrap = (windowBits >> 4) + 1;
  22016. if (windowBits < 48) {
  22017. windowBits &= 15;
  22018. }
  22019. }
  22020. /* set number of window bits, free window if different */
  22021. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22022. return Z_STREAM_ERROR;
  22023. }
  22024. if (state.window !== null && state.wbits !== windowBits) {
  22025. state.window = null;
  22026. }
  22027. /* update state and reset the rest of it */
  22028. state.wrap = wrap;
  22029. state.wbits = windowBits;
  22030. return inflateReset(strm);
  22031. }
  22032. function inflateInit2(strm, windowBits) {
  22033. var ret;
  22034. var state;
  22035. if (!strm) { return Z_STREAM_ERROR; }
  22036. //strm.msg = Z_NULL; /* in case we return an error */
  22037. state = new InflateState();
  22038. //if (state === Z_NULL) return Z_MEM_ERROR;
  22039. //Tracev((stderr, "inflate: allocated\n"));
  22040. strm.state = state;
  22041. state.window = null/*Z_NULL*/;
  22042. ret = inflateReset2(strm, windowBits);
  22043. if (ret !== Z_OK) {
  22044. strm.state = null/*Z_NULL*/;
  22045. }
  22046. return ret;
  22047. }
  22048. function inflateInit(strm) {
  22049. return inflateInit2(strm, DEF_WBITS);
  22050. }
  22051. /*
  22052. Return state with length and distance decoding tables and index sizes set to
  22053. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22054. If BUILDFIXED is defined, then instead this routine builds the tables the
  22055. first time it's called, and returns those tables the first time and
  22056. thereafter. This reduces the size of the code by about 2K bytes, in
  22057. exchange for a little execution time. However, BUILDFIXED should not be
  22058. used for threaded applications, since the rewriting of the tables and virgin
  22059. may not be thread-safe.
  22060. */
  22061. var virgin = true;
  22062. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22063. function fixedtables(state) {
  22064. /* build fixed huffman tables if first call (may not be thread safe) */
  22065. if (virgin) {
  22066. var sym;
  22067. lenfix = new utils.Buf32(512);
  22068. distfix = new utils.Buf32(32);
  22069. /* literal/length table */
  22070. sym = 0;
  22071. while (sym < 144) { state.lens[sym++] = 8; }
  22072. while (sym < 256) { state.lens[sym++] = 9; }
  22073. while (sym < 280) { state.lens[sym++] = 7; }
  22074. while (sym < 288) { state.lens[sym++] = 8; }
  22075. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22076. /* distance table */
  22077. sym = 0;
  22078. while (sym < 32) { state.lens[sym++] = 5; }
  22079. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22080. /* do this just once */
  22081. virgin = false;
  22082. }
  22083. state.lencode = lenfix;
  22084. state.lenbits = 9;
  22085. state.distcode = distfix;
  22086. state.distbits = 5;
  22087. }
  22088. /*
  22089. Update the window with the last wsize (normally 32K) bytes written before
  22090. returning. If window does not exist yet, create it. This is only called
  22091. when a window is already in use, or when output has been written during this
  22092. inflate call, but the end of the deflate stream has not been reached yet.
  22093. It is also called to create a window for dictionary data when a dictionary
  22094. is loaded.
  22095. Providing output buffers larger than 32K to inflate() should provide a speed
  22096. advantage, since only the last 32K of output is copied to the sliding window
  22097. upon return from inflate(), and since all distances after the first 32K of
  22098. output will fall in the output data, making match copies simpler and faster.
  22099. The advantage may be dependent on the size of the processor's data caches.
  22100. */
  22101. function updatewindow(strm, src, end, copy) {
  22102. var dist;
  22103. var state = strm.state;
  22104. /* if it hasn't been done already, allocate space for the window */
  22105. if (state.window === null) {
  22106. state.wsize = 1 << state.wbits;
  22107. state.wnext = 0;
  22108. state.whave = 0;
  22109. state.window = new utils.Buf8(state.wsize);
  22110. }
  22111. /* copy state->wsize or less output bytes into the circular window */
  22112. if (copy >= state.wsize) {
  22113. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22114. state.wnext = 0;
  22115. state.whave = state.wsize;
  22116. }
  22117. else {
  22118. dist = state.wsize - state.wnext;
  22119. if (dist > copy) {
  22120. dist = copy;
  22121. }
  22122. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22123. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22124. copy -= dist;
  22125. if (copy) {
  22126. //zmemcpy(state->window, end - copy, copy);
  22127. utils.arraySet(state.window,src, end - copy, copy, 0);
  22128. state.wnext = copy;
  22129. state.whave = state.wsize;
  22130. }
  22131. else {
  22132. state.wnext += dist;
  22133. if (state.wnext === state.wsize) { state.wnext = 0; }
  22134. if (state.whave < state.wsize) { state.whave += dist; }
  22135. }
  22136. }
  22137. return 0;
  22138. }
  22139. function inflate(strm, flush) {
  22140. var state;
  22141. var input, output; // input/output buffers
  22142. var next; /* next input INDEX */
  22143. var put; /* next output INDEX */
  22144. var have, left; /* available input and output */
  22145. var hold; /* bit buffer */
  22146. var bits; /* bits in bit buffer */
  22147. var _in, _out; /* save starting available input and output */
  22148. var copy; /* number of stored or match bytes to copy */
  22149. var from; /* where to copy match bytes from */
  22150. var from_source;
  22151. var here = 0; /* current decoding table entry */
  22152. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22153. //var last; /* parent table entry */
  22154. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22155. var len; /* length to copy for repeats, bits to drop */
  22156. var ret; /* return code */
  22157. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22158. var opts;
  22159. var n; // temporary var for NEED_BITS
  22160. var order = /* permutation of code lengths */
  22161. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22162. if (!strm || !strm.state || !strm.output ||
  22163. (!strm.input && strm.avail_in !== 0)) {
  22164. return Z_STREAM_ERROR;
  22165. }
  22166. state = strm.state;
  22167. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22168. //--- LOAD() ---
  22169. put = strm.next_out;
  22170. output = strm.output;
  22171. left = strm.avail_out;
  22172. next = strm.next_in;
  22173. input = strm.input;
  22174. have = strm.avail_in;
  22175. hold = state.hold;
  22176. bits = state.bits;
  22177. //---
  22178. _in = have;
  22179. _out = left;
  22180. ret = Z_OK;
  22181. inf_leave: // goto emulation
  22182. for (;;) {
  22183. switch (state.mode) {
  22184. case HEAD:
  22185. if (state.wrap === 0) {
  22186. state.mode = TYPEDO;
  22187. break;
  22188. }
  22189. //=== NEEDBITS(16);
  22190. while (bits < 16) {
  22191. if (have === 0) { break inf_leave; }
  22192. have--;
  22193. hold += input[next++] << bits;
  22194. bits += 8;
  22195. }
  22196. //===//
  22197. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22198. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22199. //=== CRC2(state.check, hold);
  22200. hbuf[0] = hold & 0xff;
  22201. hbuf[1] = (hold >>> 8) & 0xff;
  22202. state.check = crc32(state.check, hbuf, 2, 0);
  22203. //===//
  22204. //=== INITBITS();
  22205. hold = 0;
  22206. bits = 0;
  22207. //===//
  22208. state.mode = FLAGS;
  22209. break;
  22210. }
  22211. state.flags = 0; /* expect zlib header */
  22212. if (state.head) {
  22213. state.head.done = false;
  22214. }
  22215. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22216. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22217. strm.msg = 'incorrect header check';
  22218. state.mode = BAD;
  22219. break;
  22220. }
  22221. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22222. strm.msg = 'unknown compression method';
  22223. state.mode = BAD;
  22224. break;
  22225. }
  22226. //--- DROPBITS(4) ---//
  22227. hold >>>= 4;
  22228. bits -= 4;
  22229. //---//
  22230. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22231. if (state.wbits === 0) {
  22232. state.wbits = len;
  22233. }
  22234. else if (len > state.wbits) {
  22235. strm.msg = 'invalid window size';
  22236. state.mode = BAD;
  22237. break;
  22238. }
  22239. state.dmax = 1 << len;
  22240. //Tracev((stderr, "inflate: zlib header ok\n"));
  22241. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22242. state.mode = hold & 0x200 ? DICTID : TYPE;
  22243. //=== INITBITS();
  22244. hold = 0;
  22245. bits = 0;
  22246. //===//
  22247. break;
  22248. case FLAGS:
  22249. //=== NEEDBITS(16); */
  22250. while (bits < 16) {
  22251. if (have === 0) { break inf_leave; }
  22252. have--;
  22253. hold += input[next++] << bits;
  22254. bits += 8;
  22255. }
  22256. //===//
  22257. state.flags = hold;
  22258. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22259. strm.msg = 'unknown compression method';
  22260. state.mode = BAD;
  22261. break;
  22262. }
  22263. if (state.flags & 0xe000) {
  22264. strm.msg = 'unknown header flags set';
  22265. state.mode = BAD;
  22266. break;
  22267. }
  22268. if (state.head) {
  22269. state.head.text = ((hold >> 8) & 1);
  22270. }
  22271. if (state.flags & 0x0200) {
  22272. //=== CRC2(state.check, hold);
  22273. hbuf[0] = hold & 0xff;
  22274. hbuf[1] = (hold >>> 8) & 0xff;
  22275. state.check = crc32(state.check, hbuf, 2, 0);
  22276. //===//
  22277. }
  22278. //=== INITBITS();
  22279. hold = 0;
  22280. bits = 0;
  22281. //===//
  22282. state.mode = TIME;
  22283. /* falls through */
  22284. case TIME:
  22285. //=== NEEDBITS(32); */
  22286. while (bits < 32) {
  22287. if (have === 0) { break inf_leave; }
  22288. have--;
  22289. hold += input[next++] << bits;
  22290. bits += 8;
  22291. }
  22292. //===//
  22293. if (state.head) {
  22294. state.head.time = hold;
  22295. }
  22296. if (state.flags & 0x0200) {
  22297. //=== CRC4(state.check, hold)
  22298. hbuf[0] = hold & 0xff;
  22299. hbuf[1] = (hold >>> 8) & 0xff;
  22300. hbuf[2] = (hold >>> 16) & 0xff;
  22301. hbuf[3] = (hold >>> 24) & 0xff;
  22302. state.check = crc32(state.check, hbuf, 4, 0);
  22303. //===
  22304. }
  22305. //=== INITBITS();
  22306. hold = 0;
  22307. bits = 0;
  22308. //===//
  22309. state.mode = OS;
  22310. /* falls through */
  22311. case OS:
  22312. //=== NEEDBITS(16); */
  22313. while (bits < 16) {
  22314. if (have === 0) { break inf_leave; }
  22315. have--;
  22316. hold += input[next++] << bits;
  22317. bits += 8;
  22318. }
  22319. //===//
  22320. if (state.head) {
  22321. state.head.xflags = (hold & 0xff);
  22322. state.head.os = (hold >> 8);
  22323. }
  22324. if (state.flags & 0x0200) {
  22325. //=== CRC2(state.check, hold);
  22326. hbuf[0] = hold & 0xff;
  22327. hbuf[1] = (hold >>> 8) & 0xff;
  22328. state.check = crc32(state.check, hbuf, 2, 0);
  22329. //===//
  22330. }
  22331. //=== INITBITS();
  22332. hold = 0;
  22333. bits = 0;
  22334. //===//
  22335. state.mode = EXLEN;
  22336. /* falls through */
  22337. case EXLEN:
  22338. if (state.flags & 0x0400) {
  22339. //=== NEEDBITS(16); */
  22340. while (bits < 16) {
  22341. if (have === 0) { break inf_leave; }
  22342. have--;
  22343. hold += input[next++] << bits;
  22344. bits += 8;
  22345. }
  22346. //===//
  22347. state.length = hold;
  22348. if (state.head) {
  22349. state.head.extra_len = hold;
  22350. }
  22351. if (state.flags & 0x0200) {
  22352. //=== CRC2(state.check, hold);
  22353. hbuf[0] = hold & 0xff;
  22354. hbuf[1] = (hold >>> 8) & 0xff;
  22355. state.check = crc32(state.check, hbuf, 2, 0);
  22356. //===//
  22357. }
  22358. //=== INITBITS();
  22359. hold = 0;
  22360. bits = 0;
  22361. //===//
  22362. }
  22363. else if (state.head) {
  22364. state.head.extra = null/*Z_NULL*/;
  22365. }
  22366. state.mode = EXTRA;
  22367. /* falls through */
  22368. case EXTRA:
  22369. if (state.flags & 0x0400) {
  22370. copy = state.length;
  22371. if (copy > have) { copy = have; }
  22372. if (copy) {
  22373. if (state.head) {
  22374. len = state.head.extra_len - state.length;
  22375. if (!state.head.extra) {
  22376. // Use untyped array for more conveniend processing later
  22377. state.head.extra = new Array(state.head.extra_len);
  22378. }
  22379. utils.arraySet(
  22380. state.head.extra,
  22381. input,
  22382. next,
  22383. // extra field is limited to 65536 bytes
  22384. // - no need for additional size check
  22385. copy,
  22386. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22387. len
  22388. );
  22389. //zmemcpy(state.head.extra + len, next,
  22390. // len + copy > state.head.extra_max ?
  22391. // state.head.extra_max - len : copy);
  22392. }
  22393. if (state.flags & 0x0200) {
  22394. state.check = crc32(state.check, input, copy, next);
  22395. }
  22396. have -= copy;
  22397. next += copy;
  22398. state.length -= copy;
  22399. }
  22400. if (state.length) { break inf_leave; }
  22401. }
  22402. state.length = 0;
  22403. state.mode = NAME;
  22404. /* falls through */
  22405. case NAME:
  22406. if (state.flags & 0x0800) {
  22407. if (have === 0) { break inf_leave; }
  22408. copy = 0;
  22409. do {
  22410. // TODO: 2 or 1 bytes?
  22411. len = input[next + copy++];
  22412. /* use constant limit because in js we should not preallocate memory */
  22413. if (state.head && len &&
  22414. (state.length < 65536 /*state.head.name_max*/)) {
  22415. state.head.name += String.fromCharCode(len);
  22416. }
  22417. } while (len && copy < have);
  22418. if (state.flags & 0x0200) {
  22419. state.check = crc32(state.check, input, copy, next);
  22420. }
  22421. have -= copy;
  22422. next += copy;
  22423. if (len) { break inf_leave; }
  22424. }
  22425. else if (state.head) {
  22426. state.head.name = null;
  22427. }
  22428. state.length = 0;
  22429. state.mode = COMMENT;
  22430. /* falls through */
  22431. case COMMENT:
  22432. if (state.flags & 0x1000) {
  22433. if (have === 0) { break inf_leave; }
  22434. copy = 0;
  22435. do {
  22436. len = input[next + copy++];
  22437. /* use constant limit because in js we should not preallocate memory */
  22438. if (state.head && len &&
  22439. (state.length < 65536 /*state.head.comm_max*/)) {
  22440. state.head.comment += String.fromCharCode(len);
  22441. }
  22442. } while (len && copy < have);
  22443. if (state.flags & 0x0200) {
  22444. state.check = crc32(state.check, input, copy, next);
  22445. }
  22446. have -= copy;
  22447. next += copy;
  22448. if (len) { break inf_leave; }
  22449. }
  22450. else if (state.head) {
  22451. state.head.comment = null;
  22452. }
  22453. state.mode = HCRC;
  22454. /* falls through */
  22455. case HCRC:
  22456. if (state.flags & 0x0200) {
  22457. //=== NEEDBITS(16); */
  22458. while (bits < 16) {
  22459. if (have === 0) { break inf_leave; }
  22460. have--;
  22461. hold += input[next++] << bits;
  22462. bits += 8;
  22463. }
  22464. //===//
  22465. if (hold !== (state.check & 0xffff)) {
  22466. strm.msg = 'header crc mismatch';
  22467. state.mode = BAD;
  22468. break;
  22469. }
  22470. //=== INITBITS();
  22471. hold = 0;
  22472. bits = 0;
  22473. //===//
  22474. }
  22475. if (state.head) {
  22476. state.head.hcrc = ((state.flags >> 9) & 1);
  22477. state.head.done = true;
  22478. }
  22479. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22480. state.mode = TYPE;
  22481. break;
  22482. case DICTID:
  22483. //=== NEEDBITS(32); */
  22484. while (bits < 32) {
  22485. if (have === 0) { break inf_leave; }
  22486. have--;
  22487. hold += input[next++] << bits;
  22488. bits += 8;
  22489. }
  22490. //===//
  22491. strm.adler = state.check = ZSWAP32(hold);
  22492. //=== INITBITS();
  22493. hold = 0;
  22494. bits = 0;
  22495. //===//
  22496. state.mode = DICT;
  22497. /* falls through */
  22498. case DICT:
  22499. if (state.havedict === 0) {
  22500. //--- RESTORE() ---
  22501. strm.next_out = put;
  22502. strm.avail_out = left;
  22503. strm.next_in = next;
  22504. strm.avail_in = have;
  22505. state.hold = hold;
  22506. state.bits = bits;
  22507. //---
  22508. return Z_NEED_DICT;
  22509. }
  22510. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22511. state.mode = TYPE;
  22512. /* falls through */
  22513. case TYPE:
  22514. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22515. /* falls through */
  22516. case TYPEDO:
  22517. if (state.last) {
  22518. //--- BYTEBITS() ---//
  22519. hold >>>= bits & 7;
  22520. bits -= bits & 7;
  22521. //---//
  22522. state.mode = CHECK;
  22523. break;
  22524. }
  22525. //=== NEEDBITS(3); */
  22526. while (bits < 3) {
  22527. if (have === 0) { break inf_leave; }
  22528. have--;
  22529. hold += input[next++] << bits;
  22530. bits += 8;
  22531. }
  22532. //===//
  22533. state.last = (hold & 0x01)/*BITS(1)*/;
  22534. //--- DROPBITS(1) ---//
  22535. hold >>>= 1;
  22536. bits -= 1;
  22537. //---//
  22538. switch ((hold & 0x03)/*BITS(2)*/) {
  22539. case 0: /* stored block */
  22540. //Tracev((stderr, "inflate: stored block%s\n",
  22541. // state.last ? " (last)" : ""));
  22542. state.mode = STORED;
  22543. break;
  22544. case 1: /* fixed block */
  22545. fixedtables(state);
  22546. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22547. // state.last ? " (last)" : ""));
  22548. state.mode = LEN_; /* decode codes */
  22549. if (flush === Z_TREES) {
  22550. //--- DROPBITS(2) ---//
  22551. hold >>>= 2;
  22552. bits -= 2;
  22553. //---//
  22554. break inf_leave;
  22555. }
  22556. break;
  22557. case 2: /* dynamic block */
  22558. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22559. // state.last ? " (last)" : ""));
  22560. state.mode = TABLE;
  22561. break;
  22562. case 3:
  22563. strm.msg = 'invalid block type';
  22564. state.mode = BAD;
  22565. }
  22566. //--- DROPBITS(2) ---//
  22567. hold >>>= 2;
  22568. bits -= 2;
  22569. //---//
  22570. break;
  22571. case STORED:
  22572. //--- BYTEBITS() ---// /* go to byte boundary */
  22573. hold >>>= bits & 7;
  22574. bits -= bits & 7;
  22575. //---//
  22576. //=== NEEDBITS(32); */
  22577. while (bits < 32) {
  22578. if (have === 0) { break inf_leave; }
  22579. have--;
  22580. hold += input[next++] << bits;
  22581. bits += 8;
  22582. }
  22583. //===//
  22584. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22585. strm.msg = 'invalid stored block lengths';
  22586. state.mode = BAD;
  22587. break;
  22588. }
  22589. state.length = hold & 0xffff;
  22590. //Tracev((stderr, "inflate: stored length %u\n",
  22591. // state.length));
  22592. //=== INITBITS();
  22593. hold = 0;
  22594. bits = 0;
  22595. //===//
  22596. state.mode = COPY_;
  22597. if (flush === Z_TREES) { break inf_leave; }
  22598. /* falls through */
  22599. case COPY_:
  22600. state.mode = COPY;
  22601. /* falls through */
  22602. case COPY:
  22603. copy = state.length;
  22604. if (copy) {
  22605. if (copy > have) { copy = have; }
  22606. if (copy > left) { copy = left; }
  22607. if (copy === 0) { break inf_leave; }
  22608. //--- zmemcpy(put, next, copy); ---
  22609. utils.arraySet(output, input, next, copy, put);
  22610. //---//
  22611. have -= copy;
  22612. next += copy;
  22613. left -= copy;
  22614. put += copy;
  22615. state.length -= copy;
  22616. break;
  22617. }
  22618. //Tracev((stderr, "inflate: stored end\n"));
  22619. state.mode = TYPE;
  22620. break;
  22621. case TABLE:
  22622. //=== NEEDBITS(14); */
  22623. while (bits < 14) {
  22624. if (have === 0) { break inf_leave; }
  22625. have--;
  22626. hold += input[next++] << bits;
  22627. bits += 8;
  22628. }
  22629. //===//
  22630. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22631. //--- DROPBITS(5) ---//
  22632. hold >>>= 5;
  22633. bits -= 5;
  22634. //---//
  22635. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22636. //--- DROPBITS(5) ---//
  22637. hold >>>= 5;
  22638. bits -= 5;
  22639. //---//
  22640. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22641. //--- DROPBITS(4) ---//
  22642. hold >>>= 4;
  22643. bits -= 4;
  22644. //---//
  22645. //#ifndef PKZIP_BUG_WORKAROUND
  22646. if (state.nlen > 286 || state.ndist > 30) {
  22647. strm.msg = 'too many length or distance symbols';
  22648. state.mode = BAD;
  22649. break;
  22650. }
  22651. //#endif
  22652. //Tracev((stderr, "inflate: table sizes ok\n"));
  22653. state.have = 0;
  22654. state.mode = LENLENS;
  22655. /* falls through */
  22656. case LENLENS:
  22657. while (state.have < state.ncode) {
  22658. //=== NEEDBITS(3);
  22659. while (bits < 3) {
  22660. if (have === 0) { break inf_leave; }
  22661. have--;
  22662. hold += input[next++] << bits;
  22663. bits += 8;
  22664. }
  22665. //===//
  22666. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22667. //--- DROPBITS(3) ---//
  22668. hold >>>= 3;
  22669. bits -= 3;
  22670. //---//
  22671. }
  22672. while (state.have < 19) {
  22673. state.lens[order[state.have++]] = 0;
  22674. }
  22675. // We have separate tables & no pointers. 2 commented lines below not needed.
  22676. //state.next = state.codes;
  22677. //state.lencode = state.next;
  22678. // Switch to use dynamic table
  22679. state.lencode = state.lendyn;
  22680. state.lenbits = 7;
  22681. opts = {bits: state.lenbits};
  22682. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22683. state.lenbits = opts.bits;
  22684. if (ret) {
  22685. strm.msg = 'invalid code lengths set';
  22686. state.mode = BAD;
  22687. break;
  22688. }
  22689. //Tracev((stderr, "inflate: code lengths ok\n"));
  22690. state.have = 0;
  22691. state.mode = CODELENS;
  22692. /* falls through */
  22693. case CODELENS:
  22694. while (state.have < state.nlen + state.ndist) {
  22695. for (;;) {
  22696. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22697. here_bits = here >>> 24;
  22698. here_op = (here >>> 16) & 0xff;
  22699. here_val = here & 0xffff;
  22700. if ((here_bits) <= bits) { break; }
  22701. //--- PULLBYTE() ---//
  22702. if (have === 0) { break inf_leave; }
  22703. have--;
  22704. hold += input[next++] << bits;
  22705. bits += 8;
  22706. //---//
  22707. }
  22708. if (here_val < 16) {
  22709. //--- DROPBITS(here.bits) ---//
  22710. hold >>>= here_bits;
  22711. bits -= here_bits;
  22712. //---//
  22713. state.lens[state.have++] = here_val;
  22714. }
  22715. else {
  22716. if (here_val === 16) {
  22717. //=== NEEDBITS(here.bits + 2);
  22718. n = here_bits + 2;
  22719. while (bits < n) {
  22720. if (have === 0) { break inf_leave; }
  22721. have--;
  22722. hold += input[next++] << bits;
  22723. bits += 8;
  22724. }
  22725. //===//
  22726. //--- DROPBITS(here.bits) ---//
  22727. hold >>>= here_bits;
  22728. bits -= here_bits;
  22729. //---//
  22730. if (state.have === 0) {
  22731. strm.msg = 'invalid bit length repeat';
  22732. state.mode = BAD;
  22733. break;
  22734. }
  22735. len = state.lens[state.have - 1];
  22736. copy = 3 + (hold & 0x03);//BITS(2);
  22737. //--- DROPBITS(2) ---//
  22738. hold >>>= 2;
  22739. bits -= 2;
  22740. //---//
  22741. }
  22742. else if (here_val === 17) {
  22743. //=== NEEDBITS(here.bits + 3);
  22744. n = here_bits + 3;
  22745. while (bits < n) {
  22746. if (have === 0) { break inf_leave; }
  22747. have--;
  22748. hold += input[next++] << bits;
  22749. bits += 8;
  22750. }
  22751. //===//
  22752. //--- DROPBITS(here.bits) ---//
  22753. hold >>>= here_bits;
  22754. bits -= here_bits;
  22755. //---//
  22756. len = 0;
  22757. copy = 3 + (hold & 0x07);//BITS(3);
  22758. //--- DROPBITS(3) ---//
  22759. hold >>>= 3;
  22760. bits -= 3;
  22761. //---//
  22762. }
  22763. else {
  22764. //=== NEEDBITS(here.bits + 7);
  22765. n = here_bits + 7;
  22766. while (bits < n) {
  22767. if (have === 0) { break inf_leave; }
  22768. have--;
  22769. hold += input[next++] << bits;
  22770. bits += 8;
  22771. }
  22772. //===//
  22773. //--- DROPBITS(here.bits) ---//
  22774. hold >>>= here_bits;
  22775. bits -= here_bits;
  22776. //---//
  22777. len = 0;
  22778. copy = 11 + (hold & 0x7f);//BITS(7);
  22779. //--- DROPBITS(7) ---//
  22780. hold >>>= 7;
  22781. bits -= 7;
  22782. //---//
  22783. }
  22784. if (state.have + copy > state.nlen + state.ndist) {
  22785. strm.msg = 'invalid bit length repeat';
  22786. state.mode = BAD;
  22787. break;
  22788. }
  22789. while (copy--) {
  22790. state.lens[state.have++] = len;
  22791. }
  22792. }
  22793. }
  22794. /* handle error breaks in while */
  22795. if (state.mode === BAD) { break; }
  22796. /* check for end-of-block code (better have one) */
  22797. if (state.lens[256] === 0) {
  22798. strm.msg = 'invalid code -- missing end-of-block';
  22799. state.mode = BAD;
  22800. break;
  22801. }
  22802. /* build code tables -- note: do not change the lenbits or distbits
  22803. values here (9 and 6) without reading the comments in inftrees.h
  22804. concerning the ENOUGH constants, which depend on those values */
  22805. state.lenbits = 9;
  22806. opts = {bits: state.lenbits};
  22807. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22808. // We have separate tables & no pointers. 2 commented lines below not needed.
  22809. // state.next_index = opts.table_index;
  22810. state.lenbits = opts.bits;
  22811. // state.lencode = state.next;
  22812. if (ret) {
  22813. strm.msg = 'invalid literal/lengths set';
  22814. state.mode = BAD;
  22815. break;
  22816. }
  22817. state.distbits = 6;
  22818. //state.distcode.copy(state.codes);
  22819. // Switch to use dynamic table
  22820. state.distcode = state.distdyn;
  22821. opts = {bits: state.distbits};
  22822. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22823. // We have separate tables & no pointers. 2 commented lines below not needed.
  22824. // state.next_index = opts.table_index;
  22825. state.distbits = opts.bits;
  22826. // state.distcode = state.next;
  22827. if (ret) {
  22828. strm.msg = 'invalid distances set';
  22829. state.mode = BAD;
  22830. break;
  22831. }
  22832. //Tracev((stderr, 'inflate: codes ok\n'));
  22833. state.mode = LEN_;
  22834. if (flush === Z_TREES) { break inf_leave; }
  22835. /* falls through */
  22836. case LEN_:
  22837. state.mode = LEN;
  22838. /* falls through */
  22839. case LEN:
  22840. if (have >= 6 && left >= 258) {
  22841. //--- RESTORE() ---
  22842. strm.next_out = put;
  22843. strm.avail_out = left;
  22844. strm.next_in = next;
  22845. strm.avail_in = have;
  22846. state.hold = hold;
  22847. state.bits = bits;
  22848. //---
  22849. inflate_fast(strm, _out);
  22850. //--- LOAD() ---
  22851. put = strm.next_out;
  22852. output = strm.output;
  22853. left = strm.avail_out;
  22854. next = strm.next_in;
  22855. input = strm.input;
  22856. have = strm.avail_in;
  22857. hold = state.hold;
  22858. bits = state.bits;
  22859. //---
  22860. if (state.mode === TYPE) {
  22861. state.back = -1;
  22862. }
  22863. break;
  22864. }
  22865. state.back = 0;
  22866. for (;;) {
  22867. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22868. here_bits = here >>> 24;
  22869. here_op = (here >>> 16) & 0xff;
  22870. here_val = here & 0xffff;
  22871. if (here_bits <= bits) { break; }
  22872. //--- PULLBYTE() ---//
  22873. if (have === 0) { break inf_leave; }
  22874. have--;
  22875. hold += input[next++] << bits;
  22876. bits += 8;
  22877. //---//
  22878. }
  22879. if (here_op && (here_op & 0xf0) === 0) {
  22880. last_bits = here_bits;
  22881. last_op = here_op;
  22882. last_val = here_val;
  22883. for (;;) {
  22884. here = state.lencode[last_val +
  22885. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22886. here_bits = here >>> 24;
  22887. here_op = (here >>> 16) & 0xff;
  22888. here_val = here & 0xffff;
  22889. if ((last_bits + here_bits) <= bits) { break; }
  22890. //--- PULLBYTE() ---//
  22891. if (have === 0) { break inf_leave; }
  22892. have--;
  22893. hold += input[next++] << bits;
  22894. bits += 8;
  22895. //---//
  22896. }
  22897. //--- DROPBITS(last.bits) ---//
  22898. hold >>>= last_bits;
  22899. bits -= last_bits;
  22900. //---//
  22901. state.back += last_bits;
  22902. }
  22903. //--- DROPBITS(here.bits) ---//
  22904. hold >>>= here_bits;
  22905. bits -= here_bits;
  22906. //---//
  22907. state.back += here_bits;
  22908. state.length = here_val;
  22909. if (here_op === 0) {
  22910. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22911. // "inflate: literal '%c'\n" :
  22912. // "inflate: literal 0x%02x\n", here.val));
  22913. state.mode = LIT;
  22914. break;
  22915. }
  22916. if (here_op & 32) {
  22917. //Tracevv((stderr, "inflate: end of block\n"));
  22918. state.back = -1;
  22919. state.mode = TYPE;
  22920. break;
  22921. }
  22922. if (here_op & 64) {
  22923. strm.msg = 'invalid literal/length code';
  22924. state.mode = BAD;
  22925. break;
  22926. }
  22927. state.extra = here_op & 15;
  22928. state.mode = LENEXT;
  22929. /* falls through */
  22930. case LENEXT:
  22931. if (state.extra) {
  22932. //=== NEEDBITS(state.extra);
  22933. n = state.extra;
  22934. while (bits < n) {
  22935. if (have === 0) { break inf_leave; }
  22936. have--;
  22937. hold += input[next++] << bits;
  22938. bits += 8;
  22939. }
  22940. //===//
  22941. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22942. //--- DROPBITS(state.extra) ---//
  22943. hold >>>= state.extra;
  22944. bits -= state.extra;
  22945. //---//
  22946. state.back += state.extra;
  22947. }
  22948. //Tracevv((stderr, "inflate: length %u\n", state.length));
  22949. state.was = state.length;
  22950. state.mode = DIST;
  22951. /* falls through */
  22952. case DIST:
  22953. for (;;) {
  22954. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  22955. here_bits = here >>> 24;
  22956. here_op = (here >>> 16) & 0xff;
  22957. here_val = here & 0xffff;
  22958. if ((here_bits) <= bits) { break; }
  22959. //--- PULLBYTE() ---//
  22960. if (have === 0) { break inf_leave; }
  22961. have--;
  22962. hold += input[next++] << bits;
  22963. bits += 8;
  22964. //---//
  22965. }
  22966. if ((here_op & 0xf0) === 0) {
  22967. last_bits = here_bits;
  22968. last_op = here_op;
  22969. last_val = here_val;
  22970. for (;;) {
  22971. here = state.distcode[last_val +
  22972. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22973. here_bits = here >>> 24;
  22974. here_op = (here >>> 16) & 0xff;
  22975. here_val = here & 0xffff;
  22976. if ((last_bits + here_bits) <= bits) { break; }
  22977. //--- PULLBYTE() ---//
  22978. if (have === 0) { break inf_leave; }
  22979. have--;
  22980. hold += input[next++] << bits;
  22981. bits += 8;
  22982. //---//
  22983. }
  22984. //--- DROPBITS(last.bits) ---//
  22985. hold >>>= last_bits;
  22986. bits -= last_bits;
  22987. //---//
  22988. state.back += last_bits;
  22989. }
  22990. //--- DROPBITS(here.bits) ---//
  22991. hold >>>= here_bits;
  22992. bits -= here_bits;
  22993. //---//
  22994. state.back += here_bits;
  22995. if (here_op & 64) {
  22996. strm.msg = 'invalid distance code';
  22997. state.mode = BAD;
  22998. break;
  22999. }
  23000. state.offset = here_val;
  23001. state.extra = (here_op) & 15;
  23002. state.mode = DISTEXT;
  23003. /* falls through */
  23004. case DISTEXT:
  23005. if (state.extra) {
  23006. //=== NEEDBITS(state.extra);
  23007. n = state.extra;
  23008. while (bits < n) {
  23009. if (have === 0) { break inf_leave; }
  23010. have--;
  23011. hold += input[next++] << bits;
  23012. bits += 8;
  23013. }
  23014. //===//
  23015. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23016. //--- DROPBITS(state.extra) ---//
  23017. hold >>>= state.extra;
  23018. bits -= state.extra;
  23019. //---//
  23020. state.back += state.extra;
  23021. }
  23022. //#ifdef INFLATE_STRICT
  23023. if (state.offset > state.dmax) {
  23024. strm.msg = 'invalid distance too far back';
  23025. state.mode = BAD;
  23026. break;
  23027. }
  23028. //#endif
  23029. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23030. state.mode = MATCH;
  23031. /* falls through */
  23032. case MATCH:
  23033. if (left === 0) { break inf_leave; }
  23034. copy = _out - left;
  23035. if (state.offset > copy) { /* copy from window */
  23036. copy = state.offset - copy;
  23037. if (copy > state.whave) {
  23038. if (state.sane) {
  23039. strm.msg = 'invalid distance too far back';
  23040. state.mode = BAD;
  23041. break;
  23042. }
  23043. // (!) This block is disabled in zlib defailts,
  23044. // don't enable it for binary compatibility
  23045. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23046. // Trace((stderr, "inflate.c too far\n"));
  23047. // copy -= state.whave;
  23048. // if (copy > state.length) { copy = state.length; }
  23049. // if (copy > left) { copy = left; }
  23050. // left -= copy;
  23051. // state.length -= copy;
  23052. // do {
  23053. // output[put++] = 0;
  23054. // } while (--copy);
  23055. // if (state.length === 0) { state.mode = LEN; }
  23056. // break;
  23057. //#endif
  23058. }
  23059. if (copy > state.wnext) {
  23060. copy -= state.wnext;
  23061. from = state.wsize - copy;
  23062. }
  23063. else {
  23064. from = state.wnext - copy;
  23065. }
  23066. if (copy > state.length) { copy = state.length; }
  23067. from_source = state.window;
  23068. }
  23069. else { /* copy from output */
  23070. from_source = output;
  23071. from = put - state.offset;
  23072. copy = state.length;
  23073. }
  23074. if (copy > left) { copy = left; }
  23075. left -= copy;
  23076. state.length -= copy;
  23077. do {
  23078. output[put++] = from_source[from++];
  23079. } while (--copy);
  23080. if (state.length === 0) { state.mode = LEN; }
  23081. break;
  23082. case LIT:
  23083. if (left === 0) { break inf_leave; }
  23084. output[put++] = state.length;
  23085. left--;
  23086. state.mode = LEN;
  23087. break;
  23088. case CHECK:
  23089. if (state.wrap) {
  23090. //=== NEEDBITS(32);
  23091. while (bits < 32) {
  23092. if (have === 0) { break inf_leave; }
  23093. have--;
  23094. // Use '|' insdead of '+' to make sure that result is signed
  23095. hold |= input[next++] << bits;
  23096. bits += 8;
  23097. }
  23098. //===//
  23099. _out -= left;
  23100. strm.total_out += _out;
  23101. state.total += _out;
  23102. if (_out) {
  23103. strm.adler = state.check =
  23104. /*UPDATE(state.check, put - _out, _out);*/
  23105. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23106. }
  23107. _out = left;
  23108. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23109. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23110. strm.msg = 'incorrect data check';
  23111. state.mode = BAD;
  23112. break;
  23113. }
  23114. //=== INITBITS();
  23115. hold = 0;
  23116. bits = 0;
  23117. //===//
  23118. //Tracev((stderr, "inflate: check matches trailer\n"));
  23119. }
  23120. state.mode = LENGTH;
  23121. /* falls through */
  23122. case LENGTH:
  23123. if (state.wrap && state.flags) {
  23124. //=== NEEDBITS(32);
  23125. while (bits < 32) {
  23126. if (have === 0) { break inf_leave; }
  23127. have--;
  23128. hold += input[next++] << bits;
  23129. bits += 8;
  23130. }
  23131. //===//
  23132. if (hold !== (state.total & 0xffffffff)) {
  23133. strm.msg = 'incorrect length check';
  23134. state.mode = BAD;
  23135. break;
  23136. }
  23137. //=== INITBITS();
  23138. hold = 0;
  23139. bits = 0;
  23140. //===//
  23141. //Tracev((stderr, "inflate: length matches trailer\n"));
  23142. }
  23143. state.mode = DONE;
  23144. /* falls through */
  23145. case DONE:
  23146. ret = Z_STREAM_END;
  23147. break inf_leave;
  23148. case BAD:
  23149. ret = Z_DATA_ERROR;
  23150. break inf_leave;
  23151. case MEM:
  23152. return Z_MEM_ERROR;
  23153. case SYNC:
  23154. /* falls through */
  23155. default:
  23156. return Z_STREAM_ERROR;
  23157. }
  23158. }
  23159. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23160. /*
  23161. Return from inflate(), updating the total counts and the check value.
  23162. If there was no progress during the inflate() call, return a buffer
  23163. error. Call updatewindow() to create and/or update the window state.
  23164. Note: a memory error from inflate() is non-recoverable.
  23165. */
  23166. //--- RESTORE() ---
  23167. strm.next_out = put;
  23168. strm.avail_out = left;
  23169. strm.next_in = next;
  23170. strm.avail_in = have;
  23171. state.hold = hold;
  23172. state.bits = bits;
  23173. //---
  23174. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23175. (state.mode < CHECK || flush !== Z_FINISH))) {
  23176. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23177. state.mode = MEM;
  23178. return Z_MEM_ERROR;
  23179. }
  23180. }
  23181. _in -= strm.avail_in;
  23182. _out -= strm.avail_out;
  23183. strm.total_in += _in;
  23184. strm.total_out += _out;
  23185. state.total += _out;
  23186. if (state.wrap && _out) {
  23187. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23188. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23189. }
  23190. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23191. (state.mode === TYPE ? 128 : 0) +
  23192. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23193. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23194. ret = Z_BUF_ERROR;
  23195. }
  23196. return ret;
  23197. }
  23198. function inflateEnd(strm) {
  23199. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23200. return Z_STREAM_ERROR;
  23201. }
  23202. var state = strm.state;
  23203. if (state.window) {
  23204. state.window = null;
  23205. }
  23206. strm.state = null;
  23207. return Z_OK;
  23208. }
  23209. function inflateGetHeader(strm, head) {
  23210. var state;
  23211. /* check state */
  23212. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23213. state = strm.state;
  23214. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23215. /* save header structure */
  23216. state.head = head;
  23217. head.done = false;
  23218. return Z_OK;
  23219. }
  23220. exports.inflateReset = inflateReset;
  23221. exports.inflateReset2 = inflateReset2;
  23222. exports.inflateResetKeep = inflateResetKeep;
  23223. exports.inflateInit = inflateInit;
  23224. exports.inflateInit2 = inflateInit2;
  23225. exports.inflate = inflate;
  23226. exports.inflateEnd = inflateEnd;
  23227. exports.inflateGetHeader = inflateGetHeader;
  23228. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23229. /* Not implemented
  23230. exports.inflateCopy = inflateCopy;
  23231. exports.inflateGetDictionary = inflateGetDictionary;
  23232. exports.inflateMark = inflateMark;
  23233. exports.inflatePrime = inflatePrime;
  23234. exports.inflateSetDictionary = inflateSetDictionary;
  23235. exports.inflateSync = inflateSync;
  23236. exports.inflateSyncPoint = inflateSyncPoint;
  23237. exports.inflateUndermine = inflateUndermine;
  23238. */
  23239. },{"../utils/common":70,"./adler32":72,"./crc32":74,"./inffast":77,"./inftrees":79}],79:[function(require,module,exports){
  23240. 'use strict';
  23241. var utils = require('../utils/common');
  23242. var MAXBITS = 15;
  23243. var ENOUGH_LENS = 852;
  23244. var ENOUGH_DISTS = 592;
  23245. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23246. var CODES = 0;
  23247. var LENS = 1;
  23248. var DISTS = 2;
  23249. var lbase = [ /* Length codes 257..285 base */
  23250. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23251. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23252. ];
  23253. var lext = [ /* Length codes 257..285 extra */
  23254. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23255. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23256. ];
  23257. var dbase = [ /* Distance codes 0..29 base */
  23258. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23259. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23260. 8193, 12289, 16385, 24577, 0, 0
  23261. ];
  23262. var dext = [ /* Distance codes 0..29 extra */
  23263. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23264. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23265. 28, 28, 29, 29, 64, 64
  23266. ];
  23267. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23268. {
  23269. var bits = opts.bits;
  23270. //here = opts.here; /* table entry for duplication */
  23271. var len = 0; /* a code's length in bits */
  23272. var sym = 0; /* index of code symbols */
  23273. var min = 0, max = 0; /* minimum and maximum code lengths */
  23274. var root = 0; /* number of index bits for root table */
  23275. var curr = 0; /* number of index bits for current table */
  23276. var drop = 0; /* code bits to drop for sub-table */
  23277. var left = 0; /* number of prefix codes available */
  23278. var used = 0; /* code entries in table used */
  23279. var huff = 0; /* Huffman code */
  23280. var incr; /* for incrementing code, index */
  23281. var fill; /* index for replicating entries */
  23282. var low; /* low bits for current root entry */
  23283. var mask; /* mask for low root bits */
  23284. var next; /* next available space in table */
  23285. var base = null; /* base value table to use */
  23286. var base_index = 0;
  23287. // var shoextra; /* extra bits table to use */
  23288. var end; /* use base and extra for symbol > end */
  23289. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23290. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23291. var extra = null;
  23292. var extra_index = 0;
  23293. var here_bits, here_op, here_val;
  23294. /*
  23295. Process a set of code lengths to create a canonical Huffman code. The
  23296. code lengths are lens[0..codes-1]. Each length corresponds to the
  23297. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23298. symbols by length from short to long, and retaining the symbol order
  23299. for codes with equal lengths. Then the code starts with all zero bits
  23300. for the first code of the shortest length, and the codes are integer
  23301. increments for the same length, and zeros are appended as the length
  23302. increases. For the deflate format, these bits are stored backwards
  23303. from their more natural integer increment ordering, and so when the
  23304. decoding tables are built in the large loop below, the integer codes
  23305. are incremented backwards.
  23306. This routine assumes, but does not check, that all of the entries in
  23307. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23308. 1..MAXBITS is interpreted as that code length. zero means that that
  23309. symbol does not occur in this code.
  23310. The codes are sorted by computing a count of codes for each length,
  23311. creating from that a table of starting indices for each length in the
  23312. sorted table, and then entering the symbols in order in the sorted
  23313. table. The sorted table is work[], with that space being provided by
  23314. the caller.
  23315. The length counts are used for other purposes as well, i.e. finding
  23316. the minimum and maximum length codes, determining if there are any
  23317. codes at all, checking for a valid set of lengths, and looking ahead
  23318. at length counts to determine sub-table sizes when building the
  23319. decoding tables.
  23320. */
  23321. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23322. for (len = 0; len <= MAXBITS; len++) {
  23323. count[len] = 0;
  23324. }
  23325. for (sym = 0; sym < codes; sym++) {
  23326. count[lens[lens_index + sym]]++;
  23327. }
  23328. /* bound code lengths, force root to be within code lengths */
  23329. root = bits;
  23330. for (max = MAXBITS; max >= 1; max--) {
  23331. if (count[max] !== 0) { break; }
  23332. }
  23333. if (root > max) {
  23334. root = max;
  23335. }
  23336. if (max === 0) { /* no symbols to code at all */
  23337. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23338. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23339. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23340. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23341. //table.op[opts.table_index] = 64;
  23342. //table.bits[opts.table_index] = 1;
  23343. //table.val[opts.table_index++] = 0;
  23344. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23345. opts.bits = 1;
  23346. return 0; /* no symbols, but wait for decoding to report error */
  23347. }
  23348. for (min = 1; min < max; min++) {
  23349. if (count[min] !== 0) { break; }
  23350. }
  23351. if (root < min) {
  23352. root = min;
  23353. }
  23354. /* check for an over-subscribed or incomplete set of lengths */
  23355. left = 1;
  23356. for (len = 1; len <= MAXBITS; len++) {
  23357. left <<= 1;
  23358. left -= count[len];
  23359. if (left < 0) {
  23360. return -1;
  23361. } /* over-subscribed */
  23362. }
  23363. if (left > 0 && (type === CODES || max !== 1)) {
  23364. return -1; /* incomplete set */
  23365. }
  23366. /* generate offsets into symbol table for each length for sorting */
  23367. offs[1] = 0;
  23368. for (len = 1; len < MAXBITS; len++) {
  23369. offs[len + 1] = offs[len] + count[len];
  23370. }
  23371. /* sort symbols by length, by symbol order within each length */
  23372. for (sym = 0; sym < codes; sym++) {
  23373. if (lens[lens_index + sym] !== 0) {
  23374. work[offs[lens[lens_index + sym]]++] = sym;
  23375. }
  23376. }
  23377. /*
  23378. Create and fill in decoding tables. In this loop, the table being
  23379. filled is at next and has curr index bits. The code being used is huff
  23380. with length len. That code is converted to an index by dropping drop
  23381. bits off of the bottom. For codes where len is less than drop + curr,
  23382. those top drop + curr - len bits are incremented through all values to
  23383. fill the table with replicated entries.
  23384. root is the number of index bits for the root table. When len exceeds
  23385. root, sub-tables are created pointed to by the root entry with an index
  23386. of the low root bits of huff. This is saved in low to check for when a
  23387. new sub-table should be started. drop is zero when the root table is
  23388. being filled, and drop is root when sub-tables are being filled.
  23389. When a new sub-table is needed, it is necessary to look ahead in the
  23390. code lengths to determine what size sub-table is needed. The length
  23391. counts are used for this, and so count[] is decremented as codes are
  23392. entered in the tables.
  23393. used keeps track of how many table entries have been allocated from the
  23394. provided *table space. It is checked for LENS and DIST tables against
  23395. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23396. the initial root table size constants. See the comments in inftrees.h
  23397. for more information.
  23398. sym increments through all symbols, and the loop terminates when
  23399. all codes of length max, i.e. all codes, have been processed. This
  23400. routine permits incomplete codes, so another loop after this one fills
  23401. in the rest of the decoding tables with invalid code markers.
  23402. */
  23403. /* set up for code type */
  23404. // poor man optimization - use if-else instead of switch,
  23405. // to avoid deopts in old v8
  23406. if (type === CODES) {
  23407. base = extra = work; /* dummy value--not used */
  23408. end = 19;
  23409. } else if (type === LENS) {
  23410. base = lbase;
  23411. base_index -= 257;
  23412. extra = lext;
  23413. extra_index -= 257;
  23414. end = 256;
  23415. } else { /* DISTS */
  23416. base = dbase;
  23417. extra = dext;
  23418. end = -1;
  23419. }
  23420. /* initialize opts for loop */
  23421. huff = 0; /* starting code */
  23422. sym = 0; /* starting code symbol */
  23423. len = min; /* starting code length */
  23424. next = table_index; /* current table to fill in */
  23425. curr = root; /* current table index bits */
  23426. drop = 0; /* current bits to drop from code for index */
  23427. low = -1; /* trigger new sub-table when len > root */
  23428. used = 1 << root; /* use root table entries */
  23429. mask = used - 1; /* mask for comparing low */
  23430. /* check available table space */
  23431. if ((type === LENS && used > ENOUGH_LENS) ||
  23432. (type === DISTS && used > ENOUGH_DISTS)) {
  23433. return 1;
  23434. }
  23435. var i=0;
  23436. /* process all codes and make table entries */
  23437. for (;;) {
  23438. i++;
  23439. /* create table entry */
  23440. here_bits = len - drop;
  23441. if (work[sym] < end) {
  23442. here_op = 0;
  23443. here_val = work[sym];
  23444. }
  23445. else if (work[sym] > end) {
  23446. here_op = extra[extra_index + work[sym]];
  23447. here_val = base[base_index + work[sym]];
  23448. }
  23449. else {
  23450. here_op = 32 + 64; /* end of block */
  23451. here_val = 0;
  23452. }
  23453. /* replicate for those indices with low len bits equal to huff */
  23454. incr = 1 << (len - drop);
  23455. fill = 1 << curr;
  23456. min = fill; /* save offset to next table */
  23457. do {
  23458. fill -= incr;
  23459. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23460. } while (fill !== 0);
  23461. /* backwards increment the len-bit code huff */
  23462. incr = 1 << (len - 1);
  23463. while (huff & incr) {
  23464. incr >>= 1;
  23465. }
  23466. if (incr !== 0) {
  23467. huff &= incr - 1;
  23468. huff += incr;
  23469. } else {
  23470. huff = 0;
  23471. }
  23472. /* go to next symbol, update count, len */
  23473. sym++;
  23474. if (--count[len] === 0) {
  23475. if (len === max) { break; }
  23476. len = lens[lens_index + work[sym]];
  23477. }
  23478. /* create new sub-table if needed */
  23479. if (len > root && (huff & mask) !== low) {
  23480. /* if first time, transition to sub-tables */
  23481. if (drop === 0) {
  23482. drop = root;
  23483. }
  23484. /* increment past last table */
  23485. next += min; /* here min is 1 << curr */
  23486. /* determine length of next table */
  23487. curr = len - drop;
  23488. left = 1 << curr;
  23489. while (curr + drop < max) {
  23490. left -= count[curr + drop];
  23491. if (left <= 0) { break; }
  23492. curr++;
  23493. left <<= 1;
  23494. }
  23495. /* check for enough space */
  23496. used += 1 << curr;
  23497. if ((type === LENS && used > ENOUGH_LENS) ||
  23498. (type === DISTS && used > ENOUGH_DISTS)) {
  23499. return 1;
  23500. }
  23501. /* point entry in root table to sub-table */
  23502. low = huff & mask;
  23503. /*table.op[low] = curr;
  23504. table.bits[low] = root;
  23505. table.val[low] = next - opts.table_index;*/
  23506. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23507. }
  23508. }
  23509. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23510. at most one remaining entry, since if the code is incomplete, the
  23511. maximum code length that was allowed to get this far is one bit) */
  23512. if (huff !== 0) {
  23513. //table.op[next + huff] = 64; /* invalid code marker */
  23514. //table.bits[next + huff] = len - drop;
  23515. //table.val[next + huff] = 0;
  23516. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23517. }
  23518. /* set return parameters */
  23519. //opts.table_index += used;
  23520. opts.bits = root;
  23521. return 0;
  23522. };
  23523. },{"../utils/common":70}],80:[function(require,module,exports){
  23524. 'use strict';
  23525. module.exports = {
  23526. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23527. '1': 'stream end', /* Z_STREAM_END 1 */
  23528. '0': '', /* Z_OK 0 */
  23529. '-1': 'file error', /* Z_ERRNO (-1) */
  23530. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23531. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23532. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23533. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23534. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23535. };
  23536. },{}],81:[function(require,module,exports){
  23537. 'use strict';
  23538. var utils = require('../utils/common');
  23539. /* Public constants ==========================================================*/
  23540. /* ===========================================================================*/
  23541. //var Z_FILTERED = 1;
  23542. //var Z_HUFFMAN_ONLY = 2;
  23543. //var Z_RLE = 3;
  23544. var Z_FIXED = 4;
  23545. //var Z_DEFAULT_STRATEGY = 0;
  23546. /* Possible values of the data_type field (though see inflate()) */
  23547. var Z_BINARY = 0;
  23548. var Z_TEXT = 1;
  23549. //var Z_ASCII = 1; // = Z_TEXT
  23550. var Z_UNKNOWN = 2;
  23551. /*============================================================================*/
  23552. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23553. // From zutil.h
  23554. var STORED_BLOCK = 0;
  23555. var STATIC_TREES = 1;
  23556. var DYN_TREES = 2;
  23557. /* The three kinds of block type */
  23558. var MIN_MATCH = 3;
  23559. var MAX_MATCH = 258;
  23560. /* The minimum and maximum match lengths */
  23561. // From deflate.h
  23562. /* ===========================================================================
  23563. * Internal compression state.
  23564. */
  23565. var LENGTH_CODES = 29;
  23566. /* number of length codes, not counting the special END_BLOCK code */
  23567. var LITERALS = 256;
  23568. /* number of literal bytes 0..255 */
  23569. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23570. /* number of Literal or Length codes, including the END_BLOCK code */
  23571. var D_CODES = 30;
  23572. /* number of distance codes */
  23573. var BL_CODES = 19;
  23574. /* number of codes used to transfer the bit lengths */
  23575. var HEAP_SIZE = 2*L_CODES + 1;
  23576. /* maximum heap size */
  23577. var MAX_BITS = 15;
  23578. /* All codes must not exceed MAX_BITS bits */
  23579. var Buf_size = 16;
  23580. /* size of bit buffer in bi_buf */
  23581. /* ===========================================================================
  23582. * Constants
  23583. */
  23584. var MAX_BL_BITS = 7;
  23585. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23586. var END_BLOCK = 256;
  23587. /* end of block literal code */
  23588. var REP_3_6 = 16;
  23589. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23590. var REPZ_3_10 = 17;
  23591. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23592. var REPZ_11_138 = 18;
  23593. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23594. var extra_lbits = /* extra bits for each length code */
  23595. [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];
  23596. var extra_dbits = /* extra bits for each distance code */
  23597. [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];
  23598. var extra_blbits = /* extra bits for each bit length code */
  23599. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23600. var bl_order =
  23601. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23602. /* The lengths of the bit length codes are sent in order of decreasing
  23603. * probability, to avoid transmitting the lengths for unused bit length codes.
  23604. */
  23605. /* ===========================================================================
  23606. * Local data. These are initialized only once.
  23607. */
  23608. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23609. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23610. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23611. var static_ltree = new Array((L_CODES+2) * 2);
  23612. zero(static_ltree);
  23613. /* The static literal tree. Since the bit lengths are imposed, there is no
  23614. * need for the L_CODES extra codes used during heap construction. However
  23615. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23616. * below).
  23617. */
  23618. var static_dtree = new Array(D_CODES * 2);
  23619. zero(static_dtree);
  23620. /* The static distance tree. (Actually a trivial tree since all codes use
  23621. * 5 bits.)
  23622. */
  23623. var _dist_code = new Array(DIST_CODE_LEN);
  23624. zero(_dist_code);
  23625. /* Distance codes. The first 256 values correspond to the distances
  23626. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23627. * the 15 bit distances.
  23628. */
  23629. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23630. zero(_length_code);
  23631. /* length code for each normalized match length (0 == MIN_MATCH) */
  23632. var base_length = new Array(LENGTH_CODES);
  23633. zero(base_length);
  23634. /* First normalized length for each code (0 = MIN_MATCH) */
  23635. var base_dist = new Array(D_CODES);
  23636. zero(base_dist);
  23637. /* First normalized distance for each code (0 = distance of 1) */
  23638. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23639. this.static_tree = static_tree; /* static tree or NULL */
  23640. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23641. this.extra_base = extra_base; /* base index for extra_bits */
  23642. this.elems = elems; /* max number of elements in the tree */
  23643. this.max_length = max_length; /* max bit length for the codes */
  23644. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23645. this.has_stree = static_tree && static_tree.length;
  23646. };
  23647. var static_l_desc;
  23648. var static_d_desc;
  23649. var static_bl_desc;
  23650. var TreeDesc = function(dyn_tree, stat_desc) {
  23651. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23652. this.max_code = 0; /* largest code with non zero frequency */
  23653. this.stat_desc = stat_desc; /* the corresponding static tree */
  23654. };
  23655. function d_code(dist) {
  23656. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23657. }
  23658. /* ===========================================================================
  23659. * Output a short LSB first on the stream.
  23660. * IN assertion: there is enough room in pendingBuf.
  23661. */
  23662. function put_short (s, w) {
  23663. // put_byte(s, (uch)((w) & 0xff));
  23664. // put_byte(s, (uch)((ush)(w) >> 8));
  23665. s.pending_buf[s.pending++] = (w) & 0xff;
  23666. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23667. }
  23668. /* ===========================================================================
  23669. * Send a value on a given number of bits.
  23670. * IN assertion: length <= 16 and value fits in length bits.
  23671. */
  23672. function send_bits(s, value, length) {
  23673. if (s.bi_valid > (Buf_size - length)) {
  23674. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23675. put_short(s, s.bi_buf);
  23676. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23677. s.bi_valid += length - Buf_size;
  23678. } else {
  23679. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23680. s.bi_valid += length;
  23681. }
  23682. }
  23683. function send_code(s, c, tree) {
  23684. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23685. }
  23686. /* ===========================================================================
  23687. * Reverse the first len bits of a code, using straightforward code (a faster
  23688. * method would use a table)
  23689. * IN assertion: 1 <= len <= 15
  23690. */
  23691. function bi_reverse(code, len) {
  23692. var res = 0;
  23693. do {
  23694. res |= code & 1;
  23695. code >>>= 1;
  23696. res <<= 1;
  23697. } while (--len > 0);
  23698. return res >>> 1;
  23699. }
  23700. /* ===========================================================================
  23701. * Flush the bit buffer, keeping at most 7 bits in it.
  23702. */
  23703. function bi_flush(s) {
  23704. if (s.bi_valid === 16) {
  23705. put_short(s, s.bi_buf);
  23706. s.bi_buf = 0;
  23707. s.bi_valid = 0;
  23708. } else if (s.bi_valid >= 8) {
  23709. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23710. s.bi_buf >>= 8;
  23711. s.bi_valid -= 8;
  23712. }
  23713. }
  23714. /* ===========================================================================
  23715. * Compute the optimal bit lengths for a tree and update the total bit length
  23716. * for the current block.
  23717. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23718. * above are the tree nodes sorted by increasing frequency.
  23719. * OUT assertions: the field len is set to the optimal bit length, the
  23720. * array bl_count contains the frequencies for each bit length.
  23721. * The length opt_len is updated; static_len is also updated if stree is
  23722. * not null.
  23723. */
  23724. function gen_bitlen(s, desc)
  23725. // deflate_state *s;
  23726. // tree_desc *desc; /* the tree descriptor */
  23727. {
  23728. var tree = desc.dyn_tree;
  23729. var max_code = desc.max_code;
  23730. var stree = desc.stat_desc.static_tree;
  23731. var has_stree = desc.stat_desc.has_stree;
  23732. var extra = desc.stat_desc.extra_bits;
  23733. var base = desc.stat_desc.extra_base;
  23734. var max_length = desc.stat_desc.max_length;
  23735. var h; /* heap index */
  23736. var n, m; /* iterate over the tree elements */
  23737. var bits; /* bit length */
  23738. var xbits; /* extra bits */
  23739. var f; /* frequency */
  23740. var overflow = 0; /* number of elements with bit length too large */
  23741. for (bits = 0; bits <= MAX_BITS; bits++) {
  23742. s.bl_count[bits] = 0;
  23743. }
  23744. /* In a first pass, compute the optimal bit lengths (which may
  23745. * overflow in the case of the bit length tree).
  23746. */
  23747. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23748. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23749. n = s.heap[h];
  23750. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23751. if (bits > max_length) {
  23752. bits = max_length;
  23753. overflow++;
  23754. }
  23755. tree[n*2 + 1]/*.Len*/ = bits;
  23756. /* We overwrite tree[n].Dad which is no longer needed */
  23757. if (n > max_code) { continue; } /* not a leaf node */
  23758. s.bl_count[bits]++;
  23759. xbits = 0;
  23760. if (n >= base) {
  23761. xbits = extra[n-base];
  23762. }
  23763. f = tree[n * 2]/*.Freq*/;
  23764. s.opt_len += f * (bits + xbits);
  23765. if (has_stree) {
  23766. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23767. }
  23768. }
  23769. if (overflow === 0) { return; }
  23770. // Trace((stderr,"\nbit length overflow\n"));
  23771. /* This happens for example on obj2 and pic of the Calgary corpus */
  23772. /* Find the first bit length which could increase: */
  23773. do {
  23774. bits = max_length-1;
  23775. while (s.bl_count[bits] === 0) { bits--; }
  23776. s.bl_count[bits]--; /* move one leaf down the tree */
  23777. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23778. s.bl_count[max_length]--;
  23779. /* The brother of the overflow item also moves one step up,
  23780. * but this does not affect bl_count[max_length]
  23781. */
  23782. overflow -= 2;
  23783. } while (overflow > 0);
  23784. /* Now recompute all bit lengths, scanning in increasing frequency.
  23785. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23786. * lengths instead of fixing only the wrong ones. This idea is taken
  23787. * from 'ar' written by Haruhiko Okumura.)
  23788. */
  23789. for (bits = max_length; bits !== 0; bits--) {
  23790. n = s.bl_count[bits];
  23791. while (n !== 0) {
  23792. m = s.heap[--h];
  23793. if (m > max_code) { continue; }
  23794. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23795. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23796. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23797. tree[m*2 + 1]/*.Len*/ = bits;
  23798. }
  23799. n--;
  23800. }
  23801. }
  23802. }
  23803. /* ===========================================================================
  23804. * Generate the codes for a given tree and bit counts (which need not be
  23805. * optimal).
  23806. * IN assertion: the array bl_count contains the bit length statistics for
  23807. * the given tree and the field len is set for all tree elements.
  23808. * OUT assertion: the field code is set for all tree elements of non
  23809. * zero code length.
  23810. */
  23811. function gen_codes(tree, max_code, bl_count)
  23812. // ct_data *tree; /* the tree to decorate */
  23813. // int max_code; /* largest code with non zero frequency */
  23814. // ushf *bl_count; /* number of codes at each bit length */
  23815. {
  23816. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23817. var code = 0; /* running code value */
  23818. var bits; /* bit index */
  23819. var n; /* code index */
  23820. /* The distribution counts are first used to generate the code values
  23821. * without bit reversal.
  23822. */
  23823. for (bits = 1; bits <= MAX_BITS; bits++) {
  23824. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23825. }
  23826. /* Check that the bit counts in bl_count are consistent. The last code
  23827. * must be all ones.
  23828. */
  23829. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23830. // "inconsistent bit counts");
  23831. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23832. for (n = 0; n <= max_code; n++) {
  23833. var len = tree[n*2 + 1]/*.Len*/;
  23834. if (len === 0) { continue; }
  23835. /* Now reverse the bits */
  23836. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23837. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23838. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23839. }
  23840. }
  23841. /* ===========================================================================
  23842. * Initialize the various 'constant' tables.
  23843. */
  23844. function tr_static_init() {
  23845. var n; /* iterates over tree elements */
  23846. var bits; /* bit counter */
  23847. var length; /* length value */
  23848. var code; /* code value */
  23849. var dist; /* distance index */
  23850. var bl_count = new Array(MAX_BITS+1);
  23851. /* number of codes at each bit length for an optimal tree */
  23852. // do check in _tr_init()
  23853. //if (static_init_done) return;
  23854. /* For some embedded targets, global variables are not initialized: */
  23855. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23856. static_l_desc.static_tree = static_ltree;
  23857. static_l_desc.extra_bits = extra_lbits;
  23858. static_d_desc.static_tree = static_dtree;
  23859. static_d_desc.extra_bits = extra_dbits;
  23860. static_bl_desc.extra_bits = extra_blbits;
  23861. #endif*/
  23862. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23863. length = 0;
  23864. for (code = 0; code < LENGTH_CODES-1; code++) {
  23865. base_length[code] = length;
  23866. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23867. _length_code[length++] = code;
  23868. }
  23869. }
  23870. //Assert (length == 256, "tr_static_init: length != 256");
  23871. /* Note that the length 255 (match length 258) can be represented
  23872. * in two different ways: code 284 + 5 bits or code 285, so we
  23873. * overwrite length_code[255] to use the best encoding:
  23874. */
  23875. _length_code[length-1] = code;
  23876. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  23877. dist = 0;
  23878. for (code = 0 ; code < 16; code++) {
  23879. base_dist[code] = dist;
  23880. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  23881. _dist_code[dist++] = code;
  23882. }
  23883. }
  23884. //Assert (dist == 256, "tr_static_init: dist != 256");
  23885. dist >>= 7; /* from now on, all distances are divided by 128 */
  23886. for ( ; code < D_CODES; code++) {
  23887. base_dist[code] = dist << 7;
  23888. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  23889. _dist_code[256 + dist++] = code;
  23890. }
  23891. }
  23892. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  23893. /* Construct the codes of the static literal tree */
  23894. for (bits = 0; bits <= MAX_BITS; bits++) {
  23895. bl_count[bits] = 0;
  23896. }
  23897. n = 0;
  23898. while (n <= 143) {
  23899. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23900. n++;
  23901. bl_count[8]++;
  23902. }
  23903. while (n <= 255) {
  23904. static_ltree[n*2 + 1]/*.Len*/ = 9;
  23905. n++;
  23906. bl_count[9]++;
  23907. }
  23908. while (n <= 279) {
  23909. static_ltree[n*2 + 1]/*.Len*/ = 7;
  23910. n++;
  23911. bl_count[7]++;
  23912. }
  23913. while (n <= 287) {
  23914. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23915. n++;
  23916. bl_count[8]++;
  23917. }
  23918. /* Codes 286 and 287 do not exist, but we must include them in the
  23919. * tree construction to get a canonical Huffman tree (longest code
  23920. * all ones)
  23921. */
  23922. gen_codes(static_ltree, L_CODES+1, bl_count);
  23923. /* The static distance tree is trivial: */
  23924. for (n = 0; n < D_CODES; n++) {
  23925. static_dtree[n*2 + 1]/*.Len*/ = 5;
  23926. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  23927. }
  23928. // Now data ready and we can init static trees
  23929. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  23930. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  23931. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  23932. //static_init_done = true;
  23933. }
  23934. /* ===========================================================================
  23935. * Initialize a new block.
  23936. */
  23937. function init_block(s) {
  23938. var n; /* iterates over tree elements */
  23939. /* Initialize the trees. */
  23940. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  23941. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  23942. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  23943. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  23944. s.opt_len = s.static_len = 0;
  23945. s.last_lit = s.matches = 0;
  23946. }
  23947. /* ===========================================================================
  23948. * Flush the bit buffer and align the output on a byte boundary
  23949. */
  23950. function bi_windup(s)
  23951. {
  23952. if (s.bi_valid > 8) {
  23953. put_short(s, s.bi_buf);
  23954. } else if (s.bi_valid > 0) {
  23955. //put_byte(s, (Byte)s->bi_buf);
  23956. s.pending_buf[s.pending++] = s.bi_buf;
  23957. }
  23958. s.bi_buf = 0;
  23959. s.bi_valid = 0;
  23960. }
  23961. /* ===========================================================================
  23962. * Copy a stored block, storing first the length and its
  23963. * one's complement if requested.
  23964. */
  23965. function copy_block(s, buf, len, header)
  23966. //DeflateState *s;
  23967. //charf *buf; /* the input data */
  23968. //unsigned len; /* its length */
  23969. //int header; /* true if block header must be written */
  23970. {
  23971. bi_windup(s); /* align on byte boundary */
  23972. if (header) {
  23973. put_short(s, len);
  23974. put_short(s, ~len);
  23975. }
  23976. // while (len--) {
  23977. // put_byte(s, *buf++);
  23978. // }
  23979. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  23980. s.pending += len;
  23981. }
  23982. /* ===========================================================================
  23983. * Compares to subtrees, using the tree depth as tie breaker when
  23984. * the subtrees have equal frequency. This minimizes the worst case length.
  23985. */
  23986. function smaller(tree, n, m, depth) {
  23987. var _n2 = n*2;
  23988. var _m2 = m*2;
  23989. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  23990. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  23991. }
  23992. /* ===========================================================================
  23993. * Restore the heap property by moving down the tree starting at node k,
  23994. * exchanging a node with the smallest of its two sons if necessary, stopping
  23995. * when the heap property is re-established (each father smaller than its
  23996. * two sons).
  23997. */
  23998. function pqdownheap(s, tree, k)
  23999. // deflate_state *s;
  24000. // ct_data *tree; /* the tree to restore */
  24001. // int k; /* node to move down */
  24002. {
  24003. var v = s.heap[k];
  24004. var j = k << 1; /* left son of k */
  24005. while (j <= s.heap_len) {
  24006. /* Set j to the smallest of the two sons: */
  24007. if (j < s.heap_len &&
  24008. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24009. j++;
  24010. }
  24011. /* Exit if v is smaller than both sons */
  24012. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24013. /* Exchange v with the smallest son */
  24014. s.heap[k] = s.heap[j];
  24015. k = j;
  24016. /* And continue down the tree, setting j to the left son of k */
  24017. j <<= 1;
  24018. }
  24019. s.heap[k] = v;
  24020. }
  24021. // inlined manually
  24022. // var SMALLEST = 1;
  24023. /* ===========================================================================
  24024. * Send the block data compressed using the given Huffman trees
  24025. */
  24026. function compress_block(s, ltree, dtree)
  24027. // deflate_state *s;
  24028. // const ct_data *ltree; /* literal tree */
  24029. // const ct_data *dtree; /* distance tree */
  24030. {
  24031. var dist; /* distance of matched string */
  24032. var lc; /* match length or unmatched char (if dist == 0) */
  24033. var lx = 0; /* running index in l_buf */
  24034. var code; /* the code to send */
  24035. var extra; /* number of extra bits to send */
  24036. if (s.last_lit !== 0) {
  24037. do {
  24038. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24039. lc = s.pending_buf[s.l_buf + lx];
  24040. lx++;
  24041. if (dist === 0) {
  24042. send_code(s, lc, ltree); /* send a literal byte */
  24043. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24044. } else {
  24045. /* Here, lc is the match length - MIN_MATCH */
  24046. code = _length_code[lc];
  24047. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24048. extra = extra_lbits[code];
  24049. if (extra !== 0) {
  24050. lc -= base_length[code];
  24051. send_bits(s, lc, extra); /* send the extra length bits */
  24052. }
  24053. dist--; /* dist is now the match distance - 1 */
  24054. code = d_code(dist);
  24055. //Assert (code < D_CODES, "bad d_code");
  24056. send_code(s, code, dtree); /* send the distance code */
  24057. extra = extra_dbits[code];
  24058. if (extra !== 0) {
  24059. dist -= base_dist[code];
  24060. send_bits(s, dist, extra); /* send the extra distance bits */
  24061. }
  24062. } /* literal or match pair ? */
  24063. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24064. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24065. // "pendingBuf overflow");
  24066. } while (lx < s.last_lit);
  24067. }
  24068. send_code(s, END_BLOCK, ltree);
  24069. }
  24070. /* ===========================================================================
  24071. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24072. * Update the total bit length for the current block.
  24073. * IN assertion: the field freq is set for all tree elements.
  24074. * OUT assertions: the fields len and code are set to the optimal bit length
  24075. * and corresponding code. The length opt_len is updated; static_len is
  24076. * also updated if stree is not null. The field max_code is set.
  24077. */
  24078. function build_tree(s, desc)
  24079. // deflate_state *s;
  24080. // tree_desc *desc; /* the tree descriptor */
  24081. {
  24082. var tree = desc.dyn_tree;
  24083. var stree = desc.stat_desc.static_tree;
  24084. var has_stree = desc.stat_desc.has_stree;
  24085. var elems = desc.stat_desc.elems;
  24086. var n, m; /* iterate over heap elements */
  24087. var max_code = -1; /* largest code with non zero frequency */
  24088. var node; /* new node being created */
  24089. /* Construct the initial heap, with least frequent element in
  24090. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24091. * heap[0] is not used.
  24092. */
  24093. s.heap_len = 0;
  24094. s.heap_max = HEAP_SIZE;
  24095. for (n = 0; n < elems; n++) {
  24096. if (tree[n * 2]/*.Freq*/ !== 0) {
  24097. s.heap[++s.heap_len] = max_code = n;
  24098. s.depth[n] = 0;
  24099. } else {
  24100. tree[n*2 + 1]/*.Len*/ = 0;
  24101. }
  24102. }
  24103. /* The pkzip format requires that at least one distance code exists,
  24104. * and that at least one bit should be sent even if there is only one
  24105. * possible code. So to avoid special checks later on we force at least
  24106. * two codes of non zero frequency.
  24107. */
  24108. while (s.heap_len < 2) {
  24109. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24110. tree[node * 2]/*.Freq*/ = 1;
  24111. s.depth[node] = 0;
  24112. s.opt_len--;
  24113. if (has_stree) {
  24114. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24115. }
  24116. /* node is 0 or 1 so it does not have extra bits */
  24117. }
  24118. desc.max_code = max_code;
  24119. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24120. * establish sub-heaps of increasing lengths:
  24121. */
  24122. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24123. /* Construct the Huffman tree by repeatedly combining the least two
  24124. * frequent nodes.
  24125. */
  24126. node = elems; /* next internal node of the tree */
  24127. do {
  24128. //pqremove(s, tree, n); /* n = node of least frequency */
  24129. /*** pqremove ***/
  24130. n = s.heap[1/*SMALLEST*/];
  24131. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24132. pqdownheap(s, tree, 1/*SMALLEST*/);
  24133. /***/
  24134. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24135. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24136. s.heap[--s.heap_max] = m;
  24137. /* Create a new node father of n and m */
  24138. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24139. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24140. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24141. /* and insert the new node in the heap */
  24142. s.heap[1/*SMALLEST*/] = node++;
  24143. pqdownheap(s, tree, 1/*SMALLEST*/);
  24144. } while (s.heap_len >= 2);
  24145. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24146. /* At this point, the fields freq and dad are set. We can now
  24147. * generate the bit lengths.
  24148. */
  24149. gen_bitlen(s, desc);
  24150. /* The field len is now set, we can generate the bit codes */
  24151. gen_codes(tree, max_code, s.bl_count);
  24152. }
  24153. /* ===========================================================================
  24154. * Scan a literal or distance tree to determine the frequencies of the codes
  24155. * in the bit length tree.
  24156. */
  24157. function scan_tree(s, tree, max_code)
  24158. // deflate_state *s;
  24159. // ct_data *tree; /* the tree to be scanned */
  24160. // int max_code; /* and its largest code of non zero frequency */
  24161. {
  24162. var n; /* iterates over all tree elements */
  24163. var prevlen = -1; /* last emitted length */
  24164. var curlen; /* length of current code */
  24165. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24166. var count = 0; /* repeat count of the current code */
  24167. var max_count = 7; /* max repeat count */
  24168. var min_count = 4; /* min repeat count */
  24169. if (nextlen === 0) {
  24170. max_count = 138;
  24171. min_count = 3;
  24172. }
  24173. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24174. for (n = 0; n <= max_code; n++) {
  24175. curlen = nextlen;
  24176. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24177. if (++count < max_count && curlen === nextlen) {
  24178. continue;
  24179. } else if (count < min_count) {
  24180. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24181. } else if (curlen !== 0) {
  24182. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24183. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24184. } else if (count <= 10) {
  24185. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24186. } else {
  24187. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24188. }
  24189. count = 0;
  24190. prevlen = curlen;
  24191. if (nextlen === 0) {
  24192. max_count = 138;
  24193. min_count = 3;
  24194. } else if (curlen === nextlen) {
  24195. max_count = 6;
  24196. min_count = 3;
  24197. } else {
  24198. max_count = 7;
  24199. min_count = 4;
  24200. }
  24201. }
  24202. }
  24203. /* ===========================================================================
  24204. * Send a literal or distance tree in compressed form, using the codes in
  24205. * bl_tree.
  24206. */
  24207. function send_tree(s, tree, max_code)
  24208. // deflate_state *s;
  24209. // ct_data *tree; /* the tree to be scanned */
  24210. // int max_code; /* and its largest code of non zero frequency */
  24211. {
  24212. var n; /* iterates over all tree elements */
  24213. var prevlen = -1; /* last emitted length */
  24214. var curlen; /* length of current code */
  24215. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24216. var count = 0; /* repeat count of the current code */
  24217. var max_count = 7; /* max repeat count */
  24218. var min_count = 4; /* min repeat count */
  24219. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24220. if (nextlen === 0) {
  24221. max_count = 138;
  24222. min_count = 3;
  24223. }
  24224. for (n = 0; n <= max_code; n++) {
  24225. curlen = nextlen;
  24226. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24227. if (++count < max_count && curlen === nextlen) {
  24228. continue;
  24229. } else if (count < min_count) {
  24230. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24231. } else if (curlen !== 0) {
  24232. if (curlen !== prevlen) {
  24233. send_code(s, curlen, s.bl_tree);
  24234. count--;
  24235. }
  24236. //Assert(count >= 3 && count <= 6, " 3_6?");
  24237. send_code(s, REP_3_6, s.bl_tree);
  24238. send_bits(s, count-3, 2);
  24239. } else if (count <= 10) {
  24240. send_code(s, REPZ_3_10, s.bl_tree);
  24241. send_bits(s, count-3, 3);
  24242. } else {
  24243. send_code(s, REPZ_11_138, s.bl_tree);
  24244. send_bits(s, count-11, 7);
  24245. }
  24246. count = 0;
  24247. prevlen = curlen;
  24248. if (nextlen === 0) {
  24249. max_count = 138;
  24250. min_count = 3;
  24251. } else if (curlen === nextlen) {
  24252. max_count = 6;
  24253. min_count = 3;
  24254. } else {
  24255. max_count = 7;
  24256. min_count = 4;
  24257. }
  24258. }
  24259. }
  24260. /* ===========================================================================
  24261. * Construct the Huffman tree for the bit lengths and return the index in
  24262. * bl_order of the last bit length code to send.
  24263. */
  24264. function build_bl_tree(s) {
  24265. var max_blindex; /* index of last bit length code of non zero freq */
  24266. /* Determine the bit length frequencies for literal and distance trees */
  24267. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24268. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24269. /* Build the bit length tree: */
  24270. build_tree(s, s.bl_desc);
  24271. /* opt_len now includes the length of the tree representations, except
  24272. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24273. */
  24274. /* Determine the number of bit length codes to send. The pkzip format
  24275. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24276. * 3 but the actual value used is 4.)
  24277. */
  24278. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24279. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24280. break;
  24281. }
  24282. }
  24283. /* Update opt_len to include the bit length tree and counts */
  24284. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24285. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24286. // s->opt_len, s->static_len));
  24287. return max_blindex;
  24288. }
  24289. /* ===========================================================================
  24290. * Send the header for a block using dynamic Huffman trees: the counts, the
  24291. * lengths of the bit length codes, the literal tree and the distance tree.
  24292. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24293. */
  24294. function send_all_trees(s, lcodes, dcodes, blcodes)
  24295. // deflate_state *s;
  24296. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24297. {
  24298. var rank; /* index in bl_order */
  24299. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24300. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24301. // "too many codes");
  24302. //Tracev((stderr, "\nbl counts: "));
  24303. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24304. send_bits(s, dcodes-1, 5);
  24305. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24306. for (rank = 0; rank < blcodes; rank++) {
  24307. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24308. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24309. }
  24310. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24311. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24312. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24313. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24314. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24315. }
  24316. /* ===========================================================================
  24317. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24318. * - TEXT if the two conditions below are satisfied:
  24319. * a) There are no non-portable control characters belonging to the
  24320. * "black list" (0..6, 14..25, 28..31).
  24321. * b) There is at least one printable character belonging to the
  24322. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24323. * - BINARY otherwise.
  24324. * - The following partially-portable control characters form a
  24325. * "gray list" that is ignored in this detection algorithm:
  24326. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24327. * IN assertion: the fields Freq of dyn_ltree are set.
  24328. */
  24329. function detect_data_type(s) {
  24330. /* black_mask is the bit mask of black-listed bytes
  24331. * set bits 0..6, 14..25, and 28..31
  24332. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24333. */
  24334. var black_mask = 0xf3ffc07f;
  24335. var n;
  24336. /* Check for non-textual ("black-listed") bytes. */
  24337. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24338. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24339. return Z_BINARY;
  24340. }
  24341. }
  24342. /* Check for textual ("white-listed") bytes. */
  24343. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24344. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24345. return Z_TEXT;
  24346. }
  24347. for (n = 32; n < LITERALS; n++) {
  24348. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24349. return Z_TEXT;
  24350. }
  24351. }
  24352. /* There are no "black-listed" or "white-listed" bytes:
  24353. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24354. */
  24355. return Z_BINARY;
  24356. }
  24357. var static_init_done = false;
  24358. /* ===========================================================================
  24359. * Initialize the tree data structures for a new zlib stream.
  24360. */
  24361. function _tr_init(s)
  24362. {
  24363. if (!static_init_done) {
  24364. tr_static_init();
  24365. static_init_done = true;
  24366. }
  24367. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24368. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24369. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24370. s.bi_buf = 0;
  24371. s.bi_valid = 0;
  24372. /* Initialize the first block of the first file: */
  24373. init_block(s);
  24374. }
  24375. /* ===========================================================================
  24376. * Send a stored block
  24377. */
  24378. function _tr_stored_block(s, buf, stored_len, last)
  24379. //DeflateState *s;
  24380. //charf *buf; /* input block */
  24381. //ulg stored_len; /* length of input block */
  24382. //int last; /* one if this is the last block for a file */
  24383. {
  24384. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24385. copy_block(s, buf, stored_len, true); /* with header */
  24386. }
  24387. /* ===========================================================================
  24388. * Send one empty static block to give enough lookahead for inflate.
  24389. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24390. */
  24391. function _tr_align(s) {
  24392. send_bits(s, STATIC_TREES<<1, 3);
  24393. send_code(s, END_BLOCK, static_ltree);
  24394. bi_flush(s);
  24395. }
  24396. /* ===========================================================================
  24397. * Determine the best encoding for the current block: dynamic trees, static
  24398. * trees or store, and output the encoded block to the zip file.
  24399. */
  24400. function _tr_flush_block(s, buf, stored_len, last)
  24401. //DeflateState *s;
  24402. //charf *buf; /* input block, or NULL if too old */
  24403. //ulg stored_len; /* length of input block */
  24404. //int last; /* one if this is the last block for a file */
  24405. {
  24406. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24407. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24408. /* Build the Huffman trees unless a stored block is forced */
  24409. if (s.level > 0) {
  24410. /* Check if the file is binary or text */
  24411. if (s.strm.data_type === Z_UNKNOWN) {
  24412. s.strm.data_type = detect_data_type(s);
  24413. }
  24414. /* Construct the literal and distance trees */
  24415. build_tree(s, s.l_desc);
  24416. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24417. // s->static_len));
  24418. build_tree(s, s.d_desc);
  24419. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24420. // s->static_len));
  24421. /* At this point, opt_len and static_len are the total bit lengths of
  24422. * the compressed block data, excluding the tree representations.
  24423. */
  24424. /* Build the bit length tree for the above two trees, and get the index
  24425. * in bl_order of the last bit length code to send.
  24426. */
  24427. max_blindex = build_bl_tree(s);
  24428. /* Determine the best encoding. Compute the block lengths in bytes. */
  24429. opt_lenb = (s.opt_len+3+7) >>> 3;
  24430. static_lenb = (s.static_len+3+7) >>> 3;
  24431. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24432. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24433. // s->last_lit));
  24434. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24435. } else {
  24436. // Assert(buf != (char*)0, "lost buf");
  24437. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24438. }
  24439. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24440. /* 4: two words for the lengths */
  24441. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24442. * Otherwise we can't have processed more than WSIZE input bytes since
  24443. * the last block flush, because compression would have been
  24444. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24445. * transform a block into a stored block.
  24446. */
  24447. _tr_stored_block(s, buf, stored_len, last);
  24448. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24449. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24450. compress_block(s, static_ltree, static_dtree);
  24451. } else {
  24452. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24453. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24454. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24455. }
  24456. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24457. /* The above check is made mod 2^32, for files larger than 512 MB
  24458. * and uLong implemented on 32 bits.
  24459. */
  24460. init_block(s);
  24461. if (last) {
  24462. bi_windup(s);
  24463. }
  24464. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24465. // s->compressed_len-7*last));
  24466. }
  24467. /* ===========================================================================
  24468. * Save the match info and tally the frequency counts. Return true if
  24469. * the current block must be flushed.
  24470. */
  24471. function _tr_tally(s, dist, lc)
  24472. // deflate_state *s;
  24473. // unsigned dist; /* distance of matched string */
  24474. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24475. {
  24476. //var out_length, in_length, dcode;
  24477. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24478. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24479. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24480. s.last_lit++;
  24481. if (dist === 0) {
  24482. /* lc is the unmatched char */
  24483. s.dyn_ltree[lc*2]/*.Freq*/++;
  24484. } else {
  24485. s.matches++;
  24486. /* Here, lc is the match length - MIN_MATCH */
  24487. dist--; /* dist = match distance - 1 */
  24488. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24489. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24490. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24491. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24492. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24493. }
  24494. // (!) This block is disabled in zlib defailts,
  24495. // don't enable it for binary compatibility
  24496. //#ifdef TRUNCATE_BLOCK
  24497. // /* Try to guess if it is profitable to stop the current block here */
  24498. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24499. // /* Compute an upper bound for the compressed length */
  24500. // out_length = s.last_lit*8;
  24501. // in_length = s.strstart - s.block_start;
  24502. //
  24503. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24504. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24505. // }
  24506. // out_length >>>= 3;
  24507. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24508. // // s->last_lit, in_length, out_length,
  24509. // // 100L - out_length*100L/in_length));
  24510. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24511. // return true;
  24512. // }
  24513. // }
  24514. //#endif
  24515. return (s.last_lit === s.lit_bufsize-1);
  24516. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24517. * on 16 bit machines and because stored blocks are restricted to
  24518. * 64K-1 bytes.
  24519. */
  24520. }
  24521. exports._tr_init = _tr_init;
  24522. exports._tr_stored_block = _tr_stored_block;
  24523. exports._tr_flush_block = _tr_flush_block;
  24524. exports._tr_tally = _tr_tally;
  24525. exports._tr_align = _tr_align;
  24526. },{"../utils/common":70}],82:[function(require,module,exports){
  24527. 'use strict';
  24528. function ZStream() {
  24529. /* next input byte */
  24530. this.input = null; // JS specific, because we have no pointers
  24531. this.next_in = 0;
  24532. /* number of bytes available at input */
  24533. this.avail_in = 0;
  24534. /* total number of input bytes read so far */
  24535. this.total_in = 0;
  24536. /* next output byte should be put there */
  24537. this.output = null; // JS specific, because we have no pointers
  24538. this.next_out = 0;
  24539. /* remaining free space at output */
  24540. this.avail_out = 0;
  24541. /* total number of bytes output so far */
  24542. this.total_out = 0;
  24543. /* last error message, NULL if no error */
  24544. this.msg = ''/*Z_NULL*/;
  24545. /* not visible by applications */
  24546. this.state = null;
  24547. /* best guess about the data type: binary or text */
  24548. this.data_type = 2/*Z_UNKNOWN*/;
  24549. /* adler32 value of the uncompressed data */
  24550. this.adler = 0;
  24551. }
  24552. module.exports = ZStream;
  24553. },{}],83:[function(require,module,exports){
  24554. module.exports = require('./lib/retry');
  24555. },{"./lib/retry":84}],84:[function(require,module,exports){
  24556. var RetryOperation = require('./retry_operation');
  24557. exports.operation = function(options) {
  24558. var timeouts = exports.timeouts(options);
  24559. return new RetryOperation(timeouts);
  24560. };
  24561. exports.timeouts = function(options) {
  24562. if (options instanceof Array) {
  24563. return [].concat(options);
  24564. }
  24565. var opts = {
  24566. retries: 10,
  24567. factor: 2,
  24568. minTimeout: 1 * 1000,
  24569. maxTimeout: Infinity,
  24570. randomize: false
  24571. };
  24572. for (var key in options) {
  24573. opts[key] = options[key];
  24574. }
  24575. if (opts.minTimeout > opts.maxTimeout) {
  24576. throw new Error('minTimeout is greater than maxTimeout');
  24577. }
  24578. var timeouts = [];
  24579. for (var i = 0; i < opts.retries; i++) {
  24580. timeouts.push(this._createTimeout(i, opts));
  24581. }
  24582. // sort the array numerically ascending
  24583. timeouts.sort(function(a,b) {
  24584. return a - b;
  24585. });
  24586. return timeouts;
  24587. };
  24588. exports._createTimeout = function(attempt, opts) {
  24589. var random = (opts.randomize)
  24590. ? (Math.random() + 1)
  24591. : 1;
  24592. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24593. timeout = Math.min(timeout, opts.maxTimeout);
  24594. return timeout;
  24595. };
  24596. },{"./retry_operation":85}],85:[function(require,module,exports){
  24597. function RetryOperation(timeouts) {
  24598. this._timeouts = timeouts;
  24599. this._fn = null;
  24600. this._errors = [];
  24601. this._attempts = 1;
  24602. this._operationTimeout = null;
  24603. this._operationTimeoutCb = null;
  24604. this._timeout = null;
  24605. }
  24606. module.exports = RetryOperation;
  24607. RetryOperation.prototype.retry = function(err) {
  24608. if (this._timeout) {
  24609. clearTimeout(this._timeout);
  24610. }
  24611. if (!err) {
  24612. return false;
  24613. }
  24614. this._errors.push(err);
  24615. var timeout = this._timeouts.shift();
  24616. if (timeout === undefined) {
  24617. return false;
  24618. }
  24619. this._attempts++;
  24620. var self = this;
  24621. setTimeout(function() {
  24622. self._fn(self._attempts);
  24623. if (self._operationTimeoutCb) {
  24624. self._timeout = setTimeout(function() {
  24625. self._operationTimeoutCb(self._attempts);
  24626. }, self._operationTimeout);
  24627. }
  24628. }, timeout);
  24629. return true;
  24630. };
  24631. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24632. this._fn = fn;
  24633. if (timeoutOps) {
  24634. if (timeoutOps.timeout) {
  24635. this._operationTimeout = timeoutOps.timeout;
  24636. }
  24637. if (timeoutOps.cb) {
  24638. this._operationTimeoutCb = timeoutOps.cb;
  24639. }
  24640. }
  24641. this._fn(this._attempts);
  24642. var self = this;
  24643. if (this._operationTimeoutCb) {
  24644. this._timeout = setTimeout(function() {
  24645. self._operationTimeoutCb();
  24646. }, self._operationTimeout);
  24647. }
  24648. };
  24649. RetryOperation.prototype.try = function(fn) {
  24650. console.log('Using RetryOperation.try() is deprecated');
  24651. this.attempt(fn);
  24652. };
  24653. RetryOperation.prototype.start = function(fn) {
  24654. console.log('Using RetryOperation.start() is deprecated');
  24655. this.attempt(fn);
  24656. };
  24657. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24658. RetryOperation.prototype.errors = function() {
  24659. return this._errors;
  24660. };
  24661. RetryOperation.prototype.attempts = function() {
  24662. return this._attempts;
  24663. };
  24664. RetryOperation.prototype.mainError = function() {
  24665. if (this._errors.length === 0) {
  24666. return null;
  24667. }
  24668. var counts = {};
  24669. var mainError = null;
  24670. var mainErrorCount = 0;
  24671. for (var i = 0; i < this._errors.length; i++) {
  24672. var error = this._errors[i];
  24673. var message = error.message;
  24674. var count = (counts[message] || 0) + 1;
  24675. counts[message] = count;
  24676. if (count >= mainErrorCount) {
  24677. mainError = error;
  24678. mainErrorCount = count;
  24679. }
  24680. }
  24681. return mainError;
  24682. };
  24683. },{}],86:[function(require,module,exports){
  24684. module.exports = function arrayEquals(array) {
  24685. // if the other array is a falsy value, return
  24686. if (!array)
  24687. return false;
  24688. // compare lengths - can save a lot of time
  24689. if (this.length != array.length)
  24690. return false;
  24691. for (var i = 0, l = this.length; i < l; i++) {
  24692. // Check if we have nested arrays
  24693. if (this[i] instanceof Array && array[i] instanceof Array) {
  24694. // recurse into the nested arrays
  24695. if (!arrayEquals.apply(this[i], [array[i]]))
  24696. return false;
  24697. } else if (this[i] != array[i]) {
  24698. // Warning - two different object instances will never be equal:
  24699. // {x:20} != {x:20}
  24700. return false;
  24701. }
  24702. }
  24703. return true;
  24704. }
  24705. },{}],87:[function(require,module,exports){
  24706. exports.Interop = require('./interop');
  24707. },{"./interop":88}],88:[function(require,module,exports){
  24708. "use strict";
  24709. var transform = require('./transform');
  24710. var arrayEquals = require('./array-equals');
  24711. function Interop() {
  24712. /**
  24713. * This map holds the most recent Unified Plan offer/answer SDP that was
  24714. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24715. * the SDP string as values.
  24716. *
  24717. * @type {{}}
  24718. */
  24719. this.cache = {};
  24720. }
  24721. module.exports = Interop;
  24722. /**
  24723. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24724. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24725. * application.
  24726. *
  24727. * @param desc
  24728. * @returns {*}
  24729. */
  24730. Interop.prototype.toPlanB = function(desc) {
  24731. //#region Preliminary input validation.
  24732. if (typeof desc !== 'object' || desc === null ||
  24733. typeof desc.sdp !== 'string') {
  24734. console.warn('An empty description was passed as an argument.');
  24735. return desc;
  24736. }
  24737. // Objectify the SDP for easier manipulation.
  24738. var session = transform.parse(desc.sdp);
  24739. // If the SDP contains no media, there's nothing to transform.
  24740. if (typeof session.media === 'undefined' ||
  24741. !Array.isArray(session.media) || session.media.length === 0) {
  24742. console.warn('The description has no media.');
  24743. return desc;
  24744. }
  24745. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24746. // SDP has a video, an audio and a data "channel" at most.
  24747. if (session.media.length <= 3 && session.media.every(function(m) {
  24748. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24749. })) {
  24750. console.warn('This description does not look like Unified Plan.');
  24751. return desc;
  24752. }
  24753. //#endregion
  24754. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24755. // -> Unified Plan transformation.
  24756. this.cache[desc.type] = desc.sdp;
  24757. //#region Convert from Unified Plan to Plan B.
  24758. // We rebuild the session.media array.
  24759. var media = session.media;
  24760. session.media = [];
  24761. // Associative array that maps channel types to channel objects for fast
  24762. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24763. // obj.
  24764. var type2bl = {};
  24765. // Used to build the group:BUNDLE value after the channels construction
  24766. // loop.
  24767. var types = [];
  24768. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24769. media.forEach(function(unifiedLine) {
  24770. // rtcp-mux is required in the Plan B SDP.
  24771. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  24772. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  24773. unifiedLine.direction !== 'inactive') {
  24774. throw new Error('Cannot convert to Plan B because m-lines ' +
  24775. 'without the rtcp-mux attribute were found.');
  24776. }
  24777. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  24778. // as the channel basis.
  24779. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  24780. type2bl[unifiedLine.type] = unifiedLine;
  24781. }
  24782. // Add sources to the channel and handle a=msid.
  24783. if (typeof unifiedLine.sources === 'object') {
  24784. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  24785. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  24786. type2bl[unifiedLine.type].sources = {};
  24787. // Assign the sources to the channel.
  24788. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  24789. if (typeof unifiedLine.msid !== 'undefined') {
  24790. // In Plan B the msid is an SSRC attribute. Also, we don't
  24791. // care about the obsolete label and mslabel attributes.
  24792. //
  24793. // Note that it is not guaranteed that the unifiedLine will have
  24794. // an msid. recvonly channels in particular don't have one.
  24795. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  24796. }
  24797. // NOTE ssrcs in ssrc groups will share msids, as
  24798. // draft-uberti-rtcweb-plan-00 mandates.
  24799. });
  24800. }
  24801. // Add ssrc groups to the channel.
  24802. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  24803. Array.isArray(unifiedLine.ssrcGroups)) {
  24804. // Create the ssrcGroups array, if it's not defined.
  24805. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  24806. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  24807. type2bl[unifiedLine.type].ssrcGroups = [];
  24808. }
  24809. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  24810. }
  24811. if (type2bl[unifiedLine.type] === unifiedLine) {
  24812. // Copy ICE related stuff from the principal media line.
  24813. unifiedLine.candidates = media[0].candidates;
  24814. unifiedLine.iceUfrag = media[0].iceUfrag;
  24815. unifiedLine.icePwd = media[0].icePwd;
  24816. unifiedLine.fingerprint = media[0].fingerprint;
  24817. // Plan B mids are in ['audio', 'video', 'data']
  24818. unifiedLine.mid = unifiedLine.type;
  24819. // Plan B doesn't support/need the bundle-only attribute.
  24820. delete unifiedLine.bundleOnly;
  24821. // In Plan B the msid is an SSRC attribute.
  24822. delete unifiedLine.msid;
  24823. // Used to build the group:BUNDLE value after this loop.
  24824. types.push(unifiedLine.type);
  24825. // Add the channel to the new media array.
  24826. session.media.push(unifiedLine);
  24827. }
  24828. });
  24829. // We regenerate the BUNDLE group with the new mids.
  24830. session.groups.some(function(group) {
  24831. if (group.type === 'BUNDLE') {
  24832. group.mids = types.join(' ');
  24833. return true;
  24834. }
  24835. });
  24836. // msid semantic
  24837. session.msidSemantic = {
  24838. semantic: 'WMS',
  24839. token: '*'
  24840. };
  24841. var resStr = transform.write(session);
  24842. return new RTCSessionDescription({
  24843. type: desc.type,
  24844. sdp: resStr
  24845. });
  24846. //#endregion
  24847. };
  24848. /**
  24849. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24850. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24851. * to FF.
  24852. *
  24853. * @param desc
  24854. * @returns {*}
  24855. */
  24856. Interop.prototype.toUnifiedPlan = function(desc) {
  24857. //#region Preliminary input validation.
  24858. if (typeof desc !== 'object' || desc === null ||
  24859. typeof desc.sdp !== 'string') {
  24860. console.warn('An empty description was passed as an argument.');
  24861. return desc;
  24862. }
  24863. var session = transform.parse(desc.sdp);
  24864. // If the SDP contains no media, there's nothing to transform.
  24865. if (typeof session.media === 'undefined' ||
  24866. !Array.isArray(session.media) || session.media.length === 0) {
  24867. console.warn('The description has no media.');
  24868. return desc;
  24869. }
  24870. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  24871. // a video, an audio and a data "channel" at most.
  24872. if (session.media.length > 3 || !session.media.every(function(m) {
  24873. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24874. })) {
  24875. console.warn('This description does not look like Plan B.');
  24876. return desc;
  24877. }
  24878. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  24879. var mids = [];
  24880. session.media.forEach(function(m) {
  24881. mids.push(m.mid);
  24882. });
  24883. var hasBundle = false;
  24884. if (typeof session.groups !== 'undefined' &&
  24885. Array.isArray(session.groups)) {
  24886. hasBundle = session.groups.every(function(g) {
  24887. return g.type !== 'BUNDLE' ||
  24888. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  24889. });
  24890. }
  24891. if (!hasBundle) {
  24892. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  24893. " are not bundled were found.");
  24894. }
  24895. //#endregion
  24896. //#region Convert from Plan B to Unified Plan.
  24897. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  24898. // rebuild an equivalent Unified Plan offer/answer.
  24899. //
  24900. // For example, if this is a local answer (in Unified Plan style) that we
  24901. // convert to Plan B prior to handing it over to the application (the
  24902. // PeerConnection wrapper called us, for instance, after a successful
  24903. // createAnswer), we want to remember the m-line at which we've seen the
  24904. // (local) SSRC. That's because when the application wants to do call the
  24905. // SLD method, forcing us to do the inverse transformation (from Plan B to
  24906. // Unified Plan), we need to know to which m-line to assign the (local)
  24907. // SSRC. We also need to know all the other m-lines that the original
  24908. // answer had and include them in the transformed answer as well.
  24909. //
  24910. // Another example is if this is a remote offer that we convert to Plan B
  24911. // prior to giving it to the application, we want to remember the mid at
  24912. // which we've seen the (remote) SSRC.
  24913. //
  24914. // In the iteration that follows, we use the cached Unified Plan (if it
  24915. // exists) to assign mids to ssrcs.
  24916. var cached;
  24917. if (typeof this.cache[desc.type] !== 'undefined') {
  24918. cached = transform.parse(this.cache[desc.type]);
  24919. }
  24920. // A helper map that sends mids to m-line objects. We use it later to
  24921. // rebuild the Unified Plan style session.media array.
  24922. var mid2ul = {};
  24923. session.media.forEach(function(bLine) {
  24924. if ((typeof bLine.rtcpMux !== 'string' ||
  24925. bLine.rtcpMux !== 'rtcp-mux') &&
  24926. bLine.direction !== 'inactive') {
  24927. throw new Error("Cannot convert to Unified Plan because m-lines " +
  24928. "without the rtcp-mux attribute were found.");
  24929. }
  24930. // With rtcp-mux and bundle all the channels should have the same ICE
  24931. // stuff.
  24932. var sources = bLine.sources;
  24933. var ssrcGroups = bLine.ssrcGroups;
  24934. var candidates = bLine.candidates;
  24935. var iceUfrag = bLine.iceUfrag;
  24936. var icePwd = bLine.icePwd;
  24937. var fingerprint = bLine.fingerprint;
  24938. var port = bLine.port;
  24939. // We'll use the "bLine" object as a prototype for each new "mLine"
  24940. // that we create, but first we need to clean it up a bit.
  24941. delete bLine.sources;
  24942. delete bLine.ssrcGroups;
  24943. delete bLine.candidates;
  24944. delete bLine.iceUfrag;
  24945. delete bLine.icePwd;
  24946. delete bLine.fingerprint;
  24947. delete bLine.port;
  24948. delete bLine.mid;
  24949. // inverted ssrc group map
  24950. var ssrc2group = {};
  24951. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  24952. ssrcGroups.forEach(function (ssrcGroup) {
  24953. // TODO(gp) find out how to receive simulcast with FF. For the
  24954. // time being, hide it.
  24955. if (ssrcGroup.semantics === 'SIM') {
  24956. return;
  24957. }
  24958. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24959. Array.isArray(ssrcGroup.ssrcs)) {
  24960. ssrcGroup.ssrcs.forEach(function (ssrc) {
  24961. if (typeof ssrc2group[ssrc] === 'undefined') {
  24962. ssrc2group[ssrc] = [];
  24963. }
  24964. ssrc2group[ssrc].push(ssrcGroup);
  24965. });
  24966. }
  24967. });
  24968. }
  24969. // ssrc to m-line index.
  24970. var ssrc2ml = {};
  24971. if (typeof sources === 'object') {
  24972. // Explode the Plan B channel sources with one m-line per source.
  24973. Object.keys(sources).forEach(function(ssrc) {
  24974. // The (unified) m-line for this SSRC. We either create it from
  24975. // scratch or, if it's a grouped SSRC, we re-use a related
  24976. // mline. In other words, if the source is grouped with another
  24977. // source, put the two together in the same m-line.
  24978. var unifiedLine;
  24979. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  24980. Array.isArray(ssrc2group[ssrc])) {
  24981. ssrc2group[ssrc].some(function (ssrcGroup) {
  24982. // ssrcGroup.ssrcs *is* an Array, no need to check
  24983. // again here.
  24984. return ssrcGroup.ssrcs.some(function (related) {
  24985. if (typeof ssrc2ml[related] === 'object') {
  24986. unifiedLine = ssrc2ml[related];
  24987. return true;
  24988. }
  24989. });
  24990. });
  24991. }
  24992. if (typeof unifiedLine === 'object') {
  24993. // the m-line already exists. Just add the source.
  24994. unifiedLine.sources[ssrc] = sources[ssrc];
  24995. delete sources[ssrc].msid;
  24996. } else {
  24997. // Use the "bLine" as a prototype for the "unifiedLine".
  24998. unifiedLine = Object.create(bLine);
  24999. ssrc2ml[ssrc] = unifiedLine;
  25000. if (typeof sources[ssrc].msid !== 'undefined') {
  25001. // Assign the msid of the source to the m-line. Note
  25002. // that it is not guaranteed that the source will have
  25003. // msid. In particular "recvonly" sources don't have an
  25004. // msid. Note that "recvonly" is a term only defined
  25005. // for m-lines.
  25006. unifiedLine.msid = sources[ssrc].msid;
  25007. delete sources[ssrc].msid;
  25008. }
  25009. // We assign one SSRC per media line.
  25010. unifiedLine.sources = {};
  25011. unifiedLine.sources[ssrc] = sources[ssrc];
  25012. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25013. // Use the cached Unified Plan SDP (if it exists) to assign
  25014. // SSRCs to mids.
  25015. if (typeof cached !== 'undefined' &&
  25016. typeof cached.media !== 'undefined' &&
  25017. Array.isArray(cached.media)) {
  25018. cached.media.forEach(function (m) {
  25019. if (typeof m.sources === 'object') {
  25020. Object.keys(m.sources).forEach(function (s) {
  25021. if (s === ssrc) {
  25022. unifiedLine.mid = m.mid;
  25023. }
  25024. });
  25025. }
  25026. });
  25027. }
  25028. if (typeof unifiedLine.mid === 'undefined') {
  25029. // If this is an SSRC that we see for the first time
  25030. // assign it a new mid. This is typically the case when
  25031. // this method is called to transform a remote
  25032. // description for the first time or when there is a
  25033. // new SSRC in the remote description because a new
  25034. // peer has joined the conference. Local SSRCs should
  25035. // have already been added to the map in the toPlanB
  25036. // method.
  25037. //
  25038. // Because FF generates answers in Unified Plan style,
  25039. // we MUST already have a cached answer with all the
  25040. // local SSRCs mapped to some m-line/mid.
  25041. if (desc.type === 'answer') {
  25042. throw new Error("An unmapped SSRC was found.");
  25043. }
  25044. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25045. }
  25046. // Include the candidates in the 1st media line.
  25047. unifiedLine.candidates = candidates;
  25048. unifiedLine.iceUfrag = iceUfrag;
  25049. unifiedLine.icePwd = icePwd;
  25050. unifiedLine.fingerprint = fingerprint;
  25051. unifiedLine.port = port;
  25052. mid2ul[unifiedLine.mid] = unifiedLine;
  25053. }
  25054. });
  25055. }
  25056. });
  25057. // Rebuild the media array in the right order and add the missing mLines
  25058. // (missing from the Plan B SDP).
  25059. session.media = [];
  25060. mids = []; // reuse
  25061. if (desc.type === 'answer') {
  25062. // The media lines in the answer must match the media lines in the
  25063. // offer. The order is important too. Here we assume that Firefox is the
  25064. // answerer, so we merely have to use the reconstructed (unified) answer
  25065. // to update the cached (unified) answer accordingly.
  25066. //
  25067. // In the general case, one would have to use the cached (unified) offer
  25068. // to find the m-lines that are missing from the reconstructed answer,
  25069. // potentially grabbing them from the cached (unified) answer. One has
  25070. // to be carefull with this approach because inactive m-lines do not
  25071. // always have an mid, making it tricky (impossible?) to find where
  25072. // exactly and which m-lines are missing from the reconstructed answer.
  25073. for (var i = 0; i < cached.media.length; i++) {
  25074. var unifiedLine = cached.media[i];
  25075. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25076. // The mid isn't in the reconstructed (unified) answer.
  25077. // This is either a (unified) m-line containing a remote
  25078. // track only, or a (unified) m-line containing a remote
  25079. // track and a local track that has been removed.
  25080. // In either case, it MUST exist in the cached
  25081. // (unified) answer.
  25082. //
  25083. // In case this is a removed local track, clean-up
  25084. // the (unified) m-line and make sure it's 'recvonly' or
  25085. // 'inactive'.
  25086. delete unifiedLine.msid;
  25087. delete unifiedLine.sources;
  25088. delete unifiedLine.ssrcGroups;
  25089. if (!unifiedLine.direction
  25090. || unifiedLine.direction === 'sendrecv')
  25091. unifiedLine.direction = 'recvonly';
  25092. if (!unifiedLine.direction
  25093. || unifiedLine.direction === 'sendonly')
  25094. unifiedLine.direction = 'inactive';
  25095. } else {
  25096. // This is an (unified) m-line/channel that contains a local
  25097. // track (sendrecv or sendonly channel) or it's a unified
  25098. // recvonly m-line/channel. In either case, since we're
  25099. // going from PlanB -> Unified Plan this m-line MUST
  25100. // exist in the cached answer.
  25101. }
  25102. session.media.push(unifiedLine);
  25103. if (typeof unifiedLine.mid === 'string') {
  25104. // inactive lines don't/may not have an mid.
  25105. mids.push(unifiedLine.mid);
  25106. }
  25107. }
  25108. } else {
  25109. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25110. // under any circumstances. If we are no longer interested in sending a
  25111. // track, we just remove the msid and ssrc attributes and set it to
  25112. // either a=recvonly (as the reofferer, we must use recvonly if the
  25113. // other side was previously sending on the m-section, but we can also
  25114. // leave the possibility open if it wasn't previously in use), or
  25115. // a=inacive.
  25116. if (typeof cached !== 'undefined' &&
  25117. typeof cached.media !== 'undefined' &&
  25118. Array.isArray(cached.media)) {
  25119. cached.media.forEach(function(unifiedLine) {
  25120. mids.push(unifiedLine.mid);
  25121. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25122. session.media.push(mid2ul[unifiedLine.mid]);
  25123. } else {
  25124. delete unifiedLine.msid;
  25125. delete unifiedLine.sources;
  25126. delete unifiedLine.ssrcGroups;
  25127. if (!unifiedLine.direction
  25128. || unifiedLine.direction === 'sendrecv')
  25129. unifiedLine.direction = 'recvonly';
  25130. if (!unifiedLine.direction
  25131. || unifiedLine.direction === 'sendonly')
  25132. unifiedLine.direction = 'inactive';
  25133. session.media.push(unifiedLine);
  25134. }
  25135. });
  25136. }
  25137. // Add all the remaining (new) m-lines of the transformed SDP.
  25138. Object.keys(mid2ul).forEach(function(mid) {
  25139. if (mids.indexOf(mid) === -1) {
  25140. mids.push(mid);
  25141. if (typeof mid2ul[mid].direction === 'recvonly') {
  25142. // This is a remote recvonly channel. Add its SSRC to the
  25143. // appropriate sendrecv or sendonly channel.
  25144. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25145. session.media.some(function (unifiedLine) {
  25146. if ((unifiedLine.direction === 'sendrecv' ||
  25147. unifiedLine.direction === 'sendonly') &&
  25148. unifiedLine.type === mid2ul[mid].type) {
  25149. // mid2ul[mid] shouldn't have any ssrc-groups
  25150. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25151. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25152. });
  25153. return true;
  25154. }
  25155. });
  25156. } else {
  25157. session.media.push(mid2ul[mid]);
  25158. }
  25159. }
  25160. });
  25161. }
  25162. // We regenerate the BUNDLE group (since we regenerated the mids)
  25163. session.groups.some(function(group) {
  25164. if (group.type === 'BUNDLE') {
  25165. group.mids = mids.join(' ');
  25166. return true;
  25167. }
  25168. });
  25169. // msid semantic
  25170. session.msidSemantic = {
  25171. semantic: 'WMS',
  25172. token: '*'
  25173. };
  25174. var resStr = transform.write(session);
  25175. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25176. // function.
  25177. this.cache[desc.type] = resStr;
  25178. return new RTCSessionDescription({
  25179. type: desc.type,
  25180. sdp: resStr
  25181. });
  25182. //#endregion
  25183. };
  25184. },{"./array-equals":86,"./transform":89}],89:[function(require,module,exports){
  25185. var transform = require('sdp-transform');
  25186. exports.write = function(session, opts) {
  25187. if (typeof session !== 'undefined' &&
  25188. typeof session.media !== 'undefined' &&
  25189. Array.isArray(session.media)) {
  25190. session.media.forEach(function (mLine) {
  25191. // expand sources to ssrcs
  25192. if (typeof mLine.sources !== 'undefined' &&
  25193. Object.keys(mLine.sources).length !== 0) {
  25194. mLine.ssrcs = [];
  25195. Object.keys(mLine.sources).forEach(function (ssrc) {
  25196. var source = mLine.sources[ssrc];
  25197. Object.keys(source).forEach(function (attribute) {
  25198. mLine.ssrcs.push({
  25199. id: ssrc,
  25200. attribute: attribute,
  25201. value: source[attribute]
  25202. });
  25203. });
  25204. });
  25205. delete mLine.sources;
  25206. }
  25207. // join ssrcs in ssrc groups
  25208. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25209. Array.isArray(mLine.ssrcGroups)) {
  25210. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25211. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25212. Array.isArray(ssrcGroup.ssrcs)) {
  25213. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25214. }
  25215. });
  25216. }
  25217. });
  25218. }
  25219. // join group mids
  25220. if (typeof session !== 'undefined' &&
  25221. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25222. session.groups.forEach(function (g) {
  25223. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25224. g.mids = g.mids.join(' ');
  25225. }
  25226. });
  25227. }
  25228. return transform.write(session, opts);
  25229. };
  25230. exports.parse = function(sdp) {
  25231. var session = transform.parse(sdp);
  25232. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25233. Array.isArray(session.media)) {
  25234. session.media.forEach(function (mLine) {
  25235. // group sources attributes by ssrc
  25236. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25237. mLine.sources = {};
  25238. mLine.ssrcs.forEach(function (ssrc) {
  25239. if (!mLine.sources[ssrc.id])
  25240. mLine.sources[ssrc.id] = {};
  25241. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25242. });
  25243. delete mLine.ssrcs;
  25244. }
  25245. // split ssrcs in ssrc groups
  25246. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25247. Array.isArray(mLine.ssrcGroups)) {
  25248. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25249. if (typeof ssrcGroup.ssrcs === 'string') {
  25250. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25251. }
  25252. });
  25253. }
  25254. });
  25255. }
  25256. // split group mids
  25257. if (typeof session !== 'undefined' &&
  25258. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25259. session.groups.forEach(function (g) {
  25260. if (typeof g.mids === 'string') {
  25261. g.mids = g.mids.split(' ');
  25262. }
  25263. });
  25264. }
  25265. return session;
  25266. };
  25267. },{"sdp-transform":91}],90:[function(require,module,exports){
  25268. var grammar = module.exports = {
  25269. v: [{
  25270. name: 'version',
  25271. reg: /^(\d*)$/
  25272. }],
  25273. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25274. // NB: sessionId will be a String in most cases because it is huge
  25275. name: 'origin',
  25276. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25277. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25278. format: "%s %s %d %s IP%d %s"
  25279. }],
  25280. // default parsing of these only (though some of these feel outdated)
  25281. s: [{ name: 'name' }],
  25282. i: [{ name: 'description' }],
  25283. u: [{ name: 'uri' }],
  25284. e: [{ name: 'email' }],
  25285. p: [{ name: 'phone' }],
  25286. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25287. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25288. //k: [{}], // outdated thing ignored
  25289. t: [{ //t=0 0
  25290. name: 'timing',
  25291. reg: /^(\d*) (\d*)/,
  25292. names: ['start', 'stop'],
  25293. format: "%d %d"
  25294. }],
  25295. c: [{ //c=IN IP4 10.47.197.26
  25296. name: 'connection',
  25297. reg: /^IN IP(\d) (\S*)/,
  25298. names: ['version', 'ip'],
  25299. format: "IN IP%d %s"
  25300. }],
  25301. b: [{ //b=AS:4000
  25302. push: 'bandwidth',
  25303. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25304. names: ['type', 'limit'],
  25305. format: "%s:%s"
  25306. }],
  25307. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25308. // NB: special - pushes to session
  25309. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25310. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25311. names: ['type', 'port', 'protocol', 'payloads'],
  25312. format: "%s %d %s %s"
  25313. }],
  25314. a: [
  25315. { //a=rtpmap:110 opus/48000/2
  25316. push: 'rtp',
  25317. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25318. names: ['payload', 'codec', 'rate', 'encoding'],
  25319. format: function (o) {
  25320. return (o.encoding) ?
  25321. "rtpmap:%d %s/%s/%s":
  25322. "rtpmap:%d %s/%s";
  25323. }
  25324. },
  25325. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25326. push: 'fmtp',
  25327. reg: /^fmtp:(\d*) (\S*)/,
  25328. names: ['payload', 'config'],
  25329. format: "fmtp:%d %s"
  25330. },
  25331. { //a=control:streamid=0
  25332. name: 'control',
  25333. reg: /^control:(.*)/,
  25334. format: "control:%s"
  25335. },
  25336. { //a=rtcp:65179 IN IP4 193.84.77.194
  25337. name: 'rtcp',
  25338. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25339. names: ['port', 'netType', 'ipVer', 'address'],
  25340. format: function (o) {
  25341. return (o.address != null) ?
  25342. "rtcp:%d %s IP%d %s":
  25343. "rtcp:%d";
  25344. }
  25345. },
  25346. { //a=rtcp-fb:98 trr-int 100
  25347. push: 'rtcpFbTrrInt',
  25348. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25349. names: ['payload', 'value'],
  25350. format: "rtcp-fb:%d trr-int %d"
  25351. },
  25352. { //a=rtcp-fb:98 nack rpsi
  25353. push: 'rtcpFb',
  25354. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25355. names: ['payload', 'type', 'subtype'],
  25356. format: function (o) {
  25357. return (o.subtype != null) ?
  25358. "rtcp-fb:%s %s %s":
  25359. "rtcp-fb:%s %s";
  25360. }
  25361. },
  25362. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25363. //a=extmap:1/recvonly URI-gps-string
  25364. push: 'ext',
  25365. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25366. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25367. format: function (o) {
  25368. return (o.config != null) ?
  25369. "extmap:%s %s %s":
  25370. "extmap:%s %s";
  25371. }
  25372. },
  25373. {
  25374. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25375. push: 'crypto',
  25376. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25377. names: ['id', 'suite', 'config', 'sessionConfig'],
  25378. format: function (o) {
  25379. return (o.sessionConfig != null) ?
  25380. "crypto:%d %s %s %s":
  25381. "crypto:%d %s %s";
  25382. }
  25383. },
  25384. { //a=setup:actpass
  25385. name: 'setup',
  25386. reg: /^setup:(\w*)/,
  25387. format: "setup:%s"
  25388. },
  25389. { //a=mid:1
  25390. name: 'mid',
  25391. reg: /^mid:([^\s]*)/,
  25392. format: "mid:%s"
  25393. },
  25394. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25395. name: 'msid',
  25396. reg: /^msid:(.*)/,
  25397. format: "msid:%s"
  25398. },
  25399. { //a=ptime:20
  25400. name: 'ptime',
  25401. reg: /^ptime:(\d*)/,
  25402. format: "ptime:%d"
  25403. },
  25404. { //a=maxptime:60
  25405. name: 'maxptime',
  25406. reg: /^maxptime:(\d*)/,
  25407. format: "maxptime:%d"
  25408. },
  25409. { //a=sendrecv
  25410. name: 'direction',
  25411. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25412. },
  25413. { //a=ice-lite
  25414. name: 'icelite',
  25415. reg: /^(ice-lite)/
  25416. },
  25417. { //a=ice-ufrag:F7gI
  25418. name: 'iceUfrag',
  25419. reg: /^ice-ufrag:(\S*)/,
  25420. format: "ice-ufrag:%s"
  25421. },
  25422. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25423. name: 'icePwd',
  25424. reg: /^ice-pwd:(\S*)/,
  25425. format: "ice-pwd:%s"
  25426. },
  25427. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25428. name: 'fingerprint',
  25429. reg: /^fingerprint:(\S*) (\S*)/,
  25430. names: ['type', 'hash'],
  25431. format: "fingerprint:%s %s"
  25432. },
  25433. {
  25434. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25435. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25436. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25437. push:'candidates',
  25438. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25439. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25440. format: function (o) {
  25441. var str = "candidate:%s %d %s %d %s %d typ %s";
  25442. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25443. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25444. if (o.generation != null) {
  25445. str += " generation %d";
  25446. }
  25447. return str;
  25448. }
  25449. },
  25450. { //a=end-of-candidates (keep after the candidates line for readability)
  25451. name: 'endOfCandidates',
  25452. reg: /^(end-of-candidates)/
  25453. },
  25454. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25455. name: 'remoteCandidates',
  25456. reg: /^remote-candidates:(.*)/,
  25457. format: "remote-candidates:%s"
  25458. },
  25459. { //a=ice-options:google-ice
  25460. name: 'iceOptions',
  25461. reg: /^ice-options:(\S*)/,
  25462. format: "ice-options:%s"
  25463. },
  25464. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25465. push: "ssrcs",
  25466. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25467. names: ['id', 'attribute', 'value'],
  25468. format: "ssrc:%d %s:%s"
  25469. },
  25470. { //a=ssrc-group:FEC 1 2
  25471. push: "ssrcGroups",
  25472. reg: /^ssrc-group:(\w*) (.*)/,
  25473. names: ['semantics', 'ssrcs'],
  25474. format: "ssrc-group:%s %s"
  25475. },
  25476. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25477. name: "msidSemantic",
  25478. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25479. names: ['semantic', 'token'],
  25480. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25481. },
  25482. { //a=group:BUNDLE audio video
  25483. push: 'groups',
  25484. reg: /^group:(\w*) (.*)/,
  25485. names: ['type', 'mids'],
  25486. format: "group:%s %s"
  25487. },
  25488. { //a=rtcp-mux
  25489. name: 'rtcpMux',
  25490. reg: /^(rtcp-mux)/
  25491. },
  25492. { //a=rtcp-rsize
  25493. name: 'rtcpRsize',
  25494. reg: /^(rtcp-rsize)/
  25495. },
  25496. { // any a= that we don't understand is kepts verbatim on media.invalid
  25497. push: 'invalid',
  25498. names: ["value"]
  25499. }
  25500. ]
  25501. };
  25502. // set sensible defaults to avoid polluting the grammar with boring details
  25503. Object.keys(grammar).forEach(function (key) {
  25504. var objs = grammar[key];
  25505. objs.forEach(function (obj) {
  25506. if (!obj.reg) {
  25507. obj.reg = /(.*)/;
  25508. }
  25509. if (!obj.format) {
  25510. obj.format = "%s";
  25511. }
  25512. });
  25513. });
  25514. },{}],91:[function(require,module,exports){
  25515. var parser = require('./parser');
  25516. var writer = require('./writer');
  25517. exports.write = writer;
  25518. exports.parse = parser.parse;
  25519. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25520. exports.parsePayloads = parser.parsePayloads;
  25521. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25522. },{"./parser":92,"./writer":93}],92:[function(require,module,exports){
  25523. var toIntIfInt = function (v) {
  25524. return String(Number(v)) === v ? Number(v) : v;
  25525. };
  25526. var attachProperties = function (match, location, names, rawName) {
  25527. if (rawName && !names) {
  25528. location[rawName] = toIntIfInt(match[1]);
  25529. }
  25530. else {
  25531. for (var i = 0; i < names.length; i += 1) {
  25532. if (match[i+1] != null) {
  25533. location[names[i]] = toIntIfInt(match[i+1]);
  25534. }
  25535. }
  25536. }
  25537. };
  25538. var parseReg = function (obj, location, content) {
  25539. var needsBlank = obj.name && obj.names;
  25540. if (obj.push && !location[obj.push]) {
  25541. location[obj.push] = [];
  25542. }
  25543. else if (needsBlank && !location[obj.name]) {
  25544. location[obj.name] = {};
  25545. }
  25546. var keyLocation = obj.push ?
  25547. {} : // blank object that will be pushed
  25548. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25549. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25550. if (obj.push) {
  25551. location[obj.push].push(keyLocation);
  25552. }
  25553. };
  25554. var grammar = require('./grammar');
  25555. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25556. exports.parse = function (sdp) {
  25557. var session = {}
  25558. , media = []
  25559. , location = session; // points at where properties go under (one of the above)
  25560. // parse lines we understand
  25561. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25562. var type = l[0];
  25563. var content = l.slice(2);
  25564. if (type === 'm') {
  25565. media.push({rtp: [], fmtp: []});
  25566. location = media[media.length-1]; // point at latest media line
  25567. }
  25568. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25569. var obj = grammar[type][j];
  25570. if (obj.reg.test(content)) {
  25571. return parseReg(obj, location, content);
  25572. }
  25573. }
  25574. });
  25575. session.media = media; // link it up
  25576. return session;
  25577. };
  25578. var fmtpReducer = function (acc, expr) {
  25579. var s = expr.split('=');
  25580. if (s.length === 2) {
  25581. acc[s[0]] = toIntIfInt(s[1]);
  25582. }
  25583. return acc;
  25584. };
  25585. exports.parseFmtpConfig = function (str) {
  25586. return str.split(';').reduce(fmtpReducer, {});
  25587. };
  25588. exports.parsePayloads = function (str) {
  25589. return str.split(' ').map(Number);
  25590. };
  25591. exports.parseRemoteCandidates = function (str) {
  25592. var candidates = [];
  25593. var parts = str.split(' ').map(toIntIfInt);
  25594. for (var i = 0; i < parts.length; i += 3) {
  25595. candidates.push({
  25596. component: parts[i],
  25597. ip: parts[i + 1],
  25598. port: parts[i + 2]
  25599. });
  25600. }
  25601. return candidates;
  25602. };
  25603. },{"./grammar":90}],93:[function(require,module,exports){
  25604. var grammar = require('./grammar');
  25605. // customized util.format - discards excess arguments and can void middle ones
  25606. var formatRegExp = /%[sdv%]/g;
  25607. var format = function (formatStr) {
  25608. var i = 1;
  25609. var args = arguments;
  25610. var len = args.length;
  25611. return formatStr.replace(formatRegExp, function (x) {
  25612. if (i >= len) {
  25613. return x; // missing argument
  25614. }
  25615. var arg = args[i];
  25616. i += 1;
  25617. switch (x) {
  25618. case '%%':
  25619. return '%';
  25620. case '%s':
  25621. return String(arg);
  25622. case '%d':
  25623. return Number(arg);
  25624. case '%v':
  25625. return '';
  25626. }
  25627. });
  25628. // NB: we discard excess arguments - they are typically undefined from makeLine
  25629. };
  25630. var makeLine = function (type, obj, location) {
  25631. var str = obj.format instanceof Function ?
  25632. (obj.format(obj.push ? location : location[obj.name])) :
  25633. obj.format;
  25634. var args = [type + '=' + str];
  25635. if (obj.names) {
  25636. for (var i = 0; i < obj.names.length; i += 1) {
  25637. var n = obj.names[i];
  25638. if (obj.name) {
  25639. args.push(location[obj.name][n]);
  25640. }
  25641. else { // for mLine and push attributes
  25642. args.push(location[obj.names[i]]);
  25643. }
  25644. }
  25645. }
  25646. else {
  25647. args.push(location[obj.name]);
  25648. }
  25649. return format.apply(null, args);
  25650. };
  25651. // RFC specified order
  25652. // TODO: extend this with all the rest
  25653. var defaultOuterOrder = [
  25654. 'v', 'o', 's', 'i',
  25655. 'u', 'e', 'p', 'c',
  25656. 'b', 't', 'r', 'z', 'a'
  25657. ];
  25658. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25659. module.exports = function (session, opts) {
  25660. opts = opts || {};
  25661. // ensure certain properties exist
  25662. if (session.version == null) {
  25663. session.version = 0; // "v=0" must be there (only defined version atm)
  25664. }
  25665. if (session.name == null) {
  25666. session.name = " "; // "s= " must be there if no meaningful name set
  25667. }
  25668. session.media.forEach(function (mLine) {
  25669. if (mLine.payloads == null) {
  25670. mLine.payloads = "";
  25671. }
  25672. });
  25673. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25674. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25675. var sdp = [];
  25676. // loop through outerOrder for matching properties on session
  25677. outerOrder.forEach(function (type) {
  25678. grammar[type].forEach(function (obj) {
  25679. if (obj.name in session && session[obj.name] != null) {
  25680. sdp.push(makeLine(type, obj, session));
  25681. }
  25682. else if (obj.push in session && session[obj.push] != null) {
  25683. session[obj.push].forEach(function (el) {
  25684. sdp.push(makeLine(type, obj, el));
  25685. });
  25686. }
  25687. });
  25688. });
  25689. // then for each media line, follow the innerOrder
  25690. session.media.forEach(function (mLine) {
  25691. sdp.push(makeLine('m', grammar.m[0], mLine));
  25692. innerOrder.forEach(function (type) {
  25693. grammar[type].forEach(function (obj) {
  25694. if (obj.name in mLine && mLine[obj.name] != null) {
  25695. sdp.push(makeLine(type, obj, mLine));
  25696. }
  25697. else if (obj.push in mLine && mLine[obj.push] != null) {
  25698. mLine[obj.push].forEach(function (el) {
  25699. sdp.push(makeLine(type, obj, el));
  25700. });
  25701. }
  25702. });
  25703. });
  25704. });
  25705. return sdp.join('\r\n') + '\r\n';
  25706. };
  25707. },{"./grammar":90}],94:[function(require,module,exports){
  25708. var MediaStreamType = {
  25709. VIDEO_TYPE: "Video",
  25710. AUDIO_TYPE: "Audio"
  25711. };
  25712. module.exports = MediaStreamType;
  25713. },{}],95:[function(require,module,exports){
  25714. var RTCBrowserType = {
  25715. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  25716. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  25717. };
  25718. module.exports = RTCBrowserType;
  25719. },{}],96:[function(require,module,exports){
  25720. var RTCEvents = {
  25721. LASTN_CHANGED: "rtc.lastn_changed",
  25722. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  25723. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  25724. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  25725. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  25726. SIMULCAST_START: "rtc.simlcast_start",
  25727. SIMULCAST_STOP: "rtc.simlcast_stop",
  25728. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  25729. };
  25730. module.exports = RTCEvents;
  25731. },{}],97:[function(require,module,exports){
  25732. var Resolutions = {
  25733. "1080": {
  25734. width: 1920,
  25735. height: 1080,
  25736. order: 7
  25737. },
  25738. "fullhd": {
  25739. width: 1920,
  25740. height: 1080,
  25741. order: 7
  25742. },
  25743. "720": {
  25744. width: 1280,
  25745. height: 720,
  25746. order: 6
  25747. },
  25748. "hd": {
  25749. width: 1280,
  25750. height: 720,
  25751. order: 6
  25752. },
  25753. "960": {
  25754. width: 960,
  25755. height: 720,
  25756. order: 5
  25757. },
  25758. "640": {
  25759. width: 640,
  25760. height: 480,
  25761. order: 4
  25762. },
  25763. "vga": {
  25764. width: 640,
  25765. height: 480,
  25766. order: 4
  25767. },
  25768. "360": {
  25769. width: 640,
  25770. height: 360,
  25771. order: 3
  25772. },
  25773. "320": {
  25774. width: 320,
  25775. height: 240,
  25776. order: 2
  25777. },
  25778. "180": {
  25779. width: 320,
  25780. height: 180,
  25781. order: 1
  25782. }
  25783. };
  25784. module.exports = Resolutions;
  25785. },{}],98:[function(require,module,exports){
  25786. var StreamEventTypes = {
  25787. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  25788. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  25789. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  25790. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  25791. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  25792. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  25793. };
  25794. module.exports = StreamEventTypes;
  25795. },{}],99:[function(require,module,exports){
  25796. var UIEvents = {
  25797. NICKNAME_CHANGED: "UI.nickname_changed",
  25798. SELECTED_ENDPOINT: "UI.selected_endpoint",
  25799. PINNED_ENDPOINT: "UI.pinned_endpoint"
  25800. };
  25801. module.exports = UIEvents;
  25802. },{}],100:[function(require,module,exports){
  25803. var AuthenticationEvents = {
  25804. /**
  25805. * Event callback arguments:
  25806. * function(authenticationEnabled, userIdentity)
  25807. * authenticationEnabled - indicates whether authentication has been enabled
  25808. * in this session
  25809. * userIdentity - if user has been logged in then it contains user name. If
  25810. * contains 'null' or 'undefined' then user is not logged in.
  25811. */
  25812. IDENTITY_UPDATED: "authentication.identity_updated"
  25813. };
  25814. module.exports = AuthenticationEvents;
  25815. },{}],101:[function(require,module,exports){
  25816. var CQEvents = {
  25817. LOCALSTATS_UPDATED: "cq.localstats_updated",
  25818. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  25819. STOP: "cq.stop"
  25820. };
  25821. module.exports = CQEvents;
  25822. },{}],102:[function(require,module,exports){
  25823. var DesktopSharingEventTypes = {
  25824. INIT: "ds.init",
  25825. SWITCHING_DONE: "ds.switching_done",
  25826. NEW_STREAM_CREATED: "ds.new_stream_created"
  25827. };
  25828. module.exports = DesktopSharingEventTypes;
  25829. },{}],103:[function(require,module,exports){
  25830. var Events = {
  25831. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  25832. };
  25833. module.exports = Events;
  25834. },{}],104:[function(require,module,exports){
  25835. module.exports = {
  25836. getLanguages : function () {
  25837. var languages = [];
  25838. for(var lang in this)
  25839. {
  25840. if(typeof this[lang] === "string")
  25841. languages.push(this[lang]);
  25842. }
  25843. return languages;
  25844. },
  25845. EN: "en",
  25846. BG: "bg",
  25847. DE: "de",
  25848. TR: "tr"
  25849. }
  25850. },{}],105:[function(require,module,exports){
  25851. var XMPPEvents = {
  25852. CONNECTION_FAILED: "xmpp.connection.failed",
  25853. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  25854. CALL_TERMINATED: "xmpp.callterminated.jingle",
  25855. CALL_INCOMING: "xmpp.callincoming.jingle",
  25856. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  25857. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  25858. KICKED: "xmpp.kicked",
  25859. BRIDGE_DOWN: "xmpp.bridge_down",
  25860. USER_ID_CHANGED: "xmpp.user_id_changed",
  25861. STREAMS_CHANGED: "xmpp.streams_changed",
  25862. // We joined the MUC
  25863. MUC_JOINED: "xmpp.muc_joined",
  25864. // A member joined the MUC
  25865. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  25866. // A member left the MUC
  25867. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  25868. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  25869. MUC_DESTROYED: "xmpp.muc_destroyed",
  25870. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  25871. REMOTE_STATS: "xmpp.remote_stats",
  25872. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  25873. PRESENCE_STATUS: "xmpp.presence_status",
  25874. RESERVATION_ERROR: "xmpp.room_reservation_error",
  25875. SUBJECT_CHANGED: "xmpp.subject_changed",
  25876. MESSAGE_RECEIVED: "xmpp.message_received",
  25877. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  25878. PASSWORD_REQUIRED: "xmpp.password_required",
  25879. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  25880. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  25881. ETHERPAD: "xmpp.etherpad",
  25882. DEVICE_AVAILABLE: "xmpp.device_available",
  25883. START_MUTED: "xmpp.start_muted"
  25884. };
  25885. module.exports = XMPPEvents;
  25886. },{}],106:[function(require,module,exports){
  25887. /* jshint -W117 */
  25888. /* application specific logic */
  25889. var APP =
  25890. {
  25891. init: function () {
  25892. this.UI = require("./modules/UI/UI");
  25893. this.API = require("./modules/API/API");
  25894. this.connectionquality = require("./modules/connectionquality/connectionquality");
  25895. this.statistics = require("./modules/statistics/statistics");
  25896. this.RTC = require("./modules/RTC/RTC");
  25897. this.simulcast = require("./modules/simulcast/simulcast");
  25898. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  25899. this.xmpp = require("./modules/xmpp/xmpp");
  25900. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  25901. this.translation = require("./modules/translation/translation");
  25902. this.settings = require("./modules/settings/Settings");
  25903. this.DTMF = require("./modules/DTMF/DTMF");
  25904. this.members = require("./modules/members/MemberList");
  25905. }
  25906. };
  25907. function init() {
  25908. APP.RTC.start();
  25909. APP.xmpp.start();
  25910. APP.statistics.start();
  25911. APP.connectionquality.init();
  25912. // Set default desktop sharing method
  25913. APP.desktopsharing.init();
  25914. APP.keyboardshortcut.init();
  25915. APP.members.start();
  25916. }
  25917. $(document).ready(function () {
  25918. APP.init();
  25919. APP.translation.init();
  25920. if(APP.API.isEnabled())
  25921. APP.API.init();
  25922. APP.UI.start(init);
  25923. });
  25924. $(window).bind('beforeunload', function () {
  25925. if(APP.API.isEnabled())
  25926. APP.API.dispose();
  25927. });
  25928. module.exports = APP;
  25929. },{"./modules/API/API":1,"./modules/DTMF/DTMF":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":35,"./modules/desktopsharing/desktopsharing":36,"./modules/keyboardshortcut/keyboardshortcut":37,"./modules/members/MemberList":38,"./modules/settings/Settings":39,"./modules/simulcast/simulcast":44,"./modules/statistics/statistics":47,"./modules/translation/translation":48,"./modules/xmpp/xmpp":62}]},{},[106])(106)
  25930. });