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

app.bundle.js 1018KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616
  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. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. // shim for using process in browser
  254. var process = module.exports = {};
  255. var queue = [];
  256. var draining = false;
  257. function drainQueue() {
  258. if (draining) {
  259. return;
  260. }
  261. draining = true;
  262. var currentQueue;
  263. var len = queue.length;
  264. while(len) {
  265. currentQueue = queue;
  266. queue = [];
  267. var i = -1;
  268. while (++i < len) {
  269. currentQueue[i]();
  270. }
  271. len = queue.length;
  272. }
  273. draining = false;
  274. }
  275. process.nextTick = function (fun) {
  276. queue.push(fun);
  277. if (!draining) {
  278. setTimeout(drainQueue, 0);
  279. }
  280. };
  281. process.title = 'browser';
  282. process.browser = true;
  283. process.env = {};
  284. process.argv = [];
  285. process.version = ''; // empty string to avoid regexp issues
  286. process.versions = {};
  287. function noop() {}
  288. process.on = noop;
  289. process.addListener = noop;
  290. process.once = noop;
  291. process.off = noop;
  292. process.removeListener = noop;
  293. process.removeAllListeners = noop;
  294. process.emit = noop;
  295. process.binding = function (name) {
  296. throw new Error('process.binding is not supported');
  297. };
  298. // TODO(shtylman)
  299. process.cwd = function () { return '/' };
  300. process.chdir = function (dir) {
  301. throw new Error('process.chdir is not supported');
  302. };
  303. process.umask = function() { return 0; };
  304. },{}],3:[function(require,module,exports){
  305. /* jshint -W117 */
  306. /* application specific logic */
  307. var APP =
  308. {
  309. init: function () {
  310. this.UI = require("./modules/UI/UI");
  311. this.API = require("./modules/API/API");
  312. this.connectionquality = require("./modules/connectionquality/connectionquality");
  313. this.statistics = require("./modules/statistics/statistics");
  314. this.RTC = require("./modules/RTC/RTC");
  315. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  316. this.xmpp = require("./modules/xmpp/xmpp");
  317. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  318. this.translation = require("./modules/translation/translation");
  319. this.settings = require("./modules/settings/Settings");
  320. this.DTMF = require("./modules/DTMF/DTMF");
  321. this.members = require("./modules/members/MemberList");
  322. }
  323. };
  324. function init() {
  325. APP.desktopsharing.init();
  326. APP.RTC.start();
  327. APP.xmpp.start();
  328. APP.statistics.start();
  329. APP.connectionquality.init();
  330. APP.keyboardshortcut.init();
  331. APP.members.start();
  332. }
  333. $(document).ready(function () {
  334. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  335. URLPRocessor.setConfigParametersFromUrl();
  336. APP.init();
  337. APP.translation.init();
  338. if(APP.API.isEnabled())
  339. APP.API.init();
  340. APP.UI.start(init);
  341. });
  342. $(window).bind('beforeunload', function () {
  343. if(APP.API.isEnabled())
  344. APP.API.dispose();
  345. });
  346. module.exports = APP;
  347. },{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":13,"./modules/URLProcessor/URLProcessor":44,"./modules/connectionquality/connectionquality":45,"./modules/desktopsharing/desktopsharing":46,"./modules/keyboardshortcut/keyboardshortcut":47,"./modules/members/MemberList":48,"./modules/settings/Settings":49,"./modules/statistics/statistics":53,"./modules/translation/translation":54,"./modules/xmpp/xmpp":68}],4:[function(require,module,exports){
  348. /**
  349. * Implements API class that communicates with external api class
  350. * and provides interface to access Jitsi Meet features by external
  351. * applications that embed Jitsi Meet
  352. */
  353. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  354. /**
  355. * List of the available commands.
  356. * @type {{
  357. * displayName: inputDisplayNameHandler,
  358. * muteAudio: toggleAudio,
  359. * muteVideo: toggleVideo,
  360. * filmStrip: toggleFilmStrip
  361. * }}
  362. */
  363. var commands = {};
  364. function initCommands() {
  365. commands =
  366. {
  367. displayName: APP.UI.inputDisplayNameHandler,
  368. muteAudio: APP.UI.toggleAudio,
  369. muteVideo: APP.UI.toggleVideo,
  370. toggleFilmStrip: APP.UI.toggleFilmStrip,
  371. toggleChat: APP.UI.toggleChat,
  372. toggleContactList: APP.UI.toggleContactList
  373. };
  374. }
  375. /**
  376. * Maps the supported events and their status
  377. * (true it the event is enabled and false if it is disabled)
  378. * @type {{
  379. * incomingMessage: boolean,
  380. * outgoingMessage: boolean,
  381. * displayNameChange: boolean,
  382. * participantJoined: boolean,
  383. * participantLeft: boolean
  384. * }}
  385. */
  386. var events =
  387. {
  388. incomingMessage: false,
  389. outgoingMessage:false,
  390. displayNameChange: false,
  391. participantJoined: false,
  392. participantLeft: false
  393. };
  394. var displayName = {};
  395. /**
  396. * Processes commands from external applicaiton.
  397. * @param message the object with the command
  398. */
  399. function processCommand(message)
  400. {
  401. if(message.action != "execute")
  402. {
  403. console.error("Unknown action of the message");
  404. return;
  405. }
  406. for(var key in message)
  407. {
  408. if(commands[key])
  409. commands[key].apply(null, message[key]);
  410. }
  411. }
  412. /**
  413. * Processes events objects from external applications
  414. * @param event the event
  415. */
  416. function processEvent(event) {
  417. if(!event.action)
  418. {
  419. console.error("Event with no action is received.");
  420. return;
  421. }
  422. var i = 0;
  423. switch(event.action)
  424. {
  425. case "add":
  426. for(; i < event.events.length; i++)
  427. {
  428. events[event.events[i]] = true;
  429. }
  430. break;
  431. case "remove":
  432. for(; i < event.events.length; i++)
  433. {
  434. events[event.events[i]] = false;
  435. }
  436. break;
  437. default:
  438. console.error("Unknown action for event.");
  439. }
  440. }
  441. /**
  442. * Sends message to the external application.
  443. * @param object
  444. */
  445. function sendMessage(object) {
  446. window.parent.postMessage(JSON.stringify(object), "*");
  447. }
  448. /**
  449. * Processes a message event from the external application
  450. * @param event the message event
  451. */
  452. function processMessage(event)
  453. {
  454. var message;
  455. try {
  456. message = JSON.parse(event.data);
  457. } catch (e) {}
  458. if(!message.type)
  459. return;
  460. switch (message.type)
  461. {
  462. case "command":
  463. processCommand(message);
  464. break;
  465. case "event":
  466. processEvent(message);
  467. break;
  468. default:
  469. console.error("Unknown type of the message");
  470. return;
  471. }
  472. }
  473. function setupListeners() {
  474. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  475. API.triggerEvent("participantJoined", {jid: from});
  476. });
  477. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  478. if (from != myjid)
  479. API.triggerEvent("incomingMessage",
  480. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  481. });
  482. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  483. API.triggerEvent("participantLeft", {jid: jid});
  484. });
  485. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  486. name = displayName[jid];
  487. if(!name || name != newDisplayName) {
  488. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  489. displayName[jid] = newDisplayName;
  490. }
  491. });
  492. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  493. APP.API.triggerEvent("outgoingMessage", {"message": body});
  494. });
  495. }
  496. var API = {
  497. /**
  498. * Check whether the API should be enabled or not.
  499. * @returns {boolean}
  500. */
  501. isEnabled: function () {
  502. var hash = location.hash;
  503. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  504. return true;
  505. return false;
  506. },
  507. /**
  508. * Initializes the APIConnector. Setups message event listeners that will
  509. * receive information from external applications that embed Jitsi Meet.
  510. * It also sends a message to the external application that APIConnector
  511. * is initialized.
  512. */
  513. init: function () {
  514. initCommands();
  515. if (window.addEventListener)
  516. {
  517. window.addEventListener('message',
  518. processMessage, false);
  519. }
  520. else
  521. {
  522. window.attachEvent('onmessage', processMessage);
  523. }
  524. sendMessage({type: "system", loaded: true});
  525. setupListeners();
  526. },
  527. /**
  528. * Checks whether the event is enabled ot not.
  529. * @param name the name of the event.
  530. * @returns {*}
  531. */
  532. isEventEnabled: function (name) {
  533. return events[name];
  534. },
  535. /**
  536. * Sends event object to the external application that has been subscribed
  537. * for that event.
  538. * @param name the name event
  539. * @param object data associated with the event
  540. */
  541. triggerEvent: function (name, object) {
  542. if(this.isEnabled() && this.isEventEnabled(name))
  543. sendMessage({
  544. type: "event", action: "result", event: name, result: object});
  545. },
  546. /**
  547. * Removes the listeners.
  548. */
  549. dispose: function () {
  550. if(window.removeEventListener)
  551. {
  552. window.removeEventListener("message",
  553. processMessage, false);
  554. }
  555. else
  556. {
  557. window.detachEvent('onmessage', processMessage);
  558. }
  559. }
  560. };
  561. module.exports = API;
  562. },{"../../service/xmpp/XMPPEvents":110}],5:[function(require,module,exports){
  563. /* global APP */
  564. /**
  565. * A module for sending DTMF tones.
  566. */
  567. var DTMFSender;
  568. var initDtmfSender = function() {
  569. // TODO: This needs to reset this if the peerconnection changes
  570. // (e.g. the call is re-made)
  571. if (DTMFSender)
  572. return;
  573. var localAudio = APP.RTC.localAudio;
  574. if (localAudio && localAudio.getTracks().length > 0)
  575. {
  576. var peerconnection
  577. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  578. if (peerconnection) {
  579. DTMFSender =
  580. peerconnection.peerconnection
  581. .createDTMFSender(localAudio.getTracks()[0]);
  582. console.log("Initialized DTMFSender");
  583. }
  584. else {
  585. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  586. }
  587. }
  588. else {
  589. console.log("Failed to initialize DTMFSender: no audio track.");
  590. }
  591. };
  592. var DTMF = {
  593. sendTones: function (tones, duration, pause) {
  594. if (!DTMFSender)
  595. initDtmfSender();
  596. if (DTMFSender){
  597. DTMFSender.insertDTMF(tones,
  598. (duration || 200),
  599. (pause || 200));
  600. }
  601. }
  602. };
  603. module.exports = DTMF;
  604. },{}],6:[function(require,module,exports){
  605. /* global Strophe, focusedVideoSrc*/
  606. // cache datachannels to avoid garbage collection
  607. // https://code.google.com/p/chromium/issues/detail?id=405545
  608. var RTCEvents = require("../../service/RTC/RTCEvents");
  609. var _dataChannels = [];
  610. var eventEmitter = null;
  611. var DataChannels =
  612. {
  613. /**
  614. * Callback triggered by PeerConnection when new data channel is opened
  615. * on the bridge.
  616. * @param event the event info object.
  617. */
  618. onDataChannel: function (event)
  619. {
  620. var dataChannel = event.channel;
  621. dataChannel.onopen = function () {
  622. console.info("Data channel opened by the Videobridge!", dataChannel);
  623. // Code sample for sending string and/or binary data
  624. // Sends String message to the bridge
  625. //dataChannel.send("Hello bridge!");
  626. // Sends 12 bytes binary message to the bridge
  627. //dataChannel.send(new ArrayBuffer(12));
  628. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  629. };
  630. dataChannel.onerror = function (error) {
  631. console.error("Data Channel Error:", error, dataChannel);
  632. };
  633. dataChannel.onmessage = function (event) {
  634. var data = event.data;
  635. // JSON
  636. var obj;
  637. try {
  638. obj = JSON.parse(data);
  639. }
  640. catch (e) {
  641. console.error(
  642. "Failed to parse data channel message as JSON: ",
  643. data,
  644. dataChannel);
  645. }
  646. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  647. var colibriClass = obj.colibriClass;
  648. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  649. // Endpoint ID from the Videobridge.
  650. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  651. console.info(
  652. "Data channel new dominant speaker event: ",
  653. dominantSpeakerEndpoint);
  654. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  655. }
  656. else if ("InLastNChangeEvent" === colibriClass)
  657. {
  658. var oldValue = obj.oldValue;
  659. var newValue = obj.newValue;
  660. // Make sure that oldValue and newValue are of type boolean.
  661. var type;
  662. if ((type = typeof oldValue) !== 'boolean') {
  663. if (type === 'string') {
  664. oldValue = (oldValue == "true");
  665. } else {
  666. oldValue = new Boolean(oldValue).valueOf();
  667. }
  668. }
  669. if ((type = typeof newValue) !== 'boolean') {
  670. if (type === 'string') {
  671. newValue = (newValue == "true");
  672. } else {
  673. newValue = new Boolean(newValue).valueOf();
  674. }
  675. }
  676. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  677. }
  678. else if ("LastNEndpointsChangeEvent" === colibriClass)
  679. {
  680. // The new/latest list of last-n endpoint IDs.
  681. var lastNEndpoints = obj.lastNEndpoints;
  682. // The list of endpoint IDs which are entering the list of
  683. // last-n at this time i.e. were not in the old list of last-n
  684. // endpoint IDs.
  685. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  686. var stream = obj.stream;
  687. console.log(
  688. "Data channel new last-n event: ",
  689. lastNEndpoints, endpointsEnteringLastN, obj);
  690. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  691. lastNEndpoints, endpointsEnteringLastN, obj);
  692. }
  693. else
  694. {
  695. console.debug("Data channel JSON-formatted message: ", obj);
  696. }
  697. }
  698. };
  699. dataChannel.onclose = function ()
  700. {
  701. console.info("The Data Channel closed", dataChannel);
  702. var idx = _dataChannels.indexOf(dataChannel);
  703. if (idx > -1)
  704. _dataChannels = _dataChannels.splice(idx, 1);
  705. };
  706. _dataChannels.push(dataChannel);
  707. },
  708. /**
  709. * Binds "ondatachannel" event listener to given PeerConnection instance.
  710. * @param peerConnection WebRTC peer connection instance.
  711. */
  712. init: function (peerConnection, emitter) {
  713. if(!config.openSctp)
  714. return;
  715. peerConnection.ondatachannel = this.onDataChannel;
  716. eventEmitter = emitter;
  717. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  718. // Although it's not a requirement to open separate channels from both bridge
  719. // and peer as single channel can be used for sending and receiving data.
  720. // So either channel opened by the bridge or the one opened here is enough
  721. // for communication with the bridge.
  722. /*var dataChannelOptions =
  723. {
  724. reliable: true
  725. };
  726. var dataChannel
  727. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  728. // Can be used only when is in open state
  729. dataChannel.onopen = function ()
  730. {
  731. dataChannel.send("My channel !!!");
  732. };
  733. dataChannel.onmessage = function (event)
  734. {
  735. var msgData = event.data;
  736. console.info("Got My Data Channel Message:", msgData, dataChannel);
  737. };*/
  738. },
  739. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  740. handlePinnedEndpointEvent: onPinnedEndpointChanged
  741. };
  742. function onSelectedEndpointChanged(userResource)
  743. {
  744. console.log('selected endpoint changed: ', userResource);
  745. if (_dataChannels && _dataChannels.length != 0)
  746. {
  747. _dataChannels.some(function (dataChannel) {
  748. if (dataChannel.readyState == 'open')
  749. {
  750. console.log('sending selected endpoint changed '
  751. + 'notification to the bridge: ', userResource);
  752. dataChannel.send(JSON.stringify({
  753. 'colibriClass': 'SelectedEndpointChangedEvent',
  754. 'selectedEndpoint':
  755. (!userResource || userResource === null)?
  756. null : userResource
  757. }));
  758. return true;
  759. }
  760. });
  761. }
  762. }
  763. function onPinnedEndpointChanged(userResource)
  764. {
  765. console.log('pinned endpoint changed: ', userResource);
  766. if (_dataChannels && _dataChannels.length != 0)
  767. {
  768. _dataChannels.some(function (dataChannel) {
  769. if (dataChannel.readyState == 'open')
  770. {
  771. dataChannel.send(JSON.stringify({
  772. 'colibriClass': 'PinnedEndpointChangedEvent',
  773. 'pinnedEndpoint':
  774. (!userResource || userResource == null)?
  775. null : userResource
  776. }));
  777. return true;
  778. }
  779. });
  780. }
  781. }
  782. module.exports = DataChannels;
  783. },{"../../service/RTC/RTCEvents":101}],7:[function(require,module,exports){
  784. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  785. var RTCEvents = require("../../service/RTC/RTCEvents");
  786. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  787. {
  788. this.stream = stream;
  789. this.eventEmitter = eventEmitter;
  790. this.type = type;
  791. this.videoType = videoType;
  792. this.isGUMStream = true;
  793. if(isGUMStream === false)
  794. this.isGUMStream = isGUMStream;
  795. var self = this;
  796. if(type == "audio")
  797. {
  798. this.getTracks = function () {
  799. return self.stream.getAudioTracks();
  800. };
  801. }
  802. else
  803. {
  804. this.getTracks = function () {
  805. return self.stream.getVideoTracks();
  806. };
  807. }
  808. this.stream.onended = function()
  809. {
  810. self.streamEnded();
  811. };
  812. }
  813. LocalStream.prototype.streamEnded = function () {
  814. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  815. }
  816. LocalStream.prototype.getOriginalStream = function()
  817. {
  818. return this.stream;
  819. }
  820. LocalStream.prototype.isAudioStream = function () {
  821. return this.type === "audio";
  822. };
  823. LocalStream.prototype.setMute = function(mute)
  824. {
  825. if((window.location.protocol != "https:" && this.isGUMStream) ||
  826. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  827. {
  828. var tracks = this.getTracks();
  829. for (var idx = 0; idx < tracks.length; idx++) {
  830. tracks[idx].enabled = mute;
  831. }
  832. this.eventEmitter.emit(
  833. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  834. !mute);
  835. }
  836. else
  837. {
  838. if(mute === false) {
  839. APP.xmpp.removeStream(this.stream);
  840. this.stream.stop();
  841. this.eventEmitter.emit(
  842. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  843. true);
  844. }
  845. else
  846. {
  847. var self = this;
  848. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  849. (this.isAudioStream() ? ["audio"] : ["video"]),
  850. function (stream) {
  851. if(self.isAudioStream())
  852. {
  853. APP.RTC.changeLocalAudio(stream,
  854. function () {
  855. self.eventEmitter.emit(
  856. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  857. true);
  858. });
  859. }
  860. else
  861. {
  862. APP.RTC.changeLocalVideo(stream, false,
  863. function () {
  864. self.eventEmitter.emit(
  865. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  866. true);
  867. });
  868. }
  869. });
  870. }
  871. }
  872. };
  873. LocalStream.prototype.isMuted = function () {
  874. var tracks = [];
  875. if(this.type == "audio")
  876. {
  877. tracks = this.stream.getAudioTracks();
  878. }
  879. else
  880. {
  881. if(this.stream.ended)
  882. return true;
  883. tracks = this.stream.getVideoTracks();
  884. }
  885. for (var idx = 0; idx < tracks.length; idx++) {
  886. if(tracks[idx].enabled)
  887. return false;
  888. }
  889. return true;
  890. }
  891. LocalStream.prototype.getId = function () {
  892. return this.stream.getTracks()[0].id;
  893. }
  894. module.exports = LocalStream;
  895. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes.js":103}],8:[function(require,module,exports){
  896. ////These lines should be uncommented when require works in app.js
  897. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  898. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  899. /**
  900. * Creates a MediaStream object for the given data, session id and ssrc.
  901. * It is a wrapper class for the MediaStream.
  902. *
  903. * @param data the data object from which we obtain the stream,
  904. * the peerjid, etc.
  905. * @param sid the session id
  906. * @param ssrc the ssrc corresponding to this MediaStream
  907. *
  908. * @constructor
  909. */
  910. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  911. // XXX(gp) to minimize headaches in the future, we should build our
  912. // abstractions around tracks and not streams. ORTC is track based API.
  913. // Mozilla expects m-lines to represent media tracks.
  914. //
  915. // Practically, what I'm saying is that we should have a MediaTrack class
  916. // and not a MediaStream class.
  917. //
  918. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  919. // a track might have an associated RTX and FEC sources.
  920. this.sid = sid;
  921. this.stream = data.stream;
  922. this.peerjid = data.peerjid;
  923. this.videoType = data.videoType;
  924. this.ssrc = ssrc;
  925. this.type = (this.stream.getVideoTracks().length > 0)?
  926. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  927. this.muted = false;
  928. this.eventEmitter = eventEmitter;
  929. }
  930. MediaStream.prototype.getOriginalStream = function()
  931. {
  932. return this.stream;
  933. };
  934. MediaStream.prototype.setMute = function (value)
  935. {
  936. this.stream.muted = value;
  937. this.muted = value;
  938. };
  939. module.exports = MediaStream;
  940. },{"../../service/RTC/MediaStreamTypes":100,"../../service/RTC/StreamEventTypes":103}],9:[function(require,module,exports){
  941. var EventEmitter = require("events");
  942. var RTCBrowserType = require("./RTCBrowserType");
  943. var RTCUtils = require("./RTCUtils.js");
  944. var LocalStream = require("./LocalStream.js");
  945. var DataChannels = require("./DataChannels");
  946. var MediaStream = require("./MediaStream.js");
  947. var DesktopSharingEventTypes
  948. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  949. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  950. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  951. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  952. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  953. var UIEvents = require("../../service/UI/UIEvents");
  954. var eventEmitter = new EventEmitter();
  955. function getMediaStreamUsage()
  956. {
  957. var result = {
  958. audio: true,
  959. video: true
  960. };
  961. /** There are some issues with the desktop sharing
  962. * when this property is enabled.
  963. * WARNING: We must change the implementation to start video/audio if we
  964. * receive from the focus that the peer is not muted.
  965. var isSecureConnection = window.location.protocol == "https:";
  966. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  967. {
  968. result = {
  969. audio: false,
  970. video: false
  971. };
  972. }
  973. **/
  974. return result;
  975. }
  976. var RTC = {
  977. rtcUtils: null,
  978. devices: {
  979. audio: true,
  980. video: true
  981. },
  982. localStreams: [],
  983. remoteStreams: {},
  984. localAudio: null,
  985. localVideo: null,
  986. addStreamListener: function (listener, eventType) {
  987. eventEmitter.on(eventType, listener);
  988. },
  989. addListener: function (type, listener) {
  990. eventEmitter.on(type, listener);
  991. },
  992. removeStreamListener: function (listener, eventType) {
  993. if(!(eventType instanceof StreamEventTypes))
  994. throw "Illegal argument";
  995. eventEmitter.removeListener(eventType, listener);
  996. },
  997. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  998. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  999. //in firefox we have only one stream object
  1000. if(this.localStreams.length == 0 ||
  1001. this.localStreams[0].getOriginalStream() != stream)
  1002. this.localStreams.push(localStream);
  1003. if(isMuted === true)
  1004. localStream.setMute(false);
  1005. if(type == "audio")
  1006. {
  1007. this.localAudio = localStream;
  1008. }
  1009. else
  1010. {
  1011. this.localVideo = localStream;
  1012. }
  1013. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1014. if(change)
  1015. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1016. eventEmitter.emit(eventType, localStream, isMuted);
  1017. return localStream;
  1018. },
  1019. removeLocalStream: function (stream) {
  1020. for(var i = 0; i < this.localStreams.length; i++)
  1021. {
  1022. if(this.localStreams[i].getOriginalStream() === stream) {
  1023. delete this.localStreams[i];
  1024. return;
  1025. }
  1026. }
  1027. },
  1028. createRemoteStream: function (data, sid, thessrc) {
  1029. var remoteStream = new MediaStream(data, sid, thessrc,
  1030. RTCBrowserType.getBrowserType(), eventEmitter);
  1031. var jid = data.peerjid || APP.xmpp.myJid();
  1032. if(!this.remoteStreams[jid]) {
  1033. this.remoteStreams[jid] = {};
  1034. }
  1035. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1036. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1037. return remoteStream;
  1038. },
  1039. getPCConstraints: function () {
  1040. return this.rtcUtils.pc_constraints;
  1041. },
  1042. getUserMediaWithConstraints:function(um, success_callback,
  1043. failure_callback, resolution,
  1044. bandwidth, fps, desktopStream)
  1045. {
  1046. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1047. failure_callback, resolution, bandwidth, fps, desktopStream);
  1048. },
  1049. attachMediaStream: function (elSelector, stream) {
  1050. this.rtcUtils.attachMediaStream(elSelector, stream);
  1051. },
  1052. getStreamID: function (stream) {
  1053. return this.rtcUtils.getStreamID(stream);
  1054. },
  1055. getVideoSrc: function (element) {
  1056. return this.rtcUtils.getVideoSrc(element);
  1057. },
  1058. setVideoSrc: function (element, src) {
  1059. this.rtcUtils.setVideoSrc(element, src);
  1060. },
  1061. getVideoElementName: function () {
  1062. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1063. },
  1064. dispose: function() {
  1065. if (this.rtcUtils) {
  1066. this.rtcUtils = null;
  1067. }
  1068. },
  1069. stop: function () {
  1070. this.dispose();
  1071. },
  1072. start: function () {
  1073. var self = this;
  1074. APP.desktopsharing.addListener(
  1075. function (stream, isUsingScreenStream, callback) {
  1076. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1077. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1078. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1079. DataChannels.init(event.peerconnection, eventEmitter);
  1080. });
  1081. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1082. DataChannels.handleSelectedEndpointEvent);
  1083. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1084. DataChannels.handlePinnedEndpointEvent);
  1085. // In case of IE we continue from 'onReady' callback
  1086. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1087. // once it is initialized.
  1088. var onReady = function () {
  1089. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1090. self.rtcUtils.obtainAudioAndVideoPermissions(
  1091. null, null, getMediaStreamUsage());
  1092. };
  1093. this.rtcUtils = new RTCUtils(this, onReady);
  1094. // Call onReady() if Temasys plugin is not used
  1095. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1096. onReady();
  1097. }
  1098. },
  1099. muteRemoteVideoStream: function (jid, value) {
  1100. var stream;
  1101. if(this.remoteStreams[jid] &&
  1102. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  1103. {
  1104. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1105. }
  1106. if(!stream)
  1107. return true;
  1108. if (value != stream.muted) {
  1109. stream.setMute(value);
  1110. return true;
  1111. }
  1112. return false;
  1113. },
  1114. switchVideoStreams: function (new_stream) {
  1115. this.localVideo.stream = new_stream;
  1116. this.localStreams = [];
  1117. //in firefox we have only one stream object
  1118. if (this.localAudio.getOriginalStream() != new_stream)
  1119. this.localStreams.push(this.localAudio);
  1120. this.localStreams.push(this.localVideo);
  1121. },
  1122. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1123. var oldStream = this.localVideo.getOriginalStream();
  1124. var type = (isUsingScreenStream? "screen" : "video");
  1125. var localCallback = callback;
  1126. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  1127. {
  1128. localCallback = function() {
  1129. APP.xmpp.setVideoMute(false, function(mute) {
  1130. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1131. });
  1132. callback();
  1133. };
  1134. }
  1135. // FIXME: Workaround for FF/IE/Safari
  1136. if (stream && stream.videoStream) {
  1137. stream = stream.videoStream;
  1138. }
  1139. var videoStream = this.rtcUtils.createStream(stream, true);
  1140. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1141. // Stop the stream to trigger onended event for old stream
  1142. oldStream.stop();
  1143. this.switchVideoStreams(videoStream, oldStream);
  1144. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1145. },
  1146. changeLocalAudio: function (stream, callback) {
  1147. var oldStream = this.localAudio.getOriginalStream();
  1148. var newStream = this.rtcUtils.createStream(stream);
  1149. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1150. // Stop the stream to trigger onended event for old stream
  1151. oldStream.stop();
  1152. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1153. },
  1154. isVideoMuted: function (jid) {
  1155. if (jid === APP.xmpp.myJid()) {
  1156. var localVideo = APP.RTC.localVideo;
  1157. return (!localVideo || localVideo.isMuted());
  1158. }
  1159. else
  1160. {
  1161. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1162. return null;
  1163. }
  1164. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1165. }
  1166. },
  1167. /**
  1168. * Checks if video identified by given src is desktop stream.
  1169. * @param videoSrc eg.
  1170. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  1171. * @returns {boolean}
  1172. */
  1173. isVideoSrcDesktop: function (jid) {
  1174. if(!jid)
  1175. return false;
  1176. var isDesktop = false;
  1177. var stream = null;
  1178. if (APP.xmpp.myJid() === jid) {
  1179. // local video
  1180. stream = this.localVideo;
  1181. } else {
  1182. var peerStreams = this.remoteStreams[jid];
  1183. if(!peerStreams)
  1184. return false;
  1185. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1186. }
  1187. if(stream)
  1188. isDesktop = (stream.videoType === "screen");
  1189. return isDesktop;
  1190. },
  1191. setVideoMute: function(mute, callback, options) {
  1192. if(!this.localVideo)
  1193. return;
  1194. if (mute == APP.RTC.localVideo.isMuted())
  1195. {
  1196. APP.xmpp.sendVideoInfoPresence(mute);
  1197. if(callback)
  1198. callback(mute);
  1199. }
  1200. else
  1201. {
  1202. APP.RTC.localVideo.setMute(!mute);
  1203. APP.xmpp.setVideoMute(
  1204. mute,
  1205. callback,
  1206. options);
  1207. }
  1208. },
  1209. setDeviceAvailability: function (devices) {
  1210. if(!devices)
  1211. return;
  1212. if(devices.audio === true || devices.audio === false)
  1213. this.devices.audio = devices.audio;
  1214. if(devices.video === true || devices.video === false)
  1215. this.devices.video = devices.video;
  1216. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1217. }
  1218. };
  1219. module.exports = RTC;
  1220. },{"../../service/RTC/MediaStreamTypes":100,"../../service/RTC/RTCEvents.js":101,"../../service/RTC/StreamEventTypes.js":103,"../../service/UI/UIEvents":104,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../../service/xmpp/XMPPEvents":110,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCBrowserType":10,"./RTCUtils.js":11,"events":1}],10:[function(require,module,exports){
  1221. var currentBrowser;
  1222. var browserVersion;
  1223. var RTCBrowserType = {
  1224. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1225. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1226. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1227. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1228. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1229. getBrowserType: function () {
  1230. return currentBrowser;
  1231. },
  1232. isChrome: function () {
  1233. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1234. },
  1235. isOpera: function () {
  1236. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1237. },
  1238. isFirefox: function () {
  1239. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1240. },
  1241. isIExplorer: function () {
  1242. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1243. },
  1244. isSafari: function () {
  1245. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1246. },
  1247. isTemasysPluginUsed: function () {
  1248. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1249. },
  1250. getFirefoxVersion: function () {
  1251. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1252. },
  1253. getChromeVersion: function () {
  1254. return RTCBrowserType.isChrome() ? browserVersion : null;
  1255. },
  1256. usesPlanB: function() {
  1257. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  1258. || RTCBrowserType.isTemasysPluginUsed();
  1259. },
  1260. usesUnifiedPlan: function() {
  1261. return RTCBrowserType.isFirefox();
  1262. }
  1263. // Add version getters for other browsers when needed
  1264. };
  1265. // detectOpera() must be called before detectChrome() !!!
  1266. // otherwise Opera wil be detected as Chrome
  1267. function detectChrome() {
  1268. if (navigator.webkitGetUserMedia) {
  1269. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1270. var userAgent = navigator.userAgent.toLowerCase();
  1271. // We can assume that user agent is chrome, because it's
  1272. // enforced when 'ext' streaming method is set
  1273. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1274. console.log("This appears to be Chrome, ver: " + ver);
  1275. return ver;
  1276. }
  1277. return null;
  1278. }
  1279. function detectOpera() {
  1280. var userAgent = navigator.userAgent;
  1281. if (userAgent.match(/Opera|OPR/)) {
  1282. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1283. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1284. console.info("This appears to be Opera, ver: " + version);
  1285. return version;
  1286. }
  1287. return null;
  1288. }
  1289. function detectFirefox() {
  1290. if (navigator.mozGetUserMedia) {
  1291. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1292. var version = parseInt(
  1293. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1294. console.log('This appears to be Firefox, ver: ' + version);
  1295. return version;
  1296. }
  1297. return null;
  1298. }
  1299. function detectSafari() {
  1300. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1301. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1302. console.info("This appears to be Safari");
  1303. // FIXME detect Safari version when needed
  1304. return 1;
  1305. }
  1306. return null;
  1307. }
  1308. function detectIE() {
  1309. var version;
  1310. var ua = window.navigator.userAgent;
  1311. var msie = ua.indexOf('MSIE ');
  1312. if (msie > 0) {
  1313. // IE 10 or older => return version number
  1314. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1315. }
  1316. var trident = ua.indexOf('Trident/');
  1317. if (!version && trident > 0) {
  1318. // IE 11 => return version number
  1319. var rv = ua.indexOf('rv:');
  1320. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1321. }
  1322. var edge = ua.indexOf('Edge/');
  1323. if (!version && edge > 0) {
  1324. // IE 12 => return version number
  1325. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1326. }
  1327. if (version) {
  1328. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1329. console.info("This appears to be IExplorer, ver: " + version);
  1330. }
  1331. return version;
  1332. }
  1333. function detectBrowser() {
  1334. var version;
  1335. var detectors = [
  1336. detectOpera,
  1337. detectChrome,
  1338. detectFirefox,
  1339. detectIE,
  1340. detectSafari
  1341. ];
  1342. // Try all browser detectors
  1343. for (var i = 0; i < detectors.length; i++) {
  1344. version = detectors[i]();
  1345. if (version)
  1346. return version;
  1347. }
  1348. console.error("Failed to detect browser type");
  1349. return undefined;
  1350. }
  1351. browserVersion = detectBrowser();
  1352. module.exports = RTCBrowserType;
  1353. },{}],11:[function(require,module,exports){
  1354. var RTCBrowserType = require("./RTCBrowserType");
  1355. var Resolutions = require("../../service/RTC/Resolutions");
  1356. var AdapterJS = require("./adapter.screenshare");
  1357. var SDPUtil = require("../xmpp/SDPUtil");
  1358. var currentResolution = null;
  1359. function getPreviousResolution(resolution) {
  1360. if(!Resolutions[resolution])
  1361. return null;
  1362. var order = Resolutions[resolution].order;
  1363. var res = null;
  1364. var resName = null;
  1365. for(var i in Resolutions)
  1366. {
  1367. var tmp = Resolutions[i];
  1368. if(res == null || (res.order < tmp.order && tmp.order < order))
  1369. {
  1370. resName = i;
  1371. res = tmp;
  1372. }
  1373. }
  1374. return resName;
  1375. }
  1376. function setResolutionConstraints(constraints, resolution, isAndroid)
  1377. {
  1378. if (resolution && !constraints.video || isAndroid) {
  1379. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1380. }
  1381. if(Resolutions[resolution])
  1382. {
  1383. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1384. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1385. }
  1386. else
  1387. {
  1388. if (isAndroid) {
  1389. constraints.video.mandatory.minWidth = 320;
  1390. constraints.video.mandatory.minHeight = 240;
  1391. constraints.video.mandatory.maxFrameRate = 15;
  1392. }
  1393. }
  1394. if (constraints.video.mandatory.minWidth)
  1395. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1396. if (constraints.video.mandatory.minHeight)
  1397. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1398. }
  1399. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1400. {
  1401. var constraints = {audio: false, video: false};
  1402. if (um.indexOf('video') >= 0) {
  1403. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1404. }
  1405. if (um.indexOf('audio') >= 0) {
  1406. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1407. }
  1408. if (um.indexOf('screen') >= 0) {
  1409. if (RTCBrowserType.isChrome()) {
  1410. constraints.video = {
  1411. mandatory: {
  1412. chromeMediaSource: "screen",
  1413. googLeakyBucket: true,
  1414. maxWidth: window.screen.width,
  1415. maxHeight: window.screen.height,
  1416. maxFrameRate: 3
  1417. },
  1418. optional: []
  1419. };
  1420. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1421. constraints.video = {
  1422. optional: [
  1423. {
  1424. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1425. }
  1426. ]
  1427. };
  1428. } else {
  1429. console.error(
  1430. "'screen' WebRTC media source is supported only in Chrome" +
  1431. " and with Temasys plugin");
  1432. }
  1433. }
  1434. if (um.indexOf('desktop') >= 0) {
  1435. constraints.video = {
  1436. mandatory: {
  1437. chromeMediaSource: "desktop",
  1438. chromeMediaSourceId: desktopStream,
  1439. googLeakyBucket: true,
  1440. maxWidth: window.screen.width,
  1441. maxHeight: window.screen.height,
  1442. maxFrameRate: 3
  1443. },
  1444. optional: []
  1445. };
  1446. }
  1447. if (constraints.audio) {
  1448. // if it is good enough for hangouts...
  1449. constraints.audio.optional.push(
  1450. {googEchoCancellation: true},
  1451. {googAutoGainControl: true},
  1452. {googNoiseSupression: true},
  1453. {googHighpassFilter: true},
  1454. {googNoisesuppression2: true},
  1455. {googEchoCancellation2: true},
  1456. {googAutoGainControl2: true}
  1457. );
  1458. }
  1459. if (constraints.video) {
  1460. constraints.video.optional.push(
  1461. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1462. );
  1463. if (um.indexOf('video') >= 0) {
  1464. constraints.video.optional.push(
  1465. {googLeakyBucket: true}
  1466. );
  1467. }
  1468. }
  1469. if (um.indexOf('video') >= 0) {
  1470. setResolutionConstraints(constraints, resolution, isAndroid);
  1471. }
  1472. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1473. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1474. constraints.video.optional.push({bandwidth: bandwidth});
  1475. }
  1476. if (fps) { // for some cameras it might be necessary to request 30fps
  1477. // so they choose 30fps mjpg over 10fps yuy2
  1478. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1479. constraints.video.mandatory.minFrameRate = fps;
  1480. }
  1481. return constraints;
  1482. }
  1483. function RTCUtils(RTCService, onTemasysPluginReady)
  1484. {
  1485. var self = this;
  1486. this.service = RTCService;
  1487. if (RTCBrowserType.isFirefox()) {
  1488. var FFversion = RTCBrowserType.getFirefoxVersion();
  1489. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1490. this.peerconnection = mozRTCPeerConnection;
  1491. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1492. this.pc_constraints = {};
  1493. this.attachMediaStream = function (element, stream) {
  1494. // srcObject is being standardized and FF will eventually
  1495. // support that unprefixed. FF also supports the
  1496. // "element.src = URL.createObjectURL(...)" combo, but that
  1497. // will be deprecated in favour of srcObject.
  1498. //
  1499. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1500. // https://github.com/webrtc/samples/issues/302
  1501. if(!element[0])
  1502. return;
  1503. element[0].mozSrcObject = stream;
  1504. element[0].play();
  1505. };
  1506. this.getStreamID = function (stream) {
  1507. var id = stream.id;
  1508. if (!id) {
  1509. var tracks = stream.getVideoTracks();
  1510. if (!tracks || tracks.length === 0)
  1511. {
  1512. tracks = stream.getAudioTracks();
  1513. }
  1514. id = tracks[0].id;
  1515. }
  1516. return SDPUtil.filter_special_chars(id);
  1517. };
  1518. this.getVideoSrc = function (element) {
  1519. if(!element)
  1520. return null;
  1521. return element.mozSrcObject;
  1522. };
  1523. this.setVideoSrc = function (element, src) {
  1524. if(element)
  1525. element.mozSrcObject = src;
  1526. };
  1527. RTCSessionDescription = mozRTCSessionDescription;
  1528. RTCIceCandidate = mozRTCIceCandidate;
  1529. } else {
  1530. console.error(
  1531. "Firefox requirements not met, ver: " + FFversion +
  1532. ", bundle: " + config.useBundle +
  1533. ", rtcp-mux: " + config.useRtcpMux);
  1534. window.location.href = 'unsupported_browser.html';
  1535. return;
  1536. }
  1537. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1538. this.peerconnection = webkitRTCPeerConnection;
  1539. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1540. this.attachMediaStream = function (element, stream) {
  1541. element.attr('src', webkitURL.createObjectURL(stream));
  1542. };
  1543. this.getStreamID = function (stream) {
  1544. // streams from FF endpoints have the characters '{' and '}'
  1545. // that make jQuery choke.
  1546. return SDPUtil.filter_special_chars(stream.id);
  1547. };
  1548. this.getVideoSrc = function (element) {
  1549. if(!element)
  1550. return null;
  1551. return element.getAttribute("src");
  1552. };
  1553. this.setVideoSrc = function (element, src) {
  1554. if(element)
  1555. element.setAttribute("src", src);
  1556. };
  1557. // DTLS should now be enabled by default but..
  1558. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1559. if (navigator.userAgent.indexOf('Android') != -1) {
  1560. this.pc_constraints = {}; // disable DTLS on Android
  1561. }
  1562. if (!webkitMediaStream.prototype.getVideoTracks) {
  1563. webkitMediaStream.prototype.getVideoTracks = function () {
  1564. return this.videoTracks;
  1565. };
  1566. }
  1567. if (!webkitMediaStream.prototype.getAudioTracks) {
  1568. webkitMediaStream.prototype.getAudioTracks = function () {
  1569. return this.audioTracks;
  1570. };
  1571. }
  1572. }
  1573. // Detect IE/Safari
  1574. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1575. //AdapterJS.WebRTCPlugin.setLogLevel(
  1576. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1577. AdapterJS.webRTCReady(function (isPlugin) {
  1578. self.peerconnection = RTCPeerConnection;
  1579. self.getUserMedia = getUserMedia;
  1580. self.attachMediaStream = function (elSel, stream) {
  1581. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1582. return;
  1583. }
  1584. attachMediaStream(elSel[0], stream);
  1585. };
  1586. self.getStreamID = function (stream) {
  1587. var id = SDPUtil.filter_special_chars(stream.label);
  1588. return id;
  1589. };
  1590. self.getVideoSrc = function (element) {
  1591. if (!element) {
  1592. console.warn("Attempt to get video SRC of null element");
  1593. return null;
  1594. }
  1595. var src = null;
  1596. var children = element.children;
  1597. for (var i = 0; i !== children.length; ++i) {
  1598. if (children[i].name === 'streamId') {
  1599. return children[i].value;
  1600. }
  1601. }
  1602. //console.info(element.id + " SRC: " + src);
  1603. return null;
  1604. };
  1605. self.setVideoSrc = function (element, src) {
  1606. //console.info("Set video src: ", element, src);
  1607. if (!src) {
  1608. console.warn("Not attaching video stream, 'src' is null");
  1609. return;
  1610. }
  1611. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1612. var stream = AdapterJS.WebRTCPlugin.plugin
  1613. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1614. attachMediaStream(element, stream);
  1615. };
  1616. onTemasysPluginReady(isPlugin);
  1617. });
  1618. } else {
  1619. try {
  1620. console.log('Browser does not appear to be WebRTC-capable');
  1621. } catch (e) { }
  1622. window.location.href = 'unsupported_browser.html';
  1623. }
  1624. }
  1625. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1626. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1627. desktopStream)
  1628. {
  1629. currentResolution = resolution;
  1630. // Check if we are running on Android device
  1631. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1632. var constraints = getConstraints(
  1633. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1634. console.info("Get media constraints", constraints);
  1635. var self = this;
  1636. try {
  1637. this.getUserMedia(constraints,
  1638. function (stream) {
  1639. console.log('onUserMediaSuccess');
  1640. self.setAvailableDevices(um, true);
  1641. success_callback(stream);
  1642. },
  1643. function (error) {
  1644. self.setAvailableDevices(um, false);
  1645. console.warn('Failed to get access to local media. Error ',
  1646. error, constraints);
  1647. if (failure_callback) {
  1648. failure_callback(error);
  1649. }
  1650. });
  1651. } catch (e) {
  1652. console.error('GUM failed: ', e);
  1653. if(failure_callback) {
  1654. failure_callback(e);
  1655. }
  1656. }
  1657. };
  1658. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1659. var devices = {};
  1660. if(um.indexOf("video") != -1)
  1661. {
  1662. devices.video = available;
  1663. }
  1664. if(um.indexOf("audio") != -1)
  1665. {
  1666. devices.audio = available;
  1667. }
  1668. this.service.setDeviceAvailability(devices);
  1669. }
  1670. /**
  1671. * We ask for audio and video combined stream in order to get permissions and
  1672. * not to ask twice.
  1673. */
  1674. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1675. function(devices, callback, usageOptions)
  1676. {
  1677. var self = this;
  1678. // Get AV
  1679. var successCallback = function (stream) {
  1680. if(callback)
  1681. callback(stream, usageOptions);
  1682. else
  1683. self.successCallback(stream, usageOptions);
  1684. };
  1685. if(!devices)
  1686. devices = ['audio', 'video'];
  1687. var newDevices = [];
  1688. if(usageOptions)
  1689. for(var i = 0; i < devices.length; i++)
  1690. {
  1691. var device = devices[i];
  1692. if(usageOptions[device] === true)
  1693. newDevices.push(device);
  1694. }
  1695. else
  1696. newDevices = devices;
  1697. if(newDevices.length === 0)
  1698. {
  1699. successCallback();
  1700. return;
  1701. }
  1702. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1703. // With FF/IE we can't split the stream into audio and video because FF
  1704. // doesn't support media stream constructors. So, we need to get the
  1705. // audio stream separately from the video stream using two distinct GUM
  1706. // calls. Not very user friendly :-( but we don't have many other
  1707. // options neither.
  1708. //
  1709. // Note that we pack those 2 streams in a single object and pass it to
  1710. // the successCallback method.
  1711. var obtainVideo = function (audioStream) {
  1712. self.getUserMediaWithConstraints(
  1713. ['video'],
  1714. function (videoStream) {
  1715. return successCallback({
  1716. audioStream: audioStream,
  1717. videoStream: videoStream
  1718. });
  1719. },
  1720. function (error) {
  1721. console.error(
  1722. 'failed to obtain video stream - stop', error);
  1723. self.errorCallback(error);
  1724. },
  1725. config.resolution || '360');
  1726. };
  1727. var obtainAudio = function () {
  1728. self.getUserMediaWithConstraints(
  1729. ['audio'],
  1730. function (audioStream) {
  1731. if (newDevices.indexOf('video') !== -1)
  1732. obtainVideo(audioStream);
  1733. },
  1734. function (error) {
  1735. console.error(
  1736. 'failed to obtain audio stream - stop', error);
  1737. self.errorCallback(error);
  1738. }
  1739. );
  1740. };
  1741. if (newDevices.indexOf('audio') !== -1) {
  1742. obtainAudio();
  1743. } else {
  1744. obtainVideo(null);
  1745. }
  1746. } else {
  1747. this.getUserMediaWithConstraints(
  1748. newDevices,
  1749. function (stream) {
  1750. successCallback(stream);
  1751. },
  1752. function (error) {
  1753. self.errorCallback(error);
  1754. },
  1755. config.resolution || '360');
  1756. }
  1757. };
  1758. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1759. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1760. // it's an object with two properties: audioStream, videoStream.
  1761. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1762. console.log('got', stream, stream.getAudioTracks().length,
  1763. stream.getVideoTracks().length);
  1764. this.handleLocalStream(stream, usageOptions);
  1765. };
  1766. RTCUtils.prototype.errorCallback = function (error) {
  1767. var self = this;
  1768. console.error('failed to obtain audio/video stream - trying audio only', error);
  1769. var resolution = getPreviousResolution(currentResolution);
  1770. if(typeof error == "object" && error.constraintName && error.name
  1771. && (error.name == "ConstraintNotSatisfiedError" ||
  1772. error.name == "OverconstrainedError") &&
  1773. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1774. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1775. && resolution != null)
  1776. {
  1777. self.getUserMediaWithConstraints(['audio', 'video'],
  1778. function (stream) {
  1779. return self.successCallback(stream);
  1780. }, function (error) {
  1781. return self.errorCallback(error);
  1782. }, resolution);
  1783. }
  1784. else
  1785. {
  1786. self.getUserMediaWithConstraints(
  1787. ['audio'],
  1788. function (stream) {
  1789. return self.successCallback(stream);
  1790. },
  1791. function (error) {
  1792. console.error('failed to obtain audio/video stream - stop',
  1793. error);
  1794. return self.successCallback(null);
  1795. }
  1796. );
  1797. }
  1798. }
  1799. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1800. {
  1801. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1802. // an object with two properties: audioStream, videoStream.
  1803. var audioStream, videoStream;
  1804. if(window.webkitMediaStream)
  1805. {
  1806. audioStream = new webkitMediaStream();
  1807. videoStream = new webkitMediaStream();
  1808. if(stream) {
  1809. var audioTracks = stream.getAudioTracks();
  1810. for (var i = 0; i < audioTracks.length; i++) {
  1811. audioStream.addTrack(audioTracks[i]);
  1812. }
  1813. var videoTracks = stream.getVideoTracks();
  1814. for (i = 0; i < videoTracks.length; i++) {
  1815. videoStream.addTrack(videoTracks[i]);
  1816. }
  1817. }
  1818. }
  1819. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1820. { // Firefox and Temasys plugin
  1821. if (stream && stream.audioStream)
  1822. audioStream = stream.audioStream;
  1823. else
  1824. audioStream = new DummyMediaStream("dummyAudio");
  1825. if (stream && stream.videoStream)
  1826. videoStream = stream.videoStream;
  1827. else
  1828. videoStream = new DummyMediaStream("dummyVideo");
  1829. }
  1830. var audioMuted = (usageOptions && usageOptions.audio === false),
  1831. videoMuted = (usageOptions && usageOptions.video === false);
  1832. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1833. videoGUM = (!usageOptions || usageOptions.video !== false);
  1834. this.service.createLocalStream(audioStream, "audio", null, null,
  1835. audioMuted, audioGUM);
  1836. this.service.createLocalStream(videoStream, "video", null, null,
  1837. videoMuted, videoGUM);
  1838. };
  1839. function DummyMediaStream(id) {
  1840. this.id = id;
  1841. this.label = id;
  1842. this.stop = function() { };
  1843. this.getAudioTracks = function() { return []; }
  1844. this.getVideoTracks = function() { return []; }
  1845. }
  1846. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1847. var newStream = null;
  1848. if (window.webkitMediaStream) {
  1849. newStream = new webkitMediaStream();
  1850. if (newStream) {
  1851. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1852. for (i = 0; i < tracks.length; i++) {
  1853. newStream.addTrack(tracks[i]);
  1854. }
  1855. }
  1856. }
  1857. else {
  1858. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1859. if (stream) {
  1860. newStream = stream;
  1861. } else {
  1862. newStream = new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1863. }
  1864. }
  1865. return newStream;
  1866. };
  1867. module.exports = RTCUtils;
  1868. },{"../../service/RTC/Resolutions":102,"../xmpp/SDPUtil":58,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){
  1869. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1870. // Adapter's interface.
  1871. var AdapterJS = AdapterJS || {};
  1872. // Browserify compatibility
  1873. if(typeof exports !== 'undefined') {
  1874. module.exports = AdapterJS;
  1875. }
  1876. AdapterJS.options = AdapterJS.options || {};
  1877. // uncomment to get virtual webcams
  1878. // AdapterJS.options.getAllCams = true;
  1879. // uncomment to prevent the install prompt when the plugin in not yet installed
  1880. // AdapterJS.options.hidePluginInstallPrompt = true;
  1881. // AdapterJS version
  1882. AdapterJS.VERSION = '0.11.0';
  1883. // This function will be called when the WebRTC API is ready to be used
  1884. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1885. // the plugin
  1886. // You may Override this function to synchronise the start of your application
  1887. // with the WebRTC API being ready.
  1888. // If you decide not to override use this synchronisation, it may result in
  1889. // an extensive CPU usage on the plugin start (once per tab loaded)
  1890. // Params:
  1891. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1892. //
  1893. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1894. // The WebRTC API is ready.
  1895. // Override me and do whatever you want here
  1896. };
  1897. // Sets a callback function to be called when the WebRTC interface is ready.
  1898. // The first argument is the function to callback.\
  1899. // Throws an error if the first argument is not a function
  1900. AdapterJS.webRTCReady = function (callback) {
  1901. if (typeof callback !== 'function') {
  1902. throw new Error('Callback provided is not a function');
  1903. }
  1904. if (true === AdapterJS.onwebrtcreadyDone) {
  1905. // All WebRTC interfaces are ready, just call the callback
  1906. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1907. } else {
  1908. // will be triggered automatically when your browser/plugin is ready.
  1909. AdapterJS.onwebrtcready = callback;
  1910. }
  1911. };
  1912. // Plugin namespace
  1913. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1914. // The object to store plugin information
  1915. AdapterJS.WebRTCPlugin.pluginInfo = {
  1916. prefix : 'Tem',
  1917. plugName : 'TemWebRTCPlugin',
  1918. pluginId : 'plugin0',
  1919. type : 'application/x-temwebrtcplugin',
  1920. onload : '__TemWebRTCReady0',
  1921. portalLink : 'http://skylink.io/plugin/',
  1922. downloadLink : null, //set below
  1923. companyName: 'Temasys'
  1924. };
  1925. if(!!navigator.platform.match(/^Mac/i)) {
  1926. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1927. }
  1928. else if(!!navigator.platform.match(/^Win/i)) {
  1929. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1930. }
  1931. // Unique identifier of each opened page
  1932. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1933. // Use this whenever you want to call the plugin.
  1934. AdapterJS.WebRTCPlugin.plugin = null;
  1935. // Set log level for the plugin once it is ready.
  1936. // The different values are
  1937. // This is an asynchronous function that will run when the plugin is ready
  1938. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1939. // Defines webrtc's JS interface according to the plugin's implementation.
  1940. // Define plugin Browsers as WebRTC Interface.
  1941. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1942. // This function detects whether or not a plugin is installed.
  1943. // Checks if Not IE (firefox, for example), else if it's IE,
  1944. // we're running IE and do something. If not it is not supported.
  1945. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1946. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1947. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1948. // Inject the HTML DOM object element into the page.
  1949. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1950. // States of readiness that the plugin goes through when
  1951. // being injected and stated
  1952. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1953. NONE : 0, // no plugin use
  1954. INITIALIZING : 1, // Detected need for plugin
  1955. INJECTING : 2, // Injecting plugin
  1956. INJECTED: 3, // Plugin element injected but not usable yet
  1957. READY: 4 // Plugin ready to be used
  1958. };
  1959. // Current state of the plugin. You cannot use the plugin before this is
  1960. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1961. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1962. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1963. // Used to make sure AdapterJS.onwebrtcready is only called once
  1964. AdapterJS.onwebrtcreadyDone = false;
  1965. // Log levels for the plugin.
  1966. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1967. /*
  1968. Log outputs are prefixed in some cases.
  1969. INFO: Information reported by the plugin.
  1970. ERROR: Errors originating from within the plugin.
  1971. WEBRTC: Error originating from within the libWebRTC library
  1972. */
  1973. // From the least verbose to the most verbose
  1974. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1975. NONE : 'NONE',
  1976. ERROR : 'ERROR',
  1977. WARNING : 'WARNING',
  1978. INFO: 'INFO',
  1979. VERBOSE: 'VERBOSE',
  1980. SENSITIVE: 'SENSITIVE'
  1981. };
  1982. // Does a waiting check before proceeding to load the plugin.
  1983. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1984. // This methid will use an interval to wait for the plugin to be ready.
  1985. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1986. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1987. // This function will be called when plugin is ready. It sends necessary
  1988. // details to the plugin.
  1989. // The function will wait for the document to be ready and the set the
  1990. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1991. // indicating that it can start being requested.
  1992. // This function is not in the IE/Safari condition brackets so that
  1993. // TemPluginLoaded function might be called on Chrome/Firefox.
  1994. // This function is the only private function that is not encapsulated to
  1995. // allow the plugin method to be called.
  1996. __TemWebRTCReady0 = function () {
  1997. if (document.readyState === 'complete') {
  1998. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1999. AdapterJS.maybeThroughWebRTCReady();
  2000. } else {
  2001. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2002. if (document.readyState === 'complete') {
  2003. // TODO: update comments, we wait for the document to be ready
  2004. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2005. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2006. AdapterJS.maybeThroughWebRTCReady();
  2007. }
  2008. }, 100);
  2009. }
  2010. };
  2011. AdapterJS.maybeThroughWebRTCReady = function() {
  2012. if (!AdapterJS.onwebrtcreadyDone) {
  2013. AdapterJS.onwebrtcreadyDone = true;
  2014. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2015. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2016. }
  2017. }
  2018. };
  2019. // Text namespace
  2020. AdapterJS.TEXT = {
  2021. PLUGIN: {
  2022. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2023. 'to work on this browser.',
  2024. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2025. BUTTON: 'Install Now'
  2026. },
  2027. REFRESH: {
  2028. REQUIRE_REFRESH: 'Please refresh page',
  2029. BUTTON: 'Refresh Page'
  2030. }
  2031. };
  2032. // The result of ice connection states.
  2033. // - starting: Ice connection is starting.
  2034. // - checking: Ice connection is checking.
  2035. // - connected Ice connection is connected.
  2036. // - completed Ice connection is connected.
  2037. // - done Ice connection has been completed.
  2038. // - disconnected Ice connection has been disconnected.
  2039. // - failed Ice connection has failed.
  2040. // - closed Ice connection is closed.
  2041. AdapterJS._iceConnectionStates = {
  2042. starting : 'starting',
  2043. checking : 'checking',
  2044. connected : 'connected',
  2045. completed : 'connected',
  2046. done : 'completed',
  2047. disconnected : 'disconnected',
  2048. failed : 'failed',
  2049. closed : 'closed'
  2050. };
  2051. //The IceConnection states that has been fired for each peer.
  2052. AdapterJS._iceConnectionFiredStates = [];
  2053. // Check if WebRTC Interface is defined.
  2054. AdapterJS.isDefined = null;
  2055. // This function helps to retrieve the webrtc detected browser information.
  2056. // This sets:
  2057. // - webrtcDetectedBrowser: The browser agent name.
  2058. // - webrtcDetectedVersion: The browser version.
  2059. // - webrtcDetectedType: The types of webRTC support.
  2060. // - 'moz': Mozilla implementation of webRTC.
  2061. // - 'webkit': WebKit implementation of webRTC.
  2062. // - 'plugin': Using the plugin implementation.
  2063. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2064. var hasMatch, checkMatch = navigator.userAgent.match(
  2065. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2066. if (/trident/i.test(checkMatch[1])) {
  2067. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2068. webrtcDetectedBrowser = 'IE';
  2069. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2070. } else if (checkMatch[1] === 'Chrome') {
  2071. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2072. if (hasMatch !== null) {
  2073. webrtcDetectedBrowser = 'opera';
  2074. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2075. }
  2076. }
  2077. if (navigator.userAgent.indexOf('Safari')) {
  2078. if (typeof InstallTrigger !== 'undefined') {
  2079. webrtcDetectedBrowser = 'firefox';
  2080. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2081. webrtcDetectedBrowser = 'IE';
  2082. } else if (
  2083. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2084. webrtcDetectedBrowser = 'safari';
  2085. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2086. webrtcDetectedBrowser = 'opera';
  2087. } else if (!!window.chrome) {
  2088. webrtcDetectedBrowser = 'chrome';
  2089. }
  2090. }
  2091. if (!webrtcDetectedBrowser) {
  2092. webrtcDetectedVersion = checkMatch[1];
  2093. }
  2094. if (!webrtcDetectedVersion) {
  2095. try {
  2096. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2097. [navigator.appName, navigator.appVersion, '-?'];
  2098. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2099. checkMatch.splice(1, 1, hasMatch[1]);
  2100. }
  2101. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2102. } catch (error) { }
  2103. }
  2104. };
  2105. // To fix configuration as some browsers does not support
  2106. // the 'urls' attribute.
  2107. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2108. if (pcConfig === null) {
  2109. return;
  2110. }
  2111. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2112. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2113. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2114. delete pcConfig.iceServers[i].urls;
  2115. }
  2116. }
  2117. };
  2118. AdapterJS.addEvent = function(elem, evnt, func) {
  2119. if (elem.addEventListener) { // W3C DOM
  2120. elem.addEventListener(evnt, func, false);
  2121. } else if (elem.attachEvent) {// OLD IE DOM
  2122. elem.attachEvent('on'+evnt, func);
  2123. } else { // No much to do
  2124. elem[evnt] = func;
  2125. }
  2126. };
  2127. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2128. // only inject once the page is ready
  2129. if (document.readyState !== 'complete') {
  2130. return;
  2131. }
  2132. var w = window;
  2133. var i = document.createElement('iframe');
  2134. i.style.position = 'fixed';
  2135. i.style.top = '-41px';
  2136. i.style.left = 0;
  2137. i.style.right = 0;
  2138. i.style.width = '100%';
  2139. i.style.height = '40px';
  2140. i.style.backgroundColor = '#ffffe1';
  2141. i.style.border = 'none';
  2142. i.style.borderBottom = '1px solid #888888';
  2143. i.style.zIndex = '9999999';
  2144. if(typeof i.style.webkitTransition === 'string') {
  2145. i.style.webkitTransition = 'all .5s ease-out';
  2146. } else if(typeof i.style.transition === 'string') {
  2147. i.style.transition = 'all .5s ease-out';
  2148. }
  2149. document.body.appendChild(i);
  2150. c = (i.contentWindow) ? i.contentWindow :
  2151. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2152. c.document.open();
  2153. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2154. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2155. 'middle; cursor: default;">' + text + '</span>');
  2156. if(buttonText && buttonLink) {
  2157. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2158. c.document.close();
  2159. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2160. if (!!displayRefreshBar) {
  2161. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2162. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2163. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2164. }
  2165. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2166. e.preventDefault();
  2167. try {
  2168. event.cancelBubble = true;
  2169. } catch(error) { }
  2170. });
  2171. }
  2172. else {
  2173. c.document.close();
  2174. }
  2175. AdapterJS.addEvent(c.document, 'click', function() {
  2176. w.document.body.removeChild(i);
  2177. });
  2178. setTimeout(function() {
  2179. if(typeof i.style.webkitTransform === 'string') {
  2180. i.style.webkitTransform = 'translateY(40px)';
  2181. } else if(typeof i.style.transform === 'string') {
  2182. i.style.transform = 'translateY(40px)';
  2183. } else {
  2184. i.style.top = '0px';
  2185. }
  2186. }, 300);
  2187. };
  2188. // -----------------------------------------------------------
  2189. // Detected webrtc implementation. Types are:
  2190. // - 'moz': Mozilla implementation of webRTC.
  2191. // - 'webkit': WebKit implementation of webRTC.
  2192. // - 'plugin': Using the plugin implementation.
  2193. webrtcDetectedType = null;
  2194. // Detected webrtc datachannel support. Types are:
  2195. // - 'SCTP': SCTP datachannel support.
  2196. // - 'RTP': RTP datachannel support.
  2197. webrtcDetectedDCSupport = null;
  2198. // Set the settings for creating DataChannels, MediaStream for
  2199. // Cross-browser compability.
  2200. // - This is only for SCTP based support browsers.
  2201. // the 'urls' attribute.
  2202. checkMediaDataChannelSettings =
  2203. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2204. if (typeof callback !== 'function') {
  2205. return;
  2206. }
  2207. var beOfferer = true;
  2208. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2209. // Nightly version does not require MozDontOfferDataChannel for interop
  2210. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2211. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2212. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2213. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2214. // Resends an updated version of constraints for MozDataChannel to work
  2215. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2216. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2217. try {
  2218. delete constraints.mandatory.MozDontOfferDataChannel;
  2219. } catch (error) {
  2220. console.error('Failed deleting MozDontOfferDataChannel');
  2221. console.error(error);
  2222. }
  2223. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2224. constraints.mandatory.MozDontOfferDataChannel = true;
  2225. }
  2226. if (!isLocalFirefox) {
  2227. // temporary measure to remove Moz* constraints in non Firefox browsers
  2228. for (var prop in constraints.mandatory) {
  2229. if (constraints.mandatory.hasOwnProperty(prop)) {
  2230. if (prop.indexOf('Moz') !== -1) {
  2231. delete constraints.mandatory[prop];
  2232. }
  2233. }
  2234. }
  2235. }
  2236. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2237. // interopability of the media stream
  2238. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2239. beOfferer = false;
  2240. }
  2241. callback(beOfferer, constraints);
  2242. };
  2243. // Handles the differences for all browsers ice connection state output.
  2244. // - Tested outcomes are:
  2245. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2246. // - Chrome (answerer) : 'checking' > 'connected'
  2247. // - Firefox (offerer) : 'checking' > 'connected'
  2248. // - Firefox (answerer): 'checking' > 'connected'
  2249. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2250. if (typeof callback !== 'function') {
  2251. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2252. return;
  2253. }
  2254. peerId = (peerId) ? peerId : 'peer';
  2255. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2256. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2257. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2258. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2259. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2260. }
  2261. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2262. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2263. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2264. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2265. setTimeout(function () {
  2266. AdapterJS._iceConnectionFiredStates[peerId]
  2267. .push(AdapterJS._iceConnectionStates.done);
  2268. callback(AdapterJS._iceConnectionStates.done);
  2269. }, 1000);
  2270. }
  2271. callback(iceConnectionState);
  2272. }
  2273. return;
  2274. };
  2275. // Firefox:
  2276. // - Creates iceServer from the url for Firefox.
  2277. // - Create iceServer with stun url.
  2278. // - Create iceServer with turn url.
  2279. // - Ignore the transport parameter from TURN url for FF version <=27.
  2280. // - Return null for createIceServer if transport=tcp.
  2281. // - FF 27 and above supports transport parameters in TURN url,
  2282. // - So passing in the full url to create iceServer.
  2283. // Chrome:
  2284. // - Creates iceServer from the url for Chrome M33 and earlier.
  2285. // - Create iceServer with stun url.
  2286. // - Chrome M28 & above uses below TURN format.
  2287. // Plugin:
  2288. // - Creates Ice Server for Plugin Browsers
  2289. // - If Stun - Create iceServer with stun url.
  2290. // - Else - Create iceServer with turn url
  2291. // - This is a WebRTC Function
  2292. createIceServer = null;
  2293. // Firefox:
  2294. // - Creates IceServers for Firefox
  2295. // - Use .url for FireFox.
  2296. // - Multiple Urls support
  2297. // Chrome:
  2298. // - Creates iceServers from the urls for Chrome M34 and above.
  2299. // - .urls is supported since Chrome M34.
  2300. // - Multiple Urls support
  2301. // Plugin:
  2302. // - Creates Ice Servers for Plugin Browsers
  2303. // - Multiple Urls support
  2304. // - This is a WebRTC Function
  2305. createIceServers = null;
  2306. //------------------------------------------------------------
  2307. //The RTCPeerConnection object.
  2308. RTCPeerConnection = null;
  2309. // Creates RTCSessionDescription object for Plugin Browsers
  2310. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2311. RTCSessionDescription : null;
  2312. // Creates RTCIceCandidate object for Plugin Browsers
  2313. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2314. RTCIceCandidate : null;
  2315. // Get UserMedia (only difference is the prefix).
  2316. // Code from Adam Barth.
  2317. getUserMedia = null;
  2318. // Attach a media stream to an element.
  2319. attachMediaStream = null;
  2320. // Re-attach a media stream to an element.
  2321. reattachMediaStream = null;
  2322. // Detected browser agent name. Types are:
  2323. // - 'firefox': Firefox browser.
  2324. // - 'chrome': Chrome browser.
  2325. // - 'opera': Opera browser.
  2326. // - 'safari': Safari browser.
  2327. // - 'IE' - Internet Explorer browser.
  2328. webrtcDetectedBrowser = null;
  2329. // Detected browser version.
  2330. webrtcDetectedVersion = null;
  2331. // Check for browser types and react accordingly
  2332. if (navigator.mozGetUserMedia) {
  2333. webrtcDetectedBrowser = 'firefox';
  2334. webrtcDetectedVersion = parseInt(navigator
  2335. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2336. webrtcDetectedType = 'moz';
  2337. webrtcDetectedDCSupport = 'SCTP';
  2338. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2339. AdapterJS.maybeFixConfiguration(pcConfig);
  2340. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2341. };
  2342. // The RTCSessionDescription object.
  2343. RTCSessionDescription = mozRTCSessionDescription;
  2344. window.RTCSessionDescription = RTCSessionDescription;
  2345. // The RTCIceCandidate object.
  2346. RTCIceCandidate = mozRTCIceCandidate;
  2347. window.RTCIceCandidate = RTCIceCandidate;
  2348. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2349. navigator.getUserMedia = window.getUserMedia;
  2350. // Shim for MediaStreamTrack.getSources.
  2351. MediaStreamTrack.getSources = function(successCb) {
  2352. setTimeout(function() {
  2353. var infos = [
  2354. { kind: 'audio', id: 'default', label:'', facing:'' },
  2355. { kind: 'video', id: 'default', label:'', facing:'' }
  2356. ];
  2357. successCb(infos);
  2358. }, 0);
  2359. };
  2360. createIceServer = function (url, username, password) {
  2361. var iceServer = null;
  2362. var url_parts = url.split(':');
  2363. if (url_parts[0].indexOf('stun') === 0) {
  2364. iceServer = { url : url };
  2365. } else if (url_parts[0].indexOf('turn') === 0) {
  2366. if (webrtcDetectedVersion < 27) {
  2367. var turn_url_parts = url.split('?');
  2368. if (turn_url_parts.length === 1 ||
  2369. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2370. iceServer = {
  2371. url : turn_url_parts[0],
  2372. credential : password,
  2373. username : username
  2374. };
  2375. }
  2376. } else {
  2377. iceServer = {
  2378. url : url,
  2379. credential : password,
  2380. username : username
  2381. };
  2382. }
  2383. }
  2384. return iceServer;
  2385. };
  2386. createIceServers = function (urls, username, password) {
  2387. var iceServers = [];
  2388. for (i = 0; i < urls.length; i++) {
  2389. var iceServer = createIceServer(urls[i], username, password);
  2390. if (iceServer !== null) {
  2391. iceServers.push(iceServer);
  2392. }
  2393. }
  2394. return iceServers;
  2395. };
  2396. attachMediaStream = function (element, stream) {
  2397. element.mozSrcObject = stream;
  2398. if (stream !== null)
  2399. element.play();
  2400. return element;
  2401. };
  2402. reattachMediaStream = function (to, from) {
  2403. to.mozSrcObject = from.mozSrcObject;
  2404. to.play();
  2405. return to;
  2406. };
  2407. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2408. if (!callback) {
  2409. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2410. ': 1 argument required, but only 0 present.');
  2411. }
  2412. return callback([]);
  2413. };
  2414. // Fake get{Video,Audio}Tracks
  2415. if (!MediaStream.prototype.getVideoTracks) {
  2416. MediaStream.prototype.getVideoTracks = function () {
  2417. return [];
  2418. };
  2419. }
  2420. if (!MediaStream.prototype.getAudioTracks) {
  2421. MediaStream.prototype.getAudioTracks = function () {
  2422. return [];
  2423. };
  2424. }
  2425. AdapterJS.maybeThroughWebRTCReady();
  2426. } else if (navigator.webkitGetUserMedia) {
  2427. webrtcDetectedBrowser = 'chrome';
  2428. webrtcDetectedType = 'webkit';
  2429. webrtcDetectedVersion = parseInt(navigator
  2430. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2431. // check if browser is opera 20+
  2432. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2433. if (checkIfOpera !== null) {
  2434. webrtcDetectedBrowser = 'opera';
  2435. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2436. }
  2437. // check browser datachannel support
  2438. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2439. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2440. webrtcDetectedDCSupport = 'SCTP';
  2441. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2442. webrtcDetectedVersion > 24) {
  2443. webrtcDetectedDCSupport = 'RTP';
  2444. } else {
  2445. webrtcDetectedDCSupport = '';
  2446. }
  2447. createIceServer = function (url, username, password) {
  2448. var iceServer = null;
  2449. var url_parts = url.split(':');
  2450. if (url_parts[0].indexOf('stun') === 0) {
  2451. iceServer = { 'url' : url };
  2452. } else if (url_parts[0].indexOf('turn') === 0) {
  2453. iceServer = {
  2454. 'url' : url,
  2455. 'credential' : password,
  2456. 'username' : username
  2457. };
  2458. }
  2459. return iceServer;
  2460. };
  2461. createIceServers = function (urls, username, password) {
  2462. var iceServers = [];
  2463. if (webrtcDetectedVersion >= 34) {
  2464. iceServers = {
  2465. 'urls' : urls,
  2466. 'credential' : password,
  2467. 'username' : username
  2468. };
  2469. } else {
  2470. for (i = 0; i < urls.length; i++) {
  2471. var iceServer = createIceServer(urls[i], username, password);
  2472. if (iceServer !== null) {
  2473. iceServers.push(iceServer);
  2474. }
  2475. }
  2476. }
  2477. return iceServers;
  2478. };
  2479. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2480. if (webrtcDetectedVersion < 34) {
  2481. AdapterJS.maybeFixConfiguration(pcConfig);
  2482. }
  2483. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2484. };
  2485. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2486. navigator.getUserMedia = window.getUserMedia;
  2487. attachMediaStream = function (element, stream) {
  2488. if (typeof element.srcObject !== 'undefined') {
  2489. element.srcObject = stream;
  2490. } else if (typeof element.mozSrcObject !== 'undefined') {
  2491. element.mozSrcObject = stream;
  2492. } else if (typeof element.src !== 'undefined') {
  2493. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2494. } else {
  2495. console.log('Error attaching stream to element.');
  2496. }
  2497. return element;
  2498. };
  2499. reattachMediaStream = function (to, from) {
  2500. to.src = from.src;
  2501. return to;
  2502. };
  2503. AdapterJS.maybeThroughWebRTCReady();
  2504. } else { // TRY TO USE PLUGIN
  2505. // IE 9 is not offering an implementation of console.log until you open a console
  2506. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2507. /* jshint -W020 */
  2508. console = {} || console;
  2509. // Implemented based on console specs from MDN
  2510. // You may override these functions
  2511. console.log = function (arg) {};
  2512. console.info = function (arg) {};
  2513. console.error = function (arg) {};
  2514. console.dir = function (arg) {};
  2515. console.exception = function (arg) {};
  2516. console.trace = function (arg) {};
  2517. console.warn = function (arg) {};
  2518. console.count = function (arg) {};
  2519. console.debug = function (arg) {};
  2520. console.count = function (arg) {};
  2521. console.time = function (arg) {};
  2522. console.timeEnd = function (arg) {};
  2523. console.group = function (arg) {};
  2524. console.groupCollapsed = function (arg) {};
  2525. console.groupEnd = function (arg) {};
  2526. /* jshint +W020 */
  2527. }
  2528. webrtcDetectedType = 'plugin';
  2529. webrtcDetectedDCSupport = 'plugin';
  2530. AdapterJS.parseWebrtcDetectedBrowser();
  2531. isIE = webrtcDetectedBrowser === 'IE';
  2532. /* jshint -W035 */
  2533. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2534. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2535. /* empty because it needs to prevent the function from running. */
  2536. }
  2537. };
  2538. /* jshint +W035 */
  2539. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2540. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2541. // Call immediately if possible
  2542. // Once the plugin is set, the code will always take this path
  2543. callback();
  2544. } else {
  2545. // otherwise start a 100ms interval
  2546. var checkPluginReadyState = setInterval(function () {
  2547. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2548. clearInterval(checkPluginReadyState);
  2549. callback();
  2550. }
  2551. }, 100);
  2552. }
  2553. };
  2554. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2555. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2556. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2557. });
  2558. };
  2559. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2560. // only inject once the page is ready
  2561. if (document.readyState !== 'complete') {
  2562. return;
  2563. }
  2564. // Prevent multiple injections
  2565. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2566. return;
  2567. }
  2568. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2569. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2570. var frag = document.createDocumentFragment();
  2571. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2572. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2573. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2574. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2575. '<param name="pluginId" value="' +
  2576. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2577. '<param name="windowless" value="false" /> ' +
  2578. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2579. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2580. '" />' +
  2581. // uncomment to be able to use virtual cams
  2582. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2583. '</object>';
  2584. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2585. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2586. }
  2587. document.body.appendChild(frag);
  2588. // Need to re-fetch the plugin
  2589. AdapterJS.WebRTCPlugin.plugin =
  2590. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2591. } else {
  2592. // Load Plugin
  2593. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2594. AdapterJS.WebRTCPlugin.plugin.id =
  2595. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2596. // IE will only start the plugin if it's ACTUALLY visible
  2597. if (isIE) {
  2598. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2599. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2600. } else { // The size of the plugin on Safari should be 0x0px
  2601. // so that the autorisation prompt is at the top
  2602. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2603. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2604. }
  2605. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2606. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2607. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2608. '<param name="pluginId" value="' +
  2609. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2610. '<param name="windowless" value="false" /> ' +
  2611. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2612. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2613. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2614. }
  2615. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2616. };
  2617. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2618. function (comName, plugName, installedCb, notInstalledCb) {
  2619. if (!isIE) {
  2620. var pluginArray = navigator.plugins;
  2621. for (var i = 0; i < pluginArray.length; i++) {
  2622. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2623. installedCb();
  2624. return;
  2625. }
  2626. }
  2627. notInstalledCb();
  2628. } else {
  2629. try {
  2630. var axo = new ActiveXObject(comName + '.' + plugName);
  2631. } catch (e) {
  2632. notInstalledCb();
  2633. return;
  2634. }
  2635. installedCb();
  2636. }
  2637. };
  2638. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2639. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2640. AdapterJS.isDefined = function (variable) {
  2641. return variable !== null && variable !== undefined;
  2642. };
  2643. createIceServer = function (url, username, password) {
  2644. var iceServer = null;
  2645. var url_parts = url.split(':');
  2646. if (url_parts[0].indexOf('stun') === 0) {
  2647. iceServer = {
  2648. 'url' : url,
  2649. 'hasCredentials' : false
  2650. };
  2651. } else if (url_parts[0].indexOf('turn') === 0) {
  2652. iceServer = {
  2653. 'url' : url,
  2654. 'hasCredentials' : true,
  2655. 'credential' : password,
  2656. 'username' : username
  2657. };
  2658. }
  2659. return iceServer;
  2660. };
  2661. createIceServers = function (urls, username, password) {
  2662. var iceServers = [];
  2663. for (var i = 0; i < urls.length; ++i) {
  2664. iceServers.push(createIceServer(urls[i], username, password));
  2665. }
  2666. return iceServers;
  2667. };
  2668. RTCSessionDescription = function (info) {
  2669. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2670. return AdapterJS.WebRTCPlugin.plugin.
  2671. ConstructSessionDescription(info.type, info.sdp);
  2672. };
  2673. RTCPeerConnection = function (servers, constraints) {
  2674. var iceServers = null;
  2675. if (servers) {
  2676. iceServers = servers.iceServers;
  2677. for (var i = 0; i < iceServers.length; i++) {
  2678. if (iceServers[i].urls && !iceServers[i].url) {
  2679. iceServers[i].url = iceServers[i].urls;
  2680. }
  2681. iceServers[i].hasCredentials = AdapterJS.
  2682. isDefined(iceServers[i].username) &&
  2683. AdapterJS.isDefined(iceServers[i].credential);
  2684. }
  2685. }
  2686. var mandatory = (constraints && constraints.mandatory) ?
  2687. constraints.mandatory : null;
  2688. var optional = (constraints && constraints.optional) ?
  2689. constraints.optional : null;
  2690. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2691. return AdapterJS.WebRTCPlugin.plugin.
  2692. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2693. iceServers, mandatory, optional);
  2694. };
  2695. MediaStreamTrack = {};
  2696. MediaStreamTrack.getSources = function (callback) {
  2697. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2698. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2699. });
  2700. };
  2701. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2702. constraints.audio = constraints.audio || false;
  2703. constraints.video = constraints.video || false;
  2704. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2705. AdapterJS.WebRTCPlugin.plugin.
  2706. getUserMedia(constraints, successCallback, failureCallback);
  2707. });
  2708. };
  2709. window.navigator.getUserMedia = window.getUserMedia;
  2710. attachMediaStream = function (element, stream) {
  2711. if (!element || !element.parentNode) {
  2712. return;
  2713. }
  2714. var streamId
  2715. if (stream === null) {
  2716. streamId = '';
  2717. }
  2718. else {
  2719. stream.enableSoundTracks(true);
  2720. streamId = stream.id;
  2721. }
  2722. if (element.nodeName.toLowerCase() !== 'audio') {
  2723. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2724. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2725. var frag = document.createDocumentFragment();
  2726. var temp = document.createElement('div');
  2727. var classHTML = '';
  2728. if (element.className) {
  2729. classHTML = 'class="' + element.className + '" ';
  2730. } else if (element.attributes && element.attributes['class']) {
  2731. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2732. }
  2733. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2734. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2735. '<param name="pluginId" value="' + elementId + '" /> ' +
  2736. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2737. '<param name="windowless" value="true" /> ' +
  2738. '<param name="streamId" value="' + streamId + '" /> ' +
  2739. '</object>';
  2740. while (temp.firstChild) {
  2741. frag.appendChild(temp.firstChild);
  2742. }
  2743. var height = '';
  2744. var width = '';
  2745. if (element.getBoundingClientRect) {
  2746. var rectObject = element.getBoundingClientRect();
  2747. width = rectObject.width + 'px';
  2748. height = rectObject.height + 'px';
  2749. }
  2750. else if (element.width) {
  2751. width = element.width;
  2752. height = element.height;
  2753. } else {
  2754. // TODO: What scenario could bring us here?
  2755. }
  2756. element.parentNode.insertBefore(frag, element);
  2757. frag = document.getElementById(elementId);
  2758. frag.width = width;
  2759. frag.height = height;
  2760. element.parentNode.removeChild(element);
  2761. } else {
  2762. var children = element.children;
  2763. for (var i = 0; i !== children.length; ++i) {
  2764. if (children[i].name === 'streamId') {
  2765. children[i].value = streamId;
  2766. break;
  2767. }
  2768. }
  2769. element.setStreamId(streamId);
  2770. }
  2771. var newElement = document.getElementById(elementId);
  2772. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2773. if (isIE) { // on IE the event needs to be plugged manually
  2774. newElement.attachEvent('onplaying', newElement.onplaying);
  2775. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2776. newElement._TemOnClick = function (id) {
  2777. var arg = {
  2778. srcElement : document.getElementById(id)
  2779. };
  2780. newElement.onclick(arg);
  2781. };
  2782. }
  2783. return newElement;
  2784. } else {
  2785. return element;
  2786. }
  2787. };
  2788. reattachMediaStream = function (to, from) {
  2789. var stream = null;
  2790. var children = from.children;
  2791. for (var i = 0; i !== children.length; ++i) {
  2792. if (children[i].name === 'streamId') {
  2793. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2794. stream = AdapterJS.WebRTCPlugin.plugin
  2795. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2796. break;
  2797. }
  2798. }
  2799. if (stream !== null) {
  2800. return attachMediaStream(to, stream);
  2801. } else {
  2802. console.log('Could not find the stream associated with this element');
  2803. }
  2804. };
  2805. RTCIceCandidate = function (candidate) {
  2806. if (!candidate.sdpMid) {
  2807. candidate.sdpMid = '';
  2808. }
  2809. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2810. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2811. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2812. );
  2813. };
  2814. // inject plugin
  2815. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2816. AdapterJS.WebRTCPlugin.injectPlugin();
  2817. };
  2818. // This function will be called if the plugin is needed (browser different
  2819. // from Chrome or Firefox), but the plugin is not installed.
  2820. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2821. function() {
  2822. AdapterJS.addEvent(document,
  2823. 'readystatechange',
  2824. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2825. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2826. };
  2827. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2828. if (AdapterJS.options.hidePluginInstallPrompt) {
  2829. return;
  2830. }
  2831. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2832. if(downloadLink) { // if download link
  2833. var popupString;
  2834. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2835. popupString = 'This website requires you to install the ' +
  2836. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2837. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2838. ' WebRTC Plugin</a>' +
  2839. ' to work on this browser.';
  2840. } else { // no portal link, just print a generic explanation
  2841. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2842. }
  2843. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2844. } else { // no download link, just print a generic explanation
  2845. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2846. }
  2847. };
  2848. // Try to detect the plugin and act accordingly
  2849. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2850. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2851. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2852. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2853. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2854. }
  2855. (function () {
  2856. 'use strict';
  2857. var baseGetUserMedia = null;
  2858. AdapterJS.TEXT.EXTENSION = {
  2859. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2860. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2861. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2862. BUTTON_FF: 'Install Now',
  2863. BUTTON_CHROME: 'Go to Chrome Web Store'
  2864. };
  2865. var clone = function(obj) {
  2866. if (null == obj || "object" != typeof obj) return obj;
  2867. var copy = obj.constructor();
  2868. for (var attr in obj) {
  2869. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2870. }
  2871. return copy;
  2872. };
  2873. if (window.navigator.mozGetUserMedia) {
  2874. baseGetUserMedia = window.navigator.getUserMedia;
  2875. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2876. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2877. // intercepting screensharing requests
  2878. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2879. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2880. }
  2881. var updatedConstraints = clone(constraints);
  2882. //constraints.video.mediaSource = constraints.video.mediaSource;
  2883. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2884. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2885. // strange but this works anyway
  2886. var checkIfReady = setInterval(function () {
  2887. if (document.readyState === 'complete') {
  2888. clearInterval(checkIfReady);
  2889. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2890. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2891. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2892. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2893. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2894. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2895. } else {
  2896. failureCb(error);
  2897. }
  2898. });
  2899. }
  2900. }, 1);
  2901. } else { // regular GetUserMediaRequest
  2902. baseGetUserMedia(constraints, successCb, failureCb);
  2903. }
  2904. };
  2905. getUserMedia = navigator.getUserMedia;
  2906. } else if (window.navigator.webkitGetUserMedia) {
  2907. baseGetUserMedia = window.navigator.getUserMedia;
  2908. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2909. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2910. if (window.webrtcDetectedBrowser !== 'chrome') {
  2911. throw new Error('Current browser does not support screensharing');
  2912. }
  2913. // would be fine since no methods
  2914. var updatedConstraints = clone(constraints);
  2915. var chromeCallback = function(error, sourceId) {
  2916. if(!error) {
  2917. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2918. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2919. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2920. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2921. if (sourceId) {
  2922. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2923. }
  2924. delete updatedConstraints.video.mediaSource;
  2925. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2926. } else {
  2927. if (error === 'permission-denied') {
  2928. throw new Error('Permission denied for screen retrieval');
  2929. } else {
  2930. throw new Error('Failed retrieving selected screen');
  2931. }
  2932. }
  2933. };
  2934. var onIFrameCallback = function (event) {
  2935. if (!event.data) {
  2936. return;
  2937. }
  2938. if (event.data.chromeMediaSourceId) {
  2939. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2940. chromeCallback('permission-denied');
  2941. } else {
  2942. chromeCallback(null, event.data.chromeMediaSourceId);
  2943. }
  2944. }
  2945. if (event.data.chromeExtensionStatus) {
  2946. if (event.data.chromeExtensionStatus === 'not-installed') {
  2947. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2948. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2949. event.data.data, true, true);
  2950. } else {
  2951. chromeCallback(event.data.chromeExtensionStatus, null);
  2952. }
  2953. }
  2954. // this event listener is no more needed
  2955. window.removeEventListener('message', onIFrameCallback);
  2956. };
  2957. window.addEventListener('message', onIFrameCallback);
  2958. postFrameMessage({
  2959. captureSourceId: true
  2960. });
  2961. } else {
  2962. baseGetUserMedia(constraints, successCb, failureCb);
  2963. }
  2964. };
  2965. getUserMedia = navigator.getUserMedia;
  2966. } else {
  2967. baseGetUserMedia = window.navigator.getUserMedia;
  2968. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2969. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2970. // would be fine since no methods
  2971. var updatedConstraints = clone(constraints);
  2972. // wait for plugin to be ready
  2973. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2974. // check if screensharing feature is available
  2975. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2976. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2977. // set the constraints
  2978. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2979. updatedConstraints.video.optional.push({
  2980. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2981. });
  2982. delete updatedConstraints.video.mediaSource;
  2983. } else {
  2984. throw new Error('Your WebRTC plugin does not support screensharing');
  2985. }
  2986. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2987. });
  2988. } else {
  2989. baseGetUserMedia(constraints, successCb, failureCb);
  2990. }
  2991. };
  2992. getUserMedia = window.navigator.getUserMedia;
  2993. }
  2994. if (window.webrtcDetectedBrowser === 'chrome') {
  2995. var iframe = document.createElement('iframe');
  2996. iframe.onload = function() {
  2997. iframe.isLoaded = true;
  2998. };
  2999. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  3000. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  3001. iframe.style.display = 'none';
  3002. (document.body || document.documentElement).appendChild(iframe);
  3003. var postFrameMessage = function (object) {
  3004. object = object || {};
  3005. if (!iframe.isLoaded) {
  3006. setTimeout(function () {
  3007. iframe.contentWindow.postMessage(object, '*');
  3008. }, 100);
  3009. return;
  3010. }
  3011. iframe.contentWindow.postMessage(object, '*');
  3012. };
  3013. }
  3014. })();
  3015. },{}],13:[function(require,module,exports){
  3016. var UI = {};
  3017. var VideoLayout = require("./videolayout/VideoLayout.js");
  3018. var AudioLevels = require("./audio_levels/AudioLevels.js");
  3019. var Prezi = require("./prezi/Prezi.js");
  3020. var Etherpad = require("./etherpad/Etherpad.js");
  3021. var Chat = require("./side_pannels/chat/Chat.js");
  3022. var Toolbar = require("./toolbars/Toolbar");
  3023. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  3024. var BottomToolbar = require("./toolbars/BottomToolbar");
  3025. var ContactList = require("./side_pannels/contactlist/ContactList");
  3026. var Avatar = require("./avatar/Avatar");
  3027. var EventEmitter = require("events");
  3028. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  3029. var Settings = require("./../settings/Settings");
  3030. var PanelToggler = require("./side_pannels/SidePanelToggler");
  3031. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  3032. UI.messageHandler = require("./util/MessageHandler");
  3033. var messageHandler = UI.messageHandler;
  3034. var Authentication = require("./authentication/Authentication");
  3035. var UIUtil = require("./util/UIUtil");
  3036. var NicknameHandler = require("./util/NicknameHandler");
  3037. var CQEvents = require("../../service/connectionquality/CQEvents");
  3038. var DesktopSharingEventTypes
  3039. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3040. var RTCEvents = require("../../service/RTC/RTCEvents");
  3041. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3042. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  3043. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3044. var UIEvents = require("../../service/UI/UIEvents");
  3045. var MemberEvents = require("../../service/members/Events");
  3046. var eventEmitter = new EventEmitter();
  3047. var roomName = null;
  3048. function promptDisplayName() {
  3049. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  3050. message += APP.translation.translateString(
  3051. "dialog.displayNameRequired");
  3052. message += '</h2>' +
  3053. '<input name="displayName" type="text" data-i18n=' +
  3054. '"[placeholder]defaultNickname" placeholder="' +
  3055. APP.translation.translateString(
  3056. "defaultNickname", {name: "Jane Pink"}) +
  3057. '" autofocus>';
  3058. var buttonTxt
  3059. = APP.translation.generateTranslationHTML("dialog.Ok");
  3060. var buttons = [];
  3061. buttons.push({title: buttonTxt, value: "ok"});
  3062. messageHandler.openDialog(null, message,
  3063. true,
  3064. buttons,
  3065. function (e, v, m, f) {
  3066. if (v == "ok") {
  3067. var displayName = f.displayName;
  3068. if (displayName) {
  3069. VideoLayout.inputDisplayNameHandler(displayName);
  3070. return true;
  3071. }
  3072. }
  3073. e.preventDefault();
  3074. },
  3075. function () {
  3076. var form = $.prompt.getPrompt();
  3077. var input = form.find("input[name='displayName']");
  3078. input.focus();
  3079. var button = form.find("button");
  3080. button.attr("disabled", "disabled");
  3081. input.keyup(function () {
  3082. if(!input.val())
  3083. button.attr("disabled", "disabled");
  3084. else
  3085. button.removeAttr("disabled");
  3086. });
  3087. }
  3088. );
  3089. }
  3090. function notifyForInitialMute()
  3091. {
  3092. messageHandler.notify(null, "notify.mutedTitle", "connected",
  3093. "notify.muted", null, {timeOut: 120000});
  3094. }
  3095. function setupPrezi()
  3096. {
  3097. $("#reloadPresentationLink").click(function()
  3098. {
  3099. Prezi.reloadPresentation();
  3100. });
  3101. }
  3102. function setupChat()
  3103. {
  3104. Chat.init();
  3105. $("#toggle_smileys").click(function() {
  3106. Chat.toggleSmileys();
  3107. });
  3108. }
  3109. function setupToolbars() {
  3110. Toolbar.init(UI);
  3111. Toolbar.setupButtonsFromConfig();
  3112. BottomToolbar.init();
  3113. }
  3114. function streamHandler(stream, isMuted) {
  3115. switch (stream.type)
  3116. {
  3117. case "audio":
  3118. VideoLayout.changeLocalAudio(stream, isMuted);
  3119. break;
  3120. case "video":
  3121. VideoLayout.changeLocalVideo(stream, isMuted);
  3122. break;
  3123. case "stream":
  3124. VideoLayout.changeLocalStream(stream, isMuted);
  3125. break;
  3126. }
  3127. }
  3128. function onXmppConnectionFailed(stropheErrorMsg) {
  3129. var title = APP.translation.generateTranslationHTML(
  3130. "dialog.error");
  3131. var message;
  3132. if (stropheErrorMsg) {
  3133. message = APP.translation.generateTranslationHTML(
  3134. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  3135. } else {
  3136. message = APP.translation.generateTranslationHTML(
  3137. "dialog.connectError");
  3138. }
  3139. messageHandler.openDialog(
  3140. title, message, true, {}, function (e, v, m, f) { return false; });
  3141. }
  3142. function onDisposeConference(unload) {
  3143. Toolbar.showAuthenticateButton(false);
  3144. }
  3145. function onDisplayNameChanged(jid, displayName) {
  3146. ContactList.onDisplayNameChange(jid, displayName);
  3147. SettingsMenu.onDisplayNameChange(jid, displayName);
  3148. VideoLayout.onDisplayNameChanged(jid, displayName);
  3149. }
  3150. function registerListeners() {
  3151. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  3152. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  3153. APP.RTC.addStreamListener(function (stream) {
  3154. VideoLayout.onRemoteStreamAdded(stream);
  3155. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  3156. APP.RTC.addStreamListener(function (jid) {
  3157. VideoLayout.onVideoTypeChanged(jid);
  3158. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  3159. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  3160. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  3161. VideoLayout.onDominantSpeakerChanged(resourceJid);
  3162. });
  3163. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  3164. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  3165. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  3166. endpointsEnteringLastN, stream);
  3167. });
  3168. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  3169. function (devices) {
  3170. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  3171. });
  3172. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  3173. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function() {
  3174. // when the data channel becomes available, tell the bridge about video
  3175. // selections so that it can do adaptive simulcast,
  3176. // we want the notification to trigger even if userJid is undefined,
  3177. // or null.
  3178. var userJid = APP.UI.getLargeVideoJid();
  3179. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userJid);
  3180. });
  3181. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  3182. {
  3183. var resourceJid;
  3184. if(jid === APP.statistics.LOCAL_JID)
  3185. {
  3186. resourceJid = AudioLevels.LOCAL_LEVEL;
  3187. if(APP.RTC.localAudio.isMuted())
  3188. {
  3189. audioLevel = 0;
  3190. }
  3191. }
  3192. else
  3193. {
  3194. resourceJid = Strophe.getResourceFromJid(jid);
  3195. }
  3196. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  3197. UI.getLargeVideoJid());
  3198. });
  3199. APP.desktopsharing.addListener(function () {
  3200. ToolbarToggler.showDesktopSharingButton();
  3201. }, DesktopSharingEventTypes.INIT);
  3202. APP.desktopsharing.addListener(
  3203. Toolbar.changeDesktopSharingButtonState,
  3204. DesktopSharingEventTypes.SWITCHING_DONE);
  3205. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  3206. VideoLayout.updateLocalConnectionStats);
  3207. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  3208. VideoLayout.updateConnectionStats);
  3209. APP.connectionquality.addListener(CQEvents.STOP,
  3210. VideoLayout.onStatsStop);
  3211. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  3212. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  3213. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  3214. messageHandler.openMessageDialog(
  3215. 'dialog.serviceUnavailable',
  3216. 'dialog.gracefulShutdown'
  3217. );
  3218. });
  3219. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  3220. var title = APP.translation.generateTranslationHTML(
  3221. "dialog.reservationError");
  3222. var message = APP.translation.generateTranslationHTML(
  3223. "dialog.reservationErrorMsg", {code: code, msg: msg});
  3224. messageHandler.openDialog(
  3225. title,
  3226. message,
  3227. true, {},
  3228. function (event, value, message, formVals)
  3229. {
  3230. return false;
  3231. }
  3232. );
  3233. });
  3234. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  3235. messageHandler.openMessageDialog("dialog.sessTerminated",
  3236. "dialog.kickMessage");
  3237. });
  3238. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  3239. //FIXME: use Session Terminated from translation, but
  3240. // 'reason' text comes from XMPP packet and is not translated
  3241. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  3242. messageHandler.openDialog(
  3243. title, reason, true, {},
  3244. function (event, value, message, formVals)
  3245. {
  3246. return false;
  3247. }
  3248. );
  3249. });
  3250. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  3251. messageHandler.showError("dialog.error",
  3252. "dialog.bridgeUnavailable");
  3253. });
  3254. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  3255. Avatar.setUserAvatar(from, id);
  3256. });
  3257. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  3258. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  3259. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  3260. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  3261. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  3262. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  3263. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  3264. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  3265. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  3266. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  3267. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  3268. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  3269. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  3270. onAuthenticationRequired);
  3271. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  3272. function (resource, devices) {
  3273. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  3274. });
  3275. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  3276. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  3277. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function(doMuteAudio) {
  3278. UI.setAudioMuted(doMuteAudio);
  3279. });
  3280. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  3281. onDtmfSupportChanged);
  3282. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  3283. SettingsMenu.setStartMuted(audio, video);
  3284. });
  3285. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  3286. UI.setInitialMuteFromFocus(audio, video);
  3287. });
  3288. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  3289. UI.messageHandler.showError("dialog.sorry",
  3290. "dialog.internalError");
  3291. });
  3292. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function() {
  3293. messageHandler.showError("dialog.error",
  3294. "dialog.SLDFailure");
  3295. });
  3296. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function() {
  3297. messageHandler.showError("dialog.error",
  3298. "dialog.SRDFailure");
  3299. });
  3300. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function() {
  3301. messageHandler.showError();
  3302. });
  3303. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function() {
  3304. // FIXME: re-use LoginDialog which supports retries
  3305. UI.showLoginPopup(connect);
  3306. });
  3307. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function(focusComponent, retrySec) {
  3308. UI.messageHandler.notify(
  3309. null, "notify.focus",
  3310. 'disconnected', "notify.focusFail",
  3311. {component: focusComponent, ms: retrySec});
  3312. });
  3313. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function(pres) {
  3314. UI.messageHandler.openReportDialog(null,
  3315. "dialog.joinError", pres);
  3316. });
  3317. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function(pres) {
  3318. UI.messageHandler.openReportDialog(null,
  3319. "dialog.connectError", pres);
  3320. });
  3321. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function() {
  3322. var roomName = UI.generateRoomName();
  3323. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  3324. });
  3325. //NicknameHandler emits this event
  3326. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  3327. APP.xmpp.addToPresence("displayName", nickname);
  3328. });
  3329. }
  3330. /**
  3331. * Mutes/unmutes the local video.
  3332. *
  3333. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3334. * @param options an object which specifies optional arguments such as the
  3335. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3336. * specifies whether the method was initiated in response to a user command (in
  3337. * contrast to an automatic decision taken by the application logic)
  3338. */
  3339. function setVideoMute(mute, options) {
  3340. APP.RTC.setVideoMute(mute,
  3341. UI.setVideoMuteButtonsState,
  3342. options);
  3343. }
  3344. function onResize()
  3345. {
  3346. Chat.resizeChat();
  3347. VideoLayout.resizeLargeVideoContainer();
  3348. }
  3349. function bindEvents()
  3350. {
  3351. /**
  3352. * Resizes and repositions videos in full screen mode.
  3353. */
  3354. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3355. onResize);
  3356. $(window).resize(onResize);
  3357. }
  3358. UI.start = function (init) {
  3359. document.title = interfaceConfig.APP_NAME;
  3360. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3361. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3362. {
  3363. $("#videoconference_page").hide();
  3364. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3365. setupWelcomePage();
  3366. return;
  3367. }
  3368. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  3369. var leftWatermarkDiv
  3370. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  3371. leftWatermarkDiv.css({display: 'block'});
  3372. leftWatermarkDiv.parent().get(0).href
  3373. = interfaceConfig.JITSI_WATERMARK_LINK;
  3374. }
  3375. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  3376. var rightWatermarkDiv
  3377. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  3378. rightWatermarkDiv.css({display: 'block'});
  3379. rightWatermarkDiv.parent().get(0).href
  3380. = interfaceConfig.BRAND_WATERMARK_LINK;
  3381. rightWatermarkDiv.get(0).style.backgroundImage
  3382. = "url(images/rightwatermark.png)";
  3383. }
  3384. if (interfaceConfig.SHOW_POWERED_BY) {
  3385. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  3386. }
  3387. $("#welcome_page").hide();
  3388. $("#videospace").mousemove(function () {
  3389. return ToolbarToggler.showToolbar();
  3390. });
  3391. // Set the defaults for prompt dialogs.
  3392. jQuery.prompt.setDefaults({persistent: false});
  3393. VideoLayout.init(eventEmitter);
  3394. AudioLevels.init();
  3395. NicknameHandler.init(eventEmitter);
  3396. registerListeners();
  3397. bindEvents();
  3398. setupPrezi();
  3399. setupToolbars();
  3400. setupChat();
  3401. document.title = interfaceConfig.APP_NAME;
  3402. $("#downloadlog").click(function (event) {
  3403. dump(event.target);
  3404. });
  3405. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3406. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3407. {
  3408. $("#videoconference_page").hide();
  3409. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3410. setupWelcomePage();
  3411. return;
  3412. }
  3413. $("#welcome_page").hide();
  3414. // Display notice message at the top of the toolbar
  3415. if (config.noticeMessage) {
  3416. $('#noticeText').text(config.noticeMessage);
  3417. $('#notice').css({display: 'block'});
  3418. }
  3419. if (!RTCBrowserType.isIExplorer()) {
  3420. document.getElementById('largeVideo').volume = 0;
  3421. }
  3422. if(config.requireDisplayName) {
  3423. var currentSettings = Settings.getSettings();
  3424. if (!currentSettings.displayName) {
  3425. promptDisplayName();
  3426. }
  3427. }
  3428. init();
  3429. toastr.options = {
  3430. "closeButton": true,
  3431. "debug": false,
  3432. "positionClass": "notification-bottom-right",
  3433. "onclick": null,
  3434. "showDuration": "300",
  3435. "hideDuration": "1000",
  3436. "timeOut": "2000",
  3437. "extendedTimeOut": "1000",
  3438. "showEasing": "swing",
  3439. "hideEasing": "linear",
  3440. "showMethod": "fadeIn",
  3441. "hideMethod": "fadeOut",
  3442. "reposition": function() {
  3443. if(PanelToggler.isVisible()) {
  3444. $("#toast-container").addClass("notification-bottom-right-center");
  3445. } else {
  3446. $("#toast-container").removeClass("notification-bottom-right-center");
  3447. }
  3448. },
  3449. "newestOnTop": false
  3450. };
  3451. SettingsMenu.init();
  3452. };
  3453. function chatAddError(errorMessage, originalText)
  3454. {
  3455. return Chat.chatAddError(errorMessage, originalText);
  3456. };
  3457. function chatSetSubject(text)
  3458. {
  3459. return Chat.chatSetSubject(text);
  3460. };
  3461. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3462. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3463. }
  3464. function onMucJoined(jid, info) {
  3465. Toolbar.updateRoomUrl(window.location.href);
  3466. var meHTML = APP.translation.generateTranslationHTML("me");
  3467. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3468. var settings = Settings.getSettings();
  3469. // Make sure we configure our avatar id, before creating avatar for us
  3470. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3471. // Add myself to the contact list.
  3472. ContactList.addContact(jid);
  3473. // Once we've joined the muc show the toolbar
  3474. ToolbarToggler.showToolbar();
  3475. var displayName = !config.displayJids
  3476. ? info.displayName : Strophe.getResourceFromJid(jid);
  3477. if (displayName)
  3478. onDisplayNameChanged('localVideoContainer', displayName);
  3479. VideoLayout.mucJoined();
  3480. }
  3481. function initEtherpad(name) {
  3482. Etherpad.init(name);
  3483. }
  3484. function onMucMemberLeft(jid) {
  3485. console.log('left.muc', jid);
  3486. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3487. '>.displayname').html();
  3488. messageHandler.notify(displayName,'notify.somebody',
  3489. 'disconnected',
  3490. 'notify.disconnected');
  3491. if(!config.startAudioMuted ||
  3492. config.startAudioMuted > APP.members.size())
  3493. UIUtil.playSoundNotification('userLeft');
  3494. ContactList.removeContact(jid);
  3495. VideoLayout.participantLeft(jid);
  3496. };
  3497. function onLocalRoleChanged(jid, info, pres, isModerator)
  3498. {
  3499. console.info("My role changed, new role: " + info.role);
  3500. onModeratorStatusChanged(isModerator);
  3501. VideoLayout.showModeratorIndicator();
  3502. SettingsMenu.onRoleChanged();
  3503. if (isModerator) {
  3504. Authentication.closeAuthenticationWindow();
  3505. messageHandler.notify(null, "notify.me",
  3506. 'connected', "notify.moderator");
  3507. }
  3508. }
  3509. function onModeratorStatusChanged(isModerator) {
  3510. Toolbar.showSipCallButton(isModerator);
  3511. Toolbar.showRecordingButton(
  3512. isModerator); //&&
  3513. // FIXME:
  3514. // Recording visible if
  3515. // there are at least 2(+ 1 focus) participants
  3516. //Object.keys(connection.emuc.members).length >= 3);
  3517. }
  3518. function onPasswordRequired(callback) {
  3519. // password is required
  3520. Toolbar.lockLockButton();
  3521. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3522. message += APP.translation.translateString(
  3523. "dialog.passwordRequired");
  3524. message += '</h2>' +
  3525. '<input name="lockKey" type="text" data-i18n=' +
  3526. '"[placeholder]dialog.password" placeholder="' +
  3527. APP.translation.translateString("dialog.password") +
  3528. '" autofocus>';
  3529. messageHandler.openTwoButtonDialog(null, null, null, message,
  3530. true,
  3531. "dialog.Ok",
  3532. function (e, v, m, f) {},
  3533. null,
  3534. function (e, v, m, f) {
  3535. if (v) {
  3536. var lockKey = f.lockKey;
  3537. if (lockKey) {
  3538. Toolbar.setSharedKey(lockKey);
  3539. callback(lockKey);
  3540. }
  3541. }
  3542. },
  3543. ':input:first'
  3544. );
  3545. }
  3546. /**
  3547. * The dialpad button is shown iff there is at least one member that supports
  3548. * DTMF (e.g. jigasi).
  3549. */
  3550. function onDtmfSupportChanged(dtmfSupport) {
  3551. //TODO: enable when the UI is ready
  3552. //Toolbar.showDialPadButton(dtmfSupport);
  3553. }
  3554. function onMucMemberJoined(jid, id, displayName) {
  3555. messageHandler.notify(displayName,'notify.somebody',
  3556. 'connected',
  3557. 'notify.connected');
  3558. if(!config.startAudioMuted ||
  3559. config.startAudioMuted > APP.members.size())
  3560. UIUtil.playSoundNotification('userJoined');
  3561. // Configure avatar
  3562. Avatar.setUserAvatar(jid, id);
  3563. // Add Peer's container
  3564. VideoLayout.ensurePeerContainerExists(jid);
  3565. }
  3566. function onMucPresenceStatus(jid, info) {
  3567. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3568. }
  3569. function onMucRoleChanged(role, displayName) {
  3570. VideoLayout.showModeratorIndicator();
  3571. if (role === 'moderator') {
  3572. var messageKey, messageOptions = {};
  3573. if (!displayName) {
  3574. messageKey = "notify.grantedToUnknown";
  3575. }
  3576. else
  3577. {
  3578. messageKey = "notify.grantedTo";
  3579. messageOptions = {to: displayName};
  3580. }
  3581. messageHandler.notify(
  3582. displayName,'notify.somebody',
  3583. 'connected', messageKey,
  3584. messageOptions);
  3585. }
  3586. }
  3587. function onAuthenticationRequired(intervalCallback) {
  3588. Authentication.openAuthenticationDialog(
  3589. roomName, intervalCallback, function () {
  3590. Toolbar.authenticateClicked();
  3591. });
  3592. };
  3593. function onLastNChanged(oldValue, newValue) {
  3594. if (config.muteLocalVideoIfNotInLastN) {
  3595. setVideoMute(!newValue, { 'byUser': false });
  3596. }
  3597. }
  3598. UI.toggleSmileys = function () {
  3599. Chat.toggleSmileys();
  3600. };
  3601. UI.getSettings = function () {
  3602. return Settings.getSettings();
  3603. };
  3604. UI.toggleFilmStrip = function () {
  3605. return BottomToolbar.toggleFilmStrip();
  3606. };
  3607. UI.toggleChat = function () {
  3608. return BottomToolbar.toggleChat();
  3609. };
  3610. UI.toggleContactList = function () {
  3611. return BottomToolbar.toggleContactList();
  3612. };
  3613. UI.inputDisplayNameHandler = function (value) {
  3614. VideoLayout.inputDisplayNameHandler(value);
  3615. };
  3616. UI.getLargeVideoJid = function()
  3617. {
  3618. return VideoLayout.getLargeVideoJid();
  3619. };
  3620. UI.generateRoomName = function() {
  3621. if(roomName)
  3622. return roomName;
  3623. var roomnode = null;
  3624. var path = window.location.pathname;
  3625. // determinde the room node from the url
  3626. // TODO: just the roomnode or the whole bare jid?
  3627. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3628. // custom function might be responsible for doing the pushstate
  3629. roomnode = config.getroomnode(path);
  3630. } else {
  3631. /* fall back to default strategy
  3632. * this is making assumptions about how the URL->room mapping happens.
  3633. * It currently assumes deployment at root, with a rewrite like the
  3634. * following one (for nginx):
  3635. location ~ ^/([a-zA-Z0-9]+)$ {
  3636. rewrite ^/(.*)$ / break;
  3637. }
  3638. */
  3639. if (path.length > 1) {
  3640. roomnode = path.substr(1).toLowerCase();
  3641. } else {
  3642. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3643. roomnode = word.toLowerCase();
  3644. window.history.pushState('VideoChat',
  3645. 'Room: ' + word, window.location.pathname + word);
  3646. }
  3647. }
  3648. roomName = roomnode + '@' + config.hosts.muc;
  3649. return roomName;
  3650. };
  3651. UI.connectionIndicatorShowMore = function(jid)
  3652. {
  3653. return VideoLayout.showMore(jid);
  3654. };
  3655. UI.showLoginPopup = function(callback)
  3656. {
  3657. console.log('password is required');
  3658. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3659. message += APP.translation.translateString(
  3660. "dialog.passwordRequired");
  3661. message += '</h2>' +
  3662. '<input name="username" type="text" ' +
  3663. 'placeholder="user@domain.net" autofocus>' +
  3664. '<input name="password" ' +
  3665. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3666. ' placeholder="user password">';
  3667. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3668. true,
  3669. "dialog.Ok",
  3670. function (e, v, m, f) {
  3671. if (v) {
  3672. if (f.username !== null && f.password != null) {
  3673. callback(f.username, f.password);
  3674. }
  3675. }
  3676. },
  3677. null, null, ':input:first'
  3678. );
  3679. }
  3680. UI.checkForNicknameAndJoin = function () {
  3681. Authentication.closeAuthenticationDialog();
  3682. Authentication.stopInterval();
  3683. var nick = null;
  3684. if (config.useNicks) {
  3685. nick = window.prompt('Your nickname (optional)');
  3686. }
  3687. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3688. };
  3689. function dump(elem, filename) {
  3690. elem = elem.parentNode;
  3691. elem.download = filename || 'meetlog.json';
  3692. elem.href = 'data:application/json;charset=utf-8,\n';
  3693. var data = APP.xmpp.populateData();
  3694. var metadata = {};
  3695. metadata.time = new Date();
  3696. metadata.url = window.location.href;
  3697. metadata.ua = navigator.userAgent;
  3698. var log = APP.xmpp.getLogger();
  3699. if (log) {
  3700. metadata.xmpp = log;
  3701. }
  3702. data.metadata = metadata;
  3703. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3704. return false;
  3705. }
  3706. UI.getRoomName = function () {
  3707. return roomName;
  3708. };
  3709. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3710. if(muteAudio || muteVideo) notifyForInitialMute();
  3711. if(muteAudio) UI.setAudioMuted(true);
  3712. if(muteVideo) UI.setVideoMute(true);
  3713. }
  3714. /**
  3715. * Mutes/unmutes the local video.
  3716. */
  3717. UI.toggleVideo = function () {
  3718. setVideoMute(!APP.RTC.localVideo.isMuted());
  3719. };
  3720. /**
  3721. * Mutes / unmutes audio for the local participant.
  3722. */
  3723. UI.toggleAudio = function() {
  3724. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3725. };
  3726. /**
  3727. * Sets muted audio state for the local participant.
  3728. */
  3729. UI.setAudioMuted = function (mute, earlyMute) {
  3730. var audioMute = null;
  3731. if(earlyMute)
  3732. audioMute = function (mute, cb) {
  3733. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3734. };
  3735. else
  3736. audioMute = function (mute, cb) {
  3737. return APP.xmpp.setAudioMute(mute, cb);
  3738. }
  3739. if(!audioMute(mute, function () {
  3740. VideoLayout.showLocalAudioIndicator(mute);
  3741. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3742. }))
  3743. {
  3744. // We still click the button.
  3745. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3746. return;
  3747. }
  3748. }
  3749. UI.addListener = function (type, listener) {
  3750. eventEmitter.on(type, listener);
  3751. }
  3752. UI.clickOnVideo = function (videoNumber) {
  3753. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3754. if (remoteVideos.length > videoNumber) {
  3755. remoteVideos[videoNumber].click();
  3756. }
  3757. }
  3758. //Used by torture
  3759. UI.showToolbar = function () {
  3760. return ToolbarToggler.showToolbar();
  3761. }
  3762. //Used by torture
  3763. UI.dockToolbar = function (isDock) {
  3764. return ToolbarToggler.dockToolbar(isDock);
  3765. }
  3766. UI.setVideoMuteButtonsState = function (mute) {
  3767. var video = $('#video');
  3768. var communicativeClass = "icon-camera";
  3769. var muteClass = "icon-camera icon-camera-disabled";
  3770. if (mute) {
  3771. video.removeClass(communicativeClass);
  3772. video.addClass(muteClass);
  3773. } else {
  3774. video.removeClass(muteClass);
  3775. video.addClass(communicativeClass);
  3776. }
  3777. }
  3778. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3779. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3780. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3781. if(resourceJid === APP.xmpp.myResource())
  3782. SettingsMenu.changeAvatar(thumbUrl);
  3783. }
  3784. UI.setVideoMute = setVideoMute;
  3785. module.exports = UI;
  3786. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes":103,"../../service/UI/UIEvents":104,"../../service/connectionquality/CQEvents":106,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../../service/members/Events":108,"../../service/xmpp/XMPPEvents":110,"../RTC/RTCBrowserType":10,"./../settings/Settings":49,"./audio_levels/AudioLevels.js":14,"./authentication/Authentication":16,"./avatar/Avatar":18,"./etherpad/Etherpad.js":19,"./prezi/Prezi.js":20,"./side_pannels/SidePanelToggler":22,"./side_pannels/chat/Chat.js":23,"./side_pannels/contactlist/ContactList":27,"./side_pannels/settings/SettingsMenu":28,"./toolbars/BottomToolbar":29,"./toolbars/Toolbar":30,"./toolbars/ToolbarToggler":31,"./util/MessageHandler":33,"./util/NicknameHandler":34,"./util/UIUtil":35,"./videolayout/VideoLayout.js":41,"./welcome_page/RoomnameGenerator":42,"./welcome_page/WelcomePage":43,"events":1}],14:[function(require,module,exports){
  3787. var CanvasUtil = require("./CanvasUtils");
  3788. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3789. function initActiveSpeakerAudioLevels() {
  3790. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3791. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3792. // Draw a circle.
  3793. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3794. // Add a shadow around the circle
  3795. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3796. ASDrawContext.shadowOffsetX = 0;
  3797. ASDrawContext.shadowOffsetY = 0;
  3798. }
  3799. /**
  3800. * The audio Levels plugin.
  3801. */
  3802. var AudioLevels = (function(my) {
  3803. var audioLevelCanvasCache = {};
  3804. my.LOCAL_LEVEL = 'local';
  3805. my.init = function () {
  3806. initActiveSpeakerAudioLevels();
  3807. }
  3808. /**
  3809. * Updates the audio level canvas for the given peerJid. If the canvas
  3810. * didn't exist we create it.
  3811. */
  3812. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3813. var resourceJid = null;
  3814. var videoSpanId = null;
  3815. if (!peerJid)
  3816. videoSpanId = 'localVideoContainer';
  3817. else {
  3818. resourceJid = Strophe.getResourceFromJid(peerJid);
  3819. videoSpanId = 'participant_' + resourceJid;
  3820. }
  3821. var videoSpan = document.getElementById(videoSpanId);
  3822. if (!videoSpan) {
  3823. if (resourceJid)
  3824. console.error("No video element for jid", resourceJid);
  3825. else
  3826. console.error("No video element for local video.");
  3827. return;
  3828. }
  3829. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3830. var videoSpaceWidth = $('#remoteVideos').width();
  3831. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3832. var thumbnailWidth = thumbnailSize[0];
  3833. var thumbnailHeight = thumbnailSize[1];
  3834. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3835. audioLevelCanvas = document.createElement('canvas');
  3836. audioLevelCanvas.className = "audiolevel";
  3837. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3838. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3839. resizeAudioLevelCanvas( audioLevelCanvas,
  3840. thumbnailWidth,
  3841. thumbnailHeight);
  3842. videoSpan.appendChild(audioLevelCanvas);
  3843. } else {
  3844. audioLevelCanvas = audioLevelCanvas.get(0);
  3845. resizeAudioLevelCanvas( audioLevelCanvas,
  3846. thumbnailWidth,
  3847. thumbnailHeight);
  3848. }
  3849. };
  3850. /**
  3851. * Updates the audio level UI for the given resourceJid.
  3852. *
  3853. * @param resourceJid the resource jid indicating the video element for
  3854. * which we draw the audio level
  3855. * @param audioLevel the newAudio level to render
  3856. */
  3857. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3858. drawAudioLevelCanvas(resourceJid, audioLevel);
  3859. var videoSpanId = getVideoSpanId(resourceJid);
  3860. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3861. if (!audioLevelCanvas)
  3862. return;
  3863. var drawContext = audioLevelCanvas.getContext('2d');
  3864. var canvasCache = audioLevelCanvasCache[resourceJid];
  3865. drawContext.clearRect (0, 0,
  3866. audioLevelCanvas.width, audioLevelCanvas.height);
  3867. drawContext.drawImage(canvasCache, 0, 0);
  3868. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3869. if(!APP.xmpp.myJid()) {
  3870. return;
  3871. }
  3872. resourceJid = APP.xmpp.myResource();
  3873. }
  3874. if(resourceJid === largeVideoResourceJid) {
  3875. window.requestAnimationFrame(function () {
  3876. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3877. });
  3878. }
  3879. };
  3880. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3881. if($("#activeSpeaker").css("visibility") == "hidden")
  3882. return;
  3883. ASDrawContext.clearRect(0, 0, 300, 300);
  3884. if(audioLevel == 0)
  3885. return;
  3886. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3887. // Fill the shape.
  3888. ASDrawContext.fill();
  3889. };
  3890. /**
  3891. * Resizes the given audio level canvas to match the given thumbnail size.
  3892. */
  3893. function resizeAudioLevelCanvas(audioLevelCanvas,
  3894. thumbnailWidth,
  3895. thumbnailHeight) {
  3896. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3897. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3898. }
  3899. /**
  3900. * Draws the audio level canvas into the cached canvas object.
  3901. *
  3902. * @param resourceJid the resource jid indicating the video element for
  3903. * which we draw the audio level
  3904. * @param audioLevel the newAudio level to render
  3905. */
  3906. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3907. if (!audioLevelCanvasCache[resourceJid]) {
  3908. var videoSpanId = getVideoSpanId(resourceJid);
  3909. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3910. /*
  3911. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3912. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3913. * error. Since audio levels are frequently updated, the errors have
  3914. * been observed to pile into the console, strain the CPU.
  3915. */
  3916. if (audioLevelCanvasOrig)
  3917. {
  3918. audioLevelCanvasCache[resourceJid]
  3919. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3920. }
  3921. }
  3922. var canvas = audioLevelCanvasCache[resourceJid];
  3923. if (!canvas)
  3924. return;
  3925. var drawContext = canvas.getContext('2d');
  3926. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3927. var shadowLevel = getShadowLevel(audioLevel);
  3928. if (shadowLevel > 0)
  3929. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3930. CanvasUtil.drawRoundRectGlow( drawContext,
  3931. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  3932. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3933. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3934. interfaceConfig.CANVAS_RADIUS,
  3935. interfaceConfig.SHADOW_COLOR,
  3936. shadowLevel);
  3937. }
  3938. /**
  3939. * Returns the shadow/glow level for the given audio level.
  3940. *
  3941. * @param audioLevel the audio level from which we determine the shadow
  3942. * level
  3943. */
  3944. function getShadowLevel (audioLevel) {
  3945. var shadowLevel = 0;
  3946. if (audioLevel <= 0.3) {
  3947. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3948. }
  3949. else if (audioLevel <= 0.6) {
  3950. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3951. }
  3952. else {
  3953. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3954. }
  3955. return shadowLevel;
  3956. }
  3957. /**
  3958. * Returns the video span id corresponding to the given resourceJid or local
  3959. * user.
  3960. */
  3961. function getVideoSpanId(resourceJid) {
  3962. var videoSpanId = null;
  3963. if (resourceJid === AudioLevels.LOCAL_LEVEL
  3964. || (APP.xmpp.myResource() && resourceJid
  3965. === APP.xmpp.myResource()))
  3966. videoSpanId = 'localVideoContainer';
  3967. else
  3968. videoSpanId = 'participant_' + resourceJid;
  3969. return videoSpanId;
  3970. }
  3971. /**
  3972. * Indicates that the remote video has been resized.
  3973. */
  3974. $(document).bind('remotevideo.resized', function (event, width, height) {
  3975. var resized = false;
  3976. $('#remoteVideos>span>canvas').each(function() {
  3977. var canvas = $(this).get(0);
  3978. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3979. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3980. resized = true;
  3981. }
  3982. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3983. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3984. resized = true;
  3985. }
  3986. });
  3987. if (resized)
  3988. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3989. audioLevelCanvasCache[resourceJid].width
  3990. = width + interfaceConfig.CANVAS_EXTRA;
  3991. audioLevelCanvasCache[resourceJid].height
  3992. = height + interfaceConfig.CANVAS_EXTRA;
  3993. });
  3994. });
  3995. return my;
  3996. })(AudioLevels || {});
  3997. module.exports = AudioLevels;
  3998. },{"./CanvasUtils":15}],15:[function(require,module,exports){
  3999. /**
  4000. * Utility class for drawing canvas shapes.
  4001. */
  4002. var CanvasUtil = (function(my) {
  4003. /**
  4004. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  4005. * of the glow.
  4006. *
  4007. * @param drawContext the context of the canvas to draw to
  4008. * @param x the x coordinate of the round rectangle
  4009. * @param y the y coordinate of the round rectangle
  4010. * @param w the width of the round rectangle
  4011. * @param h the height of the round rectangle
  4012. * @param glowColor the color of the glow
  4013. * @param glowWidth the width of the glow
  4014. */
  4015. my.drawRoundRectGlow
  4016. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  4017. // Save the previous state of the context.
  4018. drawContext.save();
  4019. if (w < 2 * r) r = w / 2;
  4020. if (h < 2 * r) r = h / 2;
  4021. // Draw a round rectangle.
  4022. drawContext.beginPath();
  4023. drawContext.moveTo(x+r, y);
  4024. drawContext.arcTo(x+w, y, x+w, y+h, r);
  4025. drawContext.arcTo(x+w, y+h, x, y+h, r);
  4026. drawContext.arcTo(x, y+h, x, y, r);
  4027. drawContext.arcTo(x, y, x+w, y, r);
  4028. drawContext.closePath();
  4029. // Add a shadow around the rectangle
  4030. drawContext.shadowColor = glowColor;
  4031. drawContext.shadowBlur = glowWidth;
  4032. drawContext.shadowOffsetX = 0;
  4033. drawContext.shadowOffsetY = 0;
  4034. // Fill the shape.
  4035. drawContext.fill();
  4036. drawContext.save();
  4037. drawContext.restore();
  4038. // 1) Uncomment this line to use Composite Operation, which is doing the
  4039. // same as the clip function below and is also antialiasing the round
  4040. // border, but is said to be less fast performance wise.
  4041. // drawContext.globalCompositeOperation='destination-out';
  4042. drawContext.beginPath();
  4043. drawContext.moveTo(x+r, y);
  4044. drawContext.arcTo(x+w, y, x+w, y+h, r);
  4045. drawContext.arcTo(x+w, y+h, x, y+h, r);
  4046. drawContext.arcTo(x, y+h, x, y, r);
  4047. drawContext.arcTo(x, y, x+w, y, r);
  4048. drawContext.closePath();
  4049. // 2) Uncomment this line to use Composite Operation, which is doing the
  4050. // same as the clip function below and is also antialiasing the round
  4051. // border, but is said to be less fast performance wise.
  4052. // drawContext.fill();
  4053. // Comment these two lines if choosing to do the same with composite
  4054. // operation above 1 and 2.
  4055. drawContext.clip();
  4056. drawContext.clearRect(0, 0, 277, 200);
  4057. // Restore the previous context state.
  4058. drawContext.restore();
  4059. };
  4060. /**
  4061. * Clones the given canvas.
  4062. *
  4063. * @return the new cloned canvas.
  4064. */
  4065. my.cloneCanvas = function (oldCanvas) {
  4066. /*
  4067. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  4068. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  4069. * levels are frequently updated, the errors have been observed to pile
  4070. * into the console, strain the CPU.
  4071. */
  4072. if (!oldCanvas)
  4073. return oldCanvas;
  4074. //create a new canvas
  4075. var newCanvas = document.createElement('canvas');
  4076. var context = newCanvas.getContext('2d');
  4077. //set dimensions
  4078. newCanvas.width = oldCanvas.width;
  4079. newCanvas.height = oldCanvas.height;
  4080. //apply the old canvas to the new one
  4081. context.drawImage(oldCanvas, 0, 0);
  4082. //return the new canvas
  4083. return newCanvas;
  4084. };
  4085. return my;
  4086. })(CanvasUtil || {});
  4087. module.exports = CanvasUtil;
  4088. },{}],16:[function(require,module,exports){
  4089. /* global $, APP*/
  4090. var LoginDialog = require('./LoginDialog');
  4091. var Moderator = require('../../xmpp/moderator');
  4092. /* Initial "authentication required" dialog */
  4093. var authDialog = null;
  4094. /* Loop retry ID that wits for other user to create the room */
  4095. var authRetryId = null;
  4096. var authenticationWindow = null;
  4097. var Authentication = {
  4098. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  4099. // This is the loop that will wait for the room to be created by
  4100. // someone else. 'auth_required.moderator' will bring us back here.
  4101. authRetryId = window.setTimeout(intervalCallback, 5000);
  4102. // Show prompt only if it's not open
  4103. if (authDialog !== null) {
  4104. return;
  4105. }
  4106. // extract room name from 'room@muc.server.net'
  4107. var room = roomName.substr(0, roomName.indexOf('@'));
  4108. var title
  4109. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  4110. var msg
  4111. = APP.translation.generateTranslationHTML(
  4112. "dialog.WaitForHostMsg", {room: room});
  4113. var buttonTxt
  4114. = APP.translation.generateTranslationHTML("dialog.IamHost");
  4115. var buttons = [];
  4116. buttons.push({title: buttonTxt, value: "authNow"});
  4117. authDialog = APP.UI.messageHandler.openDialog(
  4118. title,
  4119. msg,
  4120. true,
  4121. buttons,
  4122. function (onSubmitEvent, submitValue) {
  4123. // Do not close the dialog yet
  4124. onSubmitEvent.preventDefault();
  4125. // Open login popup
  4126. if (submitValue === 'authNow') {
  4127. callback();
  4128. }
  4129. }
  4130. );
  4131. },
  4132. closeAuthenticationWindow: function () {
  4133. if (authenticationWindow) {
  4134. authenticationWindow.close();
  4135. authenticationWindow = null;
  4136. }
  4137. },
  4138. xmppAuthenticate: function () {
  4139. var loginDialog = LoginDialog.show(
  4140. function (connection, state) {
  4141. if (!state) {
  4142. // User cancelled
  4143. loginDialog.close();
  4144. return;
  4145. } else if (state == APP.xmpp.Status.CONNECTED) {
  4146. loginDialog.close();
  4147. Authentication.stopInterval();
  4148. Authentication.closeAuthenticationDialog();
  4149. // Close the connection as anonymous one will be used
  4150. // to create the conference. Session-id will authorize
  4151. // the request.
  4152. connection.disconnect();
  4153. var roomName = APP.UI.generateRoomName();
  4154. Moderator.allocateConferenceFocus(roomName, function () {
  4155. // If it's not "on the fly" authentication now join
  4156. // the conference room
  4157. if (!APP.xmpp.getMUCJoined()) {
  4158. APP.UI.checkForNicknameAndJoin();
  4159. }
  4160. });
  4161. }
  4162. }, true);
  4163. },
  4164. focusAuthenticationWindow: function () {
  4165. // If auth window exists just bring it to the front
  4166. if (authenticationWindow) {
  4167. authenticationWindow.focus();
  4168. return;
  4169. }
  4170. },
  4171. closeAuthenticationDialog: function () {
  4172. // Close authentication dialog if opened
  4173. if (authDialog) {
  4174. authDialog.close();
  4175. authDialog = null;
  4176. }
  4177. },
  4178. createAuthenticationWindow: function (callback, url) {
  4179. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  4180. url, 910, 660,
  4181. // On closed
  4182. function () {
  4183. // Close authentication dialog if opened
  4184. Authentication.closeAuthenticationDialog();
  4185. callback();
  4186. authenticationWindow = null;
  4187. });
  4188. return authenticationWindow;
  4189. },
  4190. stopInterval: function () {
  4191. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  4192. if (authRetryId) {
  4193. window.clearTimeout(authRetryId);
  4194. authRetryId = null;
  4195. }
  4196. }
  4197. };
  4198. module.exports = Authentication;
  4199. },{"../../xmpp/moderator":60,"./LoginDialog":17}],17:[function(require,module,exports){
  4200. /* global $, APP, config*/
  4201. var XMPP = require('../../xmpp/xmpp');
  4202. var Moderator = require('../../xmpp/moderator');
  4203. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  4204. // anonymous domain is not enabled
  4205. /**
  4206. * Creates new <tt>Dialog</tt> instance.
  4207. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  4208. * when we either fail to connect or succeed(check Strophe.Status).
  4209. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  4210. * in order to create session-id after the connection is established.
  4211. * @constructor
  4212. */
  4213. function Dialog(callback, obtainSession) {
  4214. var self = this;
  4215. var stop = false;
  4216. var connection = APP.xmpp.createConnection();
  4217. var message = '<h2 data-i18n="dialog.passwordRequired">';
  4218. message += APP.translation.translateString("dialog.passwordRequired");
  4219. message += '</h2>' +
  4220. '<input name="username" type="text" ' +
  4221. 'placeholder="user@domain.net" autofocus>' +
  4222. '<input name="password" ' +
  4223. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  4224. ' placeholder="user password">';
  4225. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  4226. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  4227. var states = {
  4228. login: {
  4229. html: message,
  4230. buttons: [
  4231. { title: okButton, value: true},
  4232. { title: cancelButton, value: false}
  4233. ],
  4234. focus: ':input:first',
  4235. submit: function (e, v, m, f) {
  4236. e.preventDefault();
  4237. if (v) {
  4238. var jid = f.username;
  4239. var password = f.password;
  4240. if (jid && password) {
  4241. stop = false;
  4242. connection.reset();
  4243. connDialog.goToState('connecting');
  4244. connection.connect(jid, password, stateHandler);
  4245. }
  4246. } else {
  4247. // User cancelled
  4248. stop = true;
  4249. callback();
  4250. }
  4251. }
  4252. },
  4253. connecting: {
  4254. title: APP.translation.translateString('dialog.connecting'),
  4255. html: '<div id="connectionStatus"></div>',
  4256. buttons: [],
  4257. defaultButton: 0
  4258. },
  4259. finished: {
  4260. title: APP.translation.translateString('dialog.error'),
  4261. html: '<div id="errorMessage"></div>',
  4262. buttons: [
  4263. {
  4264. title: APP.translation.translateString('dialog.retry'),
  4265. value: 'retry'
  4266. },
  4267. {
  4268. title: APP.translation.translateString('dialog.Cancel'),
  4269. value: 'cancel'
  4270. },
  4271. ],
  4272. defaultButton: 0,
  4273. submit: function (e, v, m, f) {
  4274. e.preventDefault();
  4275. if (v === 'retry')
  4276. connDialog.goToState('login');
  4277. else
  4278. callback();
  4279. }
  4280. }
  4281. };
  4282. var connDialog
  4283. = APP.UI.messageHandler.openDialogWithStates(states,
  4284. { persistent: true, closeText: '' }, null);
  4285. var stateHandler = function (status, message) {
  4286. if (stop) {
  4287. return;
  4288. }
  4289. var translateKey = "connection." + XMPP.getStatusString(status);
  4290. var statusStr = APP.translation.translateString(translateKey);
  4291. // Display current state
  4292. var connectionStatus =
  4293. connDialog.getState('connecting').find('#connectionStatus');
  4294. connectionStatus.text(statusStr);
  4295. switch (status) {
  4296. case XMPP.Status.CONNECTED:
  4297. stop = true;
  4298. if (!obtainSession) {
  4299. callback(connection, status);
  4300. return;
  4301. }
  4302. // Obtaining session-id status
  4303. connectionStatus.text(
  4304. APP.translation.translateString(
  4305. 'connection.FETCH_SESSION_ID'));
  4306. // Authenticate with Jicofo and obtain session-id
  4307. var roomName = APP.UI.generateRoomName();
  4308. // Jicofo will return new session-id when connected
  4309. // from authenticated domain
  4310. connection.sendIQ(
  4311. Moderator.createConferenceIq(roomName),
  4312. function (result) {
  4313. connectionStatus.text(
  4314. APP.translation.translateString(
  4315. 'connection.GOT_SESSION_ID'));
  4316. stop = true;
  4317. // Parse session-id
  4318. Moderator.parseSessionId(result);
  4319. callback(connection, status);
  4320. },
  4321. function (error) {
  4322. console.error("Auth on the fly failed", error);
  4323. stop = true;
  4324. var errorMsg =
  4325. APP.translation.translateString(
  4326. 'connection.GET_SESSION_ID_ERROR') +
  4327. $(error).find('>error').attr('code');
  4328. self.displayError(errorMsg);
  4329. connection.disconnect();
  4330. });
  4331. break;
  4332. case XMPP.Status.AUTHFAIL:
  4333. case XMPP.Status.CONNFAIL:
  4334. case XMPP.Status.DISCONNECTED:
  4335. stop = true;
  4336. callback(connection, status);
  4337. var errorMessage = statusStr;
  4338. if (message)
  4339. {
  4340. errorMessage += ': ' + message;
  4341. }
  4342. self.displayError(errorMessage);
  4343. break;
  4344. default:
  4345. break;
  4346. }
  4347. };
  4348. /**
  4349. * Displays error message in 'finished' state which allows either to cancel
  4350. * or retry.
  4351. * @param message the final message to be displayed.
  4352. */
  4353. this.displayError = function (message) {
  4354. var finishedState = connDialog.getState('finished');
  4355. var errorMessageElem = finishedState.find('#errorMessage');
  4356. errorMessageElem.text(message);
  4357. connDialog.goToState('finished');
  4358. };
  4359. /**
  4360. * Closes LoginDialog.
  4361. */
  4362. this.close = function () {
  4363. stop = true;
  4364. connDialog.close();
  4365. };
  4366. }
  4367. var LoginDialog = {
  4368. /**
  4369. * Displays login prompt used to establish new XMPP connection. Given
  4370. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4371. * called when we connect successfully(status === CONNECTED) or when we fail
  4372. * to do so. On connection failure program can call Dialog.close() method in
  4373. * order to cancel or do nothing to let the user retry.
  4374. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4375. * called when we either fail to connect or succeed(check
  4376. * Strophe.Status).
  4377. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4378. * Jicofo in order to create session-id after the connection is
  4379. * established.
  4380. * @returns {Dialog}
  4381. */
  4382. show: function (callback, obtainSession) {
  4383. return new Dialog(callback, obtainSession);
  4384. }
  4385. };
  4386. module.exports = LoginDialog;
  4387. },{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],18:[function(require,module,exports){
  4388. var Settings = require("../../settings/Settings");
  4389. var users = {};
  4390. var Avatar = {
  4391. /**
  4392. * Sets the user's avatar in the settings menu(if local user), contact list
  4393. * and thumbnail
  4394. * @param jid jid of the user
  4395. * @param id email or userID to be used as a hash
  4396. */
  4397. setUserAvatar: function (jid, id) {
  4398. if (id) {
  4399. if (users[jid] === id) {
  4400. return;
  4401. }
  4402. users[jid] = id;
  4403. }
  4404. var thumbUrl = this.getThumbUrl(jid);
  4405. var contactListUrl = this.getContactListUrl(jid);
  4406. var resourceJid = Strophe.getResourceFromJid(jid);
  4407. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4408. },
  4409. /**
  4410. * Returns image URL for the avatar to be displayed on large video area
  4411. * where current active speaker is presented.
  4412. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4413. */
  4414. getActiveSpeakerUrl: function (jid) {
  4415. return this.getGravatarUrl(jid, 100);
  4416. },
  4417. /**
  4418. * Returns image URL for the avatar to be displayed on small video thumbnail
  4419. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4420. */
  4421. getThumbUrl: function (jid) {
  4422. return this.getGravatarUrl(jid, 100);
  4423. },
  4424. /**
  4425. * Returns the URL for the avatar to be displayed as contactlist item
  4426. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4427. */
  4428. getContactListUrl: function (jid) {
  4429. return this.getGravatarUrl(jid, 30);
  4430. },
  4431. getGravatarUrl: function (jid, size) {
  4432. if (!jid) {
  4433. console.error("Get gravatar - jid is undefined");
  4434. return null;
  4435. }
  4436. var id = users[jid];
  4437. if (!id) {
  4438. console.warn("No avatar stored yet for " + jid);
  4439. return null;
  4440. }
  4441. return 'https://www.gravatar.com/avatar/' +
  4442. MD5.hexdigest(id.trim().toLowerCase()) +
  4443. "?d=wavatar&size=" + (size || "30");
  4444. }
  4445. };
  4446. module.exports = Avatar;
  4447. },{"../../settings/Settings":49}],19:[function(require,module,exports){
  4448. /* global $, config,
  4449. setLargeVideoVisible, Util */
  4450. var VideoLayout = require("../videolayout/VideoLayout");
  4451. var Prezi = require("../prezi/Prezi");
  4452. var UIUtil = require("../util/UIUtil");
  4453. var etherpadName = null;
  4454. var etherpadIFrame = null;
  4455. var domain = null;
  4456. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4457. /**
  4458. * Resizes the etherpad.
  4459. */
  4460. function resize() {
  4461. if ($('#etherpad>iframe').length) {
  4462. var remoteVideos = $('#remoteVideos');
  4463. var availableHeight
  4464. = window.innerHeight - remoteVideos.outerHeight();
  4465. var availableWidth = UIUtil.getAvailableVideoWidth();
  4466. $('#etherpad>iframe').width(availableWidth);
  4467. $('#etherpad>iframe').height(availableHeight);
  4468. }
  4469. }
  4470. /**
  4471. * Creates the Etherpad button and adds it to the toolbar.
  4472. */
  4473. function enableEtherpadButton() {
  4474. if (!$('#etherpadButton').is(":visible"))
  4475. $('#etherpadButton').css({display: 'inline-block'});
  4476. }
  4477. /**
  4478. * Creates the IFrame for the etherpad.
  4479. */
  4480. function createIFrame() {
  4481. etherpadIFrame = document.createElement('iframe');
  4482. etherpadIFrame.src = domain + etherpadName + options;
  4483. etherpadIFrame.frameBorder = 0;
  4484. etherpadIFrame.scrolling = "no";
  4485. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  4486. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  4487. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  4488. document.getElementById('etherpad').appendChild(etherpadIFrame);
  4489. etherpadIFrame.onload = function() {
  4490. document.domain = document.domain;
  4491. bubbleIframeMouseMove(etherpadIFrame);
  4492. setTimeout(function() {
  4493. // the iframes inside of the etherpad are
  4494. // not yet loaded when the etherpad iframe is loaded
  4495. var outer = etherpadIFrame.
  4496. contentDocument.getElementsByName("ace_outer")[0];
  4497. bubbleIframeMouseMove(outer);
  4498. var inner = outer.
  4499. contentDocument.getElementsByName("ace_inner")[0];
  4500. bubbleIframeMouseMove(inner);
  4501. }, 2000);
  4502. };
  4503. }
  4504. function bubbleIframeMouseMove(iframe){
  4505. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4506. iframe.contentWindow.onmousemove = function(e){
  4507. if(existingOnMouseMove) existingOnMouseMove(e);
  4508. var evt = document.createEvent("MouseEvents");
  4509. var boundingClientRect = iframe.getBoundingClientRect();
  4510. evt.initMouseEvent(
  4511. "mousemove",
  4512. true, // bubbles
  4513. false, // not cancelable
  4514. window,
  4515. e.detail,
  4516. e.screenX,
  4517. e.screenY,
  4518. e.clientX + boundingClientRect.left,
  4519. e.clientY + boundingClientRect.top,
  4520. e.ctrlKey,
  4521. e.altKey,
  4522. e.shiftKey,
  4523. e.metaKey,
  4524. e.button,
  4525. null // no related element
  4526. );
  4527. iframe.dispatchEvent(evt);
  4528. };
  4529. }
  4530. /**
  4531. * On video selected event.
  4532. */
  4533. $(document).bind('video.selected', function (event, isPresentation) {
  4534. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  4535. Etherpad.toggleEtherpad(isPresentation);
  4536. });
  4537. var Etherpad = {
  4538. /**
  4539. * Initializes the etherpad.
  4540. */
  4541. init: function (name) {
  4542. if (config.etherpad_base && !etherpadName && name) {
  4543. domain = config.etherpad_base;
  4544. etherpadName = name;
  4545. enableEtherpadButton();
  4546. /**
  4547. * Resizes the etherpad, when the window is resized.
  4548. */
  4549. $(window).resize(function () {
  4550. resize();
  4551. });
  4552. }
  4553. },
  4554. /**
  4555. * Opens/hides the Etherpad.
  4556. */
  4557. toggleEtherpad: function (isPresentation) {
  4558. if (!etherpadIFrame)
  4559. createIFrame();
  4560. var largeVideo = null;
  4561. if (Prezi.isPresentationVisible())
  4562. largeVideo = $('#presentation>iframe');
  4563. else
  4564. largeVideo = $('#largeVideo');
  4565. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  4566. $('#activeSpeaker').css('visibility', 'hidden');
  4567. largeVideo.fadeOut(300, function () {
  4568. if (Prezi.isPresentationVisible()) {
  4569. largeVideo.css({opacity: '0'});
  4570. } else {
  4571. VideoLayout.setLargeVideoVisible(false);
  4572. }
  4573. });
  4574. $('#etherpad>iframe').fadeIn(300, function () {
  4575. document.body.style.background = '#eeeeee';
  4576. $('#etherpad>iframe').css({visibility: 'visible'});
  4577. $('#etherpad').css({zIndex: 2});
  4578. });
  4579. }
  4580. else if ($('#etherpad>iframe')) {
  4581. $('#etherpad>iframe').fadeOut(300, function () {
  4582. $('#etherpad>iframe').css({visibility: 'hidden'});
  4583. $('#etherpad').css({zIndex: 0});
  4584. document.body.style.background = 'black';
  4585. });
  4586. if (!isPresentation) {
  4587. $('#largeVideo').fadeIn(300, function () {
  4588. VideoLayout.setLargeVideoVisible(true);
  4589. });
  4590. }
  4591. }
  4592. resize();
  4593. },
  4594. isVisible: function() {
  4595. var etherpadIframe = $('#etherpad>iframe');
  4596. return etherpadIframe && etherpadIframe.is(':visible');
  4597. }
  4598. };
  4599. module.exports = Etherpad;
  4600. },{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){
  4601. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4602. var UIUtil = require("../util/UIUtil");
  4603. var VideoLayout = require("../videolayout/VideoLayout");
  4604. var messageHandler = require("../util/MessageHandler");
  4605. var PreziPlayer = require("./PreziPlayer");
  4606. var preziPlayer = null;
  4607. var Prezi = {
  4608. /**
  4609. * Reloads the current presentation.
  4610. */
  4611. reloadPresentation: function() {
  4612. var iframe = document.getElementById(preziPlayer.options.preziId);
  4613. iframe.src = iframe.src;
  4614. },
  4615. /**
  4616. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4617. * otherwise.
  4618. */
  4619. isPresentationVisible: function () {
  4620. return ($('#presentation>iframe') != null
  4621. && $('#presentation>iframe').css('opacity') == 1);
  4622. },
  4623. /**
  4624. * Opens the Prezi dialog, from which the user could choose a presentation
  4625. * to load.
  4626. */
  4627. openPreziDialog: function() {
  4628. var myprezi = APP.xmpp.getPrezi();
  4629. if (myprezi) {
  4630. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4631. null,
  4632. "dialog.removePreziMsg",
  4633. null,
  4634. false,
  4635. "dialog.Remove",
  4636. function(e,v,m,f) {
  4637. if(v) {
  4638. APP.xmpp.removePreziFromPresence();
  4639. }
  4640. }
  4641. );
  4642. }
  4643. else if (preziPlayer != null) {
  4644. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4645. null, "dialog.sharePreziMsg",
  4646. null,
  4647. false,
  4648. "dialog.Ok",
  4649. function(e,v,m,f) {
  4650. $.prompt.close();
  4651. }
  4652. );
  4653. }
  4654. else {
  4655. var html = APP.translation.generateTranslationHTML(
  4656. "dialog.sharePreziTitle");
  4657. var cancelButton = APP.translation.generateTranslationHTML(
  4658. "dialog.Cancel");
  4659. var shareButton = APP.translation.generateTranslationHTML(
  4660. "dialog.Share");
  4661. var backButton = APP.translation.generateTranslationHTML(
  4662. "dialog.Back");
  4663. var buttons = [];
  4664. var buttons1 = [];
  4665. // Cancel button to both states
  4666. buttons.push({title: cancelButton, value: false});
  4667. buttons1.push({title: cancelButton, value: false});
  4668. // Share button
  4669. buttons.push({title: shareButton, value: true});
  4670. // Back button
  4671. buttons1.push({title: backButton, value: true});
  4672. var linkError = APP.translation.generateTranslationHTML(
  4673. "dialog.preziLinkError");
  4674. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4675. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4676. var openPreziState = {
  4677. state0: {
  4678. html: '<h2>' + html + '</h2>' +
  4679. '<input name="preziUrl" type="text" ' +
  4680. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4681. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4682. '\' placeholder="' + defaultUrl + '" autofocus>',
  4683. persistent: false,
  4684. buttons: buttons,
  4685. focus: ':input:first',
  4686. defaultButton: 0,
  4687. submit: function (e, v, m, f) {
  4688. e.preventDefault();
  4689. if(v)
  4690. {
  4691. var preziUrl = f.preziUrl;
  4692. if (preziUrl)
  4693. {
  4694. var urlValue
  4695. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4696. if (urlValue.indexOf('http://prezi.com/') != 0
  4697. && urlValue.indexOf('https://prezi.com/') != 0)
  4698. {
  4699. $.prompt.goToState('state1');
  4700. return false;
  4701. }
  4702. else {
  4703. var presIdTmp = urlValue.substring(
  4704. urlValue.indexOf("prezi.com/") + 10);
  4705. if (!isAlphanumeric(presIdTmp)
  4706. || presIdTmp.indexOf('/') < 2) {
  4707. $.prompt.goToState('state1');
  4708. return false;
  4709. }
  4710. else {
  4711. APP.xmpp.addToPresence("prezi", urlValue);
  4712. $.prompt.close();
  4713. }
  4714. }
  4715. }
  4716. }
  4717. else
  4718. $.prompt.close();
  4719. }
  4720. },
  4721. state1: {
  4722. html: '<h2>' + html + '</h2>' +
  4723. linkError,
  4724. persistent: false,
  4725. buttons: buttons1,
  4726. focus: ':input:first',
  4727. defaultButton: 1,
  4728. submit: function (e, v, m, f) {
  4729. e.preventDefault();
  4730. if (v === 0)
  4731. $.prompt.close();
  4732. else
  4733. $.prompt.goToState('state0');
  4734. }
  4735. }
  4736. };
  4737. messageHandler.openDialogWithStates(openPreziState);
  4738. }
  4739. }
  4740. };
  4741. /**
  4742. * A new presentation has been added.
  4743. *
  4744. * @param event the event indicating the add of a presentation
  4745. * @param jid the jid from which the presentation was added
  4746. * @param presUrl url of the presentation
  4747. * @param currentSlide the current slide to which we should move
  4748. */
  4749. function presentationAdded(event, jid, presUrl, currentSlide) {
  4750. console.log("presentation added", presUrl);
  4751. var presId = getPresentationId(presUrl);
  4752. var elementId = 'participant_'
  4753. + Strophe.getResourceFromJid(jid)
  4754. + '_' + presId;
  4755. VideoLayout.addPreziContainer(elementId);
  4756. VideoLayout.resizeThumbnails();
  4757. var controlsEnabled = false;
  4758. if (jid === APP.xmpp.myJid())
  4759. controlsEnabled = true;
  4760. setPresentationVisible(true);
  4761. $('#largeVideoContainer').hover(
  4762. function (event) {
  4763. if (Prezi.isPresentationVisible()) {
  4764. var reloadButtonRight = window.innerWidth
  4765. - $('#presentation>iframe').offset().left
  4766. - $('#presentation>iframe').width();
  4767. $('#reloadPresentation').css({ right: reloadButtonRight,
  4768. display:'inline-block'});
  4769. }
  4770. },
  4771. function (event) {
  4772. if (!Prezi.isPresentationVisible())
  4773. $('#reloadPresentation').css({display:'none'});
  4774. else {
  4775. var e = event.toElement || event.relatedTarget;
  4776. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4777. $('#reloadPresentation').css({display:'none'});
  4778. }
  4779. });
  4780. preziPlayer = new PreziPlayer(
  4781. 'presentation',
  4782. {preziId: presId,
  4783. width: getPresentationWidth(),
  4784. height: getPresentationHeihgt(),
  4785. controls: controlsEnabled,
  4786. debug: true
  4787. });
  4788. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4789. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4790. console.log("prezi status", event.value);
  4791. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4792. if (jid != APP.xmpp.myJid())
  4793. preziPlayer.flyToStep(currentSlide);
  4794. }
  4795. });
  4796. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4797. console.log("event value", event.value);
  4798. APP.xmpp.addToPresence("preziSlide", event.value);
  4799. });
  4800. $("#" + elementId).css( 'background-image',
  4801. 'url(../images/avatarprezi.png)');
  4802. $("#" + elementId).click(
  4803. function () {
  4804. setPresentationVisible(true);
  4805. }
  4806. );
  4807. };
  4808. /**
  4809. * A presentation has been removed.
  4810. *
  4811. * @param event the event indicating the remove of a presentation
  4812. * @param jid the jid for which the presentation was removed
  4813. * @param the url of the presentation
  4814. */
  4815. function presentationRemoved(event, jid, presUrl) {
  4816. console.log('presentation removed', presUrl);
  4817. var presId = getPresentationId(presUrl);
  4818. setPresentationVisible(false);
  4819. $('#participant_'
  4820. + Strophe.getResourceFromJid(jid)
  4821. + '_' + presId).remove();
  4822. $('#presentation>iframe').remove();
  4823. if (preziPlayer != null) {
  4824. preziPlayer.destroy();
  4825. preziPlayer = null;
  4826. }
  4827. };
  4828. /**
  4829. * Indicates if the given string is an alphanumeric string.
  4830. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4831. * purpose of checking URIs.
  4832. */
  4833. function isAlphanumeric(unsafeText) {
  4834. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4835. return regex.test(unsafeText);
  4836. }
  4837. /**
  4838. * Returns the presentation id from the given url.
  4839. */
  4840. function getPresentationId (presUrl) {
  4841. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4842. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4843. }
  4844. /**
  4845. * Returns the presentation width.
  4846. */
  4847. function getPresentationWidth() {
  4848. var availableWidth = UIUtil.getAvailableVideoWidth();
  4849. var availableHeight = getPresentationHeihgt();
  4850. var aspectRatio = 16.0 / 9.0;
  4851. if (availableHeight < availableWidth / aspectRatio) {
  4852. availableWidth = Math.floor(availableHeight * aspectRatio);
  4853. }
  4854. return availableWidth;
  4855. }
  4856. /**
  4857. * Returns the presentation height.
  4858. */
  4859. function getPresentationHeihgt() {
  4860. var remoteVideos = $('#remoteVideos');
  4861. return window.innerHeight - remoteVideos.outerHeight();
  4862. }
  4863. /**
  4864. * Resizes the presentation iframe.
  4865. */
  4866. function resize() {
  4867. if ($('#presentation>iframe')) {
  4868. $('#presentation>iframe').width(getPresentationWidth());
  4869. $('#presentation>iframe').height(getPresentationHeihgt());
  4870. }
  4871. }
  4872. /**
  4873. * Shows/hides a presentation.
  4874. */
  4875. function setPresentationVisible(visible) {
  4876. var prezi = $('#presentation>iframe');
  4877. if (visible) {
  4878. // Trigger the video.selected event to indicate a change in the
  4879. // large video.
  4880. $(document).trigger("video.selected", [true]);
  4881. $('#largeVideo').fadeOut(300);
  4882. prezi.fadeIn(300, function() {
  4883. prezi.css({opacity:'1'});
  4884. ToolbarToggler.dockToolbar(true);
  4885. VideoLayout.setLargeVideoVisible(false);
  4886. });
  4887. $('#activeSpeaker').css('visibility', 'hidden');
  4888. }
  4889. else {
  4890. if (prezi.css('opacity') == '1') {
  4891. prezi.fadeOut(300, function () {
  4892. prezi.css({opacity:'0'});
  4893. $('#reloadPresentation').css({display:'none'});
  4894. $('#largeVideo').fadeIn(300, function() {
  4895. VideoLayout.setLargeVideoVisible(true);
  4896. ToolbarToggler.dockToolbar(false);
  4897. });
  4898. });
  4899. }
  4900. }
  4901. }
  4902. /**
  4903. * Presentation has been removed.
  4904. */
  4905. $(document).bind('presentationremoved.muc', presentationRemoved);
  4906. /**
  4907. * Presentation has been added.
  4908. */
  4909. $(document).bind('presentationadded.muc', presentationAdded);
  4910. /*
  4911. * Indicates presentation slide change.
  4912. */
  4913. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4914. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4915. preziPlayer.flyToStep(current);
  4916. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4917. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4918. preziPlayer.flyToStep(current, i);
  4919. }
  4920. }
  4921. });
  4922. /**
  4923. * On video selected event.
  4924. */
  4925. $(document).bind('video.selected', function (event, isPresentation) {
  4926. if (!isPresentation && $('#presentation>iframe')) {
  4927. setPresentationVisible(false);
  4928. }
  4929. });
  4930. $(window).resize(function () {
  4931. resize();
  4932. });
  4933. module.exports = Prezi;
  4934. },{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){
  4935. (function() {
  4936. "use strict";
  4937. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4938. window.PreziPlayer = (function() {
  4939. PreziPlayer.API_VERSION = 1;
  4940. PreziPlayer.CURRENT_STEP = 'currentStep';
  4941. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4942. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4943. PreziPlayer.STATUS_LOADING = 'loading';
  4944. PreziPlayer.STATUS_READY = 'ready';
  4945. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4946. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4947. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4948. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4949. PreziPlayer.EVENT_STATUS = "statusChange";
  4950. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4951. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4952. PreziPlayer.domain = "https://prezi.com";
  4953. PreziPlayer.path = "/player/";
  4954. PreziPlayer.players = {};
  4955. PreziPlayer.binded_methods = ['changesHandler'];
  4956. PreziPlayer.createMultiplePlayers = function(optionArray){
  4957. for(var i=0; i<optionArray.length; i++) {
  4958. var optionSet = optionArray[i];
  4959. new PreziPlayer(optionSet.id, optionSet);
  4960. };
  4961. };
  4962. PreziPlayer.messageReceived = function(event){
  4963. var message, item, player;
  4964. try {
  4965. message = JSON.parse(event.data);
  4966. if (message.id && (player = PreziPlayer.players[message.id])) {
  4967. if (player.options.debug === true) {
  4968. if (console && console.log)
  4969. console.log('received', message);
  4970. }
  4971. if (message.type === "changes") {
  4972. player.changesHandler(message);
  4973. }
  4974. for (var i = 0; i < player.callbacks.length; i++) {
  4975. item = player.callbacks[i];
  4976. if (item && message.type === item.event) {
  4977. item.callback(message);
  4978. }
  4979. }
  4980. }
  4981. } catch (e) { }
  4982. };
  4983. function PreziPlayer(id, options) {
  4984. var params, paramString = "", _this = this;
  4985. if (PreziPlayer.players[id]){
  4986. PreziPlayer.players[id].destroy();
  4987. }
  4988. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4989. var method_name = PreziPlayer.binded_methods[i];
  4990. _this[method_name] = __bind(_this[method_name], _this);
  4991. };
  4992. options = options || {};
  4993. this.options = options;
  4994. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4995. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4996. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4997. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4998. this.callbacks = [];
  4999. this.id = id;
  5000. this.embedTo = document.getElementById(id);
  5001. if (!this.embedTo) {
  5002. throw "The element id is not available.";
  5003. }
  5004. this.iframe = document.createElement('iframe');
  5005. params = [
  5006. { name: 'oid', value: options.preziId },
  5007. { name: 'explorable', value: options.explorable ? 1 : 0 },
  5008. { name: 'controls', value: options.controls ? 1 : 0 }
  5009. ];
  5010. for(var i=0; i<params.length; i++) {
  5011. var param = params[i];
  5012. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  5013. };
  5014. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  5015. this.iframe.frameBorder = 0;
  5016. this.iframe.scrolling = "no";
  5017. this.iframe.width = options.width || 640;
  5018. this.iframe.height = options.height || 480;
  5019. this.embedTo.innerHTML = '';
  5020. // JITSI: IN CASE SOMETHING GOES WRONG.
  5021. try {
  5022. this.embedTo.appendChild(this.iframe);
  5023. }
  5024. catch (err) {
  5025. console.log("CATCH ERROR");
  5026. }
  5027. // JITSI: Increase interval from 200 to 500, which fixes prezi
  5028. // crashes for us.
  5029. this.initPollInterval = setInterval(function(){
  5030. _this.sendMessage({'action': 'init'});
  5031. }, 500);
  5032. PreziPlayer.players[id] = this;
  5033. }
  5034. PreziPlayer.prototype.changesHandler = function(message) {
  5035. var key, value, j, item;
  5036. if (this.initPollInterval) {
  5037. clearInterval(this.initPollInterval);
  5038. this.initPollInterval = false;
  5039. }
  5040. for (key in message.data) {
  5041. if (message.data.hasOwnProperty(key)){
  5042. value = message.data[key];
  5043. this.values[key] = value;
  5044. for (j=0; j<this.callbacks.length; j++) {
  5045. item = this.callbacks[j];
  5046. if (item && item.event === key + "Change"){
  5047. item.callback({type: item.event, value: value});
  5048. }
  5049. }
  5050. }
  5051. }
  5052. };
  5053. PreziPlayer.prototype.destroy = function() {
  5054. if (this.initPollInterval) {
  5055. clearInterval(this.initPollInterval);
  5056. this.initPollInterval = false;
  5057. }
  5058. this.embedTo.innerHTML = '';
  5059. };
  5060. PreziPlayer.prototype.sendMessage = function(message) {
  5061. if (this.options.debug === true) {
  5062. if (console && console.log) console.log('sent', message);
  5063. }
  5064. message.version = PreziPlayer.API_VERSION;
  5065. message.id = this.id;
  5066. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  5067. };
  5068. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  5069. PreziPlayer.prototype.flyToNextStep = function() {
  5070. return this.sendMessage({
  5071. 'action': 'present',
  5072. 'data': ['moveToNextStep']
  5073. });
  5074. };
  5075. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  5076. PreziPlayer.prototype.flyToPreviousStep = function() {
  5077. return this.sendMessage({
  5078. 'action': 'present',
  5079. 'data': ['moveToPrevStep']
  5080. });
  5081. };
  5082. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  5083. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  5084. var obj = this;
  5085. // check animation_step
  5086. if (animation_step > 0 &&
  5087. obj.values.animationCountOnSteps &&
  5088. obj.values.animationCountOnSteps[step] <= animation_step) {
  5089. animation_step = obj.values.animationCountOnSteps[step];
  5090. }
  5091. // jump to animation steps by calling flyToNextStep()
  5092. function doAnimationSteps() {
  5093. if (obj.values.isMoving == true) {
  5094. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  5095. return;
  5096. }
  5097. while (animation_step-- > 0) {
  5098. obj.flyToNextStep(); // do the animation steps
  5099. }
  5100. }
  5101. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  5102. // jump to the step
  5103. return this.sendMessage({
  5104. 'action': 'present',
  5105. 'data': ['moveToStep', step]
  5106. });
  5107. };
  5108. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  5109. PreziPlayer.prototype.flyToObject = function(objectId) {
  5110. return this.sendMessage({
  5111. 'action': 'present',
  5112. 'data': ['moveToObject', objectId]
  5113. });
  5114. };
  5115. PreziPlayer.prototype.play = function(defaultDelay) {
  5116. return this.sendMessage({
  5117. 'action': 'present',
  5118. 'data': ['startAutoPlay', defaultDelay]
  5119. });
  5120. };
  5121. PreziPlayer.prototype.stop = function() {
  5122. return this.sendMessage({
  5123. 'action': 'present',
  5124. 'data': ['stopAutoPlay']
  5125. });
  5126. };
  5127. PreziPlayer.prototype.pause = function(defaultDelay) {
  5128. return this.sendMessage({
  5129. 'action': 'present',
  5130. 'data': ['pauseAutoPlay', defaultDelay]
  5131. });
  5132. };
  5133. PreziPlayer.prototype.getCurrentStep = function() {
  5134. return this.values.currentStep;
  5135. };
  5136. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  5137. return this.values.currentAnimationStep;
  5138. };
  5139. PreziPlayer.prototype.getCurrentObject = function() {
  5140. return this.values.currentObject;
  5141. };
  5142. PreziPlayer.prototype.getStatus = function() {
  5143. return this.values.status;
  5144. };
  5145. PreziPlayer.prototype.isPlaying = function() {
  5146. return this.values.isAutoPlaying;
  5147. };
  5148. PreziPlayer.prototype.getStepCount = function() {
  5149. return this.values.stepCount;
  5150. };
  5151. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  5152. return this.values.animationCountOnSteps;
  5153. };
  5154. PreziPlayer.prototype.getTitle = function() {
  5155. return this.values.title;
  5156. };
  5157. PreziPlayer.prototype.setDimensions = function(dims) {
  5158. for (var parameter in dims) {
  5159. this.iframe[parameter] = dims[parameter];
  5160. }
  5161. }
  5162. PreziPlayer.prototype.getDimensions = function() {
  5163. return {
  5164. width: parseInt(this.iframe.width, 10),
  5165. height: parseInt(this.iframe.height, 10)
  5166. }
  5167. }
  5168. PreziPlayer.prototype.on = function(event, callback) {
  5169. this.callbacks.push({
  5170. event: event,
  5171. callback: callback
  5172. });
  5173. };
  5174. PreziPlayer.prototype.off = function(event, callback) {
  5175. var j, item;
  5176. if (event === undefined) {
  5177. this.callbacks = [];
  5178. }
  5179. j = this.callbacks.length;
  5180. while (j--) {
  5181. item = this.callbacks[j];
  5182. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  5183. this.callbacks.splice(j, 1);
  5184. }
  5185. }
  5186. };
  5187. if (window.addEventListener) {
  5188. window.addEventListener('message', PreziPlayer.messageReceived, false);
  5189. } else {
  5190. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  5191. }
  5192. return PreziPlayer;
  5193. })();
  5194. })();
  5195. module.exports = PreziPlayer;
  5196. },{}],22:[function(require,module,exports){
  5197. var Chat = require("./chat/Chat");
  5198. var ContactList = require("./contactlist/ContactList");
  5199. var Settings = require("./../../settings/Settings");
  5200. var SettingsMenu = require("./settings/SettingsMenu");
  5201. var VideoLayout = require("../videolayout/VideoLayout");
  5202. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  5203. var UIUtil = require("../util/UIUtil");
  5204. var LargeVideo = require("../videolayout/LargeVideo");
  5205. /**
  5206. * Toggler for the chat, contact list, settings menu, etc..
  5207. */
  5208. var PanelToggler = (function(my) {
  5209. var currentlyOpen = null;
  5210. var buttons = {
  5211. '#chatspace': '#chatBottomButton',
  5212. '#contactlist': '#contactListButton',
  5213. '#settingsmenu': '#settingsButton'
  5214. };
  5215. /**
  5216. * Toggles the windows in the side panel
  5217. * @param object the window that should be shown
  5218. * @param selector the selector for the element containing the panel
  5219. * @param onOpenComplete function to be called when the panel is opened
  5220. * @param onOpen function to be called if the window is going to be opened
  5221. * @param onClose function to be called if the window is going to be closed
  5222. */
  5223. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  5224. UIUtil.buttonClick(buttons[selector], "active");
  5225. if (object.isVisible()) {
  5226. $("#toast-container").animate({
  5227. right: '5px'
  5228. },
  5229. {
  5230. queue: false,
  5231. duration: 500
  5232. });
  5233. $(selector).hide("slide", {
  5234. direction: "right",
  5235. queue: false,
  5236. duration: 500
  5237. });
  5238. if(typeof onClose === "function") {
  5239. onClose();
  5240. }
  5241. currentlyOpen = null;
  5242. }
  5243. else {
  5244. // Undock the toolbar when the chat is shown and if we're in a
  5245. // video mode.
  5246. if (LargeVideo.isLargeVideoVisible()) {
  5247. ToolbarToggler.dockToolbar(false);
  5248. }
  5249. if(currentlyOpen) {
  5250. var current = $(currentlyOpen);
  5251. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  5252. current.css('z-index', 4);
  5253. setTimeout(function () {
  5254. current.css('display', 'none');
  5255. current.css('z-index', 5);
  5256. }, 500);
  5257. }
  5258. $("#toast-container").animate({
  5259. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  5260. },
  5261. {
  5262. queue: false,
  5263. duration: 500
  5264. });
  5265. $(selector).show("slide", {
  5266. direction: "right",
  5267. queue: false,
  5268. duration: 500,
  5269. complete: onOpenComplete
  5270. });
  5271. if(typeof onOpen === "function") {
  5272. onOpen();
  5273. }
  5274. currentlyOpen = selector;
  5275. }
  5276. };
  5277. /**
  5278. * Opens / closes the chat area.
  5279. */
  5280. my.toggleChat = function() {
  5281. var chatCompleteFunction = Chat.isVisible() ?
  5282. function() {} : function () {
  5283. Chat.scrollChatToBottom();
  5284. $('#chatspace').trigger('shown');
  5285. };
  5286. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  5287. toggle(Chat,
  5288. '#chatspace',
  5289. function () {
  5290. // Request the focus in the nickname field or the chat input field.
  5291. if ($('#nickname').css('visibility') === 'visible') {
  5292. $('#nickinput').focus();
  5293. } else {
  5294. $('#usermsg').focus();
  5295. }
  5296. },
  5297. null,
  5298. Chat.resizeChat,
  5299. null);
  5300. };
  5301. /**
  5302. * Opens / closes the contact list area.
  5303. */
  5304. my.toggleContactList = function () {
  5305. var completeFunction = ContactList.isVisible() ?
  5306. function() {} : function () { $('#contactlist').trigger('shown');};
  5307. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5308. toggle(ContactList,
  5309. '#contactlist',
  5310. null,
  5311. function() {
  5312. ContactList.setVisualNotification(false);
  5313. },
  5314. null);
  5315. };
  5316. /**
  5317. * Opens / closes the settings menu
  5318. */
  5319. my.toggleSettingsMenu = function() {
  5320. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5321. toggle(SettingsMenu,
  5322. '#settingsmenu',
  5323. null,
  5324. function() {
  5325. var settings = Settings.getSettings();
  5326. $('#setDisplayName').get(0).value = settings.displayName;
  5327. $('#setEmail').get(0).value = settings.email;
  5328. },
  5329. null);
  5330. };
  5331. /**
  5332. * Returns the size of the side panel.
  5333. */
  5334. my.getPanelSize = function () {
  5335. var availableHeight = window.innerHeight;
  5336. var availableWidth = window.innerWidth;
  5337. var panelWidth = 200;
  5338. if (availableWidth * 0.2 < 200) {
  5339. panelWidth = availableWidth * 0.2;
  5340. }
  5341. return [panelWidth, availableHeight];
  5342. };
  5343. my.isVisible = function() {
  5344. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5345. };
  5346. return my;
  5347. }(PanelToggler || {}));
  5348. module.exports = PanelToggler;
  5349. },{"../toolbars/ToolbarToggler":31,"../util/UIUtil":35,"../videolayout/LargeVideo":37,"../videolayout/VideoLayout":41,"./../../settings/Settings":49,"./chat/Chat":23,"./contactlist/ContactList":27,"./settings/SettingsMenu":28}],23:[function(require,module,exports){
  5350. /* global $, Util, nickname:true */
  5351. var Replacement = require("./Replacement");
  5352. var CommandsProcessor = require("./Commands");
  5353. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5354. var smileys = require("./smileys.json").smileys;
  5355. var NicknameHandler = require("../../util/NicknameHandler");
  5356. var UIUtil = require("../../util/UIUtil");
  5357. var UIEvents = require("../../../../service/UI/UIEvents");
  5358. var notificationInterval = false;
  5359. var unreadMessages = 0;
  5360. /**
  5361. * Shows/hides a visual notification, indicating that a message has arrived.
  5362. */
  5363. function setVisualNotification(show) {
  5364. var unreadMsgElement = document.getElementById('unreadMessages');
  5365. var unreadMsgBottomElement
  5366. = document.getElementById('bottomUnreadMessages');
  5367. var glower = $('#chatButton');
  5368. var bottomGlower = $('#chatBottomButton');
  5369. if (unreadMessages) {
  5370. unreadMsgElement.innerHTML = unreadMessages.toString();
  5371. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5372. ToolbarToggler.dockToolbar(true);
  5373. var chatButtonElement
  5374. = document.getElementById('chatButton').parentNode;
  5375. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5376. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5377. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5378. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5379. unreadMsgElement.setAttribute(
  5380. 'style',
  5381. 'top:' + topIndent +
  5382. '; left:' + leftIndent + ';');
  5383. var chatBottomButtonElement
  5384. = document.getElementById('chatBottomButton').parentNode;
  5385. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5386. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5387. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5388. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5389. unreadMsgBottomElement.setAttribute(
  5390. 'style',
  5391. 'top:' + bottomTopIndent +
  5392. '; left:' + bottomLeftIndent + ';');
  5393. if (!glower.hasClass('icon-chat-simple')) {
  5394. glower.removeClass('icon-chat');
  5395. glower.addClass('icon-chat-simple');
  5396. }
  5397. }
  5398. else {
  5399. unreadMsgElement.innerHTML = '';
  5400. unreadMsgBottomElement.innerHTML = '';
  5401. glower.removeClass('icon-chat-simple');
  5402. glower.addClass('icon-chat');
  5403. }
  5404. if (show && !notificationInterval) {
  5405. notificationInterval = window.setInterval(function () {
  5406. glower.toggleClass('active');
  5407. bottomGlower.toggleClass('active glowing');
  5408. }, 800);
  5409. }
  5410. else if (!show && notificationInterval) {
  5411. window.clearInterval(notificationInterval);
  5412. notificationInterval = false;
  5413. glower.removeClass('active');
  5414. bottomGlower.removeClass('glowing');
  5415. bottomGlower.addClass('active');
  5416. }
  5417. }
  5418. /**
  5419. * Returns the current time in the format it is shown to the user
  5420. * @returns {string}
  5421. */
  5422. function getCurrentTime(stamp) {
  5423. var now = (stamp? new Date(stamp): new Date());
  5424. var hour = now.getHours();
  5425. var minute = now.getMinutes();
  5426. var second = now.getSeconds();
  5427. if(hour.toString().length === 1) {
  5428. hour = '0'+hour;
  5429. }
  5430. if(minute.toString().length === 1) {
  5431. minute = '0'+minute;
  5432. }
  5433. if(second.toString().length === 1) {
  5434. second = '0'+second;
  5435. }
  5436. return hour+':'+minute+':'+second;
  5437. }
  5438. function toggleSmileys()
  5439. {
  5440. var smileys = $('#smileysContainer');
  5441. if(!smileys.is(':visible')) {
  5442. smileys.show("slide", { direction: "down", duration: 300});
  5443. } else {
  5444. smileys.hide("slide", { direction: "down", duration: 300});
  5445. }
  5446. $('#usermsg').focus();
  5447. }
  5448. function addClickFunction(smiley, number) {
  5449. smiley.onclick = function addSmileyToMessage() {
  5450. var usermsg = $('#usermsg');
  5451. var message = usermsg.val();
  5452. message += smileys['smiley' + number];
  5453. usermsg.val(message);
  5454. usermsg.get(0).setSelectionRange(message.length, message.length);
  5455. toggleSmileys();
  5456. usermsg.focus();
  5457. };
  5458. }
  5459. /**
  5460. * Adds the smileys container to the chat
  5461. */
  5462. function addSmileys() {
  5463. var smileysContainer = document.createElement('div');
  5464. smileysContainer.id = 'smileysContainer';
  5465. for(var i = 1; i <= 21; i++) {
  5466. var smileyContainer = document.createElement('div');
  5467. smileyContainer.id = 'smiley' + i;
  5468. smileyContainer.className = 'smileyContainer';
  5469. var smiley = document.createElement('img');
  5470. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5471. smiley.className = 'smiley';
  5472. addClickFunction(smiley, i);
  5473. smileyContainer.appendChild(smiley);
  5474. smileysContainer.appendChild(smileyContainer);
  5475. }
  5476. $("#chatspace").append(smileysContainer);
  5477. }
  5478. /**
  5479. * Resizes the chat conversation.
  5480. */
  5481. function resizeChatConversation() {
  5482. var msgareaHeight = $('#usermsg').outerHeight();
  5483. var chatspace = $('#chatspace');
  5484. var width = chatspace.width();
  5485. var chat = $('#chatconversation');
  5486. var smileys = $('#smileysarea');
  5487. smileys.height(msgareaHeight);
  5488. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5489. $('#smileysContainer').css('bottom', msgareaHeight);
  5490. chat.width(width - 10);
  5491. chat.height(window.innerHeight - 15 - msgareaHeight);
  5492. }
  5493. /**
  5494. * Chat related user interface.
  5495. */
  5496. var Chat = (function (my) {
  5497. /**
  5498. * Initializes chat related interface.
  5499. */
  5500. my.init = function () {
  5501. if(NicknameHandler.getNickname())
  5502. Chat.setChatConversationMode(true);
  5503. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5504. function (nickname) {
  5505. Chat.setChatConversationMode(true);
  5506. });
  5507. $('#nickinput').keydown(function (event) {
  5508. if (event.keyCode === 13) {
  5509. event.preventDefault();
  5510. var val = UIUtil.escapeHtml(this.value);
  5511. this.value = '';
  5512. if (!NicknameHandler.getNickname()) {
  5513. NicknameHandler.setNickname(val);
  5514. return;
  5515. }
  5516. }
  5517. });
  5518. $('#usermsg').keydown(function (event) {
  5519. if (event.keyCode === 13) {
  5520. event.preventDefault();
  5521. var value = this.value;
  5522. $('#usermsg').val('').trigger('autosize.resize');
  5523. this.focus();
  5524. var command = new CommandsProcessor(value);
  5525. if(command.isCommand())
  5526. {
  5527. command.processCommand();
  5528. }
  5529. else
  5530. {
  5531. var message = UIUtil.escapeHtml(value);
  5532. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5533. }
  5534. }
  5535. });
  5536. var onTextAreaResize = function () {
  5537. resizeChatConversation();
  5538. Chat.scrollChatToBottom();
  5539. };
  5540. $('#usermsg').autosize({callback: onTextAreaResize});
  5541. $("#chatspace").bind("shown",
  5542. function () {
  5543. unreadMessages = 0;
  5544. setVisualNotification(false);
  5545. });
  5546. addSmileys();
  5547. };
  5548. /**
  5549. * Appends the given message to the chat conversation.
  5550. */
  5551. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  5552. var divClassName = '';
  5553. if (APP.xmpp.myJid() === from) {
  5554. divClassName = "localuser";
  5555. }
  5556. else {
  5557. divClassName = "remoteuser";
  5558. if (!Chat.isVisible()) {
  5559. unreadMessages++;
  5560. UIUtil.playSoundNotification('chatNotification');
  5561. setVisualNotification(true);
  5562. }
  5563. }
  5564. // replace links and smileys
  5565. // Strophe already escapes special symbols on sending,
  5566. // so we escape here only tags to avoid double &amp;
  5567. var escMessage = message.replace(/</g, '&lt;').
  5568. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5569. var escDisplayName = UIUtil.escapeHtml(displayName);
  5570. message = Replacement.processReplacements(escMessage);
  5571. var messageContainer =
  5572. '<div class="chatmessage">'+
  5573. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5574. '<div class="username ' + divClassName +'">' + escDisplayName +
  5575. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5576. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5577. '</div>';
  5578. $('#chatconversation').append(messageContainer);
  5579. $('#chatconversation').animate(
  5580. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5581. };
  5582. /**
  5583. * Appends error message to the conversation
  5584. * @param errorMessage the received error message.
  5585. * @param originalText the original message.
  5586. */
  5587. my.chatAddError = function(errorMessage, originalText)
  5588. {
  5589. errorMessage = UIUtil.escapeHtml(errorMessage);
  5590. originalText = UIUtil.escapeHtml(originalText);
  5591. $('#chatconversation').append(
  5592. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5593. (originalText? (' \"'+ originalText + '\"') : "") +
  5594. ' was not sent.' +
  5595. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5596. $('#chatconversation').animate(
  5597. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5598. };
  5599. /**
  5600. * Sets the subject to the UI
  5601. * @param subject the subject
  5602. */
  5603. my.chatSetSubject = function(subject)
  5604. {
  5605. if(subject)
  5606. subject = subject.trim();
  5607. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5608. if(subject === "")
  5609. {
  5610. $("#subject").css({display: "none"});
  5611. }
  5612. else
  5613. {
  5614. $("#subject").css({display: "block"});
  5615. }
  5616. };
  5617. /**
  5618. * Sets the chat conversation mode.
  5619. */
  5620. my.setChatConversationMode = function (isConversationMode) {
  5621. if (isConversationMode) {
  5622. $('#nickname').css({visibility: 'hidden'});
  5623. $('#chatconversation').css({visibility: 'visible'});
  5624. $('#usermsg').css({visibility: 'visible'});
  5625. $('#smileysarea').css({visibility: 'visible'});
  5626. $('#usermsg').focus();
  5627. }
  5628. };
  5629. /**
  5630. * Resizes the chat area.
  5631. */
  5632. my.resizeChat = function () {
  5633. var chatSize = require("../SidePanelToggler").getPanelSize();
  5634. $('#chatspace').width(chatSize[0]);
  5635. $('#chatspace').height(chatSize[1]);
  5636. resizeChatConversation();
  5637. };
  5638. /**
  5639. * Indicates if the chat is currently visible.
  5640. */
  5641. my.isVisible = function () {
  5642. return $('#chatspace').is(":visible");
  5643. };
  5644. /**
  5645. * Shows and hides the window with the smileys
  5646. */
  5647. my.toggleSmileys = toggleSmileys;
  5648. /**
  5649. * Scrolls chat to the bottom.
  5650. */
  5651. my.scrollChatToBottom = function() {
  5652. setTimeout(function () {
  5653. $('#chatconversation').scrollTop(
  5654. $('#chatconversation')[0].scrollHeight);
  5655. }, 5);
  5656. };
  5657. return my;
  5658. }(Chat || {}));
  5659. module.exports = Chat;
  5660. },{"../../../../service/UI/UIEvents":104,"../../toolbars/ToolbarToggler":31,"../../util/NicknameHandler":34,"../../util/UIUtil":35,"../SidePanelToggler":22,"./Commands":24,"./Replacement":25,"./smileys.json":26}],24:[function(require,module,exports){
  5661. var UIUtil = require("../../util/UIUtil");
  5662. /**
  5663. * List with supported commands. The keys are the names of the commands and
  5664. * the value is the function that processes the message.
  5665. * @type {{String: function}}
  5666. */
  5667. var commands = {
  5668. "topic" : processTopic
  5669. };
  5670. /**
  5671. * Extracts the command from the message.
  5672. * @param message the received message
  5673. * @returns {string} the command
  5674. */
  5675. function getCommand(message)
  5676. {
  5677. if(message)
  5678. {
  5679. for(var command in commands)
  5680. {
  5681. if(message.indexOf("/" + command) == 0)
  5682. return command;
  5683. }
  5684. }
  5685. return "";
  5686. };
  5687. /**
  5688. * Processes the data for topic command.
  5689. * @param commandArguments the arguments of the topic command.
  5690. */
  5691. function processTopic(commandArguments)
  5692. {
  5693. var topic = UIUtil.escapeHtml(commandArguments);
  5694. APP.xmpp.setSubject(topic);
  5695. }
  5696. /**
  5697. * Constructs new CommandProccessor instance from a message that
  5698. * handles commands received via chat messages.
  5699. * @param message the message
  5700. * @constructor
  5701. */
  5702. function CommandsProcessor(message)
  5703. {
  5704. var command = getCommand(message);
  5705. /**
  5706. * Returns the name of the command.
  5707. * @returns {String} the command
  5708. */
  5709. this.getCommand = function()
  5710. {
  5711. return command;
  5712. };
  5713. var messageArgument = message.substr(command.length + 2);
  5714. /**
  5715. * Returns the arguments of the command.
  5716. * @returns {string}
  5717. */
  5718. this.getArgument = function()
  5719. {
  5720. return messageArgument;
  5721. };
  5722. }
  5723. /**
  5724. * Checks whether this instance is valid command or not.
  5725. * @returns {boolean}
  5726. */
  5727. CommandsProcessor.prototype.isCommand = function()
  5728. {
  5729. if(this.getCommand())
  5730. return true;
  5731. return false;
  5732. };
  5733. /**
  5734. * Processes the command.
  5735. */
  5736. CommandsProcessor.prototype.processCommand = function()
  5737. {
  5738. if(!this.isCommand())
  5739. return;
  5740. commands[this.getCommand()](this.getArgument());
  5741. };
  5742. module.exports = CommandsProcessor;
  5743. },{"../../util/UIUtil":35}],25:[function(require,module,exports){
  5744. var Smileys = require("./smileys.json");
  5745. /**
  5746. * Processes links and smileys in "body"
  5747. */
  5748. function processReplacements(body)
  5749. {
  5750. //make links clickable
  5751. body = linkify(body);
  5752. //add smileys
  5753. body = smilify(body);
  5754. return body;
  5755. }
  5756. /**
  5757. * Finds and replaces all links in the links in "body"
  5758. * with their <a href=""></a>
  5759. */
  5760. function linkify(inputText)
  5761. {
  5762. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5763. //URLs starting with http://, https://, or ftp://
  5764. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5765. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5766. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5767. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5768. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5769. //Change email addresses to mailto:: links.
  5770. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5771. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5772. return replacedText;
  5773. }
  5774. /**
  5775. * Replaces common smiley strings with images
  5776. */
  5777. function smilify(body)
  5778. {
  5779. if(!body) {
  5780. return body;
  5781. }
  5782. var regexs = Smileys["regexs"];
  5783. for(var smiley in regexs) {
  5784. if(regexs.hasOwnProperty(smiley)) {
  5785. body = body.replace(regexs[smiley],
  5786. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5787. }
  5788. }
  5789. return body;
  5790. }
  5791. module.exports = {
  5792. processReplacements: processReplacements,
  5793. linkify: linkify
  5794. };
  5795. },{"./smileys.json":26}],26:[function(require,module,exports){
  5796. module.exports={
  5797. "smileys": {
  5798. "smiley1": ":)",
  5799. "smiley2": ":(",
  5800. "smiley3": ":D",
  5801. "smiley4": "(y)",
  5802. "smiley5": " :P",
  5803. "smiley6": "(wave)",
  5804. "smiley7": "(blush)",
  5805. "smiley8": "(chuckle)",
  5806. "smiley9": "(shocked)",
  5807. "smiley10": ":*",
  5808. "smiley11": "(n)",
  5809. "smiley12": "(search)",
  5810. "smiley13": " <3",
  5811. "smiley14": "(oops)",
  5812. "smiley15": "(angry)",
  5813. "smiley16": "(angel)",
  5814. "smiley17": "(sick)",
  5815. "smiley18": ";(",
  5816. "smiley19": "(bomb)",
  5817. "smiley20": "(clap)",
  5818. "smiley21": " ;)"
  5819. },
  5820. "regexs": {
  5821. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5822. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5823. "smiley1": /(:-\)|:\))/gi,
  5824. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5825. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5826. "smiley6": /(\(wave\))/gi,
  5827. "smiley7": /(\(blush\))/gi,
  5828. "smiley8": /(\(chuckle\))/gi,
  5829. "smiley9": /(:-0|\(shocked\))/gi,
  5830. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5831. "smiley11": /(\(n\))/gi,
  5832. "smiley12": /(\(search\))/g,
  5833. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5834. "smiley14": /(\(oops\))/gi,
  5835. "smiley15": /(\(angry\))/gi,
  5836. "smiley16": /(\(angel\))/gi,
  5837. "smiley17": /(\(sick\))/gi,
  5838. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5839. "smiley19": /(\(bomb\))/gi,
  5840. "smiley20": /(\(clap\))/gi,
  5841. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5842. }
  5843. }
  5844. },{}],27:[function(require,module,exports){
  5845. var Avatar = require('../../avatar/Avatar');
  5846. var numberOfContacts = 0;
  5847. var notificationInterval;
  5848. /**
  5849. * Updates the number of participants in the contact list button and sets
  5850. * the glow
  5851. * @param delta indicates whether a new user has joined (1) or someone has
  5852. * left(-1)
  5853. */
  5854. function updateNumberOfParticipants(delta) {
  5855. numberOfContacts += delta;
  5856. if (numberOfContacts === 1) {
  5857. // when the user is alone we don't show the number of participants
  5858. $("#numberOfParticipants").text('');
  5859. ContactList.setVisualNotification(false);
  5860. } else if (numberOfContacts > 1) {
  5861. ContactList.setVisualNotification(!ContactList.isVisible());
  5862. $("#numberOfParticipants").text(numberOfContacts);
  5863. } else {
  5864. console.error("Invalid number of participants: " + numberOfContacts);
  5865. }
  5866. }
  5867. /**
  5868. * Creates the avatar element.
  5869. *
  5870. * @return the newly created avatar element
  5871. */
  5872. function createAvatar(jid) {
  5873. var avatar = document.createElement('img');
  5874. avatar.className = "icon-avatar avatar";
  5875. avatar.src = Avatar.getContactListUrl(jid);
  5876. return avatar;
  5877. }
  5878. /**
  5879. * Creates the display name paragraph.
  5880. *
  5881. * @param displayName the display name to set
  5882. */
  5883. function createDisplayNameParagraph(key, displayName) {
  5884. var p = document.createElement('p');
  5885. if(displayName)
  5886. p.innerText = displayName;
  5887. else if(key)
  5888. {
  5889. p.setAttribute("data-i18n",key);
  5890. p.innerText = APP.translation.translateString(key);
  5891. }
  5892. return p;
  5893. }
  5894. function stopGlowing(glower) {
  5895. window.clearInterval(notificationInterval);
  5896. notificationInterval = false;
  5897. glower.removeClass('glowing');
  5898. if (!ContactList.isVisible()) {
  5899. glower.removeClass('active');
  5900. }
  5901. }
  5902. /**
  5903. * Contact list.
  5904. */
  5905. var ContactList = {
  5906. /**
  5907. * Indicates if the chat is currently visible.
  5908. *
  5909. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5910. * otherwise
  5911. */
  5912. isVisible: function () {
  5913. return $('#contactlist').is(":visible");
  5914. },
  5915. /**
  5916. * Adds a contact for the given peerJid if such doesn't yet exist.
  5917. *
  5918. * @param peerJid the peerJid corresponding to the contact
  5919. */
  5920. ensureAddContact: function (peerJid) {
  5921. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5922. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5923. if (!contact || contact.length <= 0)
  5924. ContactList.addContact(peerJid);
  5925. },
  5926. /**
  5927. * Adds a contact for the given peer jid.
  5928. *
  5929. * @param peerJid the jid of the contact to add
  5930. */
  5931. addContact: function (peerJid) {
  5932. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5933. var contactlist = $('#contacts');
  5934. var newContact = document.createElement('li');
  5935. newContact.id = resourceJid;
  5936. newContact.className = "clickable";
  5937. newContact.onclick = function (event) {
  5938. if (event.currentTarget.className === "clickable") {
  5939. $(ContactList).trigger('contactclicked', [peerJid]);
  5940. }
  5941. };
  5942. newContact.appendChild(createAvatar(peerJid));
  5943. newContact.appendChild(createDisplayNameParagraph("participant"));
  5944. if (resourceJid === APP.xmpp.myResource()) {
  5945. contactlist.prepend(newContact);
  5946. }
  5947. else {
  5948. contactlist.append(newContact);
  5949. }
  5950. updateNumberOfParticipants(1);
  5951. },
  5952. /**
  5953. * Removes a contact for the given peer jid.
  5954. *
  5955. * @param peerJid the peerJid corresponding to the contact to remove
  5956. */
  5957. removeContact: function (peerJid) {
  5958. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5959. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5960. if (contact && contact.length > 0) {
  5961. var contactlist = $('#contactlist>ul');
  5962. contactlist.get(0).removeChild(contact.get(0));
  5963. updateNumberOfParticipants(-1);
  5964. }
  5965. },
  5966. setVisualNotification: function (show, stopGlowingIn) {
  5967. var glower = $('#contactListButton');
  5968. if (show && !notificationInterval) {
  5969. notificationInterval = window.setInterval(function () {
  5970. glower.toggleClass('active glowing');
  5971. }, 800);
  5972. }
  5973. else if (!show && notificationInterval) {
  5974. stopGlowing(glower);
  5975. }
  5976. if (stopGlowingIn) {
  5977. setTimeout(function () {
  5978. stopGlowing(glower);
  5979. }, stopGlowingIn);
  5980. }
  5981. },
  5982. setClickable: function (resourceJid, isClickable) {
  5983. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5984. if (isClickable) {
  5985. contact.addClass('clickable');
  5986. } else {
  5987. contact.removeClass('clickable');
  5988. }
  5989. },
  5990. onDisplayNameChange: function (peerJid, displayName) {
  5991. if (peerJid === 'localVideoContainer')
  5992. peerJid = APP.xmpp.myJid();
  5993. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5994. var contactName = $('#contacts #' + resourceJid + '>p');
  5995. if (contactName && displayName && displayName.length > 0)
  5996. contactName.html(displayName);
  5997. },
  5998. userAvatarChanged: function (resourceJid, contactListUrl) {
  5999. // set the avatar in the contact list
  6000. var contact = $('#' + resourceJid + '>img');
  6001. if (contact && contact.length > 0) {
  6002. contact.get(0).src = contactListUrl;
  6003. }
  6004. }
  6005. };
  6006. module.exports = ContactList;
  6007. },{"../../avatar/Avatar":18}],28:[function(require,module,exports){
  6008. var Avatar = require("../../avatar/Avatar");
  6009. var Settings = require("./../../../settings/Settings");
  6010. var UIUtil = require("../../util/UIUtil");
  6011. var languages = require("../../../../service/translation/languages");
  6012. function generateLanguagesSelectBox()
  6013. {
  6014. var currentLang = APP.translation.getCurrentLanguage();
  6015. var html = "<select id=\"languages_selectbox\">";
  6016. var langArray = languages.getLanguages();
  6017. for(var i = 0; i < langArray.length; i++)
  6018. {
  6019. var lang = langArray[i];
  6020. html += "<option ";
  6021. if(lang === currentLang)
  6022. html += "selected ";
  6023. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  6024. html += "</option>";
  6025. }
  6026. return html + "</select>";
  6027. }
  6028. var SettingsMenu = {
  6029. init: function () {
  6030. $("#startMutedOptions").before(generateLanguagesSelectBox());
  6031. APP.translation.translateElement($("#languages_selectbox"));
  6032. $('#settingsmenu>input').keyup(function(event){
  6033. if(event.keyCode === 13) {//enter
  6034. SettingsMenu.update();
  6035. }
  6036. });
  6037. if(APP.xmpp.isModerator())
  6038. {
  6039. $("#startMutedOptions").css("display", "block");
  6040. }
  6041. else
  6042. {
  6043. $("#startMutedOptions").css("display", "none");
  6044. }
  6045. $("#updateSettings").click(function () {
  6046. SettingsMenu.update();
  6047. });
  6048. },
  6049. onRoleChanged: function () {
  6050. if(APP.xmpp.isModerator())
  6051. {
  6052. $("#startMutedOptions").css("display", "block");
  6053. }
  6054. else
  6055. {
  6056. $("#startMutedOptions").css("display", "none");
  6057. }
  6058. },
  6059. setStartMuted: function (audio, video) {
  6060. $("#startAudioMuted").attr("checked", audio);
  6061. $("#startVideoMuted").attr("checked", video);
  6062. },
  6063. update: function() {
  6064. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  6065. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  6066. if(newDisplayName) {
  6067. var displayName = Settings.setDisplayName(newDisplayName);
  6068. APP.xmpp.addToPresence("displayName", displayName, true);
  6069. }
  6070. var language = $("#languages_selectbox").val();
  6071. APP.translation.setLanguage(language);
  6072. Settings.setLanguage(language);
  6073. APP.xmpp.addToPresence("email", newEmail);
  6074. var email = Settings.setEmail(newEmail);
  6075. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  6076. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  6077. APP.xmpp.addToPresence("startMuted",
  6078. [startAudioMuted, startVideoMuted]);
  6079. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  6080. },
  6081. isVisible: function() {
  6082. return $('#settingsmenu').is(':visible');
  6083. },
  6084. setDisplayName: function(newDisplayName) {
  6085. var displayName = Settings.setDisplayName(newDisplayName);
  6086. $('#setDisplayName').get(0).value = displayName;
  6087. },
  6088. onDisplayNameChange: function(peerJid, newDisplayName) {
  6089. if(peerJid === 'localVideoContainer' ||
  6090. peerJid === APP.xmpp.myJid()) {
  6091. this.setDisplayName(newDisplayName);
  6092. }
  6093. },
  6094. changeAvatar: function (thumbUrl) {
  6095. $('#avatar').get(0).src = thumbUrl;
  6096. }
  6097. };
  6098. module.exports = SettingsMenu;
  6099. },{"../../../../service/translation/languages":109,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":49}],29:[function(require,module,exports){
  6100. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6101. var buttonHandlers = {
  6102. "bottom_toolbar_contact_list": function () {
  6103. BottomToolbar.toggleContactList();
  6104. },
  6105. "bottom_toolbar_film_strip": function () {
  6106. BottomToolbar.toggleFilmStrip();
  6107. },
  6108. "bottom_toolbar_chat": function () {
  6109. BottomToolbar.toggleChat();
  6110. }
  6111. };
  6112. var BottomToolbar = (function (my) {
  6113. my.init = function () {
  6114. for(var k in buttonHandlers)
  6115. $("#" + k).click(buttonHandlers[k]);
  6116. };
  6117. my.toggleChat = function() {
  6118. PanelToggler.toggleChat();
  6119. };
  6120. my.toggleContactList = function() {
  6121. PanelToggler.toggleContactList();
  6122. };
  6123. my.toggleFilmStrip = function() {
  6124. var filmstrip = $("#remoteVideos");
  6125. filmstrip.toggleClass("hidden");
  6126. };
  6127. $(document).bind("remotevideo.resized", function (event, width, height) {
  6128. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  6129. $('#bottomToolbar').css({bottom: bottom + 'px'});
  6130. });
  6131. return my;
  6132. }(BottomToolbar || {}));
  6133. module.exports = BottomToolbar;
  6134. },{"../side_pannels/SidePanelToggler":22}],30:[function(require,module,exports){
  6135. /* global APP,$, buttonClick, config, lockRoom,
  6136. setSharedKey, Util */
  6137. var messageHandler = require("../util/MessageHandler");
  6138. var BottomToolbar = require("./BottomToolbar");
  6139. var Prezi = require("../prezi/Prezi");
  6140. var Etherpad = require("../etherpad/Etherpad");
  6141. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6142. var Authentication = require("../authentication/Authentication");
  6143. var UIUtil = require("../util/UIUtil");
  6144. var AuthenticationEvents
  6145. = require("../../../service/authentication/AuthenticationEvents");
  6146. var roomUrl = null;
  6147. var sharedKey = '';
  6148. var UI = null;
  6149. var buttonHandlers =
  6150. {
  6151. "toolbar_button_mute": function () {
  6152. return APP.UI.toggleAudio();
  6153. },
  6154. "toolbar_button_camera": function () {
  6155. return APP.UI.toggleVideo();
  6156. },
  6157. /*"toolbar_button_authentication": function () {
  6158. return Toolbar.authenticateClicked();
  6159. },*/
  6160. "toolbar_button_record": function () {
  6161. return toggleRecording();
  6162. },
  6163. "toolbar_button_security": function () {
  6164. return Toolbar.openLockDialog();
  6165. },
  6166. "toolbar_button_link": function () {
  6167. return Toolbar.openLinkDialog();
  6168. },
  6169. "toolbar_button_chat": function () {
  6170. return BottomToolbar.toggleChat();
  6171. },
  6172. "toolbar_button_prezi": function () {
  6173. return Prezi.openPreziDialog();
  6174. },
  6175. "toolbar_button_etherpad": function () {
  6176. return Etherpad.toggleEtherpad(0);
  6177. },
  6178. "toolbar_button_desktopsharing": function () {
  6179. return APP.desktopsharing.toggleScreenSharing();
  6180. },
  6181. "toolbar_button_fullScreen": function()
  6182. {
  6183. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  6184. return Toolbar.toggleFullScreen();
  6185. },
  6186. "toolbar_button_sip": function () {
  6187. return callSipButtonClicked();
  6188. },
  6189. "toolbar_button_dialpad": function () {
  6190. return dialpadButtonClicked();
  6191. },
  6192. "toolbar_button_settings": function () {
  6193. PanelToggler.toggleSettingsMenu();
  6194. },
  6195. "toolbar_button_hangup": function () {
  6196. return hangup();
  6197. },
  6198. "toolbar_button_login": function () {
  6199. Toolbar.authenticateClicked();
  6200. },
  6201. "toolbar_button_logout": function () {
  6202. // Ask for confirmation
  6203. messageHandler.openTwoButtonDialog(
  6204. "dialog.logoutTitle",
  6205. null,
  6206. "dialog.logoutQuestion",
  6207. null,
  6208. false,
  6209. "dialog.Yes",
  6210. function (evt, yes) {
  6211. if (yes) {
  6212. APP.xmpp.logout(function (url) {
  6213. if (url) {
  6214. window.location.href = url;
  6215. } else {
  6216. hangup();
  6217. }
  6218. });
  6219. }
  6220. });
  6221. }
  6222. };
  6223. function hangup() {
  6224. APP.xmpp.disposeConference();
  6225. if(config.enableWelcomePage)
  6226. {
  6227. setTimeout(function()
  6228. {
  6229. window.localStorage.welcomePageDisabled = false;
  6230. window.location.pathname = "/";
  6231. }, 10000);
  6232. }
  6233. var title = APP.translation.generateTranslationHTML(
  6234. "dialog.sessTerminated");
  6235. var msg = APP.translation.generateTranslationHTML(
  6236. "dialog.hungUp");
  6237. var button = APP.translation.generateTranslationHTML(
  6238. "dialog.joinAgain");
  6239. var buttons = [];
  6240. buttons.push({title: button, value: true});
  6241. UI.messageHandler.openDialog(
  6242. title,
  6243. msg,
  6244. true,
  6245. buttons,
  6246. function(event, value, message, formVals)
  6247. {
  6248. window.location.reload();
  6249. return false;
  6250. }
  6251. );
  6252. }
  6253. /**
  6254. * Starts or stops the recording for the conference.
  6255. */
  6256. function toggleRecording() {
  6257. APP.xmpp.toggleRecording(function (callback) {
  6258. var msg = APP.translation.generateTranslationHTML(
  6259. "dialog.recordingToken");
  6260. var token = APP.translation.translateString("dialog.token");
  6261. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  6262. '<h2>' + msg + '</h2>' +
  6263. '<input name="recordingToken" type="text" ' +
  6264. ' data-i18n="[placeholder]dialog.token" ' +
  6265. 'placeholder="' + token + '" autofocus>',
  6266. false,
  6267. "dialog.Save",
  6268. function (e, v, m, f) {
  6269. if (v) {
  6270. var token = f.recordingToken;
  6271. if (token) {
  6272. callback(UIUtil.escapeHtml(token));
  6273. }
  6274. }
  6275. },
  6276. null,
  6277. function () { },
  6278. ':input:first'
  6279. );
  6280. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  6281. }
  6282. /**
  6283. * Locks / unlocks the room.
  6284. */
  6285. function lockRoom(lock) {
  6286. var currentSharedKey = '';
  6287. if (lock)
  6288. currentSharedKey = sharedKey;
  6289. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6290. // password is required
  6291. if (sharedKey)
  6292. {
  6293. console.log('set room password');
  6294. Toolbar.lockLockButton();
  6295. }
  6296. else
  6297. {
  6298. console.log('removed room password');
  6299. Toolbar.unlockLockButton();
  6300. }
  6301. }, function (err) {
  6302. console.warn('setting password failed', err);
  6303. messageHandler.showError("dialog.lockTitle",
  6304. "dialog.lockMessage");
  6305. Toolbar.setSharedKey('');
  6306. }, function () {
  6307. console.warn('room passwords not supported');
  6308. messageHandler.showError("dialog.warning",
  6309. "dialog.passwordNotSupported");
  6310. Toolbar.setSharedKey('');
  6311. });
  6312. };
  6313. /**
  6314. * Invite participants to conference.
  6315. */
  6316. function inviteParticipants() {
  6317. if (roomUrl === null)
  6318. return;
  6319. var sharedKeyText = "";
  6320. if (sharedKey && sharedKey.length > 0) {
  6321. sharedKeyText =
  6322. APP.translation.translateString("email.sharedKey",
  6323. {sharedKey: sharedKey});
  6324. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6325. }
  6326. var supportedBrowsers = "Chromium, Google Chrome " +
  6327. APP.translation.translateString("email.and") + " Opera";
  6328. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6329. var subject = APP.translation.translateString("email.subject",
  6330. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6331. var body = APP.translation.translateString("email.body",
  6332. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6333. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6334. body = body.replace(/\n/g, "%0D%0A");
  6335. if (window.localStorage.displayname) {
  6336. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6337. }
  6338. if (interfaceConfig.INVITATION_POWERED_BY) {
  6339. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6340. }
  6341. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6342. }
  6343. function dialpadButtonClicked()
  6344. {
  6345. //TODO show the dialpad window
  6346. }
  6347. function callSipButtonClicked()
  6348. {
  6349. var defaultNumber
  6350. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6351. var sipMsg = APP.translation.generateTranslationHTML(
  6352. "dialog.sipMsg");
  6353. messageHandler.openTwoButtonDialog(null, null, null,
  6354. '<h2>' + sipMsg + '</h2>' +
  6355. '<input name="sipNumber" type="text"' +
  6356. ' value="' + defaultNumber + '" autofocus>',
  6357. false,
  6358. "dialog.Dial",
  6359. function (e, v, m, f) {
  6360. if (v) {
  6361. var numberInput = f.sipNumber;
  6362. if (numberInput) {
  6363. APP.xmpp.dial(
  6364. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6365. }
  6366. }
  6367. },
  6368. null, null, ':input:first'
  6369. );
  6370. }
  6371. var Toolbar = (function (my) {
  6372. my.init = function (ui) {
  6373. for(var k in buttonHandlers)
  6374. $("#" + k).click(buttonHandlers[k]);
  6375. UI = ui;
  6376. // Update login info
  6377. APP.xmpp.addListener(
  6378. AuthenticationEvents.IDENTITY_UPDATED,
  6379. function (authenticationEnabled, userIdentity) {
  6380. var loggedIn = false;
  6381. if (userIdentity) {
  6382. loggedIn = true;
  6383. }
  6384. Toolbar.showAuthenticateButton(authenticationEnabled);
  6385. if (authenticationEnabled) {
  6386. Toolbar.setAuthenticatedIdentity(userIdentity);
  6387. Toolbar.showLoginButton(!loggedIn);
  6388. Toolbar.showLogoutButton(loggedIn);
  6389. }
  6390. }
  6391. );
  6392. },
  6393. /**
  6394. * Sets shared key
  6395. * @param sKey the shared key
  6396. */
  6397. my.setSharedKey = function (sKey) {
  6398. sharedKey = sKey;
  6399. };
  6400. my.authenticateClicked = function () {
  6401. Authentication.focusAuthenticationWindow();
  6402. if (!APP.xmpp.isExternalAuthEnabled()) {
  6403. Authentication.xmppAuthenticate();
  6404. return;
  6405. }
  6406. // Get authentication URL
  6407. if (!APP.xmpp.getMUCJoined()) {
  6408. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6409. // If conference has not been started yet - redirect to login page
  6410. window.location.href = url;
  6411. });
  6412. } else {
  6413. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6414. // Otherwise - open popup with authentication URL
  6415. var authenticationWindow = Authentication.createAuthenticationWindow(
  6416. function () {
  6417. // On popup closed - retry room allocation
  6418. APP.xmpp.allocateConferenceFocus(
  6419. APP.UI.getRoomName(),
  6420. function () { console.info("AUTH DONE"); }
  6421. );
  6422. }, url);
  6423. if (!authenticationWindow) {
  6424. messageHandler.openMessageDialog(
  6425. null, "dialog.popupError");
  6426. }
  6427. });
  6428. }
  6429. };
  6430. /**
  6431. * Updates the room invite url.
  6432. */
  6433. my.updateRoomUrl = function (newRoomUrl) {
  6434. roomUrl = newRoomUrl;
  6435. // If the invite dialog has been already opened we update the information.
  6436. var inviteLink = document.getElementById('inviteLinkRef');
  6437. if (inviteLink) {
  6438. inviteLink.value = roomUrl;
  6439. inviteLink.select();
  6440. $('#inviteLinkRef').parent()
  6441. .find('button[value=true]').prop('disabled', false);
  6442. }
  6443. };
  6444. /**
  6445. * Disables and enables some of the buttons.
  6446. */
  6447. my.setupButtonsFromConfig = function () {
  6448. if (config.disablePrezi)
  6449. {
  6450. $("#prezi_button").css({display: "none"});
  6451. }
  6452. };
  6453. /**
  6454. * Opens the lock room dialog.
  6455. */
  6456. my.openLockDialog = function () {
  6457. // Only the focus is able to set a shared key.
  6458. if (!APP.xmpp.isModerator()) {
  6459. if (sharedKey) {
  6460. messageHandler.openMessageDialog(null,
  6461. "dialog.passwordError");
  6462. } else {
  6463. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6464. }
  6465. } else {
  6466. if (sharedKey) {
  6467. messageHandler.openTwoButtonDialog(null, null,
  6468. "dialog.passwordCheck",
  6469. null,
  6470. false,
  6471. "dialog.Remove",
  6472. function (e, v) {
  6473. if (v) {
  6474. Toolbar.setSharedKey('');
  6475. lockRoom(false);
  6476. }
  6477. });
  6478. } else {
  6479. var msg = APP.translation.generateTranslationHTML(
  6480. "dialog.passwordMsg");
  6481. var yourPassword = APP.translation.translateString(
  6482. "dialog.yourPassword");
  6483. messageHandler.openTwoButtonDialog(null, null, null,
  6484. '<h2>' + msg + '</h2>' +
  6485. '<input name="lockKey" type="text"' +
  6486. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6487. 'placeholder="' + yourPassword + '" autofocus>',
  6488. false,
  6489. "dialog.Save",
  6490. function (e, v, m, f) {
  6491. if (v) {
  6492. var lockKey = f.lockKey;
  6493. if (lockKey) {
  6494. Toolbar.setSharedKey(
  6495. UIUtil.escapeHtml(lockKey));
  6496. lockRoom(true);
  6497. }
  6498. }
  6499. },
  6500. null, null, 'input:first'
  6501. );
  6502. }
  6503. }
  6504. };
  6505. /**
  6506. * Opens the invite link dialog.
  6507. */
  6508. my.openLinkDialog = function () {
  6509. var inviteAttreibutes;
  6510. if (roomUrl === null) {
  6511. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6512. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6513. } else {
  6514. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6515. }
  6516. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6517. null, null,
  6518. '<input id="inviteLinkRef" type="text" ' +
  6519. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6520. false,
  6521. "dialog.Invite",
  6522. function (e, v) {
  6523. if (v) {
  6524. if (roomUrl) {
  6525. inviteParticipants();
  6526. }
  6527. }
  6528. },
  6529. function (event) {
  6530. if (roomUrl) {
  6531. document.getElementById('inviteLinkRef').select();
  6532. } else {
  6533. if (event && event.target)
  6534. $(event.target)
  6535. .find('button[value=true]').prop('disabled', true);
  6536. }
  6537. }
  6538. );
  6539. };
  6540. /**
  6541. * Opens the settings dialog.
  6542. * FIXME: not used ?
  6543. */
  6544. my.openSettingsDialog = function () {
  6545. var settings1 = APP.translation.generateTranslationHTML(
  6546. "dialog.settings1");
  6547. var settings2 = APP.translation.generateTranslationHTML(
  6548. "dialog.settings2");
  6549. var settings3 = APP.translation.generateTranslationHTML(
  6550. "dialog.settings3");
  6551. var yourPassword = APP.translation.translateString(
  6552. "dialog.yourPassword");
  6553. messageHandler.openTwoButtonDialog(null,
  6554. '<h2>' + settings1 + '</h2>' +
  6555. '<input type="checkbox" id="initMuted">' +
  6556. settings2 + '<br/>' +
  6557. '<input type="checkbox" id="requireNicknames">' +
  6558. settings3 +
  6559. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6560. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6561. null,
  6562. null,
  6563. false,
  6564. "dialog.Save",
  6565. function () {
  6566. document.getElementById('lockKey').focus();
  6567. },
  6568. function (e, v) {
  6569. if (v) {
  6570. if ($('#initMuted').is(":checked")) {
  6571. // it is checked
  6572. }
  6573. if ($('#requireNicknames').is(":checked")) {
  6574. // it is checked
  6575. }
  6576. /*
  6577. var lockKey = document.getElementById('lockKey');
  6578. if (lockKey.value) {
  6579. setSharedKey(lockKey.value);
  6580. lockRoom(true);
  6581. }
  6582. */
  6583. }
  6584. }
  6585. );
  6586. };
  6587. /**
  6588. * Toggles the application in and out of full screen mode
  6589. * (a.k.a. presentation mode in Chrome).
  6590. */
  6591. my.toggleFullScreen = function () {
  6592. var fsElement = document.documentElement;
  6593. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6594. //Enter Full Screen
  6595. if (fsElement.mozRequestFullScreen) {
  6596. fsElement.mozRequestFullScreen();
  6597. }
  6598. else {
  6599. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6600. }
  6601. } else {
  6602. //Exit Full Screen
  6603. if (document.mozCancelFullScreen) {
  6604. document.mozCancelFullScreen();
  6605. } else {
  6606. document.webkitCancelFullScreen();
  6607. }
  6608. }
  6609. };
  6610. /**
  6611. * Unlocks the lock button state.
  6612. */
  6613. my.unlockLockButton = function () {
  6614. if ($("#lockIcon").hasClass("icon-security-locked"))
  6615. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6616. };
  6617. /**
  6618. * Updates the lock button state to locked.
  6619. */
  6620. my.lockLockButton = function () {
  6621. if ($("#lockIcon").hasClass("icon-security"))
  6622. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6623. };
  6624. /**
  6625. * Shows or hides authentication button
  6626. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6627. */
  6628. my.showAuthenticateButton = function (show) {
  6629. if (show) {
  6630. $('#authentication').css({display: "inline"});
  6631. }
  6632. else {
  6633. $('#authentication').css({display: "none"});
  6634. }
  6635. };
  6636. // Shows or hides the 'recording' button.
  6637. my.showRecordingButton = function (show) {
  6638. if (!config.enableRecording) {
  6639. return;
  6640. }
  6641. if (show) {
  6642. $('#recording').css({display: "inline"});
  6643. }
  6644. else {
  6645. $('#recording').css({display: "none"});
  6646. }
  6647. };
  6648. // Sets the state of the recording button
  6649. my.setRecordingButtonState = function (isRecording) {
  6650. var selector = $('#recordButton');
  6651. if (isRecording) {
  6652. selector.removeClass("icon-recEnable");
  6653. selector.addClass("icon-recEnable active");
  6654. } else {
  6655. selector.removeClass("icon-recEnable active");
  6656. selector.addClass("icon-recEnable");
  6657. }
  6658. };
  6659. // Shows or hides SIP calls button
  6660. my.showSipCallButton = function (show) {
  6661. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6662. $('#sipCallButton').css({display: "inline-block"});
  6663. } else {
  6664. $('#sipCallButton').css({display: "none"});
  6665. }
  6666. };
  6667. // Shows or hides the dialpad button
  6668. my.showDialPadButton = function (show) {
  6669. if (show) {
  6670. $('#dialPadButton').css({display: "inline-block"});
  6671. } else {
  6672. $('#dialPadButton').css({display: "none"});
  6673. }
  6674. };
  6675. /**
  6676. * Displays user authenticated identity name(login).
  6677. * @param authIdentity identity name to be displayed.
  6678. */
  6679. my.setAuthenticatedIdentity = function (authIdentity) {
  6680. if (authIdentity) {
  6681. var selector = $('#toolbar_auth_identity');
  6682. selector.css({display: "list-item"});
  6683. selector.text(authIdentity);
  6684. } else {
  6685. $('#toolbar_auth_identity').css({display: "none"});
  6686. }
  6687. };
  6688. /**
  6689. * Shows/hides login button.
  6690. * @param show <tt>true</tt> to show
  6691. */
  6692. my.showLoginButton = function (show) {
  6693. if (show) {
  6694. $('#toolbar_button_login').css({display: "list-item"});
  6695. } else {
  6696. $('#toolbar_button_login').css({display: "none"});
  6697. }
  6698. };
  6699. /**
  6700. * Shows/hides logout button.
  6701. * @param show <tt>true</tt> to show
  6702. */
  6703. my.showLogoutButton = function (show) {
  6704. if (show) {
  6705. $('#toolbar_button_logout').css({display: "list-item"});
  6706. } else {
  6707. $('#toolbar_button_logout').css({display: "none"});
  6708. }
  6709. };
  6710. /**
  6711. * Sets the state of the button. The button has blue glow if desktop
  6712. * streaming is active.
  6713. * @param active the state of the desktop streaming.
  6714. */
  6715. my.changeDesktopSharingButtonState = function (active) {
  6716. var button = $("#desktopsharing > a");
  6717. if (active)
  6718. {
  6719. button.addClass("glow");
  6720. }
  6721. else
  6722. {
  6723. button.removeClass("glow");
  6724. }
  6725. };
  6726. return my;
  6727. }(Toolbar || {}));
  6728. module.exports = Toolbar;
  6729. },{"../../../service/authentication/AuthenticationEvents":105,"../authentication/Authentication":16,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../side_pannels/SidePanelToggler":22,"../util/MessageHandler":33,"../util/UIUtil":35,"./BottomToolbar":29}],31:[function(require,module,exports){
  6730. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  6731. var toolbarTimeoutObject,
  6732. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6733. function showDesktopSharingButton() {
  6734. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6735. $('#desktopsharing').css({display: "inline"});
  6736. } else {
  6737. $('#desktopsharing').css({display: "none"});
  6738. }
  6739. }
  6740. /**
  6741. * Hides the toolbar.
  6742. */
  6743. function hideToolbar() {
  6744. if(config.alwaysVisibleToolbar)
  6745. return;
  6746. var header = $("#header"),
  6747. bottomToolbar = $("#bottomToolbar");
  6748. var isToolbarHover = false;
  6749. header.find('*').each(function () {
  6750. var id = $(this).attr('id');
  6751. if ($("#" + id + ":hover").length > 0) {
  6752. isToolbarHover = true;
  6753. }
  6754. });
  6755. if ($("#bottomToolbar:hover").length > 0) {
  6756. isToolbarHover = true;
  6757. }
  6758. clearTimeout(toolbarTimeoutObject);
  6759. toolbarTimeoutObject = null;
  6760. if (!isToolbarHover) {
  6761. header.hide("slide", { direction: "up", duration: 300});
  6762. $('#subject').animate({top: "-=40"}, 300);
  6763. if ($("#remoteVideos").hasClass("hidden")) {
  6764. bottomToolbar.hide(
  6765. "slide", {direction: "right", duration: 300});
  6766. }
  6767. }
  6768. else {
  6769. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6770. }
  6771. }
  6772. var ToolbarToggler = {
  6773. /**
  6774. * Shows the main toolbar.
  6775. */
  6776. showToolbar: function () {
  6777. var header = $("#header"),
  6778. bottomToolbar = $("#bottomToolbar");
  6779. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6780. header.show("slide", { direction: "up", duration: 300});
  6781. $('#subject').animate({top: "+=40"}, 300);
  6782. if (!bottomToolbar.is(":visible")) {
  6783. bottomToolbar.show(
  6784. "slide", {direction: "right", duration: 300});
  6785. }
  6786. if (toolbarTimeoutObject) {
  6787. clearTimeout(toolbarTimeoutObject);
  6788. toolbarTimeoutObject = null;
  6789. }
  6790. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6791. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6792. }
  6793. if (APP.xmpp.isModerator())
  6794. {
  6795. // TODO: Enable settings functionality.
  6796. // Need to uncomment the settings button in index.html.
  6797. // $('#settingsButton').css({visibility:"visible"});
  6798. }
  6799. // Show/hide desktop sharing button
  6800. showDesktopSharingButton();
  6801. },
  6802. /**
  6803. * Docks/undocks the toolbar.
  6804. *
  6805. * @param isDock indicates what operation to perform
  6806. */
  6807. dockToolbar: function (isDock) {
  6808. if (isDock) {
  6809. // First make sure the toolbar is shown.
  6810. if (!$('#header').is(':visible')) {
  6811. this.showToolbar();
  6812. }
  6813. // Then clear the time out, to dock the toolbar.
  6814. if (toolbarTimeoutObject) {
  6815. clearTimeout(toolbarTimeoutObject);
  6816. toolbarTimeoutObject = null;
  6817. }
  6818. }
  6819. else {
  6820. if (!$('#header').is(':visible')) {
  6821. this.showToolbar();
  6822. }
  6823. else {
  6824. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6825. }
  6826. }
  6827. },
  6828. showDesktopSharingButton: showDesktopSharingButton
  6829. };
  6830. module.exports = ToolbarToggler;
  6831. },{}],32:[function(require,module,exports){
  6832. var JitsiPopover = (function () {
  6833. /**
  6834. * Constructs new JitsiPopover and attaches it to the element
  6835. * @param element jquery selector
  6836. * @param options the options for the popover.
  6837. * @constructor
  6838. */
  6839. function JitsiPopover(element, options)
  6840. {
  6841. this.options = {
  6842. skin: "white",
  6843. content: ""
  6844. };
  6845. if(options)
  6846. {
  6847. if(options.skin)
  6848. this.options.skin = options.skin;
  6849. if(options.content)
  6850. this.options.content = options.content;
  6851. }
  6852. this.elementIsHovered = false;
  6853. this.popoverIsHovered = false;
  6854. this.popoverShown = false;
  6855. element.data("jitsi_popover", this);
  6856. this.element = element;
  6857. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6858. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6859. '<div class="jitsiPopupmenuPadding"></div></div>';
  6860. var self = this;
  6861. this.element.on("mouseenter", function () {
  6862. self.elementIsHovered = true;
  6863. self.show();
  6864. }).on("mouseleave", function () {
  6865. self.elementIsHovered = false;
  6866. setTimeout(function () {
  6867. self.hide();
  6868. }, 10);
  6869. });
  6870. }
  6871. /**
  6872. * Shows the popover
  6873. */
  6874. JitsiPopover.prototype.show = function () {
  6875. this.createPopover();
  6876. this.popoverShown = true;
  6877. };
  6878. /**
  6879. * Hides the popover
  6880. */
  6881. JitsiPopover.prototype.hide = function () {
  6882. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  6883. {
  6884. this.forceHide();
  6885. }
  6886. };
  6887. /**
  6888. * Hides the popover
  6889. */
  6890. JitsiPopover.prototype.forceHide = function () {
  6891. $(".jitsipopover").remove();
  6892. this.popoverShown = false;
  6893. };
  6894. /**
  6895. * Creates the popover html
  6896. */
  6897. JitsiPopover.prototype.createPopover = function () {
  6898. $("body").append(this.template);
  6899. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6900. var self = this;
  6901. $(".jitsipopover").on("mouseenter", function () {
  6902. self.popoverIsHovered = true;
  6903. }).on("mouseleave", function () {
  6904. self.popoverIsHovered = false;
  6905. self.hide();
  6906. });
  6907. this.refreshPosition();
  6908. };
  6909. /**
  6910. * Refreshes the position of the popover
  6911. */
  6912. JitsiPopover.prototype.refreshPosition = function () {
  6913. $(".jitsipopover").position({
  6914. my: "bottom",
  6915. at: "top",
  6916. collision: "fit",
  6917. of: this.element,
  6918. using: function (position, elements) {
  6919. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  6920. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  6921. $(".jitsipopover > .arrow").css({left: calcLeft});
  6922. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  6923. }
  6924. });
  6925. };
  6926. /**
  6927. * Updates the content of popover.
  6928. * @param content new content
  6929. */
  6930. JitsiPopover.prototype.updateContent = function (content) {
  6931. this.options.content = content;
  6932. if(!this.popoverShown)
  6933. return;
  6934. $(".jitsipopover").remove();
  6935. this.createPopover();
  6936. };
  6937. return JitsiPopover;
  6938. })();
  6939. module.exports = JitsiPopover;
  6940. },{}],33:[function(require,module,exports){
  6941. /* global $, APP, jQuery, toastr */
  6942. var messageHandler = (function(my) {
  6943. /**
  6944. * Shows a message to the user.
  6945. *
  6946. * @param titleString the title of the message
  6947. * @param messageString the text of the message
  6948. */
  6949. my.openMessageDialog = function(titleKey, messageKey) {
  6950. var title = null;
  6951. if(titleKey)
  6952. {
  6953. title = APP.translation.generateTranslationHTML(titleKey);
  6954. }
  6955. var message = APP.translation.generateTranslationHTML(messageKey);
  6956. $.prompt(message,
  6957. {
  6958. title: title,
  6959. persistent: false
  6960. }
  6961. );
  6962. };
  6963. /**
  6964. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6965. *
  6966. * @param titleString the title of the message
  6967. * @param msgString the text of the message
  6968. * @param persistent boolean value which determines whether the message is persistent or not
  6969. * @param leftButton the fist button's text
  6970. * @param submitFunction function to be called on submit
  6971. * @param loadedFunction function to be called after the prompt is fully loaded
  6972. * @param closeFunction function to be called after the prompt is closed
  6973. * @param focus optional focus selector or button index to be focused after
  6974. * the dialog is opened
  6975. * @param defaultButton index of default button which will be activated when
  6976. * the user press 'enter'. Indexed from 0.
  6977. */
  6978. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6979. persistent, leftButtonKey, submitFunction, loadedFunction,
  6980. closeFunction, focus, defaultButton)
  6981. {
  6982. var buttons = [];
  6983. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6984. buttons.push({ title: leftButton, value: true});
  6985. var cancelButton
  6986. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6987. buttons.push({title: cancelButton, value: false});
  6988. var message = msgString, title = titleString;
  6989. if (titleKey)
  6990. {
  6991. title = APP.translation.generateTranslationHTML(titleKey);
  6992. }
  6993. if (msgKey) {
  6994. message = APP.translation.generateTranslationHTML(msgKey);
  6995. }
  6996. $.prompt(message, {
  6997. title: title,
  6998. persistent: false,
  6999. buttons: buttons,
  7000. defaultButton: defaultButton,
  7001. focus: focus,
  7002. loaded: loadedFunction,
  7003. submit: submitFunction,
  7004. close: closeFunction
  7005. });
  7006. };
  7007. /**
  7008. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  7009. *
  7010. * @param titleString the title of the message
  7011. * @param msgString the text of the message
  7012. * @param persistent boolean value which determines whether the message is persistent or not
  7013. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  7014. * that will be passed to submitFunction
  7015. * @param submitFunction function to be called on submit
  7016. * @param loadedFunction function to be called after the prompt is fully loaded
  7017. */
  7018. my.openDialog = function (titleString, msgString, persistent, buttons,
  7019. submitFunction, loadedFunction) {
  7020. var args = {
  7021. title: titleString,
  7022. persistent: persistent,
  7023. buttons: buttons,
  7024. defaultButton: 1,
  7025. loaded: loadedFunction,
  7026. submit: submitFunction
  7027. };
  7028. if (persistent) {
  7029. args.closeText = '';
  7030. }
  7031. return new Impromptu(msgString, args);
  7032. };
  7033. /**
  7034. * Closes currently opened dialog.
  7035. */
  7036. my.closeDialog = function () {
  7037. $.prompt.close();
  7038. };
  7039. /**
  7040. * Shows a dialog with different states to the user.
  7041. *
  7042. * @param statesObject object containing all the states of the dialog
  7043. */
  7044. my.openDialogWithStates = function (statesObject, options) {
  7045. return new Impromptu(statesObject, options);
  7046. };
  7047. /**
  7048. * Opens new popup window for given <tt>url</tt> centered over current
  7049. * window.
  7050. *
  7051. * @param url the URL to be displayed in the popup window
  7052. * @param w the width of the popup window
  7053. * @param h the height of the popup window
  7054. * @param onPopupClosed optional callback function called when popup window
  7055. * has been closed.
  7056. *
  7057. * @returns popup window object if opened successfully or undefined
  7058. * in case we failed to open it(popup blocked)
  7059. */
  7060. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  7061. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  7062. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  7063. var popup = window.open(
  7064. url, '_blank',
  7065. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  7066. if (popup && onPopupClosed) {
  7067. var pollTimer = window.setInterval(function () {
  7068. if (popup.closed !== false) {
  7069. window.clearInterval(pollTimer);
  7070. onPopupClosed();
  7071. }
  7072. }, 200);
  7073. }
  7074. return popup;
  7075. };
  7076. /**
  7077. * Shows a dialog prompting the user to send an error report.
  7078. *
  7079. * @param titleString the title of the message
  7080. * @param msgString the text of the message
  7081. * @param error the error that is being reported
  7082. */
  7083. my.openReportDialog = function(titleKey, msgKey, error) {
  7084. my.openMessageDialog(titleKey, msgKey);
  7085. console.log(error);
  7086. //FIXME send the error to the server
  7087. };
  7088. /**
  7089. * Shows an error dialog to the user.
  7090. * @param title the title of the message
  7091. * @param message the text of the messafe
  7092. */
  7093. my.showError = function(titleKey, msgKey) {
  7094. if(!titleKey) {
  7095. titleKey = "dialog.oops";
  7096. }
  7097. if(!msgKey)
  7098. {
  7099. msgKey = "dialog.defaultError";
  7100. }
  7101. messageHandler.openMessageDialog(titleKey, msgKey);
  7102. };
  7103. my.notify = function(displayName, displayNameKey,
  7104. cls, messageKey, messageArguments, options) {
  7105. var displayNameSpan = '<span class="nickname" ';
  7106. if(displayName)
  7107. {
  7108. displayNameSpan += ">" + displayName;
  7109. }
  7110. else
  7111. {
  7112. displayNameSpan += "data-i18n='" + displayNameKey +
  7113. "'>" + APP.translation.translateString(displayNameKey);
  7114. }
  7115. displayNameSpan += "</span>";
  7116. toastr.info(
  7117. displayNameSpan + '<br>' +
  7118. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  7119. (messageArguments?
  7120. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  7121. : "") + ">" +
  7122. APP.translation.translateString(messageKey,
  7123. messageArguments) +
  7124. '</span>', null, options);
  7125. };
  7126. return my;
  7127. }(messageHandler || {}));
  7128. module.exports = messageHandler;
  7129. },{}],34:[function(require,module,exports){
  7130. var UIEvents = require("../../../service/UI/UIEvents");
  7131. var nickname = null;
  7132. var eventEmitter = null;
  7133. var NickanameHandler = {
  7134. init: function (emitter) {
  7135. eventEmitter = emitter;
  7136. var storedDisplayName = window.localStorage.displayname;
  7137. if (storedDisplayName) {
  7138. nickname = storedDisplayName;
  7139. }
  7140. },
  7141. setNickname: function (newNickname) {
  7142. if (!newNickname || nickname === newNickname)
  7143. return;
  7144. nickname = newNickname;
  7145. window.localStorage.displayname = nickname;
  7146. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  7147. },
  7148. getNickname: function () {
  7149. return nickname;
  7150. },
  7151. addListener: function (type, listener) {
  7152. eventEmitter.on(type, listener);
  7153. }
  7154. };
  7155. module.exports = NickanameHandler;
  7156. },{"../../../service/UI/UIEvents":104}],35:[function(require,module,exports){
  7157. /**
  7158. * Created by hristo on 12/22/14.
  7159. */
  7160. module.exports = {
  7161. /**
  7162. * Returns the available video width.
  7163. */
  7164. getAvailableVideoWidth: function (isVisible) {
  7165. var PanelToggler = require("../side_pannels/SidePanelToggler");
  7166. if(typeof isVisible === "undefined" || isVisible === null)
  7167. isVisible = PanelToggler.isVisible();
  7168. var rightPanelWidth
  7169. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  7170. return window.innerWidth - rightPanelWidth;
  7171. },
  7172. /**
  7173. * Changes the style class of the element given by id.
  7174. */
  7175. buttonClick: function(id, classname) {
  7176. $(id).toggleClass(classname); // add the class to the clicked element
  7177. },
  7178. /**
  7179. * Returns the text width for the given element.
  7180. *
  7181. * @param el the element
  7182. */
  7183. getTextWidth: function (el) {
  7184. return (el.clientWidth + 1);
  7185. },
  7186. /**
  7187. * Returns the text height for the given element.
  7188. *
  7189. * @param el the element
  7190. */
  7191. getTextHeight: function (el) {
  7192. return (el.clientHeight + 1);
  7193. },
  7194. /**
  7195. * Plays the sound given by id.
  7196. *
  7197. * @param id the identifier of the audio element.
  7198. */
  7199. playSoundNotification: function (id) {
  7200. document.getElementById(id).play();
  7201. },
  7202. /**
  7203. * Escapes the given text.
  7204. */
  7205. escapeHtml: function (unsafeText) {
  7206. return $('<div/>').text(unsafeText).html();
  7207. },
  7208. imageToGrayScale: function (canvas) {
  7209. var context = canvas.getContext('2d');
  7210. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  7211. var pixels = imgData.data;
  7212. for (var i = 0, n = pixels.length; i < n; i += 4) {
  7213. var grayscale
  7214. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  7215. pixels[i ] = grayscale; // red
  7216. pixels[i+1] = grayscale; // green
  7217. pixels[i+2] = grayscale; // blue
  7218. // pixels[i+3] is alpha
  7219. }
  7220. // redraw the image in black & white
  7221. context.putImageData(imgData, 0, 0);
  7222. },
  7223. setTooltip: function (element, key, position) {
  7224. element.setAttribute("data-i18n", "[data-content]" + key);
  7225. element.setAttribute("data-toggle", "popover");
  7226. element.setAttribute("data-placement", position);
  7227. element.setAttribute("data-html", true);
  7228. element.setAttribute("data-container", "body");
  7229. }
  7230. };
  7231. },{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){
  7232. var JitsiPopover = require("../util/JitsiPopover");
  7233. /**
  7234. * Constructs new connection indicator.
  7235. * @param videoContainer the video container associated with the indicator.
  7236. * @constructor
  7237. */
  7238. function ConnectionIndicator(videoContainer, jid)
  7239. {
  7240. this.videoContainer = videoContainer;
  7241. this.bandwidth = null;
  7242. this.packetLoss = null;
  7243. this.bitrate = null;
  7244. this.showMoreValue = false;
  7245. this.resolution = null;
  7246. this.transport = [];
  7247. this.popover = null;
  7248. this.jid = jid;
  7249. this.create();
  7250. }
  7251. /**
  7252. * Values for the connection quality
  7253. * @type {{98: string,
  7254. * 81: string,
  7255. * 64: string,
  7256. * 47: string,
  7257. * 30: string,
  7258. * 0: string}}
  7259. */
  7260. ConnectionIndicator.connectionQualityValues = {
  7261. 98: "18px", //full
  7262. 81: "15px",//4 bars
  7263. 64: "11px",//3 bars
  7264. 47: "7px",//2 bars
  7265. 30: "3px",//1 bar
  7266. 0: "0px"//empty
  7267. };
  7268. ConnectionIndicator.getIP = function(value)
  7269. {
  7270. return value.substring(0, value.lastIndexOf(":"));
  7271. };
  7272. ConnectionIndicator.getPort = function(value)
  7273. {
  7274. return value.substring(value.lastIndexOf(":") + 1, value.length);
  7275. };
  7276. ConnectionIndicator.getStringFromArray = function (array) {
  7277. var res = "";
  7278. for(var i = 0; i < array.length; i++)
  7279. {
  7280. res += (i === 0? "" : ", ") + array[i];
  7281. }
  7282. return res;
  7283. };
  7284. /**
  7285. * Generates the html content.
  7286. * @returns {string} the html content.
  7287. */
  7288. ConnectionIndicator.prototype.generateText = function () {
  7289. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7290. var translate = APP.translation.translateString;
  7291. if(this.bitrate === null)
  7292. {
  7293. downloadBitrate = "N/A";
  7294. uploadBitrate = "N/A";
  7295. }
  7296. else
  7297. {
  7298. downloadBitrate =
  7299. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7300. uploadBitrate =
  7301. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7302. }
  7303. if(this.packetLoss === null)
  7304. {
  7305. packetLoss = "N/A";
  7306. }
  7307. else
  7308. {
  7309. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7310. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  7311. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7312. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  7313. }
  7314. var resolutionValue = null;
  7315. if(this.resolution && this.jid != null)
  7316. {
  7317. var keys = Object.keys(this.resolution);
  7318. for(var ssrc in this.resolution)
  7319. {
  7320. resolutionValue = this.resolution[ssrc];
  7321. }
  7322. }
  7323. if(this.jid === null)
  7324. {
  7325. resolution = "";
  7326. if(this.resolution === null || !Object.keys(this.resolution) ||
  7327. Object.keys(this.resolution).length === 0)
  7328. {
  7329. resolution = "N/A";
  7330. }
  7331. else
  7332. for(i in this.resolution)
  7333. {
  7334. resolutionValue = this.resolution[i];
  7335. if(resolutionValue)
  7336. {
  7337. if(resolutionValue.height &&
  7338. resolutionValue.width)
  7339. {
  7340. resolution += (resolution === ""? "" : ", ") +
  7341. resolutionValue.width + "x" +
  7342. resolutionValue.height;
  7343. }
  7344. }
  7345. }
  7346. }
  7347. else if(!resolutionValue ||
  7348. !resolutionValue.height ||
  7349. !resolutionValue.width)
  7350. {
  7351. resolution = "N/A";
  7352. }
  7353. else
  7354. {
  7355. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7356. }
  7357. var result = "<table style='width:100%'>" +
  7358. "<tr>" +
  7359. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7360. translate("connectionindicator.bitrate") + "</span></td>" +
  7361. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7362. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7363. uploadBitrate + "</td>" +
  7364. "</tr><tr>" +
  7365. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7366. translate("connectionindicator.packetloss") + "</span></td>" +
  7367. "<td>" + packetLoss + "</td>" +
  7368. "</tr><tr>" +
  7369. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7370. translate("connectionindicator.resolution") + "</span></td>" +
  7371. "<td>" + resolution + "</td></tr></table>";
  7372. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7373. result += "<div class=\"jitsipopover_showmore\" " +
  7374. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7375. // FIXME: we do not know local jid when this text is generated
  7376. //this.jid + "')\" data-i18n='connectionindicator." +
  7377. "local')\" data-i18n='connectionindicator." +
  7378. (this.showMoreValue ? "less" : "more") + "'>" +
  7379. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7380. "</div><br />";
  7381. }
  7382. if(this.showMoreValue)
  7383. {
  7384. var downloadBandwidth, uploadBandwidth, transport;
  7385. if(this.bandwidth === null)
  7386. {
  7387. downloadBandwidth = "N/A";
  7388. uploadBandwidth = "N/A";
  7389. }
  7390. else
  7391. {
  7392. downloadBandwidth = this.bandwidth.download?
  7393. this.bandwidth.download + " Kbps" :
  7394. "N/A";
  7395. uploadBandwidth = this.bandwidth.upload?
  7396. this.bandwidth.upload + " Kbps" :
  7397. "N/A";
  7398. }
  7399. if(!this.transport || this.transport.length === 0)
  7400. {
  7401. transport = "<tr>" +
  7402. "<td><span class='jitsipopover_blue' " +
  7403. "data-i18n='connectionindicator.address'>" +
  7404. translate("connectionindicator.address") + "</span></td>" +
  7405. "<td> N/A</td></tr>";
  7406. }
  7407. else
  7408. {
  7409. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7410. for(i = 0; i < this.transport.length; i++)
  7411. {
  7412. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7413. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7414. var localIP =
  7415. ConnectionIndicator.getIP(this.transport[i].localip);
  7416. var localPort =
  7417. ConnectionIndicator.getPort(this.transport[i].localip);
  7418. if(data.remoteIP.indexOf(ip) == -1)
  7419. {
  7420. data.remoteIP.push(ip);
  7421. }
  7422. if(data.remotePort.indexOf(port) == -1)
  7423. {
  7424. data.remotePort.push(port);
  7425. }
  7426. if(data.localIP.indexOf(localIP) == -1)
  7427. {
  7428. data.localIP.push(localIP);
  7429. }
  7430. if(data.localPort.indexOf(localPort) == -1)
  7431. {
  7432. data.localPort.push(localPort);
  7433. }
  7434. }
  7435. var local_address_key = "connectionindicator.localaddress";
  7436. var remote_address_key = "connectionindicator.remoteaddress";
  7437. var localTransport =
  7438. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7439. local_address_key +"' data-i18n-options='" +
  7440. JSON.stringify({count: data.localIP.length}) + "'>" +
  7441. translate(local_address_key, {count: data.localIP.length}) +
  7442. "</span></td><td> " +
  7443. ConnectionIndicator.getStringFromArray(data.localIP) +
  7444. "</td></tr>";
  7445. transport =
  7446. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7447. remote_address_key + "' data-i18n-options='" +
  7448. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7449. translate(remote_address_key,
  7450. {count: data.remoteIP.length}) +
  7451. "</span></td><td> " +
  7452. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7453. "</td></tr>";
  7454. var key_remote = "connectionindicator.remoteport",
  7455. key_local = "connectionindicator.localport";
  7456. transport += "<tr>" +
  7457. "<td>" +
  7458. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7459. "' data-i18n-options='" +
  7460. JSON.stringify({count: this.transport.length}) + "'>" +
  7461. translate(key_remote, {count: this.transport.length}) +
  7462. "</span></td><td>";
  7463. localTransport += "<tr>" +
  7464. "<td>" +
  7465. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7466. "' data-i18n-options='" +
  7467. JSON.stringify({count: this.transport.length}) + "'>" +
  7468. translate(key_local, {count: this.transport.length}) +
  7469. "</span></td><td>";
  7470. transport +=
  7471. ConnectionIndicator.getStringFromArray(data.remotePort);
  7472. localTransport +=
  7473. ConnectionIndicator.getStringFromArray(data.localPort);
  7474. transport += "</td></tr>";
  7475. transport += localTransport + "</td></tr>";
  7476. transport +="<tr>" +
  7477. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7478. translate("connectionindicator.transport") + "</span></td>" +
  7479. "<td>" + this.transport[0].type + "</td></tr>";
  7480. }
  7481. result += "<table style='width:100%'>" +
  7482. "<tr>" +
  7483. "<td>" +
  7484. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7485. translate("connectionindicator.bandwidth") + "</span>" +
  7486. "</td><td>" +
  7487. "<span class='jitsipopover_green'>&darr;</span>" +
  7488. downloadBandwidth +
  7489. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7490. uploadBandwidth + "</td></tr>";
  7491. result += transport + "</table>";
  7492. }
  7493. return result;
  7494. };
  7495. /**
  7496. * Shows or hide the additional information.
  7497. */
  7498. ConnectionIndicator.prototype.showMore = function () {
  7499. this.showMoreValue = !this.showMoreValue;
  7500. this.updatePopoverData();
  7501. };
  7502. function createIcon(classes)
  7503. {
  7504. var icon = document.createElement("span");
  7505. for(var i in classes)
  7506. {
  7507. icon.classList.add(classes[i]);
  7508. }
  7509. icon.appendChild(
  7510. document.createElement("i")).classList.add("icon-connection");
  7511. return icon;
  7512. }
  7513. /**
  7514. * Creates the indicator
  7515. */
  7516. ConnectionIndicator.prototype.create = function () {
  7517. this.connectionIndicatorContainer = document.createElement("div");
  7518. this.connectionIndicatorContainer.className = "connectionindicator";
  7519. this.connectionIndicatorContainer.style.display = "none";
  7520. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  7521. this.popover = new JitsiPopover(
  7522. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7523. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7524. APP.translation.translateString("connectionindicator.na") + "</div>",
  7525. skin: "black"});
  7526. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7527. createIcon(["connection", "connection_empty"]));
  7528. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7529. createIcon(["connection", "connection_full"]));
  7530. };
  7531. /**
  7532. * Removes the indicator
  7533. */
  7534. ConnectionIndicator.prototype.remove = function()
  7535. {
  7536. if (this.connectionIndicatorContainer.parentNode) {
  7537. this.connectionIndicatorContainer.parentNode.removeChild(
  7538. this.connectionIndicatorContainer);
  7539. }
  7540. this.popover.forceHide();
  7541. };
  7542. /**
  7543. * Updates the data of the indicator
  7544. * @param percent the percent of connection quality
  7545. * @param object the statistics data.
  7546. */
  7547. ConnectionIndicator.prototype.updateConnectionQuality =
  7548. function (percent, object) {
  7549. if(percent === null)
  7550. {
  7551. this.connectionIndicatorContainer.style.display = "none";
  7552. this.popover.forceHide();
  7553. return;
  7554. }
  7555. else
  7556. {
  7557. if(this.connectionIndicatorContainer.style.display == "none") {
  7558. this.connectionIndicatorContainer.style.display = "block";
  7559. this.videoContainer.updateIconPositions();
  7560. }
  7561. }
  7562. this.bandwidth = object.bandwidth;
  7563. this.bitrate = object.bitrate;
  7564. this.packetLoss = object.packetLoss;
  7565. this.transport = object.transport;
  7566. if(object.resolution)
  7567. {
  7568. this.resolution = object.resolution;
  7569. }
  7570. for(var quality in ConnectionIndicator.connectionQualityValues)
  7571. {
  7572. if(percent >= quality)
  7573. {
  7574. this.fullIcon.style.width =
  7575. ConnectionIndicator.connectionQualityValues[quality];
  7576. }
  7577. }
  7578. this.updatePopoverData();
  7579. };
  7580. /**
  7581. * Updates the resolution
  7582. * @param resolution the new resolution
  7583. */
  7584. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7585. this.resolution = resolution;
  7586. this.updatePopoverData();
  7587. };
  7588. /**
  7589. * Updates the content of the popover
  7590. */
  7591. ConnectionIndicator.prototype.updatePopoverData = function () {
  7592. this.popover.updateContent(
  7593. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7594. APP.translation.translateElement($(".connection_info"));
  7595. };
  7596. /**
  7597. * Hides the popover
  7598. */
  7599. ConnectionIndicator.prototype.hide = function () {
  7600. this.popover.forceHide();
  7601. };
  7602. /**
  7603. * Hides the indicator
  7604. */
  7605. ConnectionIndicator.prototype.hideIndicator = function () {
  7606. this.connectionIndicatorContainer.style.display = "none";
  7607. if(this.popover)
  7608. this.popover.forceHide();
  7609. };
  7610. module.exports = ConnectionIndicator;
  7611. },{"../util/JitsiPopover":32}],37:[function(require,module,exports){
  7612. var Avatar = require("../avatar/Avatar");
  7613. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7614. var UIUtil = require("../util/UIUtil");
  7615. var UIEvents = require("../../../service/UI/UIEvents");
  7616. var xmpp = require("../../xmpp/xmpp");
  7617. // FIXME: With Temasys we have to re-select everytime
  7618. //var video = $('#largeVideo');
  7619. var currentVideoWidth = null;
  7620. var currentVideoHeight = null;
  7621. // By default we use camera
  7622. var getVideoSize = getCameraVideoSize;
  7623. var getVideoPosition = getCameraVideoPosition;
  7624. var currentSmallVideo = null;
  7625. /**
  7626. * Sets the size and position of the given video element.
  7627. *
  7628. * @param video the video element to position
  7629. * @param width the desired video width
  7630. * @param height the desired video height
  7631. * @param horizontalIndent the left and right indent
  7632. * @param verticalIndent the top and bottom indent
  7633. */
  7634. function positionVideo(video,
  7635. width,
  7636. height,
  7637. horizontalIndent,
  7638. verticalIndent,
  7639. animate) {
  7640. if(animate)
  7641. {
  7642. video.animate({
  7643. width: width,
  7644. height: height,
  7645. top: verticalIndent,
  7646. bottom: verticalIndent,
  7647. left: horizontalIndent,
  7648. right: horizontalIndent
  7649. },
  7650. {
  7651. queue: false,
  7652. duration: 500
  7653. });
  7654. }
  7655. else
  7656. {
  7657. video.width(width);
  7658. video.height(height);
  7659. video.css({ top: verticalIndent + 'px',
  7660. bottom: verticalIndent + 'px',
  7661. left: horizontalIndent + 'px',
  7662. right: horizontalIndent + 'px'});
  7663. }
  7664. }
  7665. /**
  7666. * Returns an array of the video dimensions, so that it keeps it's aspect
  7667. * ratio and fits available area with it's larger dimension. This method
  7668. * ensures that whole video will be visible and can leave empty areas.
  7669. *
  7670. * @return an array with 2 elements, the video width and the video height
  7671. */
  7672. function getDesktopVideoSize(videoWidth,
  7673. videoHeight,
  7674. videoSpaceWidth,
  7675. videoSpaceHeight) {
  7676. if (!videoWidth)
  7677. videoWidth = currentVideoWidth;
  7678. if (!videoHeight)
  7679. videoHeight = currentVideoHeight;
  7680. var aspectRatio = videoWidth / videoHeight;
  7681. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7682. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7683. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7684. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7685. {
  7686. availableHeight = videoSpaceHeight;
  7687. availableWidth = availableHeight * aspectRatio;
  7688. }
  7689. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7690. {
  7691. availableWidth = videoSpaceWidth;
  7692. availableHeight = availableWidth / aspectRatio;
  7693. }
  7694. return [availableWidth, availableHeight];
  7695. }
  7696. /**
  7697. * Returns an array of the video horizontal and vertical indents,
  7698. * so that if fits its parent.
  7699. *
  7700. * @return an array with 2 elements, the horizontal indent and the vertical
  7701. * indent
  7702. */
  7703. function getCameraVideoPosition(videoWidth,
  7704. videoHeight,
  7705. videoSpaceWidth,
  7706. videoSpaceHeight) {
  7707. // Parent height isn't completely calculated when we position the video in
  7708. // full screen mode and this is why we use the screen height in this case.
  7709. // Need to think it further at some point and implement it properly.
  7710. var isFullScreen = document.fullScreen ||
  7711. document.mozFullScreen ||
  7712. document.webkitIsFullScreen;
  7713. if (isFullScreen)
  7714. videoSpaceHeight = window.innerHeight;
  7715. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7716. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7717. return [horizontalIndent, verticalIndent];
  7718. }
  7719. /**
  7720. * Returns an array of the video horizontal and vertical indents.
  7721. * Centers horizontally and top aligns vertically.
  7722. *
  7723. * @return an array with 2 elements, the horizontal indent and the vertical
  7724. * indent
  7725. */
  7726. function getDesktopVideoPosition(videoWidth,
  7727. videoHeight,
  7728. videoSpaceWidth,
  7729. videoSpaceHeight) {
  7730. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7731. var verticalIndent = 0;// Top aligned
  7732. return [horizontalIndent, verticalIndent];
  7733. }
  7734. /**
  7735. * Returns an array of the video dimensions, so that it covers the screen.
  7736. * It leaves no empty areas, but some parts of the video might not be visible.
  7737. *
  7738. * @return an array with 2 elements, the video width and the video height
  7739. */
  7740. function getCameraVideoSize(videoWidth,
  7741. videoHeight,
  7742. videoSpaceWidth,
  7743. videoSpaceHeight) {
  7744. if (!videoWidth)
  7745. videoWidth = currentVideoWidth;
  7746. if (!videoHeight)
  7747. videoHeight = currentVideoHeight;
  7748. var aspectRatio = videoWidth / videoHeight;
  7749. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7750. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7751. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7752. availableHeight = videoSpaceHeight;
  7753. availableWidth = availableHeight * aspectRatio;
  7754. }
  7755. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7756. availableWidth = videoSpaceWidth;
  7757. availableHeight = availableWidth / aspectRatio;
  7758. }
  7759. return [availableWidth, availableHeight];
  7760. }
  7761. /**
  7762. * Updates the src of the active speaker avatar
  7763. * @param jid of the current active speaker
  7764. */
  7765. function updateActiveSpeakerAvatarSrc() {
  7766. var avatar = $("#activeSpeakerAvatar")[0];
  7767. var jid = currentSmallVideo.peerJid;
  7768. var url = Avatar.getActiveSpeakerUrl(jid);
  7769. if (avatar.src === url)
  7770. return;
  7771. var isMuted = null;
  7772. if (!currentSmallVideo.isLocal &&
  7773. !LargeVideo.VideoLayout.isInLastN(currentSmallVideo.getResourceJid())) {
  7774. isMuted = true;
  7775. }
  7776. else
  7777. {
  7778. isMuted = APP.RTC.isVideoMuted(jid);
  7779. }
  7780. if (jid && isMuted !== null) {
  7781. avatar.src = url;
  7782. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  7783. currentSmallVideo.showAvatar(isMuted);
  7784. }
  7785. }
  7786. function changeVideo(isVisible) {
  7787. if (!currentSmallVideo) {
  7788. console.error("Unable to change large video - no 'currentSmallVideo'");
  7789. return;
  7790. }
  7791. updateActiveSpeakerAvatarSrc();
  7792. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7793. var videoTransform = document.getElementById('largeVideo')
  7794. .style.webkitTransform;
  7795. var flipX = currentSmallVideo.flipX;
  7796. if (flipX && videoTransform !== 'scaleX(-1)') {
  7797. document.getElementById('largeVideo').style.webkitTransform
  7798. = "scaleX(-1)";
  7799. }
  7800. else if (!flipX && videoTransform === 'scaleX(-1)') {
  7801. document.getElementById('largeVideo').style.webkitTransform
  7802. = "none";
  7803. }
  7804. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7805. // Change the way we'll be measuring and positioning large video
  7806. getVideoSize = isDesktop
  7807. ? getDesktopVideoSize
  7808. : getCameraVideoSize;
  7809. getVideoPosition = isDesktop
  7810. ? getDesktopVideoPosition
  7811. : getCameraVideoPosition;
  7812. // Only if the large video is currently visible.
  7813. if (isVisible) {
  7814. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7815. $('#largeVideo').fadeIn(300);
  7816. }
  7817. }
  7818. var LargeVideo = {
  7819. init: function (VideoLayout, emitter) {
  7820. this.VideoLayout = VideoLayout;
  7821. this.eventEmitter = emitter;
  7822. var self = this;
  7823. // Listen for large video size updates
  7824. var largeVideo = $('#largeVideo')[0];
  7825. var onplaying = function (arg1, arg2, arg3) {
  7826. // re-select
  7827. if (RTCBrowserType.isTemasysPluginUsed())
  7828. largeVideo = $('#largeVideo')[0];
  7829. currentVideoWidth = largeVideo.videoWidth;
  7830. currentVideoHeight = largeVideo.videoHeight;
  7831. self.position(currentVideoWidth, currentVideoHeight);
  7832. };
  7833. largeVideo.onplaying = onplaying;
  7834. },
  7835. /**
  7836. * Indicates if the large video is currently visible.
  7837. *
  7838. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7839. */
  7840. isLargeVideoVisible: function() {
  7841. return $('#largeVideo').is(':visible');
  7842. },
  7843. /**
  7844. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7845. */
  7846. isCurrentlyOnLarge: function (resourceJid) {
  7847. return currentSmallVideo && resourceJid &&
  7848. currentSmallVideo.getResourceJid() === resourceJid;
  7849. },
  7850. /**
  7851. * Updates the large video with the given new video source.
  7852. */
  7853. updateLargeVideo: function (resourceJid, forceUpdate) {
  7854. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7855. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7856. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7857. $('#activeSpeaker').css('visibility', 'hidden');
  7858. var oldSmallVideo = null;
  7859. if (currentSmallVideo) {
  7860. oldSmallVideo = currentSmallVideo;
  7861. }
  7862. currentSmallVideo = newSmallVideo;
  7863. var oldJid = null;
  7864. if (oldSmallVideo)
  7865. oldJid = oldSmallVideo.peerJid;
  7866. if (oldJid !== resourceJid) {
  7867. // we want the notification to trigger even if userJid is undefined,
  7868. // or null.
  7869. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7870. }
  7871. if (RTCBrowserType.isSafari()) {
  7872. // FIXME In Safari fadeOut works only for the first time
  7873. changeVideo(this.isLargeVideoVisible());
  7874. } else {
  7875. $('#largeVideo').fadeOut(300,
  7876. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7877. }
  7878. } else {
  7879. if (currentSmallVideo) {
  7880. currentSmallVideo.showAvatar();
  7881. }
  7882. }
  7883. },
  7884. /**
  7885. * Shows/hides the large video.
  7886. */
  7887. setLargeVideoVisible: function(isVisible) {
  7888. if (isVisible) {
  7889. $('#largeVideo').css({visibility: 'visible'});
  7890. $('.watermark').css({visibility: 'visible'});
  7891. if(currentSmallVideo)
  7892. currentSmallVideo.enableDominantSpeaker(true);
  7893. }
  7894. else {
  7895. $('#largeVideo').css({visibility: 'hidden'});
  7896. $('#activeSpeaker').css('visibility', 'hidden');
  7897. $('.watermark').css({visibility: 'hidden'});
  7898. if(currentSmallVideo)
  7899. currentSmallVideo.enableDominantSpeaker(false);
  7900. }
  7901. },
  7902. onVideoTypeChanged: function (jid) {
  7903. var resourceJid = Strophe.getResourceFromJid(jid);
  7904. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7905. {
  7906. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7907. getVideoSize = isDesktop
  7908. ? getDesktopVideoSize
  7909. : getCameraVideoSize;
  7910. getVideoPosition = isDesktop
  7911. ? getDesktopVideoPosition
  7912. : getCameraVideoPosition;
  7913. this.position(null, null);
  7914. }
  7915. },
  7916. /**
  7917. * Positions the large video.
  7918. *
  7919. * @param videoWidth the stream video width
  7920. * @param videoHeight the stream video height
  7921. */
  7922. position: function (videoWidth, videoHeight,
  7923. videoSpaceWidth, videoSpaceHeight, animate) {
  7924. if(!videoSpaceWidth)
  7925. videoSpaceWidth = $('#videospace').width();
  7926. if(!videoSpaceHeight)
  7927. videoSpaceHeight = window.innerHeight;
  7928. var videoSize = getVideoSize(videoWidth,
  7929. videoHeight,
  7930. videoSpaceWidth,
  7931. videoSpaceHeight);
  7932. var largeVideoWidth = videoSize[0];
  7933. var largeVideoHeight = videoSize[1];
  7934. var videoPosition = getVideoPosition(largeVideoWidth,
  7935. largeVideoHeight,
  7936. videoSpaceWidth,
  7937. videoSpaceHeight);
  7938. var horizontalIndent = videoPosition[0];
  7939. var verticalIndent = videoPosition[1];
  7940. positionVideo($('#largeVideo'),
  7941. largeVideoWidth,
  7942. largeVideoHeight,
  7943. horizontalIndent, verticalIndent, animate);
  7944. },
  7945. isLargeVideoOnTop: function () {
  7946. var Etherpad = require("../etherpad/Etherpad");
  7947. var Prezi = require("../prezi/Prezi");
  7948. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7949. },
  7950. resize: function (animate, isVisible, completeFunction) {
  7951. var availableHeight = window.innerHeight;
  7952. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7953. if (availableWidth < 0 || availableHeight < 0) return;
  7954. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7955. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7956. $('#activeSpeaker').css('top', top);
  7957. if(animate)
  7958. {
  7959. $('#videospace').animate({
  7960. right: window.innerWidth - availableWidth,
  7961. width: availableWidth,
  7962. height: availableHeight
  7963. },
  7964. {
  7965. queue: false,
  7966. duration: 500,
  7967. complete: completeFunction
  7968. });
  7969. $('#largeVideoContainer').animate({
  7970. width: availableWidth,
  7971. height: availableHeight
  7972. },
  7973. {
  7974. queue: false,
  7975. duration: 500
  7976. });
  7977. }
  7978. else
  7979. {
  7980. $('#videospace').width(availableWidth);
  7981. $('#videospace').height(availableHeight);
  7982. $('#largeVideoContainer').width(availableWidth);
  7983. $('#largeVideoContainer').height(availableHeight);
  7984. }
  7985. return [availableWidth, availableHeight];
  7986. },
  7987. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7988. var size = this.resize(true, isVisible, completeFunction);
  7989. this.position(null, null, size[0], size[1], true);
  7990. },
  7991. getResourceJid: function () {
  7992. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7993. },
  7994. updateAvatar: function (resourceJid) {
  7995. if (resourceJid === this.getResourceJid()) {
  7996. updateActiveSpeakerAvatarSrc();
  7997. }
  7998. },
  7999. showAvatar: function (resourceJid, show) {
  8000. if(this.getResourceJid() === resourceJid
  8001. && LargeVideo.isLargeVideoOnTop())
  8002. {
  8003. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  8004. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  8005. return true;
  8006. }
  8007. return false;
  8008. }
  8009. }
  8010. module.exports = LargeVideo;
  8011. },{"../../../service/UI/UIEvents":104,"../../RTC/RTCBrowserType":10,"../../xmpp/xmpp":68,"../avatar/Avatar":18,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../util/UIUtil":35}],38:[function(require,module,exports){
  8012. var SmallVideo = require("./SmallVideo");
  8013. var ConnectionIndicator = require("./ConnectionIndicator");
  8014. var NicknameHandler = require("../util/NicknameHandler");
  8015. var UIUtil = require("../util/UIUtil");
  8016. var LargeVideo = require("./LargeVideo");
  8017. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8018. function LocalVideo(VideoLayout)
  8019. {
  8020. this.videoSpanId = "localVideoContainer";
  8021. this.container = $("#localVideoContainer").get(0);
  8022. this.VideoLayout = VideoLayout;
  8023. this.flipX = true;
  8024. this.isLocal = true;
  8025. this.peerJid = null;
  8026. }
  8027. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  8028. LocalVideo.prototype.constructor = LocalVideo;
  8029. /**
  8030. * Creates the edit display name button.
  8031. *
  8032. * @returns the edit button
  8033. */
  8034. function createEditDisplayNameButton() {
  8035. var editButton = document.createElement('a');
  8036. editButton.className = 'displayname';
  8037. UIUtil.setTooltip(editButton,
  8038. "videothumbnail.editnickname",
  8039. "top");
  8040. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  8041. return editButton;
  8042. }
  8043. /**
  8044. * Sets the display name for the given video span id.
  8045. */
  8046. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  8047. if (!this.container) {
  8048. console.warn(
  8049. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8050. return;
  8051. }
  8052. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8053. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  8054. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8055. // If we already have a display name for this video.
  8056. if (nameSpan.length > 0) {
  8057. if (nameSpan.text() !== displayName) {
  8058. if (displayName && displayName.length > 0)
  8059. {
  8060. var meHTML = APP.translation.generateTranslationHTML("me");
  8061. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  8062. }
  8063. else
  8064. $('#localDisplayName').html(defaultLocalDisplayName);
  8065. }
  8066. } else {
  8067. var editButton = createEditDisplayNameButton();
  8068. nameSpan = document.createElement('span');
  8069. nameSpan.className = 'displayname';
  8070. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8071. if (displayName && displayName.length > 0) {
  8072. var meHTML = APP.translation.generateTranslationHTML("me");
  8073. nameSpan.innerHTML = displayName + meHTML;
  8074. }
  8075. else {
  8076. nameSpan.innerHTML = defaultLocalDisplayName;
  8077. }
  8078. nameSpan.id = 'localDisplayName';
  8079. this.container.appendChild(editButton);
  8080. //translates popover of edit button
  8081. APP.translation.translateElement($("a.displayname"));
  8082. var editableText = document.createElement('input');
  8083. editableText.className = 'displayname';
  8084. editableText.type = 'text';
  8085. editableText.id = 'editDisplayName';
  8086. if (displayName && displayName.length) {
  8087. editableText.value = displayName;
  8088. }
  8089. var defaultNickname = APP.translation.translateString(
  8090. "defaultNickname", {name: "Jane Pink"});
  8091. editableText.setAttribute('style', 'display:none;');
  8092. editableText.setAttribute('data-18n',
  8093. '[placeholder]defaultNickname');
  8094. editableText.setAttribute("data-i18n-options",
  8095. JSON.stringify({name: "Jane Pink"}));
  8096. editableText.setAttribute("placeholder", defaultNickname);
  8097. this.container.appendChild(editableText);
  8098. var self = this;
  8099. $('#localVideoContainer .displayname')
  8100. .bind("click", function (e) {
  8101. e.preventDefault();
  8102. e.stopPropagation();
  8103. $('#localDisplayName').hide();
  8104. $('#editDisplayName').show();
  8105. $('#editDisplayName').focus();
  8106. $('#editDisplayName').select();
  8107. $('#editDisplayName').one("focusout", function (e) {
  8108. self.VideoLayout.inputDisplayNameHandler(this.value);
  8109. });
  8110. $('#editDisplayName').on('keydown', function (e) {
  8111. if (e.keyCode === 13) {
  8112. e.preventDefault();
  8113. self.VideoLayout.inputDisplayNameHandler(this.value);
  8114. }
  8115. });
  8116. });
  8117. }
  8118. }
  8119. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  8120. NicknameHandler.setNickname(name);
  8121. if (!$('#localDisplayName').is(":visible")) {
  8122. if (NicknameHandler.getNickname())
  8123. {
  8124. var meHTML = APP.translation.generateTranslationHTML("me");
  8125. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  8126. }
  8127. else
  8128. {
  8129. var defaultHTML = APP.translation.generateTranslationHTML(
  8130. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8131. $('#localDisplayName')
  8132. .html(defaultHTML);
  8133. }
  8134. $('#localDisplayName').show();
  8135. }
  8136. $('#editDisplayName').hide();
  8137. }
  8138. LocalVideo.prototype.createConnectionIndicator = function()
  8139. {
  8140. if(this.connectionIndicator)
  8141. return;
  8142. this.connectionIndicator
  8143. = new ConnectionIndicator(this, null);
  8144. }
  8145. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  8146. var self = this;
  8147. function localVideoClick(event) {
  8148. // FIXME: with Temasys plugin event arg is not an event, but
  8149. // the clicked object itself, so we have to skip this call
  8150. if (event.stopPropagation) {
  8151. event.stopPropagation();
  8152. }
  8153. self.VideoLayout.handleVideoThumbClicked(
  8154. false,
  8155. APP.xmpp.myResource());
  8156. }
  8157. $('#localVideoContainer').off('click');
  8158. $('#localVideoContainer').on('click', localVideoClick);
  8159. // Add hover handler
  8160. $('#localVideoContainer').hover(
  8161. function() {
  8162. self.showDisplayName(true);
  8163. },
  8164. function() {
  8165. if (!LargeVideo.isLargeVideoVisible() ||
  8166. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8167. self.showDisplayName(false);
  8168. }
  8169. );
  8170. if(isMuted)
  8171. {
  8172. APP.UI.setVideoMute(true);
  8173. return;
  8174. }
  8175. this.flipX = (stream.videoType == "screen")? false : true;
  8176. var localVideo = document.createElement('video');
  8177. localVideo.id = 'localVideo_' +
  8178. APP.RTC.getStreamID(stream.getOriginalStream());
  8179. if (!RTCBrowserType.isIExplorer()) {
  8180. localVideo.autoplay = true;
  8181. localVideo.volume = 0; // is it required if audio is separated ?
  8182. }
  8183. localVideo.oncontextmenu = function () { return false; };
  8184. var localVideoContainer = document.getElementById('localVideoWrapper');
  8185. localVideoContainer.appendChild(localVideo);
  8186. var localVideoSelector = $('#' + localVideo.id);
  8187. // Add click handler to both video and video wrapper elements in case
  8188. // there's no video.
  8189. // onclick has to be used with Temasys plugin
  8190. localVideo.onclick = localVideoClick;
  8191. if (this.flipX) {
  8192. localVideoSelector.addClass("flipVideoX");
  8193. }
  8194. // Attach WebRTC stream
  8195. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  8196. // Add stream ended handler
  8197. stream.getOriginalStream().onended = function () {
  8198. // We have to re-select after attach when Temasys plugin is used,
  8199. // because <video> element is replaced with <object>
  8200. localVideo = $('#' + localVideo.id)[0];
  8201. localVideoContainer.removeChild(localVideo);
  8202. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  8203. };
  8204. };
  8205. LocalVideo.prototype.joined = function (jid) {
  8206. this.peerJid = jid;
  8207. };
  8208. LocalVideo.prototype.getResourceJid = function () {
  8209. var myResource = APP.xmpp.myResource();
  8210. if (!myResource) {
  8211. console.error("Requested local resource before we're in the MUC");
  8212. }
  8213. return myResource;
  8214. };
  8215. module.exports = LocalVideo;
  8216. },{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){
  8217. var ConnectionIndicator = require("./ConnectionIndicator");
  8218. var SmallVideo = require("./SmallVideo");
  8219. var AudioLevels = require("../audio_levels/AudioLevels");
  8220. var LargeVideo = require("./LargeVideo");
  8221. var Avatar = require("../avatar/Avatar");
  8222. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8223. function RemoteVideo(peerJid, VideoLayout)
  8224. {
  8225. this.peerJid = peerJid;
  8226. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8227. this.videoSpanId = 'participant_' + this.resourceJid;
  8228. this.VideoLayout = VideoLayout;
  8229. this.addRemoteVideoContainer();
  8230. this.connectionIndicator = new ConnectionIndicator(
  8231. this, this.peerJid);
  8232. this.setDisplayName();
  8233. var nickfield = document.createElement('span');
  8234. nickfield.className = "nick";
  8235. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8236. this.container.appendChild(nickfield);
  8237. this.flipX = false;
  8238. this.isLocal = false;
  8239. }
  8240. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8241. RemoteVideo.prototype.constructor = RemoteVideo;
  8242. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8243. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8244. if (APP.xmpp.isModerator())
  8245. this.addRemoteVideoMenu();
  8246. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8247. return this.container;
  8248. };
  8249. /**
  8250. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8251. * given <tt>parentElement</tt>.
  8252. *
  8253. * @param jid the jid indicating the video for which we're adding a menu.
  8254. * @param parentElement the parent element where this menu will be added
  8255. */
  8256. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8257. var spanElement = document.createElement('span');
  8258. spanElement.className = 'remotevideomenu';
  8259. this.container.appendChild(spanElement);
  8260. var menuElement = document.createElement('i');
  8261. menuElement.className = 'fa fa-angle-down';
  8262. menuElement.title = 'Remote user controls';
  8263. spanElement.appendChild(menuElement);
  8264. var popupmenuElement = document.createElement('ul');
  8265. popupmenuElement.className = 'popupmenu';
  8266. popupmenuElement.id
  8267. = 'remote_popupmenu_' + this.getResourceJid();
  8268. spanElement.appendChild(popupmenuElement);
  8269. var muteMenuItem = document.createElement('li');
  8270. var muteLinkItem = document.createElement('a');
  8271. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  8272. if (!this.isMuted) {
  8273. muteLinkItem.innerHTML = mutedIndicator +
  8274. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8275. muteLinkItem.className = 'mutelink';
  8276. }
  8277. else {
  8278. muteLinkItem.innerHTML = mutedIndicator +
  8279. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  8280. muteLinkItem.className = 'mutelink disabled';
  8281. }
  8282. var self = this;
  8283. muteLinkItem.onclick = function(){
  8284. if ($(this).attr('disabled') != undefined) {
  8285. event.preventDefault();
  8286. }
  8287. var isMute = self.isMuted == true;
  8288. APP.xmpp.setMute(self.peerJid, !isMute);
  8289. popupmenuElement.setAttribute('style', 'display:none;');
  8290. if (isMute) {
  8291. this.innerHTML = mutedIndicator +
  8292. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  8293. this.className = 'mutelink disabled';
  8294. }
  8295. else {
  8296. this.innerHTML = mutedIndicator +
  8297. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8298. this.className = 'mutelink';
  8299. }
  8300. };
  8301. muteMenuItem.appendChild(muteLinkItem);
  8302. popupmenuElement.appendChild(muteMenuItem);
  8303. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8304. var ejectMenuItem = document.createElement('li');
  8305. var ejectLinkItem = document.createElement('a');
  8306. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8307. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8308. ejectLinkItem.onclick = function(){
  8309. APP.xmpp.eject(self.peerJid);
  8310. popupmenuElement.setAttribute('style', 'display:none;');
  8311. };
  8312. ejectMenuItem.appendChild(ejectLinkItem);
  8313. popupmenuElement.appendChild(ejectMenuItem);
  8314. var paddingSpan = document.createElement('span');
  8315. paddingSpan.className = 'popupmenuPadding';
  8316. popupmenuElement.appendChild(paddingSpan);
  8317. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  8318. }
  8319. /**
  8320. * Removes the remote stream element corresponding to the given stream and
  8321. * parent container.
  8322. *
  8323. * @param stream the stream
  8324. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8325. * @param container
  8326. */
  8327. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  8328. if (!this.container)
  8329. return false;
  8330. var select = null;
  8331. if (isVideo) {
  8332. select = $('#' + id);
  8333. }
  8334. else
  8335. select = $('#' + this.videoSpanId + '>audio');
  8336. // Mark video as removed to cancel waiting loop(if video is removed
  8337. // before has started)
  8338. select.removed = true;
  8339. select.remove();
  8340. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  8341. var videoCount = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName()).length;
  8342. if (!audioCount && !videoCount) {
  8343. console.log("Remove whole user", this.videoSpanId);
  8344. if(this.connectionIndicator)
  8345. this.connectionIndicator.remove();
  8346. // Remove whole container
  8347. if (this.container.parentNode)
  8348. this.container.parentNode.removeChild(this.container);
  8349. this.VideoLayout.resizeThumbnails();
  8350. }
  8351. if (isVideo)
  8352. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8353. };
  8354. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8355. var isVideo = stream.getVideoTracks().length > 0;
  8356. if (!isVideo || stream.id === 'mixedmslabel') {
  8357. return;
  8358. }
  8359. var self = this;
  8360. var resourceJid = this.getResourceJid();
  8361. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8362. // when video playback starts
  8363. var onPlayingHandler = function () {
  8364. // FIXME: why do i have to do this for FF?
  8365. if (RTCBrowserType.isFirefox()) {
  8366. APP.RTC.attachMediaStream(sel, stream);
  8367. }
  8368. if (RTCBrowserType.isTemasysPluginUsed()) {
  8369. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8370. }
  8371. self.VideoLayout.videoactive(sel, resourceJid);
  8372. sel[0].onplaying = null;
  8373. if (RTCBrowserType.isTemasysPluginUsed()) {
  8374. // 'currentTime' is used to check if the video has started
  8375. // and the value is not set by the plugin, so we do it
  8376. sel[0].currentTime = 1;
  8377. }
  8378. };
  8379. sel[0].onplaying = onPlayingHandler;
  8380. };
  8381. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8382. if (!this.container)
  8383. return;
  8384. var self = this;
  8385. var isVideo = stream.getVideoTracks().length > 0;
  8386. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8387. var newElementId = streamElement.id;
  8388. this.container.appendChild(streamElement);
  8389. var sel = $('#' + newElementId);
  8390. sel.hide();
  8391. // If the container is currently visible we attach the stream.
  8392. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8393. this.waitForPlayback(sel, stream);
  8394. APP.RTC.attachMediaStream(sel, stream);
  8395. }
  8396. stream.onended = function () {
  8397. console.log('stream ended', this);
  8398. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8399. };
  8400. // Name of video element name is different for IE/Safari
  8401. var videoElem = APP.RTC.getVideoElementName();
  8402. // Add click handler.
  8403. var onClickHandler = function (event) {
  8404. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8405. // On IE we need to populate this handler on video <object>
  8406. // and it does not give event instance as an argument,
  8407. // so we check here for methods.
  8408. if (event.stopPropagation && event.preventDefault) {
  8409. event.stopPropagation();
  8410. event.preventDefault();
  8411. }
  8412. return false;
  8413. };
  8414. this.container.onclick = onClickHandler;
  8415. // reselect
  8416. if (RTCBrowserType.isTemasysPluginUsed())
  8417. sel = $('#' + newElementId);
  8418. sel[0].onclick = onClickHandler;
  8419. //FIXME
  8420. // Add hover handler
  8421. $(this.container).hover(
  8422. function() {
  8423. self.showDisplayName(true);
  8424. },
  8425. function() {
  8426. // If the video has been "pinned" by the user we want to
  8427. // keep the display name on place.
  8428. if (!LargeVideo.isLargeVideoVisible() ||
  8429. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8430. self.showDisplayName(false);
  8431. }
  8432. );
  8433. },
  8434. /**
  8435. * Show/hide peer container for the given resourceJid.
  8436. */
  8437. RemoteVideo.prototype.showPeerContainer = function (state) {
  8438. if (!this.container)
  8439. return;
  8440. var isHide = state === 'hide';
  8441. var resizeThumbnails = false;
  8442. if (!isHide) {
  8443. if (!$(this.container).is(':visible')) {
  8444. resizeThumbnails = true;
  8445. $(this.container).show();
  8446. }
  8447. this.showAvatar(state !== 'show');
  8448. }
  8449. else if ($(this.container).is(':visible') && isHide)
  8450. {
  8451. resizeThumbnails = true;
  8452. $(this.container).hide();
  8453. if(this.connectionIndicator)
  8454. this.connectionIndicator.hide();
  8455. }
  8456. if (resizeThumbnails) {
  8457. this.VideoLayout.resizeThumbnails();
  8458. }
  8459. // We want to be able to pin a participant from the contact list, even
  8460. // if he's not in the lastN set!
  8461. // ContactList.setClickable(resourceJid, !isHide);
  8462. };
  8463. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8464. if(this.connectionIndicator)
  8465. this.connectionIndicator.remove();
  8466. }
  8467. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8468. if(this.connectionIndicator)
  8469. this.connectionIndicator.hide();
  8470. }
  8471. /**
  8472. * Updates the remote video menu.
  8473. *
  8474. * @param jid the jid indicating the video for which we're adding a menu.
  8475. * @param isMuted indicates the current mute state
  8476. */
  8477. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8478. var muteMenuItem
  8479. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8480. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8481. if (muteMenuItem.length) {
  8482. var muteLink = muteMenuItem.get(0);
  8483. if (isMuted === 'true') {
  8484. muteLink.innerHTML = mutedIndicator + ' Muted';
  8485. muteLink.className = 'mutelink disabled';
  8486. }
  8487. else {
  8488. muteLink.innerHTML = mutedIndicator + ' Mute';
  8489. muteLink.className = 'mutelink';
  8490. }
  8491. }
  8492. };
  8493. /**
  8494. * Sets the display name for the given video span id.
  8495. */
  8496. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8497. if (!this.container) {
  8498. console.warn(
  8499. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8500. return;
  8501. }
  8502. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8503. // If we already have a display name for this video.
  8504. if (nameSpan.length > 0) {
  8505. if (displayName && displayName.length > 0)
  8506. {
  8507. $('#' + this.videoSpanId + '_name').html(displayName);
  8508. }
  8509. else if (key && key.length > 0)
  8510. {
  8511. var nameHtml = APP.translation.generateTranslationHTML(key);
  8512. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8513. }
  8514. else
  8515. $('#' + this.videoSpanId + '_name').text(
  8516. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8517. } else {
  8518. nameSpan = document.createElement('span');
  8519. nameSpan.className = 'displayname';
  8520. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8521. if (displayName && displayName.length > 0) {
  8522. nameSpan.innerText = displayName;
  8523. }
  8524. else
  8525. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8526. nameSpan.id = this.videoSpanId + '_name';
  8527. }
  8528. }
  8529. /**
  8530. * Removes remote video menu element from video element identified by
  8531. * given <tt>videoElementId</tt>.
  8532. *
  8533. * @param videoElementId the id of local or remote video element.
  8534. */
  8535. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8536. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8537. if (menuSpan.length) {
  8538. menuSpan.remove();
  8539. }
  8540. };
  8541. RemoteVideo.prototype.getResourceJid = function () {
  8542. if (!this.resourceJid) {
  8543. console.error("Undefined resource jid");
  8544. }
  8545. return this.resourceJid;
  8546. };
  8547. RemoteVideo.createContainer = function (spanId) {
  8548. var container = document.createElement('span');
  8549. container.id = spanId;
  8550. container.className = 'videocontainer';
  8551. var remotes = document.getElementById('remoteVideos');
  8552. return remotes.appendChild(container);
  8553. };
  8554. module.exports = RemoteVideo;
  8555. },{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){
  8556. var Avatar = require("../avatar/Avatar");
  8557. var UIUtil = require("../util/UIUtil");
  8558. var LargeVideo = require("./LargeVideo");
  8559. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8560. function SmallVideo(){
  8561. this.isMuted = false;
  8562. this.hasAvatar = false;
  8563. }
  8564. function setVisibility(selector, show) {
  8565. if (selector && selector.length > 0) {
  8566. selector.css("visibility", show ? "visible" : "hidden");
  8567. }
  8568. }
  8569. SmallVideo.prototype.showDisplayName = function(isShow) {
  8570. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8571. if (isShow) {
  8572. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8573. nameSpan.setAttribute("style", "display:inline-block;");
  8574. }
  8575. else {
  8576. if (nameSpan)
  8577. nameSpan.setAttribute("style", "display:none;");
  8578. }
  8579. };
  8580. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8581. if(!this.container)
  8582. return;
  8583. $("#" + this.videoSpanId + " > .noMic").remove();
  8584. $("#" + this.videoSpanId + " > .noVideo").remove();
  8585. if(!devices.audio)
  8586. {
  8587. this.container.appendChild(
  8588. document.createElement("div")).setAttribute("class","noMic");
  8589. }
  8590. if(!devices.video)
  8591. {
  8592. this.container.appendChild(
  8593. document.createElement("div")).setAttribute("class","noVideo");
  8594. }
  8595. if(!devices.audio && !devices.video)
  8596. {
  8597. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  8598. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  8599. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  8600. }
  8601. }
  8602. /**
  8603. * Shows the presence status message for the given video.
  8604. */
  8605. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8606. if (!this.container) {
  8607. // No container
  8608. return;
  8609. }
  8610. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8611. if (!statusSpan.length) {
  8612. //Add status span
  8613. statusSpan = document.createElement('span');
  8614. statusSpan.className = 'status';
  8615. statusSpan.id = this.videoSpanId + '_status';
  8616. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8617. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8618. }
  8619. // Display status
  8620. if (statusMsg && statusMsg.length) {
  8621. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8622. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8623. }
  8624. else {
  8625. // Hide
  8626. statusSpan.get(0).setAttribute("style", "display:none;");
  8627. }
  8628. };
  8629. /**
  8630. * Creates an audio or video stream element.
  8631. */
  8632. SmallVideo.createStreamElement = function (sid, stream) {
  8633. var isVideo = stream.getVideoTracks().length > 0;
  8634. var element = isVideo
  8635. ? document.createElement('video')
  8636. : document.createElement('audio');
  8637. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  8638. + sid + '_' + APP.RTC.getStreamID(stream);
  8639. element.id = id;
  8640. if (!RTCBrowserType.isIExplorer()) {
  8641. element.autoplay = true;
  8642. }
  8643. element.oncontextmenu = function () { return false; };
  8644. return element;
  8645. };
  8646. /**
  8647. * Updates the data for the indicator
  8648. * @param id the id of the indicator
  8649. * @param percent the percent for connection quality
  8650. * @param object the data
  8651. */
  8652. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8653. if(this.connectionIndicator)
  8654. this.connectionIndicator.updateConnectionQuality(percent, object);
  8655. }
  8656. SmallVideo.prototype.hideIndicator = function () {
  8657. if(this.connectionIndicator)
  8658. this.connectionIndicator.hideIndicator();
  8659. }
  8660. /**
  8661. * Shows audio muted indicator over small videos.
  8662. * @param {string} isMuted
  8663. */
  8664. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8665. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8666. if (!isMuted) {
  8667. if (audioMutedSpan.length > 0) {
  8668. audioMutedSpan.popover('hide');
  8669. audioMutedSpan.remove();
  8670. }
  8671. }
  8672. else {
  8673. if(audioMutedSpan.length == 0 ) {
  8674. audioMutedSpan = document.createElement('span');
  8675. audioMutedSpan.className = 'audioMuted';
  8676. UIUtil.setTooltip(audioMutedSpan,
  8677. "videothumbnail.mute",
  8678. "top");
  8679. this.container.appendChild(audioMutedSpan);
  8680. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8681. var mutedIndicator = document.createElement('i');
  8682. mutedIndicator.className = 'icon-mic-disabled';
  8683. audioMutedSpan.appendChild(mutedIndicator);
  8684. }
  8685. this.updateIconPositions();
  8686. }
  8687. this.isMuted = isMuted;
  8688. };
  8689. /**
  8690. * Shows video muted indicator over small videos.
  8691. */
  8692. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8693. this.showAvatar(isMuted);
  8694. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8695. if (isMuted === false) {
  8696. if (videoMutedSpan.length > 0) {
  8697. videoMutedSpan.remove();
  8698. }
  8699. }
  8700. else {
  8701. if(videoMutedSpan.length == 0) {
  8702. videoMutedSpan = document.createElement('span');
  8703. videoMutedSpan.className = 'videoMuted';
  8704. this.container.appendChild(videoMutedSpan);
  8705. var mutedIndicator = document.createElement('i');
  8706. mutedIndicator.className = 'icon-camera-disabled';
  8707. UIUtil.setTooltip(mutedIndicator,
  8708. "videothumbnail.videomute",
  8709. "top");
  8710. videoMutedSpan.appendChild(mutedIndicator);
  8711. //translate texts for muted indicator
  8712. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8713. }
  8714. this.updateIconPositions();
  8715. }
  8716. };
  8717. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  8718. {
  8719. var resourceJid = this.getResourceJid();
  8720. var displayName = resourceJid;
  8721. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8722. if (nameSpan.length > 0)
  8723. displayName = nameSpan.html();
  8724. console.log("UI enable dominant speaker",
  8725. displayName,
  8726. resourceJid,
  8727. isEnable);
  8728. if (!this.container) {
  8729. return;
  8730. }
  8731. if (isEnable) {
  8732. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  8733. if (!this.container.classList.contains("dominantspeaker"))
  8734. this.container.classList.add("dominantspeaker");
  8735. }
  8736. else {
  8737. this.showDisplayName(false);
  8738. if (this.container.classList.contains("dominantspeaker"))
  8739. this.container.classList.remove("dominantspeaker");
  8740. }
  8741. this.showAvatar();
  8742. };
  8743. SmallVideo.prototype.updateIconPositions = function () {
  8744. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8745. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8746. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8747. if(connectionIndicator.length > 0
  8748. && connectionIndicator[0].style.display != "none") {
  8749. audioMutedSpan.css({right: "23px"});
  8750. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8751. }
  8752. else
  8753. {
  8754. audioMutedSpan.css({right: "0px"});
  8755. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8756. }
  8757. }
  8758. /**
  8759. * Creates the element indicating the moderator(owner) of the conference.
  8760. *
  8761. * @param parentElement the parent element where the owner indicator will
  8762. * be added
  8763. */
  8764. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8765. // Show moderator indicator
  8766. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8767. if (!indicatorSpan || indicatorSpan.length === 0) {
  8768. indicatorSpan = document.createElement('span');
  8769. indicatorSpan.className = 'focusindicator';
  8770. this.container.appendChild(indicatorSpan);
  8771. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8772. }
  8773. if (indicatorSpan.children().length !== 0)
  8774. return;
  8775. var moderatorIndicator = document.createElement('i');
  8776. moderatorIndicator.className = 'fa fa-star';
  8777. indicatorSpan[0].appendChild(moderatorIndicator);
  8778. UIUtil.setTooltip(indicatorSpan[0],
  8779. "videothumbnail.moderator",
  8780. "top");
  8781. //translates text in focus indicators
  8782. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8783. }
  8784. SmallVideo.prototype.getSrc = function () {
  8785. var videoElement = APP.RTC.getVideoElementName();
  8786. return APP.RTC.getVideoSrc(
  8787. $('#' + this.videoSpanId).find(videoElement).get(0));
  8788. },
  8789. SmallVideo.prototype.focus = function(isFocused)
  8790. {
  8791. if(!isFocused) {
  8792. this.container.classList.remove("videoContainerFocused");
  8793. }
  8794. else
  8795. {
  8796. this.container.classList.add("videoContainerFocused");
  8797. }
  8798. }
  8799. SmallVideo.prototype.hasVideo = function () {
  8800. return $("#" + this.videoSpanId).find(
  8801. APP.RTC.getVideoElementName()).length !== 0;
  8802. }
  8803. /**
  8804. * Hides or shows the user's avatar
  8805. * @param show whether we should show the avatar or not
  8806. * video because there is no dominant speaker and no focused speaker
  8807. */
  8808. SmallVideo.prototype.showAvatar = function (show) {
  8809. if (!this.hasAvatar) {
  8810. if (this.peerJid) {
  8811. // Init avatar
  8812. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8813. } else {
  8814. console.error("Unable to init avatar - no peerjid", this);
  8815. return;
  8816. }
  8817. }
  8818. var resourceJid = this.getResourceJid();
  8819. var videoElem = APP.RTC.getVideoElementName();
  8820. var video = $('#' + this.videoSpanId).find(videoElem);
  8821. var avatar = $('#avatar_' + resourceJid);
  8822. if (show === undefined || show === null) {
  8823. if (!this.isLocal &&
  8824. !this.VideoLayout.isInLastN(resourceJid)) {
  8825. show = true;
  8826. }
  8827. else
  8828. {
  8829. show = APP.RTC.isVideoMuted(this.peerJid);
  8830. }
  8831. }
  8832. if (LargeVideo.showAvatar(resourceJid, show))
  8833. {
  8834. setVisibility(avatar, false);
  8835. setVisibility(video, false);
  8836. } else {
  8837. if (video && video.length > 0) {
  8838. setVisibility(video, !show);
  8839. }
  8840. setVisibility(avatar, show);
  8841. }
  8842. };
  8843. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8844. var thumbnail = $('#' + this.videoSpanId);
  8845. var resourceJid = this.getResourceJid();
  8846. var avatar = $('#avatar_' + resourceJid);
  8847. this.hasAvatar = true;
  8848. // set the avatar in the thumbnail
  8849. if (avatar && avatar.length > 0) {
  8850. avatar[0].src = thumbUrl;
  8851. } else {
  8852. if (thumbnail && thumbnail.length > 0) {
  8853. avatar = document.createElement('img');
  8854. avatar.id = 'avatar_' + resourceJid;
  8855. avatar.className = 'userAvatar';
  8856. avatar.src = thumbUrl;
  8857. thumbnail.append(avatar);
  8858. }
  8859. }
  8860. }
  8861. module.exports = SmallVideo;
  8862. },{"../../RTC/RTCBrowserType":10,"../avatar/Avatar":18,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){
  8863. var AudioLevels = require("../audio_levels/AudioLevels");
  8864. var Avatar = require("../avatar/Avatar");
  8865. var ContactList = require("../side_pannels/contactlist/ContactList");
  8866. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8867. var UIEvents = require("../../../service/UI/UIEvents");
  8868. var RTC = require("../../RTC/RTC");
  8869. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8870. var RemoteVideo = require("./RemoteVideo");
  8871. var LargeVideo = require("./LargeVideo");
  8872. var LocalVideo = require("./LocalVideo");
  8873. var remoteVideos = {};
  8874. var localVideoThumbnail = null;
  8875. var currentDominantSpeaker = null;
  8876. var lastNCount = config.channelLastN;
  8877. var localLastNCount = config.channelLastN;
  8878. var localLastNSet = [];
  8879. var lastNEndpointsCache = [];
  8880. var lastNPickupJid = null;
  8881. var eventEmitter = null;
  8882. /**
  8883. * Currently focused video jid
  8884. * @type {String}
  8885. */
  8886. var focusedVideoResourceJid = null;
  8887. var VideoLayout = (function (my) {
  8888. my.init = function (emitter) {
  8889. eventEmitter = emitter;
  8890. localVideoThumbnail = new LocalVideo(VideoLayout);
  8891. VideoLayout.resizeLargeVideoContainer();
  8892. LargeVideo.init(VideoLayout, emitter);
  8893. };
  8894. my.isInLastN = function(resource) {
  8895. return lastNCount < 0 // lastN is disabled, return true
  8896. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  8897. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  8898. };
  8899. my.changeLocalStream = function (stream, isMuted) {
  8900. VideoLayout.changeLocalVideo(stream, isMuted);
  8901. };
  8902. my.changeLocalAudio = function(stream, isMuted) {
  8903. if (isMuted)
  8904. APP.UI.setAudioMuted(true, true);
  8905. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8906. var localAudio = document.getElementById('localAudio');
  8907. // Writing volume not allowed in IE
  8908. if (!RTCBrowserType.isIExplorer()) {
  8909. localAudio.autoplay = true;
  8910. localAudio.volume = 0;
  8911. }
  8912. };
  8913. my.changeLocalVideo = function(stream, isMuted) {
  8914. // Set default display name.
  8915. localVideoThumbnail.setDisplayName();
  8916. localVideoThumbnail.createConnectionIndicator();
  8917. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8918. localVideoThumbnail.changeVideo(stream, isMuted);
  8919. /* force update if we're currently being displayed */
  8920. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8921. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8922. }
  8923. };
  8924. my.mucJoined = function () {
  8925. var myResourceJid = APP.xmpp.myResource();
  8926. localVideoThumbnail.joined(APP.xmpp.myJid());
  8927. if (!LargeVideo.getResourceJid())
  8928. LargeVideo.updateLargeVideo(myResourceJid, true);
  8929. };
  8930. /**
  8931. * Adds or removes icons for not available camera and microphone.
  8932. * @param resourceJid the jid of user
  8933. * @param devices available devices
  8934. */
  8935. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8936. if(!devices)
  8937. return;
  8938. if(!resourceJid)
  8939. {
  8940. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8941. }
  8942. else
  8943. {
  8944. if(remoteVideos[resourceJid])
  8945. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8946. }
  8947. }
  8948. /**
  8949. * Checks if removed video is currently displayed and tries to display
  8950. * another one instead.
  8951. * @param removedVideoSrc src stream identifier of the video.
  8952. */
  8953. my.updateRemovedVideo = function(resourceJid) {
  8954. if (resourceJid === LargeVideo.getResourceJid()) {
  8955. var newResourceJid;
  8956. // We'll show user's avatar if he is the dominant speaker or if
  8957. // his video thumbnail is pinned
  8958. if (remoteVideos[resourceJid] &&
  8959. resourceJid === focusedVideoResourceJid ||
  8960. resourceJid === currentDominantSpeaker) {
  8961. newResourceJid = resourceJid;
  8962. } else {
  8963. // Otherwise select last visible video
  8964. newResourceJid = this.electLastVisibleVideo();
  8965. }
  8966. LargeVideo.updateLargeVideo(newResourceJid);
  8967. }
  8968. };
  8969. my.electLastVisibleVideo = function() {
  8970. // pick the last visible video in the row
  8971. // if nobody else is left, this picks the local video
  8972. var jid;
  8973. var videoElem = RTC.getVideoElementName();
  8974. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  8975. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8976. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8977. } else {
  8978. console.info("Last visible video no longer exists");
  8979. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  8980. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  8981. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  8982. } else {
  8983. // Try local video
  8984. console.info("Fallback to local video...");
  8985. jid = APP.xmpp.myResource();
  8986. }
  8987. }
  8988. console.info("electLastVisibleVideo: " + jid);
  8989. return jid;
  8990. };
  8991. my.onRemoteStreamAdded = function (stream) {
  8992. if (stream.peerjid) {
  8993. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8994. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8995. remoteVideos[resourceJid].addRemoteStreamElement(
  8996. stream.sid,
  8997. stream.getOriginalStream(),
  8998. stream.ssrc);
  8999. }
  9000. };
  9001. my.getLargeVideoJid = function () {
  9002. return LargeVideo.getResourceJid();
  9003. };
  9004. /**
  9005. * Called when large video update is finished
  9006. * @param currentSmallVideo small video currently displayed on large video
  9007. */
  9008. my.largeVideoUpdated = function (currentSmallVideo) {
  9009. // Makes sure that dominant speaker UI
  9010. // is enabled only on current small video
  9011. localVideoThumbnail.enableDominantSpeaker(
  9012. localVideoThumbnail === currentSmallVideo);
  9013. Object.keys(remoteVideos).forEach(
  9014. function (resourceJid) {
  9015. var remoteVideo = remoteVideos[resourceJid];
  9016. if (remoteVideo) {
  9017. remoteVideo.enableDominantSpeaker(
  9018. remoteVideo === currentSmallVideo);
  9019. }
  9020. }
  9021. );
  9022. };
  9023. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  9024. resourceJid) {
  9025. if(focusedVideoResourceJid) {
  9026. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9027. if(oldSmallVideo)
  9028. oldSmallVideo.focus(false);
  9029. }
  9030. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9031. // Unlock current focused.
  9032. if (focusedVideoResourceJid === resourceJid)
  9033. {
  9034. focusedVideoResourceJid = null;
  9035. // Enable the currently set dominant speaker.
  9036. if (currentDominantSpeaker) {
  9037. if(smallVideo && smallVideo.hasVideo())
  9038. {
  9039. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  9040. }
  9041. }
  9042. if (!noPinnedEndpointChangedEvent) {
  9043. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  9044. }
  9045. return;
  9046. }
  9047. // Lock new video
  9048. focusedVideoResourceJid = resourceJid;
  9049. // Update focused/pinned interface.
  9050. if (resourceJid)
  9051. {
  9052. if(smallVideo)
  9053. smallVideo.focus(true);
  9054. if (!noPinnedEndpointChangedEvent) {
  9055. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  9056. }
  9057. }
  9058. // Triggers a "video.selected" event. The "false" parameter indicates
  9059. // this isn't a prezi.
  9060. $(document).trigger("video.selected", [false]);
  9061. LargeVideo.updateLargeVideo(resourceJid);
  9062. // Writing volume not allowed in IE
  9063. if (!RTCBrowserType.isIExplorer()) {
  9064. $('audio').each(function (idx, el) {
  9065. el.volume = 0;
  9066. el.volume = 1;
  9067. });
  9068. }
  9069. };
  9070. /**
  9071. * Checks if container for participant identified by given peerJid exists
  9072. * in the document and creates it eventually.
  9073. *
  9074. * @param peerJid peer Jid to check.
  9075. *
  9076. * @return Returns <tt>true</tt> if the peer container exists,
  9077. * <tt>false</tt> - otherwise
  9078. */
  9079. my.ensurePeerContainerExists = function(peerJid) {
  9080. ContactList.ensureAddContact(peerJid);
  9081. var resourceJid = Strophe.getResourceFromJid(peerJid);
  9082. if(!remoteVideos[resourceJid])
  9083. {
  9084. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  9085. // In case this is not currently in the last n we don't show it.
  9086. if (localLastNCount
  9087. && localLastNCount > 0
  9088. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  9089. remoteVideos[resourceJid].showPeerContainer('hide');
  9090. }
  9091. else
  9092. VideoLayout.resizeThumbnails();
  9093. }
  9094. };
  9095. my.inputDisplayNameHandler = function (name) {
  9096. localVideoThumbnail.inputDisplayNameHandler(name);
  9097. };
  9098. my.videoactive = function (videoelem, resourceJid) {
  9099. console.info(resourceJid + " video is now active");
  9100. videoelem.show();
  9101. VideoLayout.resizeThumbnails();
  9102. // Update the large video to the last added video only if there's no
  9103. // current dominant, focused speaker or prezi playing or update it to
  9104. // the current dominant speaker.
  9105. if ((!focusedVideoResourceJid &&
  9106. !currentDominantSpeaker &&
  9107. !require("../prezi/Prezi").isPresentationVisible()) ||
  9108. focusedVideoResourceJid === resourceJid ||
  9109. (resourceJid &&
  9110. currentDominantSpeaker === resourceJid)) {
  9111. LargeVideo.updateLargeVideo(resourceJid, true);
  9112. }
  9113. }
  9114. /**
  9115. * Shows the presence status message for the given video.
  9116. */
  9117. my.setPresenceStatus = function (resourceJid, statusMsg) {
  9118. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  9119. };
  9120. /**
  9121. * Shows a visual indicator for the moderator of the conference.
  9122. */
  9123. my.showModeratorIndicator = function () {
  9124. var isModerator = APP.xmpp.isModerator();
  9125. if (isModerator) {
  9126. localVideoThumbnail.createModeratorIndicatorElement();
  9127. }
  9128. var members = APP.xmpp.getMembers();
  9129. Object.keys(members).forEach(function (jid) {
  9130. if (Strophe.getResourceFromJid(jid) === 'focus') {
  9131. // Skip server side focus
  9132. return;
  9133. }
  9134. var resourceJid = Strophe.getResourceFromJid(jid);
  9135. var member = members[jid];
  9136. if (member.role === 'moderator') {
  9137. remoteVideos[resourceJid].removeRemoteVideoMenu();
  9138. remoteVideos[resourceJid].createModeratorIndicatorElement();
  9139. } else if (isModerator) {
  9140. // We are moderator, but user is not - add menu
  9141. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  9142. remoteVideos[resourceJid].addRemoteVideoMenu();
  9143. }
  9144. }
  9145. });
  9146. };
  9147. /*
  9148. * Shows or hides the audio muted indicator over the local thumbnail video.
  9149. * @param {boolean} isMuted
  9150. */
  9151. my.showLocalAudioIndicator = function(isMuted) {
  9152. localVideoThumbnail.showAudioIndicator(isMuted);
  9153. };
  9154. /**
  9155. * Resizes the large video container.
  9156. */
  9157. my.resizeLargeVideoContainer = function () {
  9158. LargeVideo.resize();
  9159. VideoLayout.resizeThumbnails();
  9160. LargeVideo.position();
  9161. };
  9162. /**
  9163. * Resizes thumbnails.
  9164. */
  9165. my.resizeThumbnails = function(animate) {
  9166. var videoSpaceWidth = $('#remoteVideos').width();
  9167. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  9168. var width = thumbnailSize[0];
  9169. var height = thumbnailSize[1];
  9170. $('.userAvatar').css('left', (width - height) / 2);
  9171. if(animate)
  9172. {
  9173. $('#remoteVideos').animate({
  9174. height: height
  9175. },
  9176. {
  9177. queue: false,
  9178. duration: 500
  9179. });
  9180. $('#remoteVideos>span').animate({
  9181. height: height,
  9182. width: width
  9183. },
  9184. {
  9185. queue: false,
  9186. duration: 500,
  9187. complete: function () {
  9188. $(document).trigger(
  9189. "remotevideo.resized",
  9190. [width,
  9191. height]);
  9192. }
  9193. });
  9194. }
  9195. else
  9196. {
  9197. // size videos so that while keeping AR and max height, we have a
  9198. // nice fit
  9199. $('#remoteVideos').height(height);
  9200. $('#remoteVideos>span').width(width);
  9201. $('#remoteVideos>span').height(height);
  9202. $(document).trigger("remotevideo.resized", [width, height]);
  9203. }
  9204. };
  9205. /**
  9206. * Calculates the thumbnail size.
  9207. *
  9208. * @param videoSpaceWidth the width of the video space
  9209. */
  9210. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9211. // Calculate the available height, which is the inner window height minus
  9212. // 39px for the header minus 2px for the delimiter lines on the top and
  9213. // bottom of the large video, minus the 36px space inside the remoteVideos
  9214. // container used for highlighting shadow.
  9215. var availableHeight = 100;
  9216. var numvids = $('#remoteVideos>span:visible').length;
  9217. if (localLastNCount && localLastNCount > 0) {
  9218. numvids = Math.min(localLastNCount + 1, numvids);
  9219. }
  9220. // Remove the 3px borders arround videos and border around the remote
  9221. // videos area and the 4 pixels between the local video and the others
  9222. //TODO: Find out where the 4 pixels come from and remove them
  9223. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9224. var availableWidth = availableWinWidth / numvids;
  9225. var aspectRatio = 16.0 / 9.0;
  9226. var maxHeight = Math.min(160, availableHeight);
  9227. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  9228. if (availableHeight < availableWidth / aspectRatio) {
  9229. availableWidth = Math.floor(availableHeight * aspectRatio);
  9230. }
  9231. return [availableWidth, availableHeight];
  9232. };
  9233. /**
  9234. * Returns the corresponding resource jid to the given peer container
  9235. * DOM element.
  9236. *
  9237. * @return the corresponding resource jid to the given peer container
  9238. * DOM element
  9239. */
  9240. my.getPeerContainerResourceJid = function (containerElement) {
  9241. var i = containerElement.id.indexOf('participant_');
  9242. if (i >= 0)
  9243. return containerElement.id.substring(i + 12);
  9244. };
  9245. my.getPeerVideoSel = function (peerResourceJid) {
  9246. return $('#participant_' + peerResourceJid +
  9247. '>' + APP.RTC.getVideoElementName());
  9248. };
  9249. /**
  9250. * On contact list item clicked.
  9251. */
  9252. $(ContactList).bind('contactclicked', function(event, jid) {
  9253. if (!jid) {
  9254. return;
  9255. }
  9256. if (jid === APP.xmpp.myJid()) {
  9257. $("#localVideoContainer").click();
  9258. return;
  9259. }
  9260. var resource = Strophe.getResourceFromJid(jid);
  9261. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9262. if (videoSel.length > 0) {
  9263. var videoThumb = videoSel[0];
  9264. // It is not always the case that a videoThumb exists (if there is
  9265. // no actual video).
  9266. if (RTC.getVideoSrc(videoThumb)) {
  9267. // We have a video src, great! Let's update the large video
  9268. // now.
  9269. VideoLayout.handleVideoThumbClicked(
  9270. false,
  9271. Strophe.getResourceFromJid(jid));
  9272. } else {
  9273. // If we don't have a video src for jid, there's absolutely
  9274. // no point in calling handleVideoThumbClicked; Quite
  9275. // simply, it won't work because it needs an src to attach
  9276. // to the large video.
  9277. //
  9278. // Instead, we trigger the pinned endpoint changed event to
  9279. // let the bridge adjust its lastN set for myjid and store
  9280. // the pinned user in the lastNPickupJid variable to be
  9281. // picked up later by the lastN changed event handler.
  9282. lastNPickupJid = jid;
  9283. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9284. Strophe.getResourceFromJid(jid));
  9285. }
  9286. }
  9287. });
  9288. /**
  9289. * On audio muted event.
  9290. */
  9291. my.onAudioMute = function (jid, isMuted) {
  9292. var resourceJid = Strophe.getResourceFromJid(jid);
  9293. if (resourceJid === APP.xmpp.myResource()) {
  9294. localVideoThumbnail.showAudioIndicator(isMuted);
  9295. } else {
  9296. VideoLayout.ensurePeerContainerExists(jid);
  9297. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9298. if (APP.xmpp.isModerator()) {
  9299. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9300. }
  9301. }
  9302. };
  9303. /**
  9304. * On video muted event.
  9305. */
  9306. my.onVideoMute = function (jid, value) {
  9307. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  9308. return;
  9309. if (jid === APP.xmpp.myJid()) {
  9310. localVideoThumbnail.showVideoIndicator(value);
  9311. } else {
  9312. var resource = Strophe.getResourceFromJid(jid);
  9313. VideoLayout.ensurePeerContainerExists(jid);
  9314. remoteVideos[resource].showVideoIndicator(value);
  9315. var el = VideoLayout.getPeerVideoSel(resource);
  9316. if (!value)
  9317. el.show();
  9318. else
  9319. el.hide();
  9320. }
  9321. };
  9322. /**
  9323. * Display name changed.
  9324. */
  9325. my.onDisplayNameChanged =
  9326. function (jid, displayName, status) {
  9327. if (jid === 'localVideoContainer'
  9328. || jid === APP.xmpp.myJid()) {
  9329. localVideoThumbnail.setDisplayName(displayName);
  9330. } else {
  9331. VideoLayout.ensurePeerContainerExists(jid);
  9332. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9333. displayName,
  9334. status);
  9335. }
  9336. };
  9337. /**
  9338. * On dominant speaker changed event.
  9339. */
  9340. my.onDominantSpeakerChanged = function (resourceJid) {
  9341. // We ignore local user events.
  9342. if (resourceJid === APP.xmpp.myResource())
  9343. return;
  9344. var members = APP.xmpp.getMembers();
  9345. // Update the current dominant speaker.
  9346. if (resourceJid !== currentDominantSpeaker) {
  9347. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9348. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9349. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9350. !members[currentJID].displayName)) {
  9351. remoteVideos[resourceJid].setDisplayName(null);
  9352. }
  9353. if(resourceJid && (!members || !members[newJID] ||
  9354. !members[newJID].displayName)) {
  9355. remoteVideos[resourceJid].setDisplayName(null,
  9356. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9357. }
  9358. currentDominantSpeaker = resourceJid;
  9359. } else {
  9360. return;
  9361. }
  9362. // Obtain container for new dominant speaker.
  9363. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9364. // Local video will not have container found, but that's ok
  9365. // since we don't want to switch to local video.
  9366. if (!focusedVideoResourceJid && videoSel.length)
  9367. {
  9368. // Update the large video if the video source is already available,
  9369. // otherwise wait for the "videoactive.jingle" event.
  9370. if (videoSel[0].currentTime > 0) {
  9371. LargeVideo.updateLargeVideo(resourceJid);
  9372. }
  9373. }
  9374. };
  9375. /**
  9376. * On last N change event.
  9377. *
  9378. * @param lastNEndpoints the list of last N endpoints
  9379. * @param endpointsEnteringLastN the list currently entering last N
  9380. * endpoints
  9381. */
  9382. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  9383. endpointsEnteringLastN,
  9384. stream) {
  9385. if (lastNCount !== lastNEndpoints.length)
  9386. lastNCount = lastNEndpoints.length;
  9387. lastNEndpointsCache = lastNEndpoints;
  9388. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9389. //
  9390. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9391. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9392. // so E sees them. C is only in E's local LastN set.
  9393. //
  9394. // If F starts talking and LastN = 3, then E should see thumbnails for
  9395. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9396. // enters E's local LastN ejecting C.
  9397. // Increase the local LastN set size, if necessary.
  9398. if (lastNCount > localLastNCount) {
  9399. localLastNCount = lastNCount;
  9400. }
  9401. // Update the local LastN set preserving the order in which the
  9402. // endpoints appeared in the LastN/local LastN set.
  9403. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9404. for (var i = 0; i < localLastNSet.length; i++) {
  9405. if (nextLocalLastNSet.length >= localLastNCount) {
  9406. break;
  9407. }
  9408. var resourceJid = localLastNSet[i];
  9409. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9410. nextLocalLastNSet.push(resourceJid);
  9411. }
  9412. }
  9413. localLastNSet = nextLocalLastNSet;
  9414. var updateLargeVideo = false;
  9415. // Handle LastN/local LastN changes.
  9416. $('#remoteVideos>span').each(function( index, element ) {
  9417. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9418. var isReceived = true;
  9419. if (resourceJid
  9420. && lastNEndpoints.indexOf(resourceJid) < 0
  9421. && localLastNSet.indexOf(resourceJid) < 0) {
  9422. console.log("Remove from last N", resourceJid);
  9423. remoteVideos[resourceJid].showPeerContainer('hide');
  9424. isReceived = false;
  9425. } else if (resourceJid
  9426. && $('#participant_' + resourceJid).is(':visible')
  9427. && lastNEndpoints.indexOf(resourceJid) < 0
  9428. && localLastNSet.indexOf(resourceJid) >= 0) {
  9429. remoteVideos[resourceJid].showPeerContainer('avatar');
  9430. isReceived = false;
  9431. }
  9432. if (!isReceived) {
  9433. // resourceJid has dropped out of the server side lastN set, so
  9434. // it is no longer being received. If resourceJid was being
  9435. // displayed in the large video we have to switch to another
  9436. // user.
  9437. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  9438. updateLargeVideo = true;
  9439. }
  9440. }
  9441. });
  9442. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9443. endpointsEnteringLastN = lastNEndpoints;
  9444. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9445. endpointsEnteringLastN.forEach(function (resourceJid) {
  9446. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9447. remoteVideos[resourceJid].showPeerContainer('show');
  9448. if (!isVisible) {
  9449. console.log("Add to last N", resourceJid);
  9450. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9451. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9452. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9453. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9454. if (lastNPickupJid == mediaStream.peerjid) {
  9455. // Clean up the lastN pickup jid.
  9456. lastNPickupJid = null;
  9457. // Don't fire the events again, they've already
  9458. // been fired in the contact list click handler.
  9459. VideoLayout.handleVideoThumbClicked(
  9460. false,
  9461. Strophe.getResourceFromJid(mediaStream.peerjid));
  9462. updateLargeVideo = false;
  9463. }
  9464. remoteVideos[resourceJid].waitForPlayback(sel, mediaStream.stream);
  9465. }
  9466. });
  9467. }
  9468. // The endpoint that was being shown in the large video has dropped out
  9469. // of the lastN set and there was no lastN pickup jid. We need to update
  9470. // the large video now.
  9471. if (updateLargeVideo) {
  9472. var resource, container, src;
  9473. var myResource
  9474. = APP.xmpp.myResource();
  9475. // Find out which endpoint to show in the large video.
  9476. for (var i = 0; i < lastNEndpoints.length; i++) {
  9477. resource = lastNEndpoints[i];
  9478. if (!resource || resource === myResource)
  9479. continue;
  9480. // videoSrcToSsrc needs to be update for this call to succeed.
  9481. LargeVideo.updateLargeVideo(resource);
  9482. break;
  9483. }
  9484. }
  9485. };
  9486. /**
  9487. * Updates local stats
  9488. * @param percent
  9489. * @param object
  9490. */
  9491. my.updateLocalConnectionStats = function (percent, object) {
  9492. var resolution = null;
  9493. if(object.resolution !== null)
  9494. {
  9495. resolution = object.resolution;
  9496. object.resolution = resolution[APP.xmpp.myJid()];
  9497. delete resolution[APP.xmpp.myJid()];
  9498. }
  9499. localVideoThumbnail.updateStatsIndicator(percent, object);
  9500. for(var jid in resolution)
  9501. {
  9502. if(resolution[jid] === null)
  9503. continue;
  9504. var resourceJid = Strophe.getResourceFromJid(jid);
  9505. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  9506. {
  9507. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  9508. }
  9509. }
  9510. };
  9511. /**
  9512. * Updates remote stats.
  9513. * @param jid the jid associated with the stats
  9514. * @param percent the connection quality percent
  9515. * @param object the stats data
  9516. */
  9517. my.updateConnectionStats = function (jid, percent, object) {
  9518. var resourceJid = Strophe.getResourceFromJid(jid);
  9519. if(remoteVideos[resourceJid])
  9520. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9521. };
  9522. /**
  9523. * Hides the connection indicator
  9524. * @param jid
  9525. */
  9526. my.hideConnectionIndicator = function (jid) {
  9527. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9528. };
  9529. /**
  9530. * Hides all the indicators
  9531. */
  9532. my.onStatsStop = function () {
  9533. for(var video in remoteVideos)
  9534. {
  9535. remoteVideos[video].hideIndicator();
  9536. }
  9537. localVideoThumbnail.hideIndicator();
  9538. };
  9539. my.participantLeft = function (jid) {
  9540. // Unlock large video
  9541. var resourceJid = Strophe.getResourceFromJid(jid);
  9542. if (focusedVideoResourceJid === resourceJid)
  9543. {
  9544. console.info("Focused video owner has left the conference");
  9545. focusedVideoResourceJid = null;
  9546. }
  9547. if (currentDominantSpeaker === resourceJid)
  9548. {
  9549. console.info("Dominant speaker has left the conference");
  9550. currentDominantSpeaker = null;
  9551. }
  9552. var remoteVideo = remoteVideos[resourceJid];
  9553. if (remoteVideo) {
  9554. remoteVideo.removeConnectionIndicator();
  9555. // Remove remote video
  9556. delete remoteVideos[resourceJid];
  9557. } else {
  9558. console.warn("No remote video for " + resourceJid);
  9559. }
  9560. VideoLayout.resizeThumbnails();
  9561. };
  9562. my.onVideoTypeChanged = function (jid) {
  9563. LargeVideo.onVideoTypeChanged(jid);
  9564. };
  9565. my.showMore = function (jid) {
  9566. if (jid === 'local')
  9567. {
  9568. localVideoThumbnail.connectionIndicator.showMore();
  9569. }
  9570. else
  9571. {
  9572. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9573. if (remoteVideo) {
  9574. remoteVideo.connectionIndicator.showMore();
  9575. } else {
  9576. console.info("Error - no remote video for jid: " + jid);
  9577. }
  9578. }
  9579. };
  9580. my.addPreziContainer = function (id) {
  9581. return RemoteVideo.createContainer(id);
  9582. };
  9583. my.setLargeVideoVisible = function (isVisible) {
  9584. LargeVideo.setLargeVideoVisible(isVisible);
  9585. if(!isVisible && focusedVideoResourceJid)
  9586. {
  9587. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9588. if(smallVideo)
  9589. smallVideo.focus(false);
  9590. smallVideo.showAvatar();
  9591. focusedVideoResourceJid = null;
  9592. }
  9593. };
  9594. /**
  9595. * Resizes the video area
  9596. * @param completeFunction a function to be called when the video space is resized
  9597. */
  9598. my.resizeVideoArea = function(isVisible, completeFunction) {
  9599. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  9600. VideoLayout.resizeThumbnails(true);
  9601. };
  9602. my.getSmallVideo = function (resourceJid) {
  9603. if(resourceJid == APP.xmpp.myResource())
  9604. {
  9605. return localVideoThumbnail;
  9606. }
  9607. else
  9608. {
  9609. if(!remoteVideos[resourceJid])
  9610. return null;
  9611. return remoteVideos[resourceJid];
  9612. }
  9613. };
  9614. my.userAvatarChanged = function(resourceJid, thumbUrl)
  9615. {
  9616. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9617. if(smallVideo)
  9618. smallVideo.avatarChanged(thumbUrl);
  9619. else
  9620. console.warn(
  9621. "Missed avatar update - no small video yet for " + resourceJid);
  9622. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9623. };
  9624. return my;
  9625. }(VideoLayout || {}));
  9626. module.exports = VideoLayout;
  9627. },{"../../../service/RTC/MediaStreamTypes":100,"../../../service/UI/UIEvents":104,"../../RTC/RTC":9,"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"../prezi/Prezi":20,"../side_pannels/contactlist/ContactList":27,"./LargeVideo":37,"./LocalVideo":38,"./RemoteVideo":39}],42:[function(require,module,exports){
  9628. //var nouns = [
  9629. //];
  9630. var pluralNouns = [
  9631. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9632. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9633. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9634. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9635. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9636. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9637. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9638. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9639. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9640. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9641. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9642. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9643. ];
  9644. //var places = [
  9645. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9646. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9647. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9648. // "Bridge"
  9649. //];
  9650. var verbs = [
  9651. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9652. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9653. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9654. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9655. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9656. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9657. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9658. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9659. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9660. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9661. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9662. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9663. ];
  9664. var adverbs = [
  9665. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9666. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9667. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9668. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9669. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9670. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9671. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9672. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9673. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9674. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9675. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9676. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9677. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9678. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9679. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9680. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9681. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9682. ];
  9683. var adjectives = [
  9684. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9685. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9686. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9687. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9688. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9689. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9690. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9691. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9692. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9693. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9694. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9695. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9696. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9697. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9698. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9699. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9700. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9701. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9702. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9703. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9704. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9705. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9706. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9707. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9708. "Zealous"
  9709. ];
  9710. //var pronouns = [
  9711. //];
  9712. //var conjunctions = [
  9713. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9714. //];
  9715. /*
  9716. * Maps a string (category name) to the array of words from that category.
  9717. */
  9718. var CATEGORIES =
  9719. {
  9720. //"_NOUN_": nouns,
  9721. "_PLURALNOUN_": pluralNouns,
  9722. //"_PLACE_": places,
  9723. "_VERB_": verbs,
  9724. "_ADVERB_": adverbs,
  9725. "_ADJECTIVE_": adjectives
  9726. //"_PRONOUN_": pronouns,
  9727. //"_CONJUNCTION_": conjunctions,
  9728. };
  9729. var PATTERNS = [
  9730. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9731. // BeautifulFungiOrSpaghetti
  9732. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9733. // AmazinglyScaryToy
  9734. //"_ADVERB__ADJECTIVE__NOUN_",
  9735. // NeitherTrashNorRifle
  9736. //"Neither_NOUN_Nor_NOUN_",
  9737. //"Either_NOUN_Or_NOUN_",
  9738. // EitherCopulateOrInvestigate
  9739. //"Either_VERB_Or_VERB_",
  9740. //"Neither_VERB_Nor_VERB_",
  9741. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9742. //"The_ADVERB__ADJECTIVE__NOUN_",
  9743. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9744. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9745. // WolvesComputeBadly
  9746. //"_PLURALNOUN__VERB__ADVERB_",
  9747. // UniteFacilitateAndMerge
  9748. //"_VERB__VERB_And_VERB_",
  9749. //NastyWitchesAtThePub
  9750. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9751. ];
  9752. /*
  9753. * Returns a random element from the array 'arr'
  9754. */
  9755. function randomElement(arr)
  9756. {
  9757. return arr[Math.floor(Math.random() * arr.length)];
  9758. }
  9759. /*
  9760. * Returns true if the string 's' contains one of the
  9761. * template strings.
  9762. */
  9763. function hasTemplate(s)
  9764. {
  9765. for (var template in CATEGORIES){
  9766. if (s.indexOf(template) >= 0){
  9767. return true;
  9768. }
  9769. }
  9770. }
  9771. /**
  9772. * Generates new room name.
  9773. */
  9774. var RoomNameGenerator = {
  9775. generateRoomWithoutSeparator: function()
  9776. {
  9777. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  9778. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  9779. var name = randomElement(PATTERNS);
  9780. var word;
  9781. while (hasTemplate(name)){
  9782. for (var template in CATEGORIES){
  9783. word = randomElement(CATEGORIES[template]);
  9784. name = name.replace(template, word);
  9785. }
  9786. }
  9787. return name;
  9788. }
  9789. }
  9790. module.exports = RoomNameGenerator;
  9791. },{}],43:[function(require,module,exports){
  9792. var animateTimeout, updateTimeout;
  9793. var RoomNameGenerator = require("./RoomnameGenerator");
  9794. function enter_room()
  9795. {
  9796. var val = $("#enter_room_field").val();
  9797. if(!val) {
  9798. val = $("#enter_room_field").attr("room_name");
  9799. }
  9800. if (val) {
  9801. window.location.pathname = "/" + val;
  9802. }
  9803. }
  9804. function animate(word) {
  9805. var currentVal = $("#enter_room_field").attr("placeholder");
  9806. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9807. animateTimeout = setTimeout(function() {
  9808. animate(word.substring(1, word.length))
  9809. }, 70);
  9810. }
  9811. function update_roomname()
  9812. {
  9813. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9814. $("#enter_room_field").attr("room_name", word);
  9815. $("#enter_room_field").attr("placeholder", "");
  9816. clearTimeout(animateTimeout);
  9817. animate(word);
  9818. updateTimeout = setTimeout(update_roomname, 10000);
  9819. }
  9820. function setupWelcomePage()
  9821. {
  9822. $("#videoconference_page").hide();
  9823. $("#domain_name").text(
  9824. window.location.protocol + "//" + window.location.host + "/");
  9825. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9826. var leftWatermarkDiv
  9827. = $("#welcome_page_header div[class='watermark leftwatermark']");
  9828. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  9829. {
  9830. leftWatermarkDiv.css({display: 'block'});
  9831. leftWatermarkDiv.parent().get(0).href
  9832. = interfaceConfig.JITSI_WATERMARK_LINK;
  9833. }
  9834. }
  9835. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9836. var rightWatermarkDiv
  9837. = $("#welcome_page_header div[class='watermark rightwatermark']");
  9838. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9839. rightWatermarkDiv.css({display: 'block'});
  9840. rightWatermarkDiv.parent().get(0).href
  9841. = interfaceConfig.BRAND_WATERMARK_LINK;
  9842. rightWatermarkDiv.get(0).style.backgroundImage
  9843. = "url(images/rightwatermark.png)";
  9844. }
  9845. }
  9846. if (interfaceConfig.SHOW_POWERED_BY) {
  9847. $("#welcome_page_header>a[class='poweredby']")
  9848. .css({display: 'block'});
  9849. }
  9850. $("#enter_room_button").click(function()
  9851. {
  9852. enter_room();
  9853. });
  9854. $("#enter_room_field").keydown(function (event) {
  9855. if (event.keyCode === 13 /* enter */) {
  9856. enter_room();
  9857. }
  9858. });
  9859. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  9860. var updateTimeout;
  9861. var animateTimeout;
  9862. $("#reload_roomname").click(function () {
  9863. clearTimeout(updateTimeout);
  9864. clearTimeout(animateTimeout);
  9865. update_roomname();
  9866. });
  9867. $("#reload_roomname").show();
  9868. update_roomname();
  9869. }
  9870. $("#disable_welcome").click(function () {
  9871. window.localStorage.welcomePageDisabled
  9872. = $("#disable_welcome").is(":checked");
  9873. });
  9874. }
  9875. module.exports = setupWelcomePage;
  9876. },{"./RoomnameGenerator":42}],44:[function(require,module,exports){
  9877. var params = {};
  9878. function getConfigParamsFromUrl() {
  9879. if(!location.hash)
  9880. return {};
  9881. var hash = location.hash.substr(1);
  9882. var result = {};
  9883. hash.split("&").forEach(function(part) {
  9884. var item = part.split("=");
  9885. result[item[0]] = JSON.parse(
  9886. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9887. });
  9888. return result;
  9889. }
  9890. params = getConfigParamsFromUrl();
  9891. var URLProcessor = {
  9892. setConfigParametersFromUrl: function () {
  9893. for(var k in params)
  9894. {
  9895. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9896. continue;
  9897. var v = params[k];
  9898. var confKey = k.substr(7);
  9899. if(config[confKey] && typeof config[confKey] !== typeof v)
  9900. {
  9901. console.warn("The type of " + k +
  9902. " is wrong. That parameter won't be updated in config.js.");
  9903. continue;
  9904. }
  9905. config[confKey] = v;
  9906. }
  9907. }
  9908. };
  9909. module.exports = URLProcessor;
  9910. },{}],45:[function(require,module,exports){
  9911. var EventEmitter = require("events");
  9912. var eventEmitter = new EventEmitter();
  9913. var CQEvents = require("../../service/connectionquality/CQEvents");
  9914. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9915. /**
  9916. * local stats
  9917. * @type {{}}
  9918. */
  9919. var stats = {};
  9920. /**
  9921. * remote stats
  9922. * @type {{}}
  9923. */
  9924. var remoteStats = {};
  9925. /**
  9926. * Interval for sending statistics to other participants
  9927. * @type {null}
  9928. */
  9929. var sendIntervalId = null;
  9930. /**
  9931. * Start statistics sending.
  9932. */
  9933. function startSendingStats() {
  9934. sendStats();
  9935. sendIntervalId = setInterval(sendStats, 10000);
  9936. }
  9937. /**
  9938. * Sends statistics to other participants
  9939. */
  9940. function sendStats() {
  9941. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9942. }
  9943. /**
  9944. * Converts statistics to format for sending through XMPP
  9945. * @param stats the statistics
  9946. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9947. */
  9948. function convertToMUCStats(stats) {
  9949. return {
  9950. "bitrate_download": stats.bitrate.download,
  9951. "bitrate_upload": stats.bitrate.upload,
  9952. "packetLoss_total": stats.packetLoss.total,
  9953. "packetLoss_download": stats.packetLoss.download,
  9954. "packetLoss_upload": stats.packetLoss.upload
  9955. };
  9956. }
  9957. /**
  9958. * Converts statitistics to format used by VideoLayout
  9959. * @param stats
  9960. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9961. */
  9962. function parseMUCStats(stats) {
  9963. return {
  9964. bitrate: {
  9965. download: stats.bitrate_download,
  9966. upload: stats.bitrate_upload
  9967. },
  9968. packetLoss: {
  9969. total: stats.packetLoss_total,
  9970. download: stats.packetLoss_download,
  9971. upload: stats.packetLoss_upload
  9972. }
  9973. };
  9974. }
  9975. var ConnectionQuality = {
  9976. init: function () {
  9977. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9978. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9979. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9980. },
  9981. /**
  9982. * Updates the local statistics
  9983. * @param data new statistics
  9984. */
  9985. updateLocalStats: function (data) {
  9986. stats = data;
  9987. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9988. if (sendIntervalId == null) {
  9989. startSendingStats();
  9990. }
  9991. },
  9992. /**
  9993. * Updates remote statistics
  9994. * @param jid the jid associated with the statistics
  9995. * @param data the statistics
  9996. */
  9997. updateRemoteStats: function (jid, data) {
  9998. if (data == null || data.packetLoss_total == null) {
  9999. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  10000. return;
  10001. }
  10002. remoteStats[jid] = parseMUCStats(data);
  10003. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  10004. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  10005. },
  10006. /**
  10007. * Stops statistics sending.
  10008. */
  10009. stopSendingStats: function () {
  10010. clearInterval(sendIntervalId);
  10011. sendIntervalId = null;
  10012. //notify UI about stopping statistics gathering
  10013. eventEmitter.emit(CQEvents.STOP);
  10014. },
  10015. /**
  10016. * Returns the local statistics.
  10017. */
  10018. getStats: function () {
  10019. return stats;
  10020. },
  10021. addListener: function (type, listener) {
  10022. eventEmitter.on(type, listener);
  10023. }
  10024. };
  10025. module.exports = ConnectionQuality;
  10026. },{"../../service/connectionquality/CQEvents":106,"../../service/xmpp/XMPPEvents":110,"events":1}],46:[function(require,module,exports){
  10027. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  10028. getUserMediaWithConstraints */
  10029. /**
  10030. * Indicates that desktop stream is currently in use(for toggle purpose).
  10031. * @type {boolean}
  10032. */
  10033. var isUsingScreenStream = false;
  10034. /**
  10035. * Indicates that switch stream operation is in progress and prevent from
  10036. * triggering new events.
  10037. * @type {boolean}
  10038. */
  10039. var switchInProgress = false;
  10040. /**
  10041. * Method used to get screen sharing stream.
  10042. *
  10043. * @type {function (stream_callback, failure_callback}
  10044. */
  10045. var obtainDesktopStream = null;
  10046. /**
  10047. * Indicates whether desktop sharing extension is installed.
  10048. * @type {boolean}
  10049. */
  10050. var extInstalled = false;
  10051. /**
  10052. * Indicates whether update of desktop sharing extension is required.
  10053. * @type {boolean}
  10054. */
  10055. var extUpdateRequired = false;
  10056. var AdapterJS = require("../RTC/adapter.screenshare");
  10057. var EventEmitter = require("events");
  10058. var eventEmitter = new EventEmitter();
  10059. var DesktopSharingEventTypes
  10060. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  10061. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10062. var RTCEvents = require("../../service/RTC/RTCEvents");
  10063. /**
  10064. * Method obtains desktop stream from WebRTC 'screen' source.
  10065. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  10066. */
  10067. function obtainWebRTCScreen(streamCallback, failCallback) {
  10068. APP.RTC.getUserMediaWithConstraints(
  10069. ['screen'],
  10070. streamCallback,
  10071. failCallback
  10072. );
  10073. }
  10074. /**
  10075. * Constructs inline install URL for Chrome desktop streaming extension.
  10076. * The 'chromeExtensionId' must be defined in config.js.
  10077. * @returns {string}
  10078. */
  10079. function getWebStoreInstallUrl()
  10080. {
  10081. return "https://chrome.google.com/webstore/detail/" +
  10082. config.chromeExtensionId;
  10083. }
  10084. /**
  10085. * Checks whether extension update is required.
  10086. * @param minVersion minimal required version
  10087. * @param extVersion current extension version
  10088. * @returns {boolean}
  10089. */
  10090. function isUpdateRequired(minVersion, extVersion)
  10091. {
  10092. try
  10093. {
  10094. var s1 = minVersion.split('.');
  10095. var s2 = extVersion.split('.');
  10096. var len = Math.max(s1.length, s2.length);
  10097. for (var i = 0; i < len; i++)
  10098. {
  10099. var n1 = 0,
  10100. n2 = 0;
  10101. if (i < s1.length)
  10102. n1 = parseInt(s1[i]);
  10103. if (i < s2.length)
  10104. n2 = parseInt(s2[i]);
  10105. if (isNaN(n1) || isNaN(n2))
  10106. {
  10107. return true;
  10108. }
  10109. else if (n1 !== n2)
  10110. {
  10111. return n1 > n2;
  10112. }
  10113. }
  10114. // will happen if boths version has identical numbers in
  10115. // their components (even if one of them is longer, has more components)
  10116. return false;
  10117. }
  10118. catch (e)
  10119. {
  10120. console.error("Failed to parse extension version", e);
  10121. APP.UI.messageHandler.showError("dialog.error",
  10122. "dialog.detectext");
  10123. return true;
  10124. }
  10125. }
  10126. function checkChromeExtInstalled(callback) {
  10127. if (!chrome.runtime) {
  10128. // No API, so no extension for sure
  10129. callback(false, false);
  10130. return;
  10131. }
  10132. chrome.runtime.sendMessage(
  10133. config.chromeExtensionId,
  10134. { getVersion: true },
  10135. function (response) {
  10136. if (!response || !response.version) {
  10137. // Communication failure - assume that no endpoint exists
  10138. console.warn(
  10139. "Extension not installed?: ", chrome.runtime.lastError);
  10140. callback(false, false);
  10141. return;
  10142. }
  10143. // Check installed extension version
  10144. var extVersion = response.version;
  10145. console.log('Extension version is: ' + extVersion);
  10146. var updateRequired
  10147. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10148. callback(!updateRequired, updateRequired);
  10149. }
  10150. );
  10151. }
  10152. function doGetStreamFromExtension(streamCallback, failCallback) {
  10153. // Sends 'getStream' msg to the extension.
  10154. // Extension id must be defined in the config.
  10155. chrome.runtime.sendMessage(
  10156. config.chromeExtensionId,
  10157. { getStream: true, sources: config.desktopSharingSources },
  10158. function (response) {
  10159. if (!response) {
  10160. failCallback(chrome.runtime.lastError);
  10161. return;
  10162. }
  10163. console.log("Response from extension: " + response);
  10164. if (response.streamId) {
  10165. APP.RTC.getUserMediaWithConstraints(
  10166. ['desktop'],
  10167. function (stream) {
  10168. streamCallback(stream);
  10169. },
  10170. failCallback,
  10171. null, null, null,
  10172. response.streamId);
  10173. } else {
  10174. failCallback("Extension failed to get the stream");
  10175. }
  10176. }
  10177. );
  10178. }
  10179. /**
  10180. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10181. * stream for returned stream token.
  10182. */
  10183. function obtainScreenFromExtension(streamCallback, failCallback) {
  10184. if (extInstalled) {
  10185. doGetStreamFromExtension(streamCallback, failCallback);
  10186. } else {
  10187. if (extUpdateRequired) {
  10188. alert(
  10189. 'Jitsi Desktop Streamer requires update. ' +
  10190. 'Changes will take effect after next Chrome restart.');
  10191. }
  10192. chrome.webstore.install(
  10193. getWebStoreInstallUrl(),
  10194. function (arg) {
  10195. console.log("Extension installed successfully", arg);
  10196. extInstalled = true;
  10197. // We need to give a moment for the endpoint to become available
  10198. window.setTimeout(function () {
  10199. doGetStreamFromExtension(streamCallback, failCallback);
  10200. }, 500);
  10201. },
  10202. function (arg) {
  10203. console.log("Failed to install the extension", arg);
  10204. failCallback(arg);
  10205. APP.UI.messageHandler.showError("dialog.error",
  10206. "dialog.failtoinstall");
  10207. }
  10208. );
  10209. }
  10210. }
  10211. /**
  10212. * Call this method to toggle desktop sharing feature.
  10213. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10214. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10215. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10216. * enabled), pass any other string or nothing in order to disable this
  10217. * feature completely.
  10218. */
  10219. function setDesktopSharing(method) {
  10220. obtainDesktopStream = null;
  10221. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10222. // care about 'method' parameter
  10223. if (RTCBrowserType.isTemasysPluginUsed()) {
  10224. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10225. console.info("Screensharing not supported by this plugin version");
  10226. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10227. console.info(
  10228. "Screensharing not available with Temasys plugin on this site");
  10229. } else {
  10230. obtainDesktopStream = obtainWebRTCScreen;
  10231. console.info("Using Temasys plugin for desktop sharing");
  10232. }
  10233. } else if (RTCBrowserType.isChrome()) {
  10234. if (method == "ext") {
  10235. if (RTCBrowserType.getChromeVersion() >= 34) {
  10236. obtainDesktopStream = obtainScreenFromExtension;
  10237. console.info("Using Chrome extension for desktop sharing");
  10238. initChromeExtension();
  10239. } else {
  10240. console.info("Chrome extension not supported until ver 34");
  10241. }
  10242. } else if (method == "webrtc") {
  10243. obtainDesktopStream = obtainWebRTCScreen;
  10244. console.info("Using Chrome WebRTC for desktop sharing");
  10245. }
  10246. }
  10247. if (!obtainDesktopStream) {
  10248. console.info("Desktop sharing disabled");
  10249. }
  10250. }
  10251. /**
  10252. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10253. * config.js to support inline installs. Host site must be selected as main
  10254. * website of published extension.
  10255. */
  10256. function initInlineInstalls()
  10257. {
  10258. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10259. }
  10260. function initChromeExtension() {
  10261. // Initialize Chrome extension inline installs
  10262. initInlineInstalls();
  10263. // Check if extension is installed
  10264. checkChromeExtInstalled(function (installed, updateRequired) {
  10265. extInstalled = installed;
  10266. extUpdateRequired = updateRequired;
  10267. console.info(
  10268. "Chrome extension installed: " + extInstalled +
  10269. " updateRequired: " + extUpdateRequired);
  10270. });
  10271. }
  10272. function getVideoStreamFailed(error) {
  10273. console.error("Failed to obtain the stream to switch to", error);
  10274. switchInProgress = false;
  10275. isUsingScreenStream = false;
  10276. newStreamCreated(null);
  10277. }
  10278. function getDesktopStreamFailed(error) {
  10279. console.error("Failed to obtain the stream to switch to", error);
  10280. switchInProgress = false;
  10281. }
  10282. function streamSwitchDone() {
  10283. switchInProgress = false;
  10284. eventEmitter.emit(
  10285. DesktopSharingEventTypes.SWITCHING_DONE,
  10286. isUsingScreenStream);
  10287. }
  10288. function newStreamCreated(stream)
  10289. {
  10290. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10291. stream, isUsingScreenStream, streamSwitchDone);
  10292. }
  10293. function onEndedHandler(stream) {
  10294. if (!switchInProgress && isUsingScreenStream) {
  10295. APP.desktopsharing.toggleScreenSharing();
  10296. }
  10297. //FIXME: to be verified
  10298. if (stream.removeEventListener) {
  10299. stream.removeEventListener('ended', onEndedHandler);
  10300. } else {
  10301. stream.detachEvent('ended', onEndedHandler);
  10302. }
  10303. }
  10304. // Called when RTC finishes initialization
  10305. function onWebRtcReady() {
  10306. setDesktopSharing(config.desktopSharing);
  10307. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10308. }
  10309. module.exports = {
  10310. isUsingScreenStream: function () {
  10311. return isUsingScreenStream;
  10312. },
  10313. /**
  10314. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10315. * and enabled.
  10316. */
  10317. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10318. init: function () {
  10319. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10320. },
  10321. addListener: function (listener, type)
  10322. {
  10323. eventEmitter.on(type, listener);
  10324. },
  10325. removeListener: function (listener, type) {
  10326. eventEmitter.removeListener(type, listener);
  10327. },
  10328. /*
  10329. * Toggles screen sharing.
  10330. */
  10331. toggleScreenSharing: function () {
  10332. if (switchInProgress || !obtainDesktopStream) {
  10333. console.warn("Switch in progress or no method defined");
  10334. return;
  10335. }
  10336. switchInProgress = true;
  10337. if (!isUsingScreenStream)
  10338. {
  10339. // Switch to desktop stream
  10340. obtainDesktopStream(
  10341. function (stream) {
  10342. // We now use screen stream
  10343. isUsingScreenStream = true;
  10344. // Hook 'ended' event to restore camera
  10345. // when screen stream stops
  10346. //FIXME: to be verified
  10347. if (stream.addEventListener) {
  10348. stream.addEventListener('ended', function () {
  10349. onEndedHandler(stream);
  10350. });
  10351. } else {
  10352. stream.attachEvent('ended', function () {
  10353. onEndedHandler(stream);
  10354. });
  10355. }
  10356. newStreamCreated(stream);
  10357. },
  10358. getDesktopStreamFailed);
  10359. } else {
  10360. // Disable screen stream
  10361. APP.RTC.getUserMediaWithConstraints(
  10362. ['video'],
  10363. function (stream) {
  10364. // We are now using camera stream
  10365. isUsingScreenStream = false;
  10366. newStreamCreated(stream);
  10367. },
  10368. getVideoStreamFailed, config.resolution || '360'
  10369. );
  10370. }
  10371. }
  10372. };
  10373. },{"../../service/RTC/RTCEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],47:[function(require,module,exports){
  10374. //maps keycode to character, id of popover for given function and function
  10375. var shortcuts = {};
  10376. function initShortcutHandlers() {
  10377. shortcuts = {
  10378. 67: {
  10379. character: "C",
  10380. id: "toggleChatPopover",
  10381. function: APP.UI.toggleChat
  10382. },
  10383. 70: {
  10384. character: "F",
  10385. id: "filmstripPopover",
  10386. function: APP.UI.toggleFilmStrip
  10387. },
  10388. 77: {
  10389. character: "M",
  10390. id: "mutePopover",
  10391. function: APP.UI.toggleAudio
  10392. },
  10393. 84: {
  10394. character: "T",
  10395. function: function() {
  10396. if(!APP.RTC.localAudio.isMuted()) {
  10397. APP.UI.toggleAudio();
  10398. }
  10399. }
  10400. },
  10401. 86: {
  10402. character: "V",
  10403. id: "toggleVideoPopover",
  10404. function: APP.UI.toggleVideo
  10405. }
  10406. };
  10407. }
  10408. var KeyboardShortcut = {
  10409. init: function () {
  10410. initShortcutHandlers();
  10411. window.onkeyup = function(e) {
  10412. var keycode = e.which;
  10413. if(!($(":focus").is("input[type=text]") ||
  10414. $(":focus").is("input[type=password]") ||
  10415. $(":focus").is("textarea"))) {
  10416. if (typeof shortcuts[keycode] === "object") {
  10417. shortcuts[keycode].function();
  10418. }
  10419. else if (keycode >= "0".charCodeAt(0) &&
  10420. keycode <= "9".charCodeAt(0)) {
  10421. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10422. }
  10423. //esc while the smileys are visible hides them
  10424. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10425. APP.UI.toggleSmileys();
  10426. }
  10427. };
  10428. window.onkeydown = function(e) {
  10429. if(!($(":focus").is("input[type=text]") ||
  10430. $(":focus").is("input[type=password]") ||
  10431. $(":focus").is("textarea"))) {
  10432. if(e.which === "T".charCodeAt(0)) {
  10433. if(APP.RTC.localAudio.isMuted()) {
  10434. APP.UI.toggleAudio();
  10435. }
  10436. }
  10437. }
  10438. };
  10439. var self = this;
  10440. $('body').popover({ selector: '[data-toggle=popover]',
  10441. trigger: 'click hover',
  10442. content: function() {
  10443. return this.getAttribute("content") +
  10444. self.getShortcut(this.getAttribute("shortcut"));
  10445. }
  10446. });
  10447. },
  10448. /**
  10449. *
  10450. * @param id indicates the popover associated with the shortcut
  10451. * @returns {string} the keyboard shortcut used for the id given
  10452. */
  10453. getShortcut: function (id) {
  10454. for (var keycode in shortcuts) {
  10455. if (shortcuts.hasOwnProperty(keycode)) {
  10456. if (shortcuts[keycode].id === id) {
  10457. return " (" + shortcuts[keycode].character + ")";
  10458. }
  10459. }
  10460. }
  10461. return "";
  10462. }
  10463. };
  10464. module.exports = KeyboardShortcut;
  10465. },{}],48:[function(require,module,exports){
  10466. /* global APP */
  10467. /**
  10468. * This module is meant to (eventually) contain and manage all information
  10469. * about members/participants of the conference, so that other modules don't
  10470. * have to do it on their own, and so that other modules can access members'
  10471. * information from a single place.
  10472. *
  10473. * Currently this module only manages information about the support of jingle
  10474. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10475. * be added as needed.
  10476. */
  10477. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10478. var Events = require("../../service/members/Events");
  10479. var EventEmitter = require("events");
  10480. var eventEmitter = new EventEmitter();
  10481. /**
  10482. * The actual container.
  10483. */
  10484. var members = {};
  10485. /**
  10486. * There is at least one member that supports DTMF (i.e. is jigasi).
  10487. */
  10488. var atLeastOneDtmf = false;
  10489. function registerListeners() {
  10490. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10491. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10492. }
  10493. /**
  10494. * Handles a new member joining the MUC.
  10495. */
  10496. function onMucMemberJoined(jid, id, displayName) {
  10497. var member = {
  10498. displayName: displayName
  10499. };
  10500. APP.xmpp.getConnection().disco.info(
  10501. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10502. members[jid] = member;
  10503. }
  10504. /**
  10505. * Handles a member leaving the MUC.
  10506. */
  10507. function onMucMemberLeft(jid) {
  10508. delete members[jid];
  10509. updateAtLeastOneDtmf();
  10510. }
  10511. /**
  10512. * Handles the reception of a disco#info packet from a particular JID.
  10513. * @param jid the JID sending the packet.
  10514. * @param iq the packet.
  10515. */
  10516. function onDiscoInfoReceived(jid, iq) {
  10517. if (!members[jid])
  10518. return;
  10519. var supportsDtmf
  10520. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10521. updateDtmf(jid, supportsDtmf);
  10522. }
  10523. /**
  10524. * Updates the 'supportsDtmf' field for a member.
  10525. * @param jid the jid of the member.
  10526. * @param newValue the new value for the 'supportsDtmf' field.
  10527. */
  10528. function updateDtmf(jid, newValue) {
  10529. var oldValue = members[jid].supportsDtmf;
  10530. members[jid].supportsDtmf = newValue;
  10531. if (newValue != oldValue) {
  10532. updateAtLeastOneDtmf();
  10533. }
  10534. }
  10535. /**
  10536. * Checks each member's 'supportsDtmf' field and updates
  10537. * 'atLastOneSupportsDtmf'.
  10538. */
  10539. function updateAtLeastOneDtmf(){
  10540. var newAtLeastOneDtmf = false;
  10541. for (var key in members) {
  10542. if (typeof members[key].supportsDtmf !== 'undefined'
  10543. && members[key].supportsDtmf) {
  10544. newAtLeastOneDtmf= true;
  10545. break;
  10546. }
  10547. }
  10548. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10549. atLeastOneDtmf = newAtLeastOneDtmf;
  10550. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10551. }
  10552. }
  10553. /**
  10554. * Exported interface.
  10555. */
  10556. var Members = {
  10557. start: function(){
  10558. registerListeners();
  10559. },
  10560. addListener: function(type, listener)
  10561. {
  10562. eventEmitter.on(type, listener);
  10563. },
  10564. removeListener: function (type, listener) {
  10565. eventEmitter.removeListener(type, listener);
  10566. },
  10567. size: function () {
  10568. return Object.keys(members).length;
  10569. },
  10570. getMembers: function () {
  10571. return members;
  10572. }
  10573. };
  10574. module.exports = Members;
  10575. },{"../../service/members/Events":108,"../../service/xmpp/XMPPEvents":110,"events":1}],49:[function(require,module,exports){
  10576. var email = '';
  10577. var displayName = '';
  10578. var userId;
  10579. var language = null;
  10580. function supportsLocalStorage() {
  10581. try {
  10582. return 'localStorage' in window && window.localStorage !== null;
  10583. } catch (e) {
  10584. console.log("localstorage is not supported");
  10585. return false;
  10586. }
  10587. }
  10588. function generateUniqueId() {
  10589. function _p8() {
  10590. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10591. }
  10592. return _p8() + _p8() + _p8() + _p8();
  10593. }
  10594. if (supportsLocalStorage()) {
  10595. if (!window.localStorage.jitsiMeetId) {
  10596. window.localStorage.jitsiMeetId = generateUniqueId();
  10597. console.log("generated id", window.localStorage.jitsiMeetId);
  10598. }
  10599. userId = window.localStorage.jitsiMeetId || '';
  10600. email = window.localStorage.email || '';
  10601. displayName = window.localStorage.displayname || '';
  10602. language = window.localStorage.language;
  10603. } else {
  10604. console.log("local storage is not supported");
  10605. userId = generateUniqueId();
  10606. }
  10607. var Settings =
  10608. {
  10609. setDisplayName: function (newDisplayName) {
  10610. displayName = newDisplayName;
  10611. window.localStorage.displayname = displayName;
  10612. return displayName;
  10613. },
  10614. setEmail: function (newEmail)
  10615. {
  10616. email = newEmail;
  10617. window.localStorage.email = newEmail;
  10618. return email;
  10619. },
  10620. getSettings: function () {
  10621. return {
  10622. email: email,
  10623. displayName: displayName,
  10624. uid: userId,
  10625. language: language
  10626. };
  10627. },
  10628. setLanguage: function (lang) {
  10629. language = lang;
  10630. window.localStorage.language = lang;
  10631. }
  10632. };
  10633. module.exports = Settings;
  10634. },{}],50:[function(require,module,exports){
  10635. var callStats = null;
  10636. function initCallback (err, msg) {
  10637. console.log("Initializing Status: err="+err+" msg="+msg);
  10638. }
  10639. var CallStats = {
  10640. init: function (jingleSession) {
  10641. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10642. return;
  10643. callStats = new callstats($,io,jsSHA);
  10644. this.session = jingleSession;
  10645. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10646. this.userID = APP.xmpp.myResource();
  10647. var location = window.location;
  10648. this.confID = location.protocol + "//" +
  10649. location.hostname + location.pathname;
  10650. //userID is generated or given by the origin server
  10651. callStats.initialize(config.callStatsID,
  10652. config.callStatsSecret,
  10653. this.userID,
  10654. initCallback);
  10655. var usage = callStats.fabricUsage.unbundled;
  10656. if(config.useBundle)
  10657. usage = callStats.fabricUsage.multiplex;
  10658. callStats.addNewFabric(this.peerconnection,
  10659. Strophe.getResourceFromJid(jingleSession.peerjid),
  10660. usage,
  10661. this.confID,
  10662. this.pcCallback.bind(this));
  10663. },
  10664. pcCallback: function (err, msg) {
  10665. if(!callStats)
  10666. return;
  10667. console.log("Monitoring status: "+ err + " msg: " + msg);
  10668. callStats.sendFabricEvent(this.peerconnection,
  10669. callStats.fabricEvent.fabricSetup, this.confID);
  10670. },
  10671. sendMuteEvent: function (mute, type) {
  10672. if(!callStats)
  10673. return;
  10674. var event = null;
  10675. if(type === "video")
  10676. {
  10677. event = (mute? callStats.fabricEvent.videoPause :
  10678. callStats.fabricEvent.videoResume);
  10679. }
  10680. else
  10681. {
  10682. event = (mute? callStats.fabricEvent.audioMute :
  10683. callStats.fabricEvent.audioUnmute);
  10684. }
  10685. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10686. },
  10687. sendTerminateEvent: function () {
  10688. if(!callStats)
  10689. return;
  10690. callStats.sendFabricEvent(this.peerconnection,
  10691. callStats.fabricEvent.fabricTerminated, this.confID);
  10692. },
  10693. sendSetupFailedEvent: function () {
  10694. if(!callStats)
  10695. return;
  10696. callStats.sendFabricEvent(this.peerconnection,
  10697. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10698. }
  10699. };
  10700. module.exports = CallStats;
  10701. },{}],51:[function(require,module,exports){
  10702. /**
  10703. * Provides statistics for the local stream.
  10704. */
  10705. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10706. /**
  10707. * Size of the webaudio analizer buffer.
  10708. * @type {number}
  10709. */
  10710. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10711. /**
  10712. * Value of the webaudio analizer smoothing time parameter.
  10713. * @type {number}
  10714. */
  10715. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10716. /**
  10717. * Converts time domain data array to audio level.
  10718. * @param array the time domain data array.
  10719. * @returns {number} the audio level
  10720. */
  10721. function timeDomainDataToAudioLevel(samples) {
  10722. var maxVolume = 0;
  10723. var length = samples.length;
  10724. for (var i = 0; i < length; i++) {
  10725. if (maxVolume < samples[i])
  10726. maxVolume = samples[i];
  10727. }
  10728. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10729. };
  10730. /**
  10731. * Animates audio level change
  10732. * @param newLevel the new audio level
  10733. * @param lastLevel the last audio level
  10734. * @returns {Number} the audio level to be set
  10735. */
  10736. function animateLevel(newLevel, lastLevel)
  10737. {
  10738. var value = 0;
  10739. var diff = lastLevel - newLevel;
  10740. if(diff > 0.2)
  10741. {
  10742. value = lastLevel - 0.2;
  10743. }
  10744. else if(diff < -0.4)
  10745. {
  10746. value = lastLevel + 0.4;
  10747. }
  10748. else
  10749. {
  10750. value = newLevel;
  10751. }
  10752. return parseFloat(value.toFixed(3));
  10753. }
  10754. /**
  10755. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10756. *
  10757. * @param stream the local stream
  10758. * @param interval stats refresh interval given in ms.
  10759. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10760. * update.
  10761. * @constructor
  10762. */
  10763. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10764. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10765. this.stream = stream;
  10766. this.intervalId = null;
  10767. this.intervalMilis = interval;
  10768. this.eventEmitter = eventEmitter;
  10769. this.audioLevel = 0;
  10770. this.statisticsService = statisticsService;
  10771. }
  10772. /**
  10773. * Starts the collecting the statistics.
  10774. */
  10775. LocalStatsCollector.prototype.start = function () {
  10776. if (config.disableAudioLevels || !window.AudioContext
  10777. || RTCBrowserType.isTemasysPluginUsed())
  10778. return;
  10779. var context = new AudioContext();
  10780. var analyser = context.createAnalyser();
  10781. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10782. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10783. var source = context.createMediaStreamSource(this.stream);
  10784. source.connect(analyser);
  10785. var self = this;
  10786. this.intervalId = setInterval(
  10787. function () {
  10788. var array = new Uint8Array(analyser.frequencyBinCount);
  10789. analyser.getByteTimeDomainData(array);
  10790. var audioLevel = timeDomainDataToAudioLevel(array);
  10791. if(audioLevel != self.audioLevel) {
  10792. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10793. self.eventEmitter.emit(
  10794. "statistics.audioLevel",
  10795. self.statisticsService.LOCAL_JID,
  10796. self.audioLevel);
  10797. }
  10798. },
  10799. this.intervalMilis
  10800. );
  10801. };
  10802. /**
  10803. * Stops collecting the statistics.
  10804. */
  10805. LocalStatsCollector.prototype.stop = function () {
  10806. if (this.intervalId) {
  10807. clearInterval(this.intervalId);
  10808. this.intervalId = null;
  10809. }
  10810. };
  10811. module.exports = LocalStatsCollector;
  10812. },{"../RTC/RTCBrowserType":10}],52:[function(require,module,exports){
  10813. /* global ssrc2jid */
  10814. /* jshint -W117 */
  10815. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10816. /**
  10817. * Calculates packet lost percent using the number of lost packets and the
  10818. * number of all packet.
  10819. * @param lostPackets the number of lost packets
  10820. * @param totalPackets the number of all packets.
  10821. * @returns {number} packet loss percent
  10822. */
  10823. function calculatePacketLoss(lostPackets, totalPackets) {
  10824. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10825. return 0;
  10826. return Math.round((lostPackets/totalPackets)*100);
  10827. }
  10828. function getStatValue(item, name) {
  10829. var browserType = RTCBrowserType.getBrowserType();
  10830. if (!keyMap[browserType][name])
  10831. throw "The property isn't supported!";
  10832. var key = keyMap[browserType][name];
  10833. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10834. item.stat(key) : item[key];
  10835. }
  10836. /**
  10837. * Peer statistics data holder.
  10838. * @constructor
  10839. */
  10840. function PeerStats()
  10841. {
  10842. this.ssrc2Loss = {};
  10843. this.ssrc2AudioLevel = {};
  10844. this.ssrc2bitrate = {};
  10845. this.ssrc2resolution = {};
  10846. }
  10847. /**
  10848. * The bandwidth
  10849. * @type {{}}
  10850. */
  10851. PeerStats.bandwidth = {};
  10852. /**
  10853. * The bit rate
  10854. * @type {{}}
  10855. */
  10856. PeerStats.bitrate = {};
  10857. /**
  10858. * The packet loss rate
  10859. * @type {{}}
  10860. */
  10861. PeerStats.packetLoss = null;
  10862. /**
  10863. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10864. * represented by this instance.
  10865. * @param ssrc audio or video RTP stream SSRC.
  10866. * @param lossRate new packet loss rate value to be set.
  10867. */
  10868. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10869. {
  10870. this.ssrc2Loss[ssrc] = lossRate;
  10871. };
  10872. /**
  10873. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10874. * represented by this instance.
  10875. * @param ssrc audio or video RTP stream SSRC.
  10876. * @param resolution new resolution value to be set.
  10877. */
  10878. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10879. {
  10880. if(resolution === null && this.ssrc2resolution[ssrc])
  10881. {
  10882. delete this.ssrc2resolution[ssrc];
  10883. }
  10884. else if(resolution !== null)
  10885. this.ssrc2resolution[ssrc] = resolution;
  10886. };
  10887. /**
  10888. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10889. * represented by this instance.
  10890. * @param ssrc audio or video RTP stream SSRC.
  10891. * @param bitrate new bitrate value to be set.
  10892. */
  10893. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10894. {
  10895. if(this.ssrc2bitrate[ssrc])
  10896. {
  10897. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10898. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10899. }
  10900. else {
  10901. this.ssrc2bitrate[ssrc] = bitrate;
  10902. }
  10903. };
  10904. /**
  10905. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10906. * the stream which belongs to the peer represented by this instance.
  10907. * @param ssrc RTP stream SSRC for which current audio level value will be
  10908. * updated.
  10909. * @param audioLevel the new audio level value to be set. Value is truncated to
  10910. * fit the range from 0 to 1.
  10911. */
  10912. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10913. {
  10914. // Range limit 0 - 1
  10915. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10916. };
  10917. function formatAudioLevel(audioLevel) {
  10918. return Math.min(Math.max(audioLevel, 0), 1);
  10919. }
  10920. /**
  10921. * Array with the transport information.
  10922. * @type {Array}
  10923. */
  10924. PeerStats.transport = [];
  10925. /**
  10926. * <tt>StatsCollector</tt> registers for stats updates of given
  10927. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10928. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10929. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10930. * instance as an event source.
  10931. *
  10932. * @param peerconnection webRTC peer connection object.
  10933. * @param interval stats refresh interval given in ms.
  10934. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10935. * called on stats update.
  10936. * @constructor
  10937. */
  10938. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10939. {
  10940. this.peerconnection = peerconnection;
  10941. this.baselineAudioLevelsReport = null;
  10942. this.currentAudioLevelsReport = null;
  10943. this.currentStatsReport = null;
  10944. this.baselineStatsReport = null;
  10945. this.audioLevelsIntervalId = null;
  10946. this.eventEmitter = eventEmitter;
  10947. /**
  10948. * Gather PeerConnection stats once every this many milliseconds.
  10949. */
  10950. this.GATHER_INTERVAL = 15000;
  10951. /**
  10952. * Log stats via the focus once every this many milliseconds.
  10953. */
  10954. this.LOG_INTERVAL = 60000;
  10955. /**
  10956. * Gather stats and store them in this.statsToBeLogged.
  10957. */
  10958. this.gatherStatsIntervalId = null;
  10959. /**
  10960. * Send the stats already saved in this.statsToBeLogged to be logged via
  10961. * the focus.
  10962. */
  10963. this.logStatsIntervalId = null;
  10964. /**
  10965. * Stores the statistics which will be send to the focus to be logged.
  10966. */
  10967. this.statsToBeLogged =
  10968. {
  10969. timestamps: [],
  10970. stats: {}
  10971. };
  10972. // Updates stats interval
  10973. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10974. this.statsIntervalId = null;
  10975. this.statsIntervalMilis = statsInterval;
  10976. // Map of jids to PeerStats
  10977. this.jid2stats = {};
  10978. }
  10979. module.exports = StatsCollector;
  10980. /**
  10981. * Stops stats updates.
  10982. */
  10983. StatsCollector.prototype.stop = function () {
  10984. if (this.audioLevelsIntervalId) {
  10985. clearInterval(this.audioLevelsIntervalId);
  10986. this.audioLevelsIntervalId = null;
  10987. }
  10988. if (this.statsIntervalId)
  10989. {
  10990. clearInterval(this.statsIntervalId);
  10991. this.statsIntervalId = null;
  10992. }
  10993. if(this.logStatsIntervalId)
  10994. {
  10995. clearInterval(this.logStatsIntervalId);
  10996. this.logStatsIntervalId = null;
  10997. }
  10998. if(this.gatherStatsIntervalId)
  10999. {
  11000. clearInterval(this.gatherStatsIntervalId);
  11001. this.gatherStatsIntervalId = null;
  11002. }
  11003. };
  11004. /**
  11005. * Callback passed to <tt>getStats</tt> method.
  11006. * @param error an error that occurred on <tt>getStats</tt> call.
  11007. */
  11008. StatsCollector.prototype.errorCallback = function (error)
  11009. {
  11010. console.error("Get stats error", error);
  11011. this.stop();
  11012. };
  11013. /**
  11014. * Starts stats updates.
  11015. */
  11016. StatsCollector.prototype.start = function ()
  11017. {
  11018. var self = this;
  11019. if(!config.disableAudioLevels) {
  11020. this.audioLevelsIntervalId = setInterval(
  11021. function () {
  11022. // Interval updates
  11023. self.peerconnection.getStats(
  11024. function (report) {
  11025. var results = null;
  11026. if (!report || !report.result ||
  11027. typeof report.result != 'function') {
  11028. results = report;
  11029. }
  11030. else {
  11031. results = report.result();
  11032. }
  11033. //console.error("Got interval report", results);
  11034. self.currentAudioLevelsReport = results;
  11035. self.processAudioLevelReport();
  11036. self.baselineAudioLevelsReport =
  11037. self.currentAudioLevelsReport;
  11038. },
  11039. self.errorCallback
  11040. );
  11041. },
  11042. self.audioLevelsIntervalMilis
  11043. );
  11044. }
  11045. if(!config.disableStats && !navigator.mozGetUserMedia) {
  11046. this.statsIntervalId = setInterval(
  11047. function () {
  11048. // Interval updates
  11049. self.peerconnection.getStats(
  11050. function (report) {
  11051. var results = null;
  11052. if (!report || !report.result ||
  11053. typeof report.result != 'function') {
  11054. //firefox
  11055. results = report;
  11056. }
  11057. else {
  11058. //chrome
  11059. results = report.result();
  11060. }
  11061. //console.error("Got interval report", results);
  11062. self.currentStatsReport = results;
  11063. try {
  11064. self.processStatsReport();
  11065. }
  11066. catch (e) {
  11067. console.error("Unsupported key:" + e, e);
  11068. }
  11069. self.baselineStatsReport = self.currentStatsReport;
  11070. },
  11071. self.errorCallback
  11072. );
  11073. },
  11074. self.statsIntervalMilis
  11075. );
  11076. }
  11077. if (config.logStats && !navigator.mozGetUserMedia) {
  11078. this.gatherStatsIntervalId = setInterval(
  11079. function () {
  11080. self.peerconnection.getStats(
  11081. function (report) {
  11082. self.addStatsToBeLogged(report.result());
  11083. },
  11084. function () {
  11085. }
  11086. );
  11087. },
  11088. this.GATHER_INTERVAL
  11089. );
  11090. this.logStatsIntervalId = setInterval(
  11091. function() { self.logStats(); },
  11092. this.LOG_INTERVAL);
  11093. }
  11094. };
  11095. /**
  11096. * Checks whether a certain record should be included in the logged statistics.
  11097. */
  11098. function acceptStat(reportId, reportType, statName) {
  11099. if (reportType == "googCandidatePair" && statName == "googChannelId")
  11100. return false;
  11101. if (reportType == "ssrc") {
  11102. if (statName == "googTrackId" ||
  11103. statName == "transportId" ||
  11104. statName == "ssrc")
  11105. return false;
  11106. }
  11107. return true;
  11108. }
  11109. /**
  11110. * Checks whether a certain record should be included in the logged statistics.
  11111. */
  11112. function acceptReport(id, type) {
  11113. if (id.substring(0, 15) == "googCertificate" ||
  11114. id.substring(0, 9) == "googTrack" ||
  11115. id.substring(0, 20) == "googLibjingleSession")
  11116. return false;
  11117. if (type == "googComponent")
  11118. return false;
  11119. return true;
  11120. }
  11121. /**
  11122. * Converts the stats to the format used for logging, and saves the data in
  11123. * this.statsToBeLogged.
  11124. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11125. */
  11126. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11127. var self = this;
  11128. var num_records = this.statsToBeLogged.timestamps.length;
  11129. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11130. reports.map(function (report) {
  11131. if (!acceptReport(report.id, report.type))
  11132. return;
  11133. var stat = self.statsToBeLogged.stats[report.id];
  11134. if (!stat) {
  11135. stat = self.statsToBeLogged.stats[report.id] = {};
  11136. }
  11137. stat.type = report.type;
  11138. report.names().map(function (name) {
  11139. if (!acceptStat(report.id, report.type, name))
  11140. return;
  11141. var values = stat[name];
  11142. if (!values) {
  11143. values = stat[name] = [];
  11144. }
  11145. while (values.length < num_records) {
  11146. values.push(null);
  11147. }
  11148. values.push(report.stat(name));
  11149. });
  11150. });
  11151. };
  11152. StatsCollector.prototype.logStats = function () {
  11153. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11154. return;
  11155. // Reset the stats
  11156. this.statsToBeLogged.stats = {};
  11157. this.statsToBeLogged.timestamps = [];
  11158. };
  11159. var keyMap = {};
  11160. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11161. "ssrc": "ssrc",
  11162. "packetsReceived": "packetsReceived",
  11163. "packetsLost": "packetsLost",
  11164. "packetsSent": "packetsSent",
  11165. "bytesReceived": "bytesReceived",
  11166. "bytesSent": "bytesSent"
  11167. };
  11168. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11169. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11170. "sendBandwidth": "googAvailableSendBandwidth",
  11171. "remoteAddress": "googRemoteAddress",
  11172. "transportType": "googTransportType",
  11173. "localAddress": "googLocalAddress",
  11174. "activeConnection": "googActiveConnection",
  11175. "ssrc": "ssrc",
  11176. "packetsReceived": "packetsReceived",
  11177. "packetsSent": "packetsSent",
  11178. "packetsLost": "packetsLost",
  11179. "bytesReceived": "bytesReceived",
  11180. "bytesSent": "bytesSent",
  11181. "googFrameHeightReceived": "googFrameHeightReceived",
  11182. "googFrameWidthReceived": "googFrameWidthReceived",
  11183. "googFrameHeightSent": "googFrameHeightSent",
  11184. "googFrameWidthSent": "googFrameWidthSent",
  11185. "audioInputLevel": "audioInputLevel",
  11186. "audioOutputLevel": "audioOutputLevel"
  11187. };
  11188. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11189. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11190. /**
  11191. * Stats processing logic.
  11192. */
  11193. StatsCollector.prototype.processStatsReport = function () {
  11194. if (!this.baselineStatsReport) {
  11195. return;
  11196. }
  11197. for (var idx in this.currentStatsReport) {
  11198. var now = this.currentStatsReport[idx];
  11199. try {
  11200. if (getStatValue(now, 'receiveBandwidth') ||
  11201. getStatValue(now, 'sendBandwidth')) {
  11202. PeerStats.bandwidth = {
  11203. "download": Math.round(
  11204. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11205. "upload": Math.round(
  11206. (getStatValue(now, 'sendBandwidth')) / 1000)
  11207. };
  11208. }
  11209. }
  11210. catch(e){/*not supported*/}
  11211. if(now.type == 'googCandidatePair')
  11212. {
  11213. var ip, type, localIP, active;
  11214. try {
  11215. ip = getStatValue(now, 'remoteAddress');
  11216. type = getStatValue(now, "transportType");
  11217. localIP = getStatValue(now, "localAddress");
  11218. active = getStatValue(now, "activeConnection");
  11219. }
  11220. catch(e){/*not supported*/}
  11221. if(!ip || !type || !localIP || active != "true")
  11222. continue;
  11223. var addressSaved = false;
  11224. for(var i = 0; i < PeerStats.transport.length; i++)
  11225. {
  11226. if(PeerStats.transport[i].ip == ip &&
  11227. PeerStats.transport[i].type == type &&
  11228. PeerStats.transport[i].localip == localIP)
  11229. {
  11230. addressSaved = true;
  11231. }
  11232. }
  11233. if(addressSaved)
  11234. continue;
  11235. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11236. continue;
  11237. }
  11238. if(now.type == "candidatepair")
  11239. {
  11240. if(now.state == "succeeded")
  11241. continue;
  11242. var local = this.currentStatsReport[now.localCandidateId];
  11243. var remote = this.currentStatsReport[now.remoteCandidateId];
  11244. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11245. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11246. }
  11247. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11248. now.type != "inboundrtp") {
  11249. continue;
  11250. }
  11251. var before = this.baselineStatsReport[idx];
  11252. if (!before) {
  11253. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11254. continue;
  11255. }
  11256. var ssrc = getStatValue(now, 'ssrc');
  11257. if(!ssrc)
  11258. continue;
  11259. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11260. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11261. console.warn("No jid for ssrc: " + ssrc);
  11262. continue;
  11263. }
  11264. var jidStats = this.jid2stats[jid];
  11265. if (!jidStats) {
  11266. jidStats = new PeerStats();
  11267. this.jid2stats[jid] = jidStats;
  11268. }
  11269. var isDownloadStream = true;
  11270. var key = 'packetsReceived';
  11271. if (!getStatValue(now, key))
  11272. {
  11273. isDownloadStream = false;
  11274. key = 'packetsSent';
  11275. if (!getStatValue(now, key))
  11276. {
  11277. console.warn("No packetsReceived nor packetSent stat found");
  11278. continue;
  11279. }
  11280. }
  11281. var packetsNow = getStatValue(now, key);
  11282. if(!packetsNow || packetsNow < 0)
  11283. packetsNow = 0;
  11284. var packetsBefore = getStatValue(before, key);
  11285. if(!packetsBefore || packetsBefore < 0)
  11286. packetsBefore = 0;
  11287. var packetRate = packetsNow - packetsBefore;
  11288. if(!packetRate || packetRate < 0)
  11289. packetRate = 0;
  11290. var currentLoss = getStatValue(now, 'packetsLost');
  11291. if(!currentLoss || currentLoss < 0)
  11292. currentLoss = 0;
  11293. var previousLoss = getStatValue(before, 'packetsLost');
  11294. if(!previousLoss || previousLoss < 0)
  11295. previousLoss = 0;
  11296. var lossRate = currentLoss - previousLoss;
  11297. if(!lossRate || lossRate < 0)
  11298. lossRate = 0;
  11299. var packetsTotal = (packetRate + lossRate);
  11300. jidStats.setSsrcLoss(ssrc,
  11301. {"packetsTotal": packetsTotal,
  11302. "packetsLost": lossRate,
  11303. "isDownloadStream": isDownloadStream});
  11304. var bytesReceived = 0, bytesSent = 0;
  11305. if(getStatValue(now, "bytesReceived"))
  11306. {
  11307. bytesReceived = getStatValue(now, "bytesReceived") -
  11308. getStatValue(before, "bytesReceived");
  11309. }
  11310. if(getStatValue(now, "bytesSent"))
  11311. {
  11312. bytesSent = getStatValue(now, "bytesSent") -
  11313. getStatValue(before, "bytesSent");
  11314. }
  11315. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11316. if(bytesReceived <= 0 || time <= 0)
  11317. {
  11318. bytesReceived = 0;
  11319. }
  11320. else
  11321. {
  11322. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11323. }
  11324. if(bytesSent <= 0 || time <= 0)
  11325. {
  11326. bytesSent = 0;
  11327. }
  11328. else
  11329. {
  11330. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11331. }
  11332. jidStats.setSsrcBitrate(ssrc, {
  11333. "download": bytesReceived,
  11334. "upload": bytesSent});
  11335. var resolution = {height: null, width: null};
  11336. try {
  11337. if (getStatValue(now, "googFrameHeightReceived") &&
  11338. getStatValue(now, "googFrameWidthReceived")) {
  11339. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11340. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11341. }
  11342. else if (getStatValue(now, "googFrameHeightSent") &&
  11343. getStatValue(now, "googFrameWidthSent")) {
  11344. resolution.height = getStatValue(now, "googFrameHeightSent");
  11345. resolution.width = getStatValue(now, "googFrameWidthSent");
  11346. }
  11347. }
  11348. catch(e){/*not supported*/}
  11349. if(resolution.height && resolution.width)
  11350. {
  11351. jidStats.setSsrcResolution(ssrc, resolution);
  11352. }
  11353. else
  11354. {
  11355. jidStats.setSsrcResolution(ssrc, null);
  11356. }
  11357. }
  11358. var self = this;
  11359. // Jid stats
  11360. var totalPackets = {download: 0, upload: 0};
  11361. var lostPackets = {download: 0, upload: 0};
  11362. var bitrateDownload = 0;
  11363. var bitrateUpload = 0;
  11364. var resolutions = {};
  11365. Object.keys(this.jid2stats).forEach(
  11366. function (jid)
  11367. {
  11368. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11369. function (ssrc)
  11370. {
  11371. var type = "upload";
  11372. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11373. type = "download";
  11374. totalPackets[type] +=
  11375. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11376. lostPackets[type] +=
  11377. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11378. }
  11379. );
  11380. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11381. function (ssrc) {
  11382. bitrateDownload +=
  11383. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11384. bitrateUpload +=
  11385. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11386. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11387. }
  11388. );
  11389. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11390. }
  11391. );
  11392. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11393. PeerStats.packetLoss = {
  11394. total:
  11395. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11396. totalPackets.download + totalPackets.upload),
  11397. download:
  11398. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11399. upload:
  11400. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11401. };
  11402. this.eventEmitter.emit("statistics.connectionstats",
  11403. {
  11404. "bitrate": PeerStats.bitrate,
  11405. "packetLoss": PeerStats.packetLoss,
  11406. "bandwidth": PeerStats.bandwidth,
  11407. "resolution": resolutions,
  11408. "transport": PeerStats.transport
  11409. });
  11410. PeerStats.transport = [];
  11411. };
  11412. /**
  11413. * Stats processing logic.
  11414. */
  11415. StatsCollector.prototype.processAudioLevelReport = function ()
  11416. {
  11417. if (!this.baselineAudioLevelsReport)
  11418. {
  11419. return;
  11420. }
  11421. for (var idx in this.currentAudioLevelsReport)
  11422. {
  11423. var now = this.currentAudioLevelsReport[idx];
  11424. if (now.type != 'ssrc')
  11425. {
  11426. continue;
  11427. }
  11428. var before = this.baselineAudioLevelsReport[idx];
  11429. if (!before)
  11430. {
  11431. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11432. continue;
  11433. }
  11434. var ssrc = getStatValue(now, 'ssrc');
  11435. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11436. if (!jid)
  11437. {
  11438. if((Date.now() - now.timestamp) < 3000)
  11439. console.warn("No jid for ssrc: " + ssrc);
  11440. continue;
  11441. }
  11442. var jidStats = this.jid2stats[jid];
  11443. if (!jidStats)
  11444. {
  11445. jidStats = new PeerStats();
  11446. this.jid2stats[jid] = jidStats;
  11447. }
  11448. // Audio level
  11449. var audioLevel = null;
  11450. try {
  11451. audioLevel = getStatValue(now, 'audioInputLevel');
  11452. if (!audioLevel)
  11453. audioLevel = getStatValue(now, 'audioOutputLevel');
  11454. }
  11455. catch(e) {/*not supported*/
  11456. console.warn("Audio Levels are not available in the statistics.");
  11457. clearInterval(this.audioLevelsIntervalId);
  11458. return;
  11459. }
  11460. if (audioLevel)
  11461. {
  11462. // TODO: can't find specs about what this value really is,
  11463. // but it seems to vary between 0 and around 32k.
  11464. audioLevel = audioLevel / 32767;
  11465. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11466. if(jid != APP.xmpp.myJid())
  11467. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11468. }
  11469. }
  11470. };
  11471. },{"../RTC/RTCBrowserType":10}],53:[function(require,module,exports){
  11472. /**
  11473. * Created by hristo on 8/4/14.
  11474. */
  11475. var LocalStats = require("./LocalStatsCollector.js");
  11476. var RTPStats = require("./RTPStatsCollector.js");
  11477. var EventEmitter = require("events");
  11478. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11479. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11480. var CallStats = require("./CallStats");
  11481. var RTCEvents = require("../../service/RTC/RTCEvents");
  11482. var eventEmitter = new EventEmitter();
  11483. var localStats = null;
  11484. var rtpStats = null;
  11485. function stopLocal()
  11486. {
  11487. if(localStats)
  11488. {
  11489. localStats.stop();
  11490. localStats = null;
  11491. }
  11492. }
  11493. function stopRemote()
  11494. {
  11495. if(rtpStats)
  11496. {
  11497. rtpStats.stop();
  11498. eventEmitter.emit("statistics.stop");
  11499. rtpStats = null;
  11500. }
  11501. }
  11502. function startRemoteStats (peerconnection) {
  11503. if(rtpStats)
  11504. {
  11505. rtpStats.stop();
  11506. rtpStats = null;
  11507. }
  11508. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11509. rtpStats.start();
  11510. }
  11511. function onStreamCreated(stream)
  11512. {
  11513. if(stream.getOriginalStream().getAudioTracks().length === 0)
  11514. return;
  11515. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11516. eventEmitter);
  11517. localStats.start();
  11518. }
  11519. function onDisposeConference(onUnload) {
  11520. CallStats.sendTerminateEvent();
  11521. stopRemote();
  11522. if(onUnload) {
  11523. stopLocal();
  11524. eventEmitter.removeAllListeners();
  11525. }
  11526. }
  11527. var statistics =
  11528. {
  11529. /**
  11530. * Indicates that this audio level is for local jid.
  11531. * @type {string}
  11532. */
  11533. LOCAL_JID: 'local',
  11534. addAudioLevelListener: function(listener)
  11535. {
  11536. eventEmitter.on("statistics.audioLevel", listener);
  11537. },
  11538. removeAudioLevelListener: function(listener)
  11539. {
  11540. eventEmitter.removeListener("statistics.audioLevel", listener);
  11541. },
  11542. addConnectionStatsListener: function(listener)
  11543. {
  11544. eventEmitter.on("statistics.connectionstats", listener);
  11545. },
  11546. removeConnectionStatsListener: function(listener)
  11547. {
  11548. eventEmitter.removeListener("statistics.connectionstats", listener);
  11549. },
  11550. addRemoteStatsStopListener: function(listener)
  11551. {
  11552. eventEmitter.on("statistics.stop", listener);
  11553. },
  11554. removeRemoteStatsStopListener: function(listener)
  11555. {
  11556. eventEmitter.removeListener("statistics.stop", listener);
  11557. },
  11558. stop: function () {
  11559. stopLocal();
  11560. stopRemote();
  11561. if(eventEmitter)
  11562. {
  11563. eventEmitter.removeAllListeners();
  11564. }
  11565. },
  11566. stopRemoteStatistics: function()
  11567. {
  11568. stopRemote();
  11569. },
  11570. start: function () {
  11571. APP.RTC.addStreamListener(onStreamCreated,
  11572. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11573. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11574. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11575. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11576. startRemoteStats(event.peerconnection);
  11577. // CallStats.init(event);
  11578. });
  11579. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11580. CallStats.init(session);
  11581. })
  11582. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11583. CallStats.sendMuteEvent(mute, "audio");
  11584. });
  11585. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11586. CallStats.sendSetupFailedEvent();
  11587. })
  11588. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11589. CallStats.sendMuteEvent(mute, "video");
  11590. });
  11591. }
  11592. };
  11593. module.exports = statistics;
  11594. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes.js":103,"../../service/xmpp/XMPPEvents":110,"./CallStats":50,"./LocalStatsCollector.js":51,"./RTPStatsCollector.js":52,"events":1}],54:[function(require,module,exports){
  11595. var i18n = require("i18next-client");
  11596. var languages = require("../../service/translation/languages");
  11597. var Settings = require("../settings/Settings");
  11598. var DEFAULT_LANG = languages.EN;
  11599. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11600. return value.replace("__app__", interfaceConfig.APP_NAME);
  11601. });
  11602. var defaultOptions = {
  11603. detectLngQS: "lang",
  11604. useCookie: false,
  11605. fallbackLng: DEFAULT_LANG,
  11606. load: "unspecific",
  11607. resGetPath: 'lang/__ns__-__lng__.json',
  11608. ns: {
  11609. namespaces: ['main', 'languages'],
  11610. defaultNs: 'main'
  11611. },
  11612. lngWhitelist : languages.getLanguages(),
  11613. fallbackOnNull: true,
  11614. fallbackOnEmpty: true,
  11615. useDataAttrOptions: true,
  11616. defaultValueFromContent: false,
  11617. app: interfaceConfig.APP_NAME,
  11618. getAsync: false,
  11619. defaultValueFromContent: false,
  11620. customLoad: function(lng, ns, options, done) {
  11621. var resPath = "lang/__ns__-__lng__.json";
  11622. if(lng === languages.EN)
  11623. resPath = "lang/__ns__.json";
  11624. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11625. i18n.functions.ajax({
  11626. url: url,
  11627. success: function(data, status, xhr) {
  11628. i18n.functions.log('loaded: ' + url);
  11629. done(null, data);
  11630. },
  11631. error : function(xhr, status, error) {
  11632. if ((status && status == 200) ||
  11633. (xhr && xhr.status && xhr.status == 200)) {
  11634. // file loaded but invalid json, stop waste time !
  11635. i18n.functions.error('There is a typo in: ' + url);
  11636. } else if ((status && status == 404) ||
  11637. (xhr && xhr.status && xhr.status == 404)) {
  11638. i18n.functions.log('Does not exist: ' + url);
  11639. } else {
  11640. var theStatus = status ? status :
  11641. ((xhr && xhr.status) ? xhr.status : null);
  11642. i18n.functions.log(theStatus + ' when loading ' + url);
  11643. }
  11644. done(error, {});
  11645. },
  11646. dataType: "json",
  11647. async : options.getAsync
  11648. });
  11649. }
  11650. // options for caching
  11651. // useLocalStorage: true,
  11652. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11653. };
  11654. function initCompleted(t)
  11655. {
  11656. $("[data-i18n]").i18n();
  11657. }
  11658. function checkForParameter() {
  11659. var query = window.location.search.substring(1);
  11660. var vars = query.split("&");
  11661. for (var i=0;i<vars.length;i++) {
  11662. var pair = vars[i].split("=");
  11663. if(pair[0] == "lang")
  11664. {
  11665. return pair[1];
  11666. }
  11667. }
  11668. return null;
  11669. }
  11670. module.exports = {
  11671. init: function (lang) {
  11672. var options = defaultOptions;
  11673. if(!lang)
  11674. {
  11675. lang = checkForParameter();
  11676. if(!lang)
  11677. {
  11678. var settings = Settings.getSettings();
  11679. if(settings)
  11680. lang = settings.language;
  11681. if(!lang && config.defaultLanguage)
  11682. {
  11683. lang = config.defaultLanguage;
  11684. }
  11685. }
  11686. }
  11687. if(lang) {
  11688. options.lng = lang;
  11689. }
  11690. i18n.init(options, initCompleted);
  11691. },
  11692. translateString: function (key, options) {
  11693. return i18n.t(key, options);
  11694. },
  11695. setLanguage: function (lang) {
  11696. if(!lang)
  11697. lang = DEFAULT_LANG;
  11698. i18n.setLng(lang, defaultOptions, initCompleted);
  11699. },
  11700. getCurrentLanguage: function () {
  11701. return i18n.lng();
  11702. },
  11703. translateElement: function (selector) {
  11704. selector.i18n();
  11705. },
  11706. generateTranslationHTML: function (key, options) {
  11707. var str = "<span data-i18n=\"" + key + "\"";
  11708. if(options)
  11709. {
  11710. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11711. }
  11712. str += ">";
  11713. str += this.translateString(key, options);
  11714. str += "</span>";
  11715. return str;
  11716. }
  11717. };
  11718. },{"../../service/translation/languages":109,"../settings/Settings":49,"i18next-client":70}],55:[function(require,module,exports){
  11719. /* jshint -W117 */
  11720. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11721. var SDPDiffer = require("./SDPDiffer");
  11722. var SDPUtil = require("./SDPUtil");
  11723. var SDP = require("./SDP");
  11724. var async = require("async");
  11725. var transform = require("sdp-transform");
  11726. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11727. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11728. // Jingle stuff
  11729. function JingleSession(me, sid, connection, service, eventEmitter) {
  11730. this.me = me;
  11731. this.sid = sid;
  11732. this.connection = connection;
  11733. this.initiator = null;
  11734. this.responder = null;
  11735. this.isInitiator = null;
  11736. this.peerjid = null;
  11737. this.state = null;
  11738. this.localSDP = null;
  11739. this.remoteSDP = null;
  11740. this.relayedStreams = [];
  11741. this.startTime = null;
  11742. this.stopTime = null;
  11743. this.media_constraints = null;
  11744. this.pc_constraints = null;
  11745. this.ice_config = {};
  11746. this.drip_container = [];
  11747. this.service = service;
  11748. this.eventEmitter = eventEmitter;
  11749. this.usetrickle = true;
  11750. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11751. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11752. this.hadstuncandidate = false;
  11753. this.hadturncandidate = false;
  11754. this.lasticecandidate = false;
  11755. this.statsinterval = null;
  11756. this.reason = null;
  11757. this.addssrc = [];
  11758. this.removessrc = [];
  11759. this.pendingop = null;
  11760. this.switchstreams = false;
  11761. this.wait = true;
  11762. this.localStreamsSSRC = null;
  11763. this.ssrcOwners = {};
  11764. this.ssrcVideoTypes = {};
  11765. this.eventEmitter = eventEmitter;
  11766. /**
  11767. * The indicator which determines whether the (local) video has been muted
  11768. * in response to a user command in contrast to an automatic decision made
  11769. * by the application logic.
  11770. */
  11771. this.videoMuteByUser = false;
  11772. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11773. // We start with the queue paused. We resume it when the signaling state is
  11774. // stable and the ice connection state is connected.
  11775. this.modifySourcesQueue.pause();
  11776. }
  11777. JingleSession.prototype.updateModifySourcesQueue = function() {
  11778. var signalingState = this.peerconnection.signalingState;
  11779. var iceConnectionState = this.peerconnection.iceConnectionState;
  11780. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11781. this.modifySourcesQueue.resume();
  11782. } else {
  11783. this.modifySourcesQueue.pause();
  11784. }
  11785. };
  11786. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11787. var self = this;
  11788. if (this.state !== null) {
  11789. console.error('attempt to initiate on session ' + this.sid +
  11790. 'in state ' + this.state);
  11791. return;
  11792. }
  11793. this.isInitiator = isInitiator;
  11794. this.state = 'pending';
  11795. this.initiator = isInitiator ? this.me : peerjid;
  11796. this.responder = !isInitiator ? this.me : peerjid;
  11797. this.peerjid = peerjid;
  11798. this.hadstuncandidate = false;
  11799. this.hadturncandidate = false;
  11800. this.lasticecandidate = false;
  11801. this.peerconnection
  11802. = new TraceablePeerConnection(
  11803. this.connection.jingle.ice_config,
  11804. this.connection.jingle.pc_constraints,
  11805. this);
  11806. this.peerconnection.onicecandidate = function (event) {
  11807. self.sendIceCandidate(event.candidate);
  11808. };
  11809. this.peerconnection.onaddstream = function (event) {
  11810. if (event.stream.id !== 'default') {
  11811. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  11812. self.remoteStreamAdded(event);
  11813. } else {
  11814. // This is a recvonly stream. Clients that implement Unified Plan,
  11815. // such as Firefox use recvonly "streams/channels/tracks" for
  11816. // receiving remote stream/tracks, as opposed to Plan B where there
  11817. // are only 3 channels: audio, video and data.
  11818. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11819. }
  11820. };
  11821. this.peerconnection.onremovestream = function (event) {
  11822. // Remove the stream from remoteStreams
  11823. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11824. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11825. };
  11826. this.peerconnection.onsignalingstatechange = function (event) {
  11827. if (!(self && self.peerconnection)) return;
  11828. self.updateModifySourcesQueue();
  11829. };
  11830. this.peerconnection.oniceconnectionstatechange = function (event) {
  11831. if (!(self && self.peerconnection)) return;
  11832. self.updateModifySourcesQueue();
  11833. switch (self.peerconnection.iceConnectionState) {
  11834. case 'connected':
  11835. this.startTime = new Date();
  11836. break;
  11837. case 'disconnected':
  11838. this.stopTime = new Date();
  11839. break;
  11840. case 'failed':
  11841. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11842. break;
  11843. }
  11844. onIceConnectionStateChange(self.sid, self);
  11845. };
  11846. this.peerconnection.onnegotiationneeded = function (event) {
  11847. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11848. };
  11849. // add any local and relayed stream
  11850. APP.RTC.localStreams.forEach(function(stream) {
  11851. self.peerconnection.addStream(stream.getOriginalStream());
  11852. });
  11853. this.relayedStreams.forEach(function(stream) {
  11854. self.peerconnection.addStream(stream);
  11855. });
  11856. };
  11857. function onIceConnectionStateChange(sid, session) {
  11858. switch (session.peerconnection.iceConnectionState) {
  11859. case 'checking':
  11860. session.timeChecking = (new Date()).getTime();
  11861. session.firstconnect = true;
  11862. break;
  11863. case 'completed': // on caller side
  11864. case 'connected':
  11865. if (session.firstconnect) {
  11866. session.firstconnect = false;
  11867. var metadata = {};
  11868. metadata.setupTime
  11869. = (new Date()).getTime() - session.timeChecking;
  11870. session.peerconnection.getStats(function (res) {
  11871. if(res && res.result) {
  11872. res.result().forEach(function (report) {
  11873. if (report.type == 'googCandidatePair' &&
  11874. report.stat('googActiveConnection') == 'true') {
  11875. metadata.localCandidateType
  11876. = report.stat('googLocalCandidateType');
  11877. metadata.remoteCandidateType
  11878. = report.stat('googRemoteCandidateType');
  11879. // log pair as well so we can get nice pie
  11880. // charts
  11881. metadata.candidatePair
  11882. = report.stat('googLocalCandidateType') +
  11883. ';' +
  11884. report.stat('googRemoteCandidateType');
  11885. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11886. {
  11887. metadata.ipv6 = true;
  11888. }
  11889. }
  11890. });
  11891. }
  11892. });
  11893. }
  11894. break;
  11895. }
  11896. }
  11897. JingleSession.prototype.getVideoType = function () {
  11898. return APP.desktopsharing.isUsingScreenStream() ? 'screen' : 'camera';
  11899. };
  11900. JingleSession.prototype.accept = function () {
  11901. this.state = 'active';
  11902. var pranswer = this.peerconnection.localDescription;
  11903. if (!pranswer || pranswer.type != 'pranswer') {
  11904. return;
  11905. }
  11906. console.log('going from pranswer to answer');
  11907. if (this.usetrickle) {
  11908. // remove candidates already sent from session-accept
  11909. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11910. for (var i = 0; i < lines.length; i++) {
  11911. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11912. }
  11913. }
  11914. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11915. // FIXME: change any inactive to sendrecv or whatever they were originally
  11916. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11917. }
  11918. var prsdp = new SDP(pranswer.sdp);
  11919. var accept = $iq({to: this.peerjid,
  11920. type: 'set'})
  11921. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11922. action: 'session-accept',
  11923. initiator: this.initiator,
  11924. responder: this.responder,
  11925. sid: this.sid });
  11926. // FIXME why do we generate session-accept in 3 different places ?
  11927. prsdp.toJingle(
  11928. accept,
  11929. this.initiator == this.me ? 'initiator' : 'responder',
  11930. this.localStreamsSSRC,
  11931. self.getVideoType());
  11932. var sdp = this.peerconnection.localDescription.sdp;
  11933. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11934. // FIXME: change any inactive to sendrecv or whatever they were originally
  11935. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11936. }
  11937. var self = this;
  11938. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11939. function () {
  11940. //console.log('setLocalDescription success');
  11941. self.setLocalDescription();
  11942. self.connection.sendIQ(accept,
  11943. function () {
  11944. var ack = {};
  11945. ack.source = 'answer';
  11946. $(document).trigger('ack.jingle', [self.sid, ack]);
  11947. },
  11948. function (stanza) {
  11949. var error = ($(stanza).find('error').length) ? {
  11950. code: $(stanza).find('error').attr('code'),
  11951. reason: $(stanza).find('error :first')[0].tagName
  11952. }:{};
  11953. error.source = 'answer';
  11954. JingleSession.onJingleError(self.sid, error);
  11955. },
  11956. 10000);
  11957. },
  11958. function (e) {
  11959. console.error('setLocalDescription failed', e);
  11960. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11961. }
  11962. );
  11963. };
  11964. JingleSession.prototype.terminate = function (reason) {
  11965. this.state = 'ended';
  11966. this.reason = reason;
  11967. this.peerconnection.close();
  11968. if (this.statsinterval !== null) {
  11969. window.clearInterval(this.statsinterval);
  11970. this.statsinterval = null;
  11971. }
  11972. };
  11973. JingleSession.prototype.active = function () {
  11974. return this.state == 'active';
  11975. };
  11976. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11977. var self = this;
  11978. if (candidate && !this.lasticecandidate) {
  11979. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11980. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11981. if (!(ice && jcand)) {
  11982. console.error('failed to get ice && jcand');
  11983. return;
  11984. }
  11985. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11986. if (jcand.type === 'srflx') {
  11987. this.hadstuncandidate = true;
  11988. } else if (jcand.type === 'relay') {
  11989. this.hadturncandidate = true;
  11990. }
  11991. if (this.usetrickle) {
  11992. if (this.usedrip) {
  11993. if (this.drip_container.length === 0) {
  11994. // start 20ms callout
  11995. window.setTimeout(function () {
  11996. if (self.drip_container.length === 0) return;
  11997. self.sendIceCandidates(self.drip_container);
  11998. self.drip_container = [];
  11999. }, 20);
  12000. }
  12001. this.drip_container.push(candidate);
  12002. return;
  12003. } else {
  12004. self.sendIceCandidate([candidate]);
  12005. }
  12006. }
  12007. } else {
  12008. //console.log('sendIceCandidate: last candidate.');
  12009. if (!this.usetrickle) {
  12010. //console.log('should send full offer now...');
  12011. //FIXME why do we generate session-accept in 3 different places ?
  12012. var init = $iq({to: this.peerjid,
  12013. type: 'set'})
  12014. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12015. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  12016. initiator: this.initiator,
  12017. sid: this.sid});
  12018. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  12019. var self = this;
  12020. var sendJingle = function (ssrc) {
  12021. if(!ssrc)
  12022. ssrc = {};
  12023. self.localSDP.toJingle(
  12024. init,
  12025. self.initiator == self.me ? 'initiator' : 'responder',
  12026. ssrc,
  12027. self.getVideoType());
  12028. self.connection.sendIQ(init,
  12029. function () {
  12030. //console.log('session initiate ack');
  12031. var ack = {};
  12032. ack.source = 'offer';
  12033. $(document).trigger('ack.jingle', [self.sid, ack]);
  12034. },
  12035. function (stanza) {
  12036. self.state = 'error';
  12037. self.peerconnection.close();
  12038. var error = ($(stanza).find('error').length) ? {
  12039. code: $(stanza).find('error').attr('code'),
  12040. reason: $(stanza).find('error :first')[0].tagName,
  12041. }:{};
  12042. error.source = 'offer';
  12043. JingleSession.onJingleError(self.sid, error);
  12044. },
  12045. 10000);
  12046. }
  12047. sendJingle();
  12048. }
  12049. this.lasticecandidate = true;
  12050. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12051. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12052. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12053. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12054. }
  12055. }
  12056. };
  12057. JingleSession.prototype.sendIceCandidates = function (candidates) {
  12058. console.log('sendIceCandidates', candidates);
  12059. var cand = $iq({to: this.peerjid, type: 'set'})
  12060. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12061. action: 'transport-info',
  12062. initiator: this.initiator,
  12063. sid: this.sid});
  12064. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12065. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12066. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12067. if (cands.length > 0) {
  12068. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12069. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12070. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12071. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12072. }).c('transport', ice);
  12073. for (var i = 0; i < cands.length; i++) {
  12074. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12075. }
  12076. // add fingerprint
  12077. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12078. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12079. tmp.required = true;
  12080. cand.c(
  12081. 'fingerprint',
  12082. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12083. .t(tmp.fingerprint);
  12084. delete tmp.fingerprint;
  12085. cand.attrs(tmp);
  12086. cand.up();
  12087. }
  12088. cand.up(); // transport
  12089. cand.up(); // content
  12090. }
  12091. }
  12092. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12093. //console.log('was this the last candidate', this.lasticecandidate);
  12094. this.connection.sendIQ(cand,
  12095. function () {
  12096. var ack = {};
  12097. ack.source = 'transportinfo';
  12098. $(document).trigger('ack.jingle', [this.sid, ack]);
  12099. },
  12100. function (stanza) {
  12101. var error = ($(stanza).find('error').length) ? {
  12102. code: $(stanza).find('error').attr('code'),
  12103. reason: $(stanza).find('error :first')[0].tagName,
  12104. }:{};
  12105. error.source = 'transportinfo';
  12106. JingleSession.onJingleError(this.sid, error);
  12107. },
  12108. 10000);
  12109. };
  12110. JingleSession.prototype.sendOffer = function () {
  12111. //console.log('sendOffer...');
  12112. var self = this;
  12113. this.peerconnection.createOffer(function (sdp) {
  12114. self.createdOffer(sdp);
  12115. },
  12116. function (e) {
  12117. console.error('createOffer failed', e);
  12118. },
  12119. this.media_constraints
  12120. );
  12121. };
  12122. // FIXME createdOffer is never used in jitsi-meet
  12123. JingleSession.prototype.createdOffer = function (sdp) {
  12124. //console.log('createdOffer', sdp);
  12125. var self = this;
  12126. this.localSDP = new SDP(sdp.sdp);
  12127. //this.localSDP.mangle();
  12128. var sendJingle = function () {
  12129. var init = $iq({to: this.peerjid,
  12130. type: 'set'})
  12131. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12132. action: 'session-initiate',
  12133. initiator: this.initiator,
  12134. sid: this.sid});
  12135. self.localSDP.toJingle(
  12136. init,
  12137. this.initiator == this.me ? 'initiator' : 'responder',
  12138. this.localStreamsSSRC,
  12139. self.getVideoType());
  12140. self.connection.sendIQ(init,
  12141. function () {
  12142. var ack = {};
  12143. ack.source = 'offer';
  12144. $(document).trigger('ack.jingle', [self.sid, ack]);
  12145. },
  12146. function (stanza) {
  12147. self.state = 'error';
  12148. self.peerconnection.close();
  12149. var error = ($(stanza).find('error').length) ? {
  12150. code: $(stanza).find('error').attr('code'),
  12151. reason: $(stanza).find('error :first')[0].tagName,
  12152. }:{};
  12153. error.source = 'offer';
  12154. JingleSession.onJingleError(self.sid, error);
  12155. },
  12156. 10000);
  12157. }
  12158. sdp.sdp = this.localSDP.raw;
  12159. this.peerconnection.setLocalDescription(sdp,
  12160. function () {
  12161. if(self.usetrickle)
  12162. {
  12163. sendJingle();
  12164. }
  12165. self.setLocalDescription();
  12166. //console.log('setLocalDescription success');
  12167. },
  12168. function (e) {
  12169. console.error('setLocalDescription failed', e);
  12170. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12171. }
  12172. );
  12173. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12174. for (var i = 0; i < cands.length; i++) {
  12175. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12176. if (cand.type == 'srflx') {
  12177. this.hadstuncandidate = true;
  12178. } else if (cand.type == 'relay') {
  12179. this.hadturncandidate = true;
  12180. }
  12181. }
  12182. };
  12183. JingleSession.prototype.readSsrcInfo = function (contents) {
  12184. var self = this;
  12185. $(contents).each(function (idx, content) {
  12186. var name = $(content).attr('name');
  12187. var mediaType = this.getAttribute('name');
  12188. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12189. ssrcs.each(function () {
  12190. var ssrc = this.getAttribute('ssrc');
  12191. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12192. function () {
  12193. var owner = this.getAttribute('owner');
  12194. var videoType = this.getAttribute('video-type');
  12195. self.ssrcOwners[ssrc] = owner;
  12196. self.ssrcVideoTypes[ssrc] = videoType;
  12197. }
  12198. );
  12199. });
  12200. });
  12201. };
  12202. JingleSession.prototype.getSsrcOwner = function (ssrc) {
  12203. return this.ssrcOwners[ssrc];
  12204. };
  12205. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  12206. //console.log('setting remote description... ', desctype);
  12207. this.remoteSDP = new SDP('');
  12208. this.remoteSDP.fromJingle(elem);
  12209. this.readSsrcInfo($(elem).find(">content"));
  12210. if (this.peerconnection.remoteDescription !== null) {
  12211. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12212. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12213. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12214. for (var i = 0; i < pranswer.media.length; i++) {
  12215. // make sure we have ice ufrag and pwd
  12216. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12217. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12218. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12219. } else {
  12220. console.warn('no ice ufrag?');
  12221. }
  12222. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12223. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12224. } else {
  12225. console.warn('no ice pwd?');
  12226. }
  12227. }
  12228. // copy over candidates
  12229. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12230. for (var j = 0; j < lines.length; j++) {
  12231. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12232. }
  12233. }
  12234. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12235. }
  12236. }
  12237. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12238. this.peerconnection.setRemoteDescription(remotedesc,
  12239. function () {
  12240. //console.log('setRemoteDescription success');
  12241. },
  12242. function (e) {
  12243. console.error('setRemoteDescription error', e);
  12244. JingleSession.onJingleFatalError(self, e);
  12245. }
  12246. );
  12247. };
  12248. JingleSession.prototype.addIceCandidate = function (elem) {
  12249. var self = this;
  12250. if (this.peerconnection.signalingState == 'closed') {
  12251. return;
  12252. }
  12253. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12254. console.log('trickle ice candidate arriving before session accept...');
  12255. // create a PRANSWER for setRemoteDescription
  12256. if (!this.remoteSDP) {
  12257. var cobbled = 'v=0\r\n' +
  12258. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12259. 's=-\r\n' +
  12260. 't=0 0\r\n';
  12261. // first, take some things from the local description
  12262. for (var i = 0; i < this.localSDP.media.length; i++) {
  12263. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12264. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12265. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12266. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12267. }
  12268. cobbled += 'a=inactive\r\n';
  12269. }
  12270. this.remoteSDP = new SDP(cobbled);
  12271. }
  12272. // then add things like ice and dtls from remote candidate
  12273. elem.each(function () {
  12274. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12275. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12276. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12277. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12278. var tmp = $(this).find('transport');
  12279. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12280. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12281. tmp = $(this).find('transport>fingerprint');
  12282. if (tmp.length) {
  12283. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12284. } else {
  12285. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12286. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12287. }
  12288. break;
  12289. }
  12290. }
  12291. }
  12292. });
  12293. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12294. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12295. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12296. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12297. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12298. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12299. }).length == this.remoteSDP.media.length;
  12300. if (iscomplete) {
  12301. console.log('setting pranswer');
  12302. try {
  12303. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12304. function() {
  12305. },
  12306. function(e) {
  12307. console.log('setRemoteDescription pranswer failed', e.toString());
  12308. });
  12309. } catch (e) {
  12310. console.error('setting pranswer failed', e);
  12311. }
  12312. } else {
  12313. //console.log('not yet setting pranswer');
  12314. }
  12315. }
  12316. // operate on each content element
  12317. elem.each(function () {
  12318. // would love to deactivate this, but firefox still requires it
  12319. var idx = -1;
  12320. var i;
  12321. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12322. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12323. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12324. idx = i;
  12325. break;
  12326. }
  12327. }
  12328. if (idx == -1) { // fall back to localdescription
  12329. for (i = 0; i < self.localSDP.media.length; i++) {
  12330. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12331. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12332. idx = i;
  12333. break;
  12334. }
  12335. }
  12336. }
  12337. var name = $(this).attr('name');
  12338. // TODO: check ice-pwd and ice-ufrag?
  12339. $(this).find('transport>candidate').each(function () {
  12340. var line, candidate;
  12341. line = SDPUtil.candidateFromJingle(this);
  12342. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12343. sdpMid: name,
  12344. candidate: line});
  12345. try {
  12346. self.peerconnection.addIceCandidate(candidate);
  12347. } catch (e) {
  12348. console.error('addIceCandidate failed', e.toString(), line);
  12349. }
  12350. });
  12351. });
  12352. };
  12353. JingleSession.prototype.sendAnswer = function (provisional) {
  12354. //console.log('createAnswer', provisional);
  12355. var self = this;
  12356. this.peerconnection.createAnswer(
  12357. function (sdp) {
  12358. self.createdAnswer(sdp, provisional);
  12359. },
  12360. function (e) {
  12361. console.error('createAnswer failed', e);
  12362. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12363. },
  12364. this.media_constraints
  12365. );
  12366. };
  12367. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12368. //console.log('createAnswer callback');
  12369. var self = this;
  12370. this.localSDP = new SDP(sdp.sdp);
  12371. //this.localSDP.mangle();
  12372. this.usepranswer = provisional === true;
  12373. if (this.usetrickle) {
  12374. if (this.usepranswer) {
  12375. sdp.type = 'pranswer';
  12376. for (var i = 0; i < this.localSDP.media.length; i++) {
  12377. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12378. }
  12379. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12380. }
  12381. }
  12382. var self = this;
  12383. var sendJingle = function (ssrcs) {
  12384. // FIXME why do we generate session-accept in 3 different places ?
  12385. var accept = $iq({to: self.peerjid,
  12386. type: 'set'})
  12387. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12388. action: 'session-accept',
  12389. initiator: self.initiator,
  12390. responder: self.responder,
  12391. sid: self.sid });
  12392. self.localSDP.toJingle(
  12393. accept,
  12394. self.initiator == self.me ? 'initiator' : 'responder',
  12395. ssrcs,
  12396. self.getVideoType());
  12397. self.connection.sendIQ(accept,
  12398. function () {
  12399. var ack = {};
  12400. ack.source = 'answer';
  12401. $(document).trigger('ack.jingle', [self.sid, ack]);
  12402. },
  12403. function (stanza) {
  12404. var error = ($(stanza).find('error').length) ? {
  12405. code: $(stanza).find('error').attr('code'),
  12406. reason: $(stanza).find('error :first')[0].tagName,
  12407. }:{};
  12408. error.source = 'answer';
  12409. JingleSession.onJingleError(self.sid, error);
  12410. },
  12411. 10000);
  12412. }
  12413. sdp.sdp = this.localSDP.raw;
  12414. this.peerconnection.setLocalDescription(sdp,
  12415. function () {
  12416. //console.log('setLocalDescription success');
  12417. if (self.usetrickle && !self.usepranswer) {
  12418. sendJingle();
  12419. }
  12420. self.setLocalDescription();
  12421. },
  12422. function (e) {
  12423. console.error('setLocalDescription failed', e);
  12424. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12425. }
  12426. );
  12427. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12428. for (var j = 0; j < cands.length; j++) {
  12429. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12430. if (cand.type == 'srflx') {
  12431. this.hadstuncandidate = true;
  12432. } else if (cand.type == 'relay') {
  12433. this.hadturncandidate = true;
  12434. }
  12435. }
  12436. };
  12437. JingleSession.prototype.sendTerminate = function (reason, text) {
  12438. var self = this,
  12439. term = $iq({to: this.peerjid,
  12440. type: 'set'})
  12441. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12442. action: 'session-terminate',
  12443. initiator: this.initiator,
  12444. sid: this.sid})
  12445. .c('reason')
  12446. .c(reason || 'success');
  12447. if (text) {
  12448. term.up().c('text').t(text);
  12449. }
  12450. this.connection.sendIQ(term,
  12451. function () {
  12452. self.peerconnection.close();
  12453. self.peerconnection = null;
  12454. self.terminate();
  12455. var ack = {};
  12456. ack.source = 'terminate';
  12457. $(document).trigger('ack.jingle', [self.sid, ack]);
  12458. },
  12459. function (stanza) {
  12460. var error = ($(stanza).find('error').length) ? {
  12461. code: $(stanza).find('error').attr('code'),
  12462. reason: $(stanza).find('error :first')[0].tagName,
  12463. }:{};
  12464. $(document).trigger('ack.jingle', [self.sid, error]);
  12465. },
  12466. 10000);
  12467. if (this.statsinterval !== null) {
  12468. window.clearInterval(this.statsinterval);
  12469. this.statsinterval = null;
  12470. }
  12471. };
  12472. JingleSession.prototype.addSource = function (elem, fromJid) {
  12473. var self = this;
  12474. // FIXME: dirty waiting
  12475. if (!this.peerconnection.localDescription)
  12476. {
  12477. console.warn("addSource - localDescription not ready yet")
  12478. setTimeout(function()
  12479. {
  12480. self.addSource(elem, fromJid);
  12481. },
  12482. 200
  12483. );
  12484. return;
  12485. }
  12486. console.log('addssrc', new Date().getTime());
  12487. console.log('ice', this.peerconnection.iceConnectionState);
  12488. this.readSsrcInfo(elem);
  12489. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12490. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12491. $(elem).each(function (idx, content) {
  12492. var name = $(content).attr('name');
  12493. var lines = '';
  12494. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12495. var semantics = this.getAttribute('semantics');
  12496. var ssrcs = $(this).find('>source').map(function () {
  12497. return this.getAttribute('ssrc');
  12498. }).get();
  12499. if (ssrcs.length != 0) {
  12500. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12501. }
  12502. });
  12503. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12504. tmp.each(function () {
  12505. var ssrc = $(this).attr('ssrc');
  12506. if(mySdp.containsSSRC(ssrc)){
  12507. /**
  12508. * This happens when multiple participants change their streams at the same time and
  12509. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12510. * addssrc are scheduled for update IQ. See
  12511. */
  12512. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12513. return;
  12514. }
  12515. $(this).find('>parameter').each(function () {
  12516. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12517. if ($(this).attr('value') && $(this).attr('value').length)
  12518. lines += ':' + $(this).attr('value');
  12519. lines += '\r\n';
  12520. });
  12521. });
  12522. sdp.media.forEach(function(media, idx) {
  12523. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12524. return;
  12525. sdp.media[idx] += lines;
  12526. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12527. self.addssrc[idx] += lines;
  12528. });
  12529. sdp.raw = sdp.session + sdp.media.join('');
  12530. });
  12531. this.modifySourcesQueue.push(function() {
  12532. // When a source is added and if this is FF, a new channel is allocated
  12533. // for receiving the added source. We need to diffuse the SSRC of this
  12534. // new recvonly channel to the rest of the peers.
  12535. console.log('modify sources done');
  12536. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12537. console.log("SDPs", mySdp, newSdp);
  12538. self.notifyMySSRCUpdate(mySdp, newSdp);
  12539. });
  12540. };
  12541. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12542. var self = this;
  12543. // FIXME: dirty waiting
  12544. if (!this.peerconnection.localDescription)
  12545. {
  12546. console.warn("removeSource - localDescription not ready yet")
  12547. setTimeout(function()
  12548. {
  12549. self.removeSource(elem, fromJid);
  12550. },
  12551. 200
  12552. );
  12553. return;
  12554. }
  12555. console.log('removessrc', new Date().getTime());
  12556. console.log('ice', this.peerconnection.iceConnectionState);
  12557. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12558. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12559. $(elem).each(function (idx, content) {
  12560. var name = $(content).attr('name');
  12561. var lines = '';
  12562. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12563. var semantics = this.getAttribute('semantics');
  12564. var ssrcs = $(this).find('>source').map(function () {
  12565. return this.getAttribute('ssrc');
  12566. }).get();
  12567. if (ssrcs.length != 0) {
  12568. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12569. }
  12570. });
  12571. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12572. tmp.each(function () {
  12573. var ssrc = $(this).attr('ssrc');
  12574. // This should never happen, but can be useful for bug detection
  12575. if(mySdp.containsSSRC(ssrc)){
  12576. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12577. return;
  12578. }
  12579. $(this).find('>parameter').each(function () {
  12580. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12581. if ($(this).attr('value') && $(this).attr('value').length)
  12582. lines += ':' + $(this).attr('value');
  12583. lines += '\r\n';
  12584. });
  12585. });
  12586. sdp.media.forEach(function(media, idx) {
  12587. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12588. return;
  12589. sdp.media[idx] += lines;
  12590. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12591. self.removessrc[idx] += lines;
  12592. });
  12593. sdp.raw = sdp.session + sdp.media.join('');
  12594. });
  12595. this.modifySourcesQueue.push(function() {
  12596. // When a source is removed and if this is FF, the recvonly channel that
  12597. // receives the remote stream is deactivated . We need to diffuse the
  12598. // recvonly SSRC removal to the rest of the peers.
  12599. console.log('modify sources done');
  12600. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12601. console.log("SDPs", mySdp, newSdp);
  12602. self.notifyMySSRCUpdate(mySdp, newSdp);
  12603. });
  12604. };
  12605. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12606. var self = this;
  12607. if (this.peerconnection.signalingState == 'closed') return;
  12608. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12609. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12610. this.setLocalDescription();
  12611. if(successCallback){
  12612. successCallback();
  12613. }
  12614. queueCallback();
  12615. return;
  12616. }
  12617. // Reset switch streams flag
  12618. this.switchstreams = false;
  12619. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12620. // add sources
  12621. this.addssrc.forEach(function(lines, idx) {
  12622. sdp.media[idx] += lines;
  12623. });
  12624. this.addssrc = [];
  12625. // remove sources
  12626. this.removessrc.forEach(function(lines, idx) {
  12627. lines = lines.split('\r\n');
  12628. lines.pop(); // remove empty last element;
  12629. lines.forEach(function(line) {
  12630. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12631. });
  12632. });
  12633. this.removessrc = [];
  12634. sdp.raw = sdp.session + sdp.media.join('');
  12635. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12636. function() {
  12637. if(self.signalingState == 'closed') {
  12638. console.error("createAnswer attempt on closed state");
  12639. queueCallback("createAnswer attempt on closed state");
  12640. return;
  12641. }
  12642. self.peerconnection.createAnswer(
  12643. function(modifiedAnswer) {
  12644. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12645. if (self.pendingop !== null) {
  12646. var sdp = new SDP(modifiedAnswer.sdp);
  12647. if (sdp.media.length > 1) {
  12648. switch(self.pendingop) {
  12649. case 'mute':
  12650. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12651. break;
  12652. case 'unmute':
  12653. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12654. break;
  12655. }
  12656. sdp.raw = sdp.session + sdp.media.join('');
  12657. modifiedAnswer.sdp = sdp.raw;
  12658. }
  12659. self.pendingop = null;
  12660. }
  12661. // FIXME: pushing down an answer while ice connection state
  12662. // is still checking is bad...
  12663. //console.log(self.peerconnection.iceConnectionState);
  12664. // trying to work around another chrome bug
  12665. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12666. self.peerconnection.setLocalDescription(modifiedAnswer,
  12667. function() {
  12668. //console.log('modified setLocalDescription ok');
  12669. self.setLocalDescription();
  12670. if(successCallback){
  12671. successCallback();
  12672. }
  12673. queueCallback();
  12674. },
  12675. function(error) {
  12676. console.error('modified setLocalDescription failed', error);
  12677. queueCallback(error);
  12678. }
  12679. );
  12680. },
  12681. function(error) {
  12682. console.error('modified answer failed', error);
  12683. queueCallback(error);
  12684. }
  12685. );
  12686. },
  12687. function(error) {
  12688. console.error('modify failed', error);
  12689. queueCallback(error);
  12690. }
  12691. );
  12692. };
  12693. /**
  12694. * Switches video streams.
  12695. * @param new_stream new stream that will be used as video of this session.
  12696. * @param oldStream old video stream of this session.
  12697. * @param success_callback callback executed after successful stream switch.
  12698. */
  12699. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12700. var self = this;
  12701. // Remember SDP to figure out added/removed SSRCs
  12702. var oldSdp = null;
  12703. if(self.peerconnection) {
  12704. if(self.peerconnection.localDescription) {
  12705. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12706. }
  12707. self.peerconnection.removeStream(oldStream, true);
  12708. if(new_stream)
  12709. self.peerconnection.addStream(new_stream);
  12710. }
  12711. // Conference is not active
  12712. if(!oldSdp || !self.peerconnection) {
  12713. success_callback();
  12714. return;
  12715. }
  12716. self.switchstreams = true;
  12717. self.modifySourcesQueue.push(function() {
  12718. console.log('modify sources done');
  12719. success_callback();
  12720. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12721. console.log("SDPs", oldSdp, newSdp);
  12722. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12723. });
  12724. };
  12725. /**
  12726. * Figures out added/removed ssrcs and send update IQs.
  12727. * @param old_sdp SDP object for old description.
  12728. * @param new_sdp SDP object for new description.
  12729. */
  12730. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12731. if (!(this.peerconnection.signalingState == 'stable' &&
  12732. this.peerconnection.iceConnectionState == 'connected')){
  12733. console.log("Too early to send updates");
  12734. return;
  12735. }
  12736. // send source-remove IQ.
  12737. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12738. var remove = $iq({to: this.peerjid, type: 'set'})
  12739. .c('jingle', {
  12740. xmlns: 'urn:xmpp:jingle:1',
  12741. action: 'source-remove',
  12742. initiator: this.initiator,
  12743. sid: this.sid
  12744. }
  12745. );
  12746. var removed = sdpDiffer.toJingle(remove);
  12747. if (removed) {
  12748. this.connection.sendIQ(remove,
  12749. function (res) {
  12750. console.info('got remove result', res);
  12751. },
  12752. function (err) {
  12753. console.error('got remove error', err);
  12754. }
  12755. );
  12756. } else {
  12757. console.log('removal not necessary');
  12758. }
  12759. // send source-add IQ.
  12760. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12761. var add = $iq({to: this.peerjid, type: 'set'})
  12762. .c('jingle', {
  12763. xmlns: 'urn:xmpp:jingle:1',
  12764. action: 'source-add',
  12765. initiator: this.initiator,
  12766. sid: this.sid
  12767. }
  12768. );
  12769. var added = sdpDiffer.toJingle(add, this.getVideoType());
  12770. if (added) {
  12771. this.connection.sendIQ(add,
  12772. function (res) {
  12773. console.info('got add result', res);
  12774. },
  12775. function (err) {
  12776. console.error('got add error', err);
  12777. }
  12778. );
  12779. } else {
  12780. console.log('addition not necessary');
  12781. }
  12782. };
  12783. /**
  12784. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12785. *
  12786. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12787. * tracks; otherwise, <tt>false</tt>
  12788. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12789. * tracks have been enabled/disabled. The function may, optionally, return
  12790. * another function which is to be invoked after the whole mute/unmute operation
  12791. * has completed successfully.
  12792. * @param options an object which specifies optional arguments such as the
  12793. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12794. * specifies whether the method was initiated in response to a user command (in
  12795. * contrast to an automatic decision made by the application logic)
  12796. */
  12797. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12798. var byUser;
  12799. if (options) {
  12800. byUser = options.byUser;
  12801. if (typeof byUser === 'undefined') {
  12802. byUser = true;
  12803. }
  12804. } else {
  12805. byUser = true;
  12806. }
  12807. // The user's command to mute the (local) video takes precedence over any
  12808. // automatic decision made by the application logic.
  12809. if (byUser) {
  12810. this.videoMuteByUser = mute;
  12811. } else if (this.videoMuteByUser) {
  12812. return;
  12813. }
  12814. this.hardMuteVideo(mute);
  12815. var self = this;
  12816. var oldSdp = null;
  12817. if(self.peerconnection) {
  12818. if(self.peerconnection.localDescription) {
  12819. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12820. }
  12821. }
  12822. this.modifySourcesQueue.push(function() {
  12823. console.log('modify sources done');
  12824. callback(mute);
  12825. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12826. console.log("SDPs", oldSdp, newSdp);
  12827. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12828. });
  12829. };
  12830. JingleSession.prototype.hardMuteVideo = function (muted) {
  12831. this.pendingop = muted ? 'mute' : 'unmute';
  12832. };
  12833. JingleSession.prototype.sendMute = function (muted, content) {
  12834. var info = $iq({to: this.peerjid,
  12835. type: 'set'})
  12836. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12837. action: 'session-info',
  12838. initiator: this.initiator,
  12839. sid: this.sid });
  12840. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12841. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12842. if (content) {
  12843. info.attrs({'name': content});
  12844. }
  12845. this.connection.send(info);
  12846. };
  12847. JingleSession.prototype.sendRinging = function () {
  12848. var info = $iq({to: this.peerjid,
  12849. type: 'set'})
  12850. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12851. action: 'session-info',
  12852. initiator: this.initiator,
  12853. sid: this.sid });
  12854. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12855. this.connection.send(info);
  12856. };
  12857. JingleSession.prototype.getStats = function (interval) {
  12858. var self = this;
  12859. var recv = {audio: 0, video: 0};
  12860. var lost = {audio: 0, video: 0};
  12861. var lastrecv = {audio: 0, video: 0};
  12862. var lastlost = {audio: 0, video: 0};
  12863. var loss = {audio: 0, video: 0};
  12864. var delta = {audio: 0, video: 0};
  12865. this.statsinterval = window.setInterval(function () {
  12866. if (self && self.peerconnection && self.peerconnection.getStats) {
  12867. self.peerconnection.getStats(function (stats) {
  12868. var results = stats.result();
  12869. // TODO: there are so much statistics you can get from this..
  12870. for (var i = 0; i < results.length; ++i) {
  12871. if (results[i].type == 'ssrc') {
  12872. var packetsrecv = results[i].stat('packetsReceived');
  12873. var packetslost = results[i].stat('packetsLost');
  12874. if (packetsrecv && packetslost) {
  12875. packetsrecv = parseInt(packetsrecv, 10);
  12876. packetslost = parseInt(packetslost, 10);
  12877. if (results[i].stat('googFrameRateReceived')) {
  12878. lastlost.video = lost.video;
  12879. lastrecv.video = recv.video;
  12880. recv.video = packetsrecv;
  12881. lost.video = packetslost;
  12882. } else {
  12883. lastlost.audio = lost.audio;
  12884. lastrecv.audio = recv.audio;
  12885. recv.audio = packetsrecv;
  12886. lost.audio = packetslost;
  12887. }
  12888. }
  12889. }
  12890. }
  12891. delta.audio = recv.audio - lastrecv.audio;
  12892. delta.video = recv.video - lastrecv.video;
  12893. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12894. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12895. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12896. });
  12897. }
  12898. }, interval || 3000);
  12899. return this.statsinterval;
  12900. };
  12901. JingleSession.onJingleError = function (session, error)
  12902. {
  12903. console.error("Jingle error", error);
  12904. }
  12905. JingleSession.onJingleFatalError = function (session, error)
  12906. {
  12907. this.service.sessionTerminated = true;
  12908. this.connection.emuc.doLeave();
  12909. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12910. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  12911. }
  12912. JingleSession.prototype.setLocalDescription = function () {
  12913. var self = this;
  12914. var newssrcs = [];
  12915. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12916. session.media.forEach(function (media) {
  12917. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12918. // TODO(gp) maybe exclude FID streams?
  12919. media.ssrcs.forEach(function (ssrc) {
  12920. if (ssrc.attribute !== 'cname') {
  12921. return;
  12922. }
  12923. newssrcs.push({
  12924. 'ssrc': ssrc.id,
  12925. 'type': media.type
  12926. });
  12927. });
  12928. }
  12929. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  12930. {
  12931. newssrcs.push({
  12932. 'ssrc': self.localStreamsSSRC[media.type],
  12933. 'type': media.type
  12934. });
  12935. }
  12936. });
  12937. console.log('new ssrcs', newssrcs);
  12938. // Bind us as local SSRCs owner
  12939. if (newssrcs.length > 0) {
  12940. for (var i = 1; i <= newssrcs.length; i ++) {
  12941. var ssrc = newssrcs[i-1].ssrc;
  12942. var myJid = self.connection.emuc.myroomjid;
  12943. self.ssrcOwners[ssrc] = myJid;
  12944. if (newssrcs[i-1].type === 'video'){
  12945. self.ssrcVideoTypes[ssrc] = self.getVideoType();
  12946. }
  12947. }
  12948. }
  12949. }
  12950. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12951. function sendKeyframe(pc) {
  12952. console.log('sendkeyframe', pc.iceConnectionState);
  12953. if (pc.iceConnectionState !== 'connected') return; // safe...
  12954. var self = this;
  12955. pc.setRemoteDescription(
  12956. pc.remoteDescription,
  12957. function () {
  12958. pc.createAnswer(
  12959. function (modifiedAnswer) {
  12960. pc.setLocalDescription(
  12961. modifiedAnswer,
  12962. function () {
  12963. // noop
  12964. },
  12965. function (error) {
  12966. console.log('triggerKeyframe setLocalDescription failed', error);
  12967. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  12968. }
  12969. );
  12970. },
  12971. function (error) {
  12972. console.log('triggerKeyframe createAnswer failed', error);
  12973. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  12974. }
  12975. );
  12976. },
  12977. function (error) {
  12978. console.log('triggerKeyframe setRemoteDescription failed', error);
  12979. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  12980. }
  12981. );
  12982. }
  12983. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12984. var self = this;
  12985. var thessrc;
  12986. var streamId = APP.RTC.getStreamID(data.stream);
  12987. // look up an associated JID for a stream id
  12988. if (!streamId) {
  12989. console.error("No stream ID for", data.stream);
  12990. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12991. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12992. var ssrclines
  12993. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12994. ssrclines = ssrclines.filter(function (line) {
  12995. // NOTE(gp) previously we filtered on the mslabel, but that property
  12996. // is not always present.
  12997. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12998. if (RTCBrowserType.isTemasysPluginUsed()) {
  12999. return ((line.indexOf('mslabel:' + streamId) !== -1));
  13000. } else {
  13001. return ((line.indexOf('msid:' + streamId) !== -1));
  13002. }
  13003. });
  13004. if (ssrclines.length) {
  13005. thessrc = ssrclines[0].substring(7).split(' ')[0];
  13006. if (!self.ssrcOwners[thessrc]) {
  13007. console.error("No SSRC owner known for: " + thessrc);
  13008. return;
  13009. }
  13010. data.peerjid = self.ssrcOwners[thessrc];
  13011. data.videoType = self.ssrcVideoTypes[thessrc]
  13012. console.log('associated jid', self.ssrcOwners[thessrc],
  13013. thessrc, data.videoType);
  13014. } else {
  13015. console.error("No SSRC lines for ", streamId);
  13016. }
  13017. }
  13018. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13019. var isVideo = data.stream.getVideoTracks().length > 0;
  13020. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13021. if (isVideo &&
  13022. data.peerjid && this.peerjid === data.peerjid &&
  13023. data.stream.getVideoTracks().length === 0 &&
  13024. APP.RTC.localVideo.getTracks().length > 0) {
  13025. window.setTimeout(function () {
  13026. sendKeyframe(self.peerconnection);
  13027. }, 3000);
  13028. }
  13029. }
  13030. module.exports = JingleSession;
  13031. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTCBrowserType":10,"./SDP":56,"./SDPDiffer":57,"./SDPUtil":58,"./TraceablePeerConnection":59,"async":69,"sdp-transform":97}],56:[function(require,module,exports){
  13032. /* jshint -W117 */
  13033. var SDPUtil = require("./SDPUtil");
  13034. // SDP STUFF
  13035. function SDP(sdp) {
  13036. this.media = sdp.split('\r\nm=');
  13037. for (var i = 1; i < this.media.length; i++) {
  13038. this.media[i] = 'm=' + this.media[i];
  13039. if (i != this.media.length - 1) {
  13040. this.media[i] += '\r\n';
  13041. }
  13042. }
  13043. this.session = this.media.shift() + '\r\n';
  13044. this.raw = this.session + this.media.join('');
  13045. }
  13046. /**
  13047. * Returns map of MediaChannel mapped per channel idx.
  13048. */
  13049. SDP.prototype.getMediaSsrcMap = function() {
  13050. var self = this;
  13051. var media_ssrcs = {};
  13052. var tmp;
  13053. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13054. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13055. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13056. var media = {
  13057. mediaindex: mediaindex,
  13058. mid: mid,
  13059. ssrcs: {},
  13060. ssrcGroups: []
  13061. };
  13062. media_ssrcs[mediaindex] = media;
  13063. tmp.forEach(function (line) {
  13064. var linessrc = line.substring(7).split(' ')[0];
  13065. // allocate new ChannelSsrc
  13066. if(!media.ssrcs[linessrc]) {
  13067. media.ssrcs[linessrc] = {
  13068. ssrc: linessrc,
  13069. lines: []
  13070. };
  13071. }
  13072. media.ssrcs[linessrc].lines.push(line);
  13073. });
  13074. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13075. tmp.forEach(function(line){
  13076. var semantics = line.substr(0, idx).substr(13);
  13077. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13078. if (ssrcs.length != 0) {
  13079. media.ssrcGroups.push({
  13080. semantics: semantics,
  13081. ssrcs: ssrcs
  13082. });
  13083. }
  13084. });
  13085. }
  13086. return media_ssrcs;
  13087. };
  13088. /**
  13089. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13090. * @param ssrc the ssrc to check.
  13091. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13092. */
  13093. SDP.prototype.containsSSRC = function(ssrc) {
  13094. var medias = this.getMediaSsrcMap();
  13095. var contains = false;
  13096. Object.keys(medias).forEach(function(mediaindex){
  13097. var media = medias[mediaindex];
  13098. //console.log("Check", channel, ssrc);
  13099. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13100. contains = true;
  13101. }
  13102. });
  13103. return contains;
  13104. };
  13105. // remove iSAC and CN from SDP
  13106. SDP.prototype.mangle = function () {
  13107. var i, j, mline, lines, rtpmap, newdesc;
  13108. for (i = 0; i < this.media.length; i++) {
  13109. lines = this.media[i].split('\r\n');
  13110. lines.pop(); // remove empty last element
  13111. mline = SDPUtil.parse_mline(lines.shift());
  13112. if (mline.media != 'audio')
  13113. continue;
  13114. newdesc = '';
  13115. mline.fmt.length = 0;
  13116. for (j = 0; j < lines.length; j++) {
  13117. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13118. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13119. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13120. continue;
  13121. mline.fmt.push(rtpmap.id);
  13122. newdesc += lines[j] + '\r\n';
  13123. } else {
  13124. newdesc += lines[j] + '\r\n';
  13125. }
  13126. }
  13127. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13128. this.media[i] += newdesc;
  13129. }
  13130. this.raw = this.session + this.media.join('');
  13131. };
  13132. // remove lines matching prefix from session section
  13133. SDP.prototype.removeSessionLines = function(prefix) {
  13134. var self = this;
  13135. var lines = SDPUtil.find_lines(this.session, prefix);
  13136. lines.forEach(function(line) {
  13137. self.session = self.session.replace(line + '\r\n', '');
  13138. });
  13139. this.raw = this.session + this.media.join('');
  13140. return lines;
  13141. }
  13142. // remove lines matching prefix from a media section specified by mediaindex
  13143. // TODO: non-numeric mediaindex could match mid
  13144. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13145. var self = this;
  13146. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13147. lines.forEach(function(line) {
  13148. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13149. });
  13150. this.raw = this.session + this.media.join('');
  13151. return lines;
  13152. }
  13153. // add content's to a jingle element
  13154. SDP.prototype.toJingle = function (elem, thecreator, ssrcs, videoType) {
  13155. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13156. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13157. var self = this;
  13158. // new bundle plan
  13159. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13160. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13161. for (i = 0; i < lines.length; i++) {
  13162. tmp = lines[i].split(' ');
  13163. var semantics = tmp.shift().substr(8);
  13164. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13165. for (j = 0; j < tmp.length; j++) {
  13166. elem.c('content', {name: tmp[j]}).up();
  13167. }
  13168. elem.up();
  13169. }
  13170. }
  13171. for (i = 0; i < this.media.length; i++) {
  13172. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13173. if (!(mline.media === 'audio' ||
  13174. mline.media === 'video' ||
  13175. mline.media === 'application'))
  13176. {
  13177. continue;
  13178. }
  13179. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13180. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13181. } else {
  13182. if(ssrcs && ssrcs[mline.media])
  13183. {
  13184. ssrc = ssrcs[mline.media];
  13185. }
  13186. else
  13187. ssrc = false;
  13188. }
  13189. elem.c('content', {creator: thecreator, name: mline.media});
  13190. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13191. // prefer identifier from a=mid if present
  13192. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13193. elem.attrs({ name: mid });
  13194. }
  13195. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13196. {
  13197. elem.c('description',
  13198. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13199. media: mline.media });
  13200. if (ssrc) {
  13201. elem.attrs({ssrc: ssrc});
  13202. }
  13203. for (j = 0; j < mline.fmt.length; j++) {
  13204. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13205. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13206. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13207. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13208. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13209. for (k = 0; k < tmp.length; k++) {
  13210. elem.c('parameter', tmp[k]).up();
  13211. }
  13212. }
  13213. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13214. elem.up();
  13215. }
  13216. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13217. elem.c('encryption', {required: 1});
  13218. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13219. crypto.forEach(function(line) {
  13220. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13221. });
  13222. elem.up(); // end of encryption
  13223. }
  13224. if (ssrc) {
  13225. // new style mapping
  13226. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13227. // FIXME: group by ssrc and support multiple different ssrcs
  13228. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13229. if(ssrclines.length > 0) {
  13230. ssrclines.forEach(function (line) {
  13231. idx = line.indexOf(' ');
  13232. var linessrc = line.substr(0, idx).substr(7);
  13233. if (linessrc != ssrc) {
  13234. elem.up();
  13235. ssrc = linessrc;
  13236. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13237. }
  13238. var kv = line.substr(idx + 1);
  13239. elem.c('parameter');
  13240. if (kv.indexOf(':') == -1) {
  13241. elem.attrs({ name: kv });
  13242. } else {
  13243. var k = kv.split(':', 2)[0];
  13244. elem.attrs({ name: k });
  13245. var v = kv.split(':', 2)[1];
  13246. v = SDPUtil.filter_special_chars(v);
  13247. elem.attrs({ value: v });
  13248. }
  13249. elem.up();
  13250. });
  13251. }
  13252. else
  13253. {
  13254. elem.up();
  13255. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13256. elem.c('parameter');
  13257. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13258. elem.up();
  13259. var msid = null;
  13260. if(mline.media == "audio")
  13261. {
  13262. msid = APP.RTC.localAudio.getId();
  13263. }
  13264. else
  13265. {
  13266. msid = APP.RTC.localVideo.getId();
  13267. }
  13268. if(msid != null)
  13269. {
  13270. msid = SDPUtil.filter_special_chars(msid);
  13271. elem.c('parameter');
  13272. elem.attrs({name: "msid", value:msid});
  13273. elem.up();
  13274. elem.c('parameter');
  13275. elem.attrs({name: "mslabel", value:msid});
  13276. elem.up();
  13277. elem.c('parameter');
  13278. elem.attrs({name: "label", value:msid});
  13279. elem.up();
  13280. }
  13281. }
  13282. // Video type
  13283. if (videoType && mline.media == "video") {
  13284. elem.c('ssrc-info',
  13285. {
  13286. xmlns: 'http://jitsi.org/jitmeet',
  13287. 'video-type': videoType
  13288. }).up();
  13289. }
  13290. elem.up();
  13291. // XEP-0339 handle ssrc-group attributes
  13292. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13293. ssrc_group_lines.forEach(function(line) {
  13294. idx = line.indexOf(' ');
  13295. var semantics = line.substr(0, idx).substr(13);
  13296. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13297. if (ssrcs.length != 0) {
  13298. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13299. ssrcs.forEach(function(ssrc) {
  13300. elem.c('source', { ssrc: ssrc })
  13301. .up();
  13302. });
  13303. elem.up();
  13304. }
  13305. });
  13306. }
  13307. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13308. elem.c('rtcp-mux').up();
  13309. }
  13310. // XEP-0293 -- map a=rtcp-fb:*
  13311. this.RtcpFbToJingle(i, elem, '*');
  13312. // XEP-0294
  13313. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13314. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13315. for (j = 0; j < lines.length; j++) {
  13316. tmp = SDPUtil.parse_extmap(lines[j]);
  13317. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13318. uri: tmp.uri,
  13319. id: tmp.value });
  13320. if (tmp.hasOwnProperty('direction')) {
  13321. switch (tmp.direction) {
  13322. case 'sendonly':
  13323. elem.attrs({senders: 'responder'});
  13324. break;
  13325. case 'recvonly':
  13326. elem.attrs({senders: 'initiator'});
  13327. break;
  13328. case 'sendrecv':
  13329. elem.attrs({senders: 'both'});
  13330. break;
  13331. case 'inactive':
  13332. elem.attrs({senders: 'none'});
  13333. break;
  13334. }
  13335. }
  13336. // TODO: handle params
  13337. elem.up();
  13338. }
  13339. }
  13340. elem.up(); // end of description
  13341. }
  13342. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13343. this.TransportToJingle(i, elem);
  13344. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13345. elem.attrs({senders: 'both'});
  13346. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13347. elem.attrs({senders: 'initiator'});
  13348. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13349. elem.attrs({senders: 'responder'});
  13350. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13351. elem.attrs({senders: 'none'});
  13352. }
  13353. if (mline.port == '0') {
  13354. // estos hack to reject an m-line
  13355. elem.attrs({senders: 'rejected'});
  13356. }
  13357. elem.up(); // end of content
  13358. }
  13359. elem.up();
  13360. return elem;
  13361. };
  13362. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13363. var i = mediaindex;
  13364. var tmp;
  13365. var self = this;
  13366. elem.c('transport');
  13367. // XEP-0343 DTLS/SCTP
  13368. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13369. {
  13370. var sctpmap = SDPUtil.find_line(
  13371. this.media[i], 'a=sctpmap:', self.session);
  13372. if (sctpmap)
  13373. {
  13374. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13375. elem.c('sctpmap',
  13376. {
  13377. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13378. number: sctpAttrs[0], /* SCTP port */
  13379. protocol: sctpAttrs[1], /* protocol */
  13380. });
  13381. // Optional stream count attribute
  13382. if (sctpAttrs.length > 2)
  13383. elem.attrs({ streams: sctpAttrs[2]});
  13384. elem.up();
  13385. }
  13386. }
  13387. // XEP-0320
  13388. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13389. fingerprints.forEach(function(line) {
  13390. tmp = SDPUtil.parse_fingerprint(line);
  13391. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13392. elem.c('fingerprint').t(tmp.fingerprint);
  13393. delete tmp.fingerprint;
  13394. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13395. if (line) {
  13396. tmp.setup = line.substr(8);
  13397. }
  13398. elem.attrs(tmp);
  13399. elem.up(); // end of fingerprint
  13400. });
  13401. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13402. if (tmp) {
  13403. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13404. elem.attrs(tmp);
  13405. // XEP-0176
  13406. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13407. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13408. lines.forEach(function (line) {
  13409. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13410. });
  13411. }
  13412. }
  13413. elem.up(); // end of transport
  13414. }
  13415. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13416. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13417. lines.forEach(function (line) {
  13418. var tmp = SDPUtil.parse_rtcpfb(line);
  13419. if (tmp.type == 'trr-int') {
  13420. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13421. elem.up();
  13422. } else {
  13423. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13424. if (tmp.params.length > 0) {
  13425. elem.attrs({'subtype': tmp.params[0]});
  13426. }
  13427. elem.up();
  13428. }
  13429. });
  13430. };
  13431. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13432. var media = '';
  13433. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13434. if (tmp.length) {
  13435. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13436. if (tmp.attr('value')) {
  13437. media += tmp.attr('value');
  13438. } else {
  13439. media += '0';
  13440. }
  13441. media += '\r\n';
  13442. }
  13443. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13444. tmp.each(function () {
  13445. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13446. if ($(this).attr('subtype')) {
  13447. media += ' ' + $(this).attr('subtype');
  13448. }
  13449. media += '\r\n';
  13450. });
  13451. return media;
  13452. };
  13453. // construct an SDP from a jingle stanza
  13454. SDP.prototype.fromJingle = function (jingle) {
  13455. var self = this;
  13456. this.raw = 'v=0\r\n' +
  13457. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13458. 's=-\r\n' +
  13459. 't=0 0\r\n';
  13460. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13461. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13462. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13463. var contents = $(group).find('>content').map(function (idx, content) {
  13464. return content.getAttribute('name');
  13465. }).get();
  13466. if (contents.length > 0) {
  13467. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13468. }
  13469. });
  13470. }
  13471. this.session = this.raw;
  13472. jingle.find('>content').each(function () {
  13473. var m = self.jingle2media($(this));
  13474. self.media.push(m);
  13475. });
  13476. // reconstruct msid-semantic -- apparently not necessary
  13477. /*
  13478. var msid = SDPUtil.parse_ssrc(this.raw);
  13479. if (msid.hasOwnProperty('mslabel')) {
  13480. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13481. }
  13482. */
  13483. this.raw = this.session + this.media.join('');
  13484. };
  13485. // translate a jingle content element into an an SDP media part
  13486. SDP.prototype.jingle2media = function (content) {
  13487. var media = '',
  13488. desc = content.find('description'),
  13489. ssrc = desc.attr('ssrc'),
  13490. self = this,
  13491. tmp;
  13492. var sctp = content.find(
  13493. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13494. tmp = { media: desc.attr('media') };
  13495. tmp.port = '1';
  13496. if (content.attr('senders') == 'rejected') {
  13497. // estos hack to reject an m-line.
  13498. tmp.port = '0';
  13499. }
  13500. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13501. if (sctp.length)
  13502. tmp.proto = 'DTLS/SCTP';
  13503. else
  13504. tmp.proto = 'RTP/SAVPF';
  13505. } else {
  13506. tmp.proto = 'RTP/AVPF';
  13507. }
  13508. if (!sctp.length)
  13509. {
  13510. tmp.fmt = desc.find('payload-type').map(
  13511. function () { return this.getAttribute('id'); }).get();
  13512. media += SDPUtil.build_mline(tmp) + '\r\n';
  13513. }
  13514. else
  13515. {
  13516. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13517. media += 'a=sctpmap:' + sctp.attr('number') +
  13518. ' ' + sctp.attr('protocol');
  13519. var streamCount = sctp.attr('streams');
  13520. if (streamCount)
  13521. media += ' ' + streamCount + '\r\n';
  13522. else
  13523. media += '\r\n';
  13524. }
  13525. media += 'c=IN IP4 0.0.0.0\r\n';
  13526. if (!sctp.length)
  13527. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13528. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13529. if (tmp.length) {
  13530. if (tmp.attr('ufrag')) {
  13531. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13532. }
  13533. if (tmp.attr('pwd')) {
  13534. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13535. }
  13536. tmp.find('>fingerprint').each(function () {
  13537. // FIXME: check namespace at some point
  13538. media += 'a=fingerprint:' + this.getAttribute('hash');
  13539. media += ' ' + $(this).text();
  13540. media += '\r\n';
  13541. if (this.getAttribute('setup')) {
  13542. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13543. }
  13544. });
  13545. }
  13546. switch (content.attr('senders')) {
  13547. case 'initiator':
  13548. media += 'a=sendonly\r\n';
  13549. break;
  13550. case 'responder':
  13551. media += 'a=recvonly\r\n';
  13552. break;
  13553. case 'none':
  13554. media += 'a=inactive\r\n';
  13555. break;
  13556. case 'both':
  13557. media += 'a=sendrecv\r\n';
  13558. break;
  13559. }
  13560. media += 'a=mid:' + content.attr('name') + '\r\n';
  13561. // <description><rtcp-mux/></description>
  13562. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13563. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13564. if (desc.find('rtcp-mux').length) {
  13565. media += 'a=rtcp-mux\r\n';
  13566. }
  13567. if (desc.find('encryption').length) {
  13568. desc.find('encryption>crypto').each(function () {
  13569. media += 'a=crypto:' + this.getAttribute('tag');
  13570. media += ' ' + this.getAttribute('crypto-suite');
  13571. media += ' ' + this.getAttribute('key-params');
  13572. if (this.getAttribute('session-params')) {
  13573. media += ' ' + this.getAttribute('session-params');
  13574. }
  13575. media += '\r\n';
  13576. });
  13577. }
  13578. desc.find('payload-type').each(function () {
  13579. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13580. if ($(this).find('>parameter').length) {
  13581. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13582. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13583. media += '\r\n';
  13584. }
  13585. // xep-0293
  13586. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13587. });
  13588. // xep-0293
  13589. media += self.RtcpFbFromJingle(desc, '*');
  13590. // xep-0294
  13591. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13592. tmp.each(function () {
  13593. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13594. });
  13595. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13596. media += SDPUtil.candidateFromJingle(this);
  13597. });
  13598. // XEP-0339 handle ssrc-group attributes
  13599. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13600. var semantics = this.getAttribute('semantics');
  13601. var ssrcs = $(this).find('>source').map(function() {
  13602. return this.getAttribute('ssrc');
  13603. }).get();
  13604. if (ssrcs.length != 0) {
  13605. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13606. }
  13607. });
  13608. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13609. tmp.each(function () {
  13610. var ssrc = this.getAttribute('ssrc');
  13611. $(this).find('>parameter').each(function () {
  13612. var name = this.getAttribute('name');
  13613. var value = this.getAttribute('value');
  13614. value = SDPUtil.filter_special_chars(value);
  13615. media += 'a=ssrc:' + ssrc + ' ' + name;
  13616. if (value && value.length)
  13617. media += ':' + value;
  13618. media += '\r\n';
  13619. });
  13620. });
  13621. return media;
  13622. };
  13623. module.exports = SDP;
  13624. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13625. var SDPUtil = require("./SDPUtil");
  13626. function SDPDiffer(mySDP, otherSDP) {
  13627. this.mySDP = mySDP;
  13628. this.otherSDP = otherSDP;
  13629. }
  13630. /**
  13631. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13632. * @param otherSdp the other SDP to check ssrc with.
  13633. */
  13634. SDPDiffer.prototype.getNewMedia = function() {
  13635. // this could be useful in Array.prototype.
  13636. function arrayEquals(array) {
  13637. // if the other array is a falsy value, return
  13638. if (!array)
  13639. return false;
  13640. // compare lengths - can save a lot of time
  13641. if (this.length != array.length)
  13642. return false;
  13643. for (var i = 0, l=this.length; i < l; i++) {
  13644. // Check if we have nested arrays
  13645. if (this[i] instanceof Array && array[i] instanceof Array) {
  13646. // recurse into the nested arrays
  13647. if (!this[i].equals(array[i]))
  13648. return false;
  13649. }
  13650. else if (this[i] != array[i]) {
  13651. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13652. return false;
  13653. }
  13654. }
  13655. return true;
  13656. }
  13657. var myMedias = this.mySDP.getMediaSsrcMap();
  13658. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13659. var newMedia = {};
  13660. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13661. var myMedia = myMedias[othersMediaIdx];
  13662. var othersMedia = othersMedias[othersMediaIdx];
  13663. if(!myMedia && othersMedia) {
  13664. // Add whole channel
  13665. newMedia[othersMediaIdx] = othersMedia;
  13666. return;
  13667. }
  13668. // Look for new ssrcs accross the channel
  13669. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13670. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13671. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13672. if(!newMedia[othersMediaIdx]){
  13673. newMedia[othersMediaIdx] = {
  13674. mediaindex: othersMedia.mediaindex,
  13675. mid: othersMedia.mid,
  13676. ssrcs: {},
  13677. ssrcGroups: []
  13678. };
  13679. }
  13680. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13681. }
  13682. });
  13683. // Look for new ssrc groups across the channels
  13684. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13685. // try to match the other ssrc-group with an ssrc-group of ours
  13686. var matched = false;
  13687. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13688. var mySsrcGroup = myMedia.ssrcGroups[i];
  13689. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13690. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13691. matched = true;
  13692. break;
  13693. }
  13694. }
  13695. if (!matched) {
  13696. // Allocate channel if we've found an ssrc-group that doesn't
  13697. // exist in our channel
  13698. if(!newMedia[othersMediaIdx]){
  13699. newMedia[othersMediaIdx] = {
  13700. mediaindex: othersMedia.mediaindex,
  13701. mid: othersMedia.mid,
  13702. ssrcs: {},
  13703. ssrcGroups: []
  13704. };
  13705. }
  13706. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13707. }
  13708. });
  13709. });
  13710. return newMedia;
  13711. };
  13712. /**
  13713. * Sends SSRC update IQ.
  13714. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13715. * @param sid session identifier that will be put into the IQ.
  13716. * @param initiator initiator identifier.
  13717. * @param toJid destination Jid
  13718. * @param isAdd indicates if this is remove or add operation.
  13719. */
  13720. SDPDiffer.prototype.toJingle = function(modify, videoType) {
  13721. var sdpMediaSsrcs = this.getNewMedia();
  13722. var self = this;
  13723. // FIXME: only announce video ssrcs since we mix audio and dont need
  13724. // the audio ssrcs therefore
  13725. var modified = false;
  13726. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13727. modified = true;
  13728. var media = sdpMediaSsrcs[mediaindex];
  13729. modify.c('content', {name: media.mid});
  13730. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13731. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13732. // generate sources from lines
  13733. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13734. var mediaSsrc = media.ssrcs[ssrcNum];
  13735. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13736. modify.attrs({ssrc: mediaSsrc.ssrc});
  13737. // iterate over ssrc lines
  13738. mediaSsrc.lines.forEach(function (line) {
  13739. var idx = line.indexOf(' ');
  13740. var kv = line.substr(idx + 1);
  13741. modify.c('parameter');
  13742. if (kv.indexOf(':') == -1) {
  13743. modify.attrs({ name: kv });
  13744. } else {
  13745. var nv = kv.split(':', 2);
  13746. var name = nv[0];
  13747. var value = SDPUtil.filter_special_chars(nv[1]);
  13748. modify.attrs({ name: name });
  13749. modify.attrs({ value: value });
  13750. }
  13751. modify.up(); // end of parameter
  13752. });
  13753. // indicate video type
  13754. if (videoType && media.mid == 'video') {
  13755. modify.c('ssrc-info',
  13756. {
  13757. xmlns: 'http://jitsi.org/jitmeet',
  13758. 'video-type': videoType
  13759. })
  13760. .up();
  13761. }
  13762. modify.up(); // end of source
  13763. });
  13764. // generate source groups from lines
  13765. media.ssrcGroups.forEach(function(ssrcGroup) {
  13766. if (ssrcGroup.ssrcs.length != 0) {
  13767. modify.c('ssrc-group', {
  13768. semantics: ssrcGroup.semantics,
  13769. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13770. });
  13771. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13772. modify.c('source', { ssrc: ssrc })
  13773. .up(); // end of source
  13774. });
  13775. modify.up(); // end of ssrc-group
  13776. }
  13777. });
  13778. modify.up(); // end of description
  13779. modify.up(); // end of content
  13780. });
  13781. return modified;
  13782. };
  13783. module.exports = SDPDiffer;
  13784. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13785. SDPUtil = {
  13786. filter_special_chars: function (text) {
  13787. return text.replace(/[\\\/\{,\}\+]/g, "");
  13788. },
  13789. iceparams: function (mediadesc, sessiondesc) {
  13790. var data = null;
  13791. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13792. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13793. data = {
  13794. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13795. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13796. };
  13797. }
  13798. return data;
  13799. },
  13800. parse_iceufrag: function (line) {
  13801. return line.substring(12);
  13802. },
  13803. build_iceufrag: function (frag) {
  13804. return 'a=ice-ufrag:' + frag;
  13805. },
  13806. parse_icepwd: function (line) {
  13807. return line.substring(10);
  13808. },
  13809. build_icepwd: function (pwd) {
  13810. return 'a=ice-pwd:' + pwd;
  13811. },
  13812. parse_mid: function (line) {
  13813. return line.substring(6);
  13814. },
  13815. parse_mline: function (line) {
  13816. var parts = line.substring(2).split(' '),
  13817. data = {};
  13818. data.media = parts.shift();
  13819. data.port = parts.shift();
  13820. data.proto = parts.shift();
  13821. if (parts[parts.length - 1] === '') { // trailing whitespace
  13822. parts.pop();
  13823. }
  13824. data.fmt = parts;
  13825. return data;
  13826. },
  13827. build_mline: function (mline) {
  13828. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13829. },
  13830. parse_rtpmap: function (line) {
  13831. var parts = line.substring(9).split(' '),
  13832. data = {};
  13833. data.id = parts.shift();
  13834. parts = parts[0].split('/');
  13835. data.name = parts.shift();
  13836. data.clockrate = parts.shift();
  13837. data.channels = parts.length ? parts.shift() : '1';
  13838. return data;
  13839. },
  13840. /**
  13841. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13842. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13843. * @returns [SCTP port number, protocol, streams]
  13844. */
  13845. parse_sctpmap: function (line)
  13846. {
  13847. var parts = line.substring(10).split(' ');
  13848. var sctpPort = parts[0];
  13849. var protocol = parts[1];
  13850. // Stream count is optional
  13851. var streamCount = parts.length > 2 ? parts[2] : null;
  13852. return [sctpPort, protocol, streamCount];// SCTP port
  13853. },
  13854. build_rtpmap: function (el) {
  13855. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13856. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13857. line += '/' + el.getAttribute('channels');
  13858. }
  13859. return line;
  13860. },
  13861. parse_crypto: function (line) {
  13862. var parts = line.substring(9).split(' '),
  13863. data = {};
  13864. data.tag = parts.shift();
  13865. data['crypto-suite'] = parts.shift();
  13866. data['key-params'] = parts.shift();
  13867. if (parts.length) {
  13868. data['session-params'] = parts.join(' ');
  13869. }
  13870. return data;
  13871. },
  13872. parse_fingerprint: function (line) { // RFC 4572
  13873. var parts = line.substring(14).split(' '),
  13874. data = {};
  13875. data.hash = parts.shift();
  13876. data.fingerprint = parts.shift();
  13877. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13878. return data;
  13879. },
  13880. parse_fmtp: function (line) {
  13881. var parts = line.split(' '),
  13882. i, key, value,
  13883. data = [];
  13884. parts.shift();
  13885. parts = parts.join(' ').split(';');
  13886. for (i = 0; i < parts.length; i++) {
  13887. key = parts[i].split('=')[0];
  13888. while (key.length && key[0] == ' ') {
  13889. key = key.substring(1);
  13890. }
  13891. value = parts[i].split('=')[1];
  13892. if (key && value) {
  13893. data.push({name: key, value: value});
  13894. } else if (key) {
  13895. // rfc 4733 (DTMF) style stuff
  13896. data.push({name: '', value: key});
  13897. }
  13898. }
  13899. return data;
  13900. },
  13901. parse_icecandidate: function (line) {
  13902. var candidate = {},
  13903. elems = line.split(' ');
  13904. candidate.foundation = elems[0].substring(12);
  13905. candidate.component = elems[1];
  13906. candidate.protocol = elems[2].toLowerCase();
  13907. candidate.priority = elems[3];
  13908. candidate.ip = elems[4];
  13909. candidate.port = elems[5];
  13910. // elems[6] => "typ"
  13911. candidate.type = elems[7];
  13912. candidate.generation = 0; // default value, may be overwritten below
  13913. for (var i = 8; i < elems.length; i += 2) {
  13914. switch (elems[i]) {
  13915. case 'raddr':
  13916. candidate['rel-addr'] = elems[i + 1];
  13917. break;
  13918. case 'rport':
  13919. candidate['rel-port'] = elems[i + 1];
  13920. break;
  13921. case 'generation':
  13922. candidate.generation = elems[i + 1];
  13923. break;
  13924. case 'tcptype':
  13925. candidate.tcptype = elems[i + 1];
  13926. break;
  13927. default: // TODO
  13928. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13929. }
  13930. }
  13931. candidate.network = '1';
  13932. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13933. return candidate;
  13934. },
  13935. build_icecandidate: function (cand) {
  13936. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13937. line += ' ';
  13938. switch (cand.type) {
  13939. case 'srflx':
  13940. case 'prflx':
  13941. case 'relay':
  13942. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13943. line += 'raddr';
  13944. line += ' ';
  13945. line += cand['rel-addr'];
  13946. line += ' ';
  13947. line += 'rport';
  13948. line += ' ';
  13949. line += cand['rel-port'];
  13950. line += ' ';
  13951. }
  13952. break;
  13953. }
  13954. if (cand.hasOwnAttribute('tcptype')) {
  13955. line += 'tcptype';
  13956. line += ' ';
  13957. line += cand.tcptype;
  13958. line += ' ';
  13959. }
  13960. line += 'generation';
  13961. line += ' ';
  13962. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13963. return line;
  13964. },
  13965. parse_ssrc: function (desc) {
  13966. // proprietary mapping of a=ssrc lines
  13967. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13968. // and parse according to that
  13969. var lines = desc.split('\r\n'),
  13970. data = {};
  13971. for (var i = 0; i < lines.length; i++) {
  13972. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13973. var idx = lines[i].indexOf(' ');
  13974. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13975. }
  13976. }
  13977. return data;
  13978. },
  13979. parse_rtcpfb: function (line) {
  13980. var parts = line.substr(10).split(' ');
  13981. var data = {};
  13982. data.pt = parts.shift();
  13983. data.type = parts.shift();
  13984. data.params = parts;
  13985. return data;
  13986. },
  13987. parse_extmap: function (line) {
  13988. var parts = line.substr(9).split(' ');
  13989. var data = {};
  13990. data.value = parts.shift();
  13991. if (data.value.indexOf('/') != -1) {
  13992. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13993. data.value = data.value.substr(0, data.value.indexOf('/'));
  13994. } else {
  13995. data.direction = 'both';
  13996. }
  13997. data.uri = parts.shift();
  13998. data.params = parts;
  13999. return data;
  14000. },
  14001. find_line: function (haystack, needle, sessionpart) {
  14002. var lines = haystack.split('\r\n');
  14003. for (var i = 0; i < lines.length; i++) {
  14004. if (lines[i].substring(0, needle.length) == needle) {
  14005. return lines[i];
  14006. }
  14007. }
  14008. if (!sessionpart) {
  14009. return false;
  14010. }
  14011. // search session part
  14012. lines = sessionpart.split('\r\n');
  14013. for (var j = 0; j < lines.length; j++) {
  14014. if (lines[j].substring(0, needle.length) == needle) {
  14015. return lines[j];
  14016. }
  14017. }
  14018. return false;
  14019. },
  14020. find_lines: function (haystack, needle, sessionpart) {
  14021. var lines = haystack.split('\r\n'),
  14022. needles = [];
  14023. for (var i = 0; i < lines.length; i++) {
  14024. if (lines[i].substring(0, needle.length) == needle)
  14025. needles.push(lines[i]);
  14026. }
  14027. if (needles.length || !sessionpart) {
  14028. return needles;
  14029. }
  14030. // search session part
  14031. lines = sessionpart.split('\r\n');
  14032. for (var j = 0; j < lines.length; j++) {
  14033. if (lines[j].substring(0, needle.length) == needle) {
  14034. needles.push(lines[j]);
  14035. }
  14036. }
  14037. return needles;
  14038. },
  14039. candidateToJingle: function (line) {
  14040. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14041. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14042. if (line.indexOf('candidate:') === 0) {
  14043. line = 'a=' + line;
  14044. } else if (line.substring(0, 12) != 'a=candidate:') {
  14045. console.log('parseCandidate called with a line that is not a candidate line');
  14046. console.log(line);
  14047. return null;
  14048. }
  14049. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14050. line = line.substring(0, line.length - 2);
  14051. var candidate = {},
  14052. elems = line.split(' '),
  14053. i;
  14054. if (elems[6] != 'typ') {
  14055. console.log('did not find typ in the right place');
  14056. console.log(line);
  14057. return null;
  14058. }
  14059. candidate.foundation = elems[0].substring(12);
  14060. candidate.component = elems[1];
  14061. candidate.protocol = elems[2].toLowerCase();
  14062. candidate.priority = elems[3];
  14063. candidate.ip = elems[4];
  14064. candidate.port = elems[5];
  14065. // elems[6] => "typ"
  14066. candidate.type = elems[7];
  14067. candidate.generation = '0'; // default, may be overwritten below
  14068. for (i = 8; i < elems.length; i += 2) {
  14069. switch (elems[i]) {
  14070. case 'raddr':
  14071. candidate['rel-addr'] = elems[i + 1];
  14072. break;
  14073. case 'rport':
  14074. candidate['rel-port'] = elems[i + 1];
  14075. break;
  14076. case 'generation':
  14077. candidate.generation = elems[i + 1];
  14078. break;
  14079. case 'tcptype':
  14080. candidate.tcptype = elems[i + 1];
  14081. break;
  14082. default: // TODO
  14083. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14084. }
  14085. }
  14086. candidate.network = '1';
  14087. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14088. return candidate;
  14089. },
  14090. candidateFromJingle: function (cand) {
  14091. var line = 'a=candidate:';
  14092. line += cand.getAttribute('foundation');
  14093. line += ' ';
  14094. line += cand.getAttribute('component');
  14095. line += ' ';
  14096. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14097. line += ' ';
  14098. line += cand.getAttribute('priority');
  14099. line += ' ';
  14100. line += cand.getAttribute('ip');
  14101. line += ' ';
  14102. line += cand.getAttribute('port');
  14103. line += ' ';
  14104. line += 'typ';
  14105. line += ' ' + cand.getAttribute('type');
  14106. line += ' ';
  14107. switch (cand.getAttribute('type')) {
  14108. case 'srflx':
  14109. case 'prflx':
  14110. case 'relay':
  14111. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14112. line += 'raddr';
  14113. line += ' ';
  14114. line += cand.getAttribute('rel-addr');
  14115. line += ' ';
  14116. line += 'rport';
  14117. line += ' ';
  14118. line += cand.getAttribute('rel-port');
  14119. line += ' ';
  14120. }
  14121. break;
  14122. }
  14123. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14124. line += 'tcptype';
  14125. line += ' ';
  14126. line += cand.getAttribute('tcptype');
  14127. line += ' ';
  14128. }
  14129. line += 'generation';
  14130. line += ' ';
  14131. line += cand.getAttribute('generation') || '0';
  14132. return line + '\r\n';
  14133. }
  14134. };
  14135. module.exports = SDPUtil;
  14136. },{}],59:[function(require,module,exports){
  14137. var RTC = require('../RTC/RTC');
  14138. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14139. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14140. function TraceablePeerConnection(ice_config, constraints, session) {
  14141. var self = this;
  14142. var RTCPeerconnectionType = null;
  14143. if (RTCBrowserType.isFirefox()) {
  14144. RTCPeerconnectionType = mozRTCPeerConnection;
  14145. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14146. RTCPeerconnectionType = RTCPeerConnection;
  14147. } else {
  14148. RTCPeerconnectionType = webkitRTCPeerConnection;
  14149. }
  14150. this.peerconnection = new RTCPeerconnectionType(ice_config, constraints);
  14151. this.updateLog = [];
  14152. this.stats = {};
  14153. this.statsinterval = null;
  14154. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14155. var Interop = require('sdp-interop').Interop;
  14156. this.interop = new Interop();
  14157. var Simulcast = require('sdp-simulcast');
  14158. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14159. // override as desired
  14160. this.trace = function (what, info) {
  14161. /*console.warn('WTRACE', what, info);
  14162. if (info && RTCBrowserType.isIExplorer()) {
  14163. if (info.length > 1024) {
  14164. console.warn('WTRACE', what, info.substr(1024));
  14165. }
  14166. if (info.length > 2048) {
  14167. console.warn('WTRACE', what, info.substr(2048));
  14168. }
  14169. }*/
  14170. self.updateLog.push({
  14171. time: new Date(),
  14172. type: what,
  14173. value: info || ""
  14174. });
  14175. };
  14176. this.onicecandidate = null;
  14177. this.peerconnection.onicecandidate = function (event) {
  14178. // FIXME: this causes stack overflow with Temasys Plugin
  14179. if (!RTCBrowserType.isTemasysPluginUsed())
  14180. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14181. if (self.onicecandidate !== null) {
  14182. self.onicecandidate(event);
  14183. }
  14184. };
  14185. this.onaddstream = null;
  14186. this.peerconnection.onaddstream = function (event) {
  14187. self.trace('onaddstream', event.stream.id);
  14188. if (self.onaddstream !== null) {
  14189. self.onaddstream(event);
  14190. }
  14191. };
  14192. this.onremovestream = null;
  14193. this.peerconnection.onremovestream = function (event) {
  14194. self.trace('onremovestream', event.stream.id);
  14195. if (self.onremovestream !== null) {
  14196. self.onremovestream(event);
  14197. }
  14198. };
  14199. this.onsignalingstatechange = null;
  14200. this.peerconnection.onsignalingstatechange = function (event) {
  14201. self.trace('onsignalingstatechange', self.signalingState);
  14202. if (self.onsignalingstatechange !== null) {
  14203. self.onsignalingstatechange(event);
  14204. }
  14205. };
  14206. this.oniceconnectionstatechange = null;
  14207. this.peerconnection.oniceconnectionstatechange = function (event) {
  14208. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14209. if (self.oniceconnectionstatechange !== null) {
  14210. self.oniceconnectionstatechange(event);
  14211. }
  14212. };
  14213. this.onnegotiationneeded = null;
  14214. this.peerconnection.onnegotiationneeded = function (event) {
  14215. self.trace('onnegotiationneeded');
  14216. if (self.onnegotiationneeded !== null) {
  14217. self.onnegotiationneeded(event);
  14218. }
  14219. };
  14220. self.ondatachannel = null;
  14221. this.peerconnection.ondatachannel = function (event) {
  14222. self.trace('ondatachannel', event);
  14223. if (self.ondatachannel !== null) {
  14224. self.ondatachannel(event);
  14225. }
  14226. };
  14227. // XXX: do all non-firefox browsers which we support also support this?
  14228. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14229. this.statsinterval = window.setInterval(function() {
  14230. self.peerconnection.getStats(function(stats) {
  14231. var results = stats.result();
  14232. for (var i = 0; i < results.length; ++i) {
  14233. //console.log(results[i].type, results[i].id, results[i].names())
  14234. var now = new Date();
  14235. results[i].names().forEach(function (name) {
  14236. var id = results[i].id + '-' + name;
  14237. if (!self.stats[id]) {
  14238. self.stats[id] = {
  14239. startTime: now,
  14240. endTime: now,
  14241. values: [],
  14242. times: []
  14243. };
  14244. }
  14245. self.stats[id].values.push(results[i].stat(name));
  14246. self.stats[id].times.push(now.getTime());
  14247. if (self.stats[id].values.length > self.maxstats) {
  14248. self.stats[id].values.shift();
  14249. self.stats[id].times.shift();
  14250. }
  14251. self.stats[id].endTime = now;
  14252. });
  14253. }
  14254. });
  14255. }, 1000);
  14256. }
  14257. };
  14258. dumpSDP = function(description) {
  14259. if (typeof description === 'undefined' || description == null) {
  14260. return '';
  14261. }
  14262. return 'type: ' + description.type + '\r\n' + description.sdp;
  14263. };
  14264. /**
  14265. * Takes a SessionDescription object and returns a "normalized" version.
  14266. * Currently it only takes care of ordering the a=ssrc lines.
  14267. */
  14268. normalizePlanB = function(desc) {
  14269. if (typeof desc !== 'object' || desc === null ||
  14270. typeof desc.sdp !== 'string') {
  14271. console.warn('An empty description was passed as an argument.');
  14272. return desc;
  14273. }
  14274. var transform = require('sdp-transform');
  14275. var session = transform.parse(desc.sdp);
  14276. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14277. Array.isArray(session.media)) {
  14278. session.media.forEach(function (mLine) {
  14279. // Chrome appears to be picky about the order in which a=ssrc lines
  14280. // are listed in an m-line when rtx is enabled (and thus there are
  14281. // a=ssrc-group lines with FID semantics). Specifically if we have
  14282. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14283. // the "a=ssrc:S1" lines, SRD fails.
  14284. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14285. // first.
  14286. var firstSsrcs = [];
  14287. var newSsrcLines = [];
  14288. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14289. mLine.ssrcGroups.forEach(function (group) {
  14290. if (typeof group.semantics !== 'undefined' &&
  14291. group.semantics === 'FID') {
  14292. if (typeof group.ssrcs !== 'undefined') {
  14293. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14294. }
  14295. }
  14296. });
  14297. }
  14298. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14299. for (var i = 0; i<mLine.ssrcs.length; i++){
  14300. if (typeof mLine.ssrcs[i] === 'object'
  14301. && typeof mLine.ssrcs[i].id !== 'undefined'
  14302. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14303. newSsrcLines.push(mLine.ssrcs[i]);
  14304. delete mLine.ssrcs[i];
  14305. }
  14306. }
  14307. for (var i = 0; i<mLine.ssrcs.length; i++){
  14308. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14309. newSsrcLines.push(mLine.ssrcs[i]);
  14310. }
  14311. }
  14312. mLine.ssrcs = newSsrcLines;
  14313. }
  14314. });
  14315. }
  14316. var resStr = transform.write(session);
  14317. return new RTCSessionDescription({
  14318. type: desc.type,
  14319. sdp: resStr
  14320. });
  14321. };
  14322. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14323. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  14324. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  14325. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  14326. var desc = this.peerconnection.localDescription;
  14327. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14328. // if we're running on FF, transform to Plan B first.
  14329. if (RTCBrowserType.usesUnifiedPlan()) {
  14330. desc = this.interop.toPlanB(desc);
  14331. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14332. }
  14333. return desc;
  14334. });
  14335. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  14336. var desc = this.peerconnection.remoteDescription;
  14337. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14338. // if we're running on FF, transform to Plan B first.
  14339. if (RTCBrowserType.usesUnifiedPlan()) {
  14340. desc = this.interop.toPlanB(desc);
  14341. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14342. }
  14343. return desc;
  14344. });
  14345. }
  14346. TraceablePeerConnection.prototype.addStream = function (stream) {
  14347. this.trace('addStream', stream.id);
  14348. try
  14349. {
  14350. this.peerconnection.addStream(stream);
  14351. }
  14352. catch (e)
  14353. {
  14354. console.error(e);
  14355. return;
  14356. }
  14357. };
  14358. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14359. this.trace('removeStream', stream.id);
  14360. if(stopStreams) {
  14361. stream.getAudioTracks().forEach(function (track) {
  14362. // stop() not supported with IE
  14363. if (track.stop) {
  14364. track.stop();
  14365. }
  14366. });
  14367. stream.getVideoTracks().forEach(function (track) {
  14368. // stop() not supported with IE
  14369. if (track.stop) {
  14370. track.stop();
  14371. }
  14372. });
  14373. if (stream.stop) {
  14374. stream.stop();
  14375. }
  14376. }
  14377. try {
  14378. // FF doesn't support this yet.
  14379. if (this.peerconnection.removeStream)
  14380. this.peerconnection.removeStream(stream);
  14381. } catch (e) {
  14382. console.error(e);
  14383. }
  14384. };
  14385. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14386. this.trace('createDataChannel', label, opts);
  14387. return this.peerconnection.createDataChannel(label, opts);
  14388. };
  14389. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  14390. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14391. // if we're running on FF, transform to Plan A first.
  14392. if (RTCBrowserType.usesUnifiedPlan()) {
  14393. description = this.interop.toUnifiedPlan(description);
  14394. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14395. }
  14396. var self = this;
  14397. this.peerconnection.setLocalDescription(description,
  14398. function () {
  14399. self.trace('setLocalDescriptionOnSuccess');
  14400. successCallback();
  14401. },
  14402. function (err) {
  14403. self.trace('setLocalDescriptionOnFailure', err);
  14404. failureCallback(err);
  14405. }
  14406. );
  14407. /*
  14408. if (this.statsinterval === null && this.maxstats > 0) {
  14409. // start gathering stats
  14410. }
  14411. */
  14412. };
  14413. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  14414. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14415. // TODO the focus should squeze or explode the remote simulcast
  14416. description = this.simulcast.mungeRemoteDescription(description);
  14417. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14418. // if we're running on FF, transform to Plan A first.
  14419. if (RTCBrowserType.usesUnifiedPlan()) {
  14420. description = this.interop.toUnifiedPlan(description);
  14421. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14422. }
  14423. if (RTCBrowserType.usesPlanB()) {
  14424. description = normalizePlanB(description);
  14425. }
  14426. var self = this;
  14427. this.peerconnection.setRemoteDescription(description,
  14428. function () {
  14429. self.trace('setRemoteDescriptionOnSuccess');
  14430. successCallback();
  14431. },
  14432. function (err) {
  14433. self.trace('setRemoteDescriptionOnFailure', err);
  14434. failureCallback(err);
  14435. }
  14436. );
  14437. /*
  14438. if (this.statsinterval === null && this.maxstats > 0) {
  14439. // start gathering stats
  14440. }
  14441. */
  14442. };
  14443. TraceablePeerConnection.prototype.close = function () {
  14444. this.trace('stop');
  14445. if (this.statsinterval !== null) {
  14446. window.clearInterval(this.statsinterval);
  14447. this.statsinterval = null;
  14448. }
  14449. this.peerconnection.close();
  14450. };
  14451. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  14452. var self = this;
  14453. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14454. this.peerconnection.createOffer(
  14455. function (offer) {
  14456. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14457. // if we're running on FF, transform to Plan B first.
  14458. // NOTE this is not tested because in meet the focus generates the
  14459. // offer.
  14460. if (RTCBrowserType.usesUnifiedPlan()) {
  14461. offer = self.interop.toPlanB(offer);
  14462. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14463. }
  14464. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14465. offer = self.simulcast.mungeLocalDescription(offer);
  14466. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14467. }
  14468. successCallback(offer);
  14469. },
  14470. function(err) {
  14471. self.trace('createOfferOnFailure', err);
  14472. failureCallback(err);
  14473. },
  14474. constraints
  14475. );
  14476. };
  14477. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  14478. var self = this;
  14479. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14480. this.peerconnection.createAnswer(
  14481. function (answer) {
  14482. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  14483. // if we're running on FF, transform to Plan A first.
  14484. if (RTCBrowserType.usesUnifiedPlan()) {
  14485. answer = self.interop.toPlanB(answer);
  14486. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  14487. }
  14488. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14489. answer = self.simulcast.mungeLocalDescription(answer);
  14490. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  14491. }
  14492. successCallback(answer);
  14493. },
  14494. function(err) {
  14495. self.trace('createAnswerOnFailure', err);
  14496. failureCallback(err);
  14497. },
  14498. constraints
  14499. );
  14500. };
  14501. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  14502. var self = this;
  14503. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14504. this.peerconnection.addIceCandidate(candidate);
  14505. /* maybe later
  14506. this.peerconnection.addIceCandidate(candidate,
  14507. function () {
  14508. self.trace('addIceCandidateOnSuccess');
  14509. successCallback();
  14510. },
  14511. function (err) {
  14512. self.trace('addIceCandidateOnFailure', err);
  14513. failureCallback(err);
  14514. }
  14515. );
  14516. */
  14517. };
  14518. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14519. // TODO: Is this the correct way to handle Opera, Temasys?
  14520. if (RTCBrowserType.isFirefox()) {
  14521. // ignore for now...
  14522. if(!errback)
  14523. errback = function () {};
  14524. this.peerconnection.getStats(null,callback,errback);
  14525. } else {
  14526. this.peerconnection.getStats(callback);
  14527. }
  14528. };
  14529. module.exports = TraceablePeerConnection;
  14530. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"sdp-interop":91,"sdp-simulcast":94,"sdp-transform":97}],60:[function(require,module,exports){
  14531. /* global $, $iq, APP, config, connection, messageHandler,
  14532. roomName, sessionTerminated, Strophe, Util */
  14533. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14534. var Settings = require("../settings/Settings");
  14535. var AuthenticationEvents
  14536. = require("../../service/authentication/AuthenticationEvents");
  14537. /**
  14538. * Contains logic responsible for enabling/disabling functionality available
  14539. * only to moderator users.
  14540. */
  14541. var connection = null;
  14542. var focusUserJid;
  14543. function createExpBackoffTimer(step) {
  14544. var count = 1;
  14545. return function (reset) {
  14546. // Reset call
  14547. if (reset) {
  14548. count = 1;
  14549. return;
  14550. }
  14551. // Calculate next timeout
  14552. var timeout = Math.pow(2, count - 1);
  14553. count += 1;
  14554. return timeout * step;
  14555. };
  14556. }
  14557. var getNextTimeout = createExpBackoffTimer(1000);
  14558. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14559. // External authentication stuff
  14560. var externalAuthEnabled = false;
  14561. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14562. // it will be enabled automatically if focus detects the component through
  14563. // service discovery.
  14564. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14565. var eventEmitter = null;
  14566. var Moderator = {
  14567. isModerator: function () {
  14568. return connection && connection.emuc.isModerator();
  14569. },
  14570. isPeerModerator: function (peerJid) {
  14571. return connection &&
  14572. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14573. },
  14574. isExternalAuthEnabled: function () {
  14575. return externalAuthEnabled;
  14576. },
  14577. isSipGatewayEnabled: function () {
  14578. return sipGatewayEnabled;
  14579. },
  14580. setConnection: function (con) {
  14581. connection = con;
  14582. },
  14583. init: function (xmpp, emitter) {
  14584. this.xmppService = xmpp;
  14585. eventEmitter = emitter;
  14586. // Message listener that talks to POPUP window
  14587. function listener(event) {
  14588. if (event.data && event.data.sessionId) {
  14589. if (event.origin !== window.location.origin) {
  14590. console.warn(
  14591. "Ignoring sessionId from different origin: " + event.origin);
  14592. return;
  14593. }
  14594. localStorage.setItem('sessionId', event.data.sessionId);
  14595. // After popup is closed we will authenticate
  14596. }
  14597. }
  14598. // Register
  14599. if (window.addEventListener) {
  14600. window.addEventListener("message", listener, false);
  14601. } else {
  14602. window.attachEvent("onmessage", listener);
  14603. }
  14604. },
  14605. onMucMemberLeft: function (jid) {
  14606. console.info("Someone left is it focus ? " + jid);
  14607. var resource = Strophe.getResourceFromJid(jid);
  14608. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14609. console.info(
  14610. "Focus has left the room - leaving conference");
  14611. //hangUp();
  14612. // We'd rather reload to have everything re-initialized
  14613. // FIXME: show some message before reload
  14614. location.reload();
  14615. }
  14616. },
  14617. setFocusUserJid: function (focusJid) {
  14618. if (!focusUserJid) {
  14619. focusUserJid = focusJid;
  14620. console.info("Focus jid set to: " + focusUserJid);
  14621. }
  14622. },
  14623. getFocusUserJid: function () {
  14624. return focusUserJid;
  14625. },
  14626. getFocusComponent: function () {
  14627. // Get focus component address
  14628. var focusComponent = config.hosts.focus;
  14629. // If not specified use default: 'focus.domain'
  14630. if (!focusComponent) {
  14631. focusComponent = 'focus.' + config.hosts.domain;
  14632. }
  14633. return focusComponent;
  14634. },
  14635. createConferenceIq: function (roomName) {
  14636. // Generate create conference IQ
  14637. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14638. // Session Id used for authentication
  14639. var sessionId = localStorage.getItem('sessionId');
  14640. var machineUID = Settings.getSettings().uid;
  14641. console.info(
  14642. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14643. elem.c('conference', {
  14644. xmlns: 'http://jitsi.org/protocol/focus',
  14645. room: roomName,
  14646. 'machine-uid': machineUID
  14647. });
  14648. if (sessionId) {
  14649. elem.attrs({ 'session-id': sessionId});
  14650. }
  14651. if (config.hosts.bridge !== undefined) {
  14652. elem.c(
  14653. 'property',
  14654. { name: 'bridge', value: config.hosts.bridge})
  14655. .up();
  14656. }
  14657. // Tell the focus we have Jigasi configured
  14658. if (config.hosts.call_control !== undefined) {
  14659. elem.c(
  14660. 'property',
  14661. { name: 'call_control', value: config.hosts.call_control})
  14662. .up();
  14663. }
  14664. if (config.channelLastN !== undefined) {
  14665. elem.c(
  14666. 'property',
  14667. { name: 'channelLastN', value: config.channelLastN})
  14668. .up();
  14669. }
  14670. if (config.adaptiveLastN !== undefined) {
  14671. elem.c(
  14672. 'property',
  14673. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14674. .up();
  14675. }
  14676. if (config.adaptiveSimulcast !== undefined) {
  14677. elem.c(
  14678. 'property',
  14679. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14680. .up();
  14681. }
  14682. if (config.openSctp !== undefined) {
  14683. elem.c(
  14684. 'property',
  14685. { name: 'openSctp', value: config.openSctp})
  14686. .up();
  14687. }
  14688. if(config.startAudioMuted !== undefined)
  14689. {
  14690. elem.c(
  14691. 'property',
  14692. { name: 'startAudioMuted', value: config.startAudioMuted})
  14693. .up();
  14694. }
  14695. if(config.startVideoMuted !== undefined)
  14696. {
  14697. elem.c(
  14698. 'property',
  14699. { name: 'startVideoMuted', value: config.startVideoMuted})
  14700. .up();
  14701. }
  14702. elem.c(
  14703. 'property',
  14704. { name: 'simulcastMode', value: 'rewriting'})
  14705. .up();
  14706. elem.up();
  14707. return elem;
  14708. },
  14709. parseSessionId: function (resultIq) {
  14710. var sessionId = $(resultIq).find('conference').attr('session-id');
  14711. if (sessionId) {
  14712. console.info('Received sessionId: ' + sessionId);
  14713. localStorage.setItem('sessionId', sessionId);
  14714. }
  14715. },
  14716. parseConfigOptions: function (resultIq) {
  14717. Moderator.setFocusUserJid(
  14718. $(resultIq).find('conference').attr('focusjid'));
  14719. var authenticationEnabled
  14720. = $(resultIq).find(
  14721. '>conference>property' +
  14722. '[name=\'authentication\'][value=\'true\']').length > 0;
  14723. console.info("Authentication enabled: " + authenticationEnabled);
  14724. externalAuthEnabled
  14725. = $(resultIq).find(
  14726. '>conference>property' +
  14727. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14728. console.info('External authentication enabled: ' + externalAuthEnabled);
  14729. if (!externalAuthEnabled) {
  14730. // We expect to receive sessionId in 'internal' authentication mode
  14731. Moderator.parseSessionId(resultIq);
  14732. }
  14733. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14734. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14735. authenticationEnabled, authIdentity);
  14736. // Check if focus has auto-detected Jigasi component(this will be also
  14737. // included if we have passed our host from the config)
  14738. if ($(resultIq).find(
  14739. '>conference>property' +
  14740. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14741. sipGatewayEnabled = true;
  14742. }
  14743. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14744. },
  14745. // FIXME: we need to show the fact that we're waiting for the focus
  14746. // to the user(or that focus is not available)
  14747. allocateConferenceFocus: function (roomName, callback) {
  14748. // Try to use focus user JID from the config
  14749. Moderator.setFocusUserJid(config.focusUserJid);
  14750. // Send create conference IQ
  14751. var iq = Moderator.createConferenceIq(roomName);
  14752. var self = this;
  14753. connection.sendIQ(
  14754. iq,
  14755. function (result) {
  14756. // Setup config options
  14757. Moderator.parseConfigOptions(result);
  14758. if ('true' === $(result).find('conference').attr('ready')) {
  14759. // Reset both timers
  14760. getNextTimeout(true);
  14761. getNextErrorTimeout(true);
  14762. // Exec callback
  14763. callback();
  14764. } else {
  14765. var waitMs = getNextTimeout();
  14766. console.info("Waiting for the focus... " + waitMs);
  14767. // Reset error timeout
  14768. getNextErrorTimeout(true);
  14769. window.setTimeout(
  14770. function () {
  14771. Moderator.allocateConferenceFocus(
  14772. roomName, callback);
  14773. }, waitMs);
  14774. }
  14775. },
  14776. function (error) {
  14777. // Invalid session ? remove and try again
  14778. // without session ID to get a new one
  14779. var invalidSession
  14780. = $(error).find('>error>session-invalid').length;
  14781. if (invalidSession) {
  14782. console.info("Session expired! - removing");
  14783. localStorage.removeItem("sessionId");
  14784. }
  14785. if ($(error).find('>error>graceful-shutdown').length) {
  14786. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14787. return;
  14788. }
  14789. // Check for error returned by the reservation system
  14790. var reservationErr = $(error).find('>error>reservation-error');
  14791. if (reservationErr.length) {
  14792. // Trigger error event
  14793. var errorCode = reservationErr.attr('error-code');
  14794. var errorMsg;
  14795. if ($(error).find('>error>text')) {
  14796. errorMsg = $(error).find('>error>text').text();
  14797. }
  14798. eventEmitter.emit(
  14799. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14800. return;
  14801. }
  14802. // Not authorized to create new room
  14803. if ($(error).find('>error>not-authorized').length) {
  14804. console.warn("Unauthorized to start the conference", error);
  14805. var toDomain
  14806. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14807. if (toDomain !== config.hosts.anonymousdomain) {
  14808. // FIXME: "is external" should come either from
  14809. // the focus or config.js
  14810. externalAuthEnabled = true;
  14811. }
  14812. eventEmitter.emit(
  14813. XMPPEvents.AUTHENTICATION_REQUIRED,
  14814. function () {
  14815. Moderator.allocateConferenceFocus(
  14816. roomName, callback);
  14817. });
  14818. return;
  14819. }
  14820. var waitMs = getNextErrorTimeout();
  14821. console.error("Focus error, retry after " + waitMs, error);
  14822. // Show message
  14823. var focusComponent = Moderator.getFocusComponent();
  14824. var retrySec = waitMs / 1000;
  14825. // FIXME: message is duplicated ?
  14826. // Do not show in case of session invalid
  14827. // which means just a retry
  14828. if (!invalidSession) {
  14829. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED, focusComponent, retrySec);
  14830. }
  14831. // Reset response timeout
  14832. getNextTimeout(true);
  14833. window.setTimeout(
  14834. function () {
  14835. Moderator.allocateConferenceFocus(roomName, callback);
  14836. }, waitMs);
  14837. }
  14838. );
  14839. },
  14840. getLoginUrl: function (roomName, urlCallback) {
  14841. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14842. iq.c('login-url', {
  14843. xmlns: 'http://jitsi.org/protocol/focus',
  14844. room: roomName,
  14845. 'machine-uid': Settings.getSettings().uid
  14846. });
  14847. connection.sendIQ(
  14848. iq,
  14849. function (result) {
  14850. var url = $(result).find('login-url').attr('url');
  14851. url = url = decodeURIComponent(url);
  14852. if (url) {
  14853. console.info("Got auth url: " + url);
  14854. urlCallback(url);
  14855. } else {
  14856. console.error(
  14857. "Failed to get auth url from the focus", result);
  14858. }
  14859. },
  14860. function (error) {
  14861. console.error("Get auth url error", error);
  14862. }
  14863. );
  14864. },
  14865. getPopupLoginUrl: function (roomName, urlCallback) {
  14866. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14867. iq.c('login-url', {
  14868. xmlns: 'http://jitsi.org/protocol/focus',
  14869. room: roomName,
  14870. 'machine-uid': Settings.getSettings().uid,
  14871. popup: true
  14872. });
  14873. connection.sendIQ(
  14874. iq,
  14875. function (result) {
  14876. var url = $(result).find('login-url').attr('url');
  14877. url = url = decodeURIComponent(url);
  14878. if (url) {
  14879. console.info("Got POPUP auth url: " + url);
  14880. urlCallback(url);
  14881. } else {
  14882. console.error(
  14883. "Failed to get POPUP auth url from the focus", result);
  14884. }
  14885. },
  14886. function (error) {
  14887. console.error('Get POPUP auth url error', error);
  14888. }
  14889. );
  14890. },
  14891. logout: function (callback) {
  14892. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14893. var sessionId = localStorage.getItem('sessionId');
  14894. if (!sessionId) {
  14895. callback();
  14896. return;
  14897. }
  14898. iq.c('logout', {
  14899. xmlns: 'http://jitsi.org/protocol/focus',
  14900. 'session-id': sessionId
  14901. });
  14902. connection.sendIQ(
  14903. iq,
  14904. function (result) {
  14905. var logoutUrl = $(result).find('logout').attr('logout-url');
  14906. if (logoutUrl) {
  14907. logoutUrl = decodeURIComponent(logoutUrl);
  14908. }
  14909. console.info("Log out OK, url: " + logoutUrl, result);
  14910. localStorage.removeItem('sessionId');
  14911. callback(logoutUrl);
  14912. },
  14913. function (error) {
  14914. console.error("Logout error", error);
  14915. }
  14916. );
  14917. }
  14918. };
  14919. module.exports = Moderator;
  14920. },{"../../service/authentication/AuthenticationEvents":105,"../../service/xmpp/XMPPEvents":110,"../settings/Settings":49}],61:[function(require,module,exports){
  14921. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14922. Toolbar, Util */
  14923. var Moderator = require("./moderator");
  14924. var recordingToken = null;
  14925. var recordingEnabled;
  14926. /**
  14927. * Whether to use a jirecon component for recording, or use the videobridge
  14928. * through COLIBRI.
  14929. */
  14930. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14931. /**
  14932. * The ID of the jirecon recording session. Jirecon generates it when we
  14933. * initially start recording, and it needs to be used in subsequent requests
  14934. * to jirecon.
  14935. */
  14936. var jireconRid = null;
  14937. function setRecordingToken(token) {
  14938. recordingToken = token;
  14939. }
  14940. function setRecording(state, token, callback, connection) {
  14941. if (useJirecon){
  14942. setRecordingJirecon(state, token, callback, connection);
  14943. } else {
  14944. setRecordingColibri(state, token, callback, connection);
  14945. }
  14946. }
  14947. function setRecordingJirecon(state, token, callback, connection) {
  14948. if (state == recordingEnabled){
  14949. return;
  14950. }
  14951. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14952. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14953. action: state ? 'start' : 'stop',
  14954. mucjid: connection.emuc.roomjid});
  14955. if (!state){
  14956. iq.attrs({rid: jireconRid});
  14957. }
  14958. console.log('Start recording');
  14959. connection.sendIQ(
  14960. iq,
  14961. function (result) {
  14962. // TODO wait for an IQ with the real status, since this is
  14963. // provisional?
  14964. jireconRid = $(result).find('recording').attr('rid');
  14965. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14966. '(jirecon)' + result);
  14967. recordingEnabled = state;
  14968. if (!state){
  14969. jireconRid = null;
  14970. }
  14971. callback(state);
  14972. },
  14973. function (error) {
  14974. console.log('Failed to start recording, error: ', error);
  14975. callback(recordingEnabled);
  14976. });
  14977. }
  14978. // Sends a COLIBRI message which enables or disables (according to 'state')
  14979. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14980. // with the new recording state, according to the IQ.
  14981. function setRecordingColibri(state, token, callback, connection) {
  14982. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14983. elem.c('conference', {
  14984. xmlns: 'http://jitsi.org/protocol/colibri'
  14985. });
  14986. elem.c('recording', {state: state, token: token});
  14987. connection.sendIQ(elem,
  14988. function (result) {
  14989. console.log('Set recording "', state, '". Result:', result);
  14990. var recordingElem = $(result).find('>conference>recording');
  14991. var newState = ('true' === recordingElem.attr('state'));
  14992. recordingEnabled = newState;
  14993. callback(newState);
  14994. },
  14995. function (error) {
  14996. console.warn(error);
  14997. callback(recordingEnabled);
  14998. }
  14999. );
  15000. }
  15001. var Recording = {
  15002. toggleRecording: function (tokenEmptyCallback,
  15003. startingCallback, startedCallback, connection) {
  15004. if (!Moderator.isModerator()) {
  15005. console.log(
  15006. 'non-focus, or conference not yet organized:' +
  15007. ' not enabling recording');
  15008. return;
  15009. }
  15010. var self = this;
  15011. // Jirecon does not (currently) support a token.
  15012. if (!recordingToken && !useJirecon) {
  15013. tokenEmptyCallback(function (value) {
  15014. setRecordingToken(value);
  15015. self.toggleRecording(tokenEmptyCallback,
  15016. startingCallback, startedCallback, connection);
  15017. });
  15018. return;
  15019. }
  15020. var oldState = recordingEnabled;
  15021. startingCallback(!oldState);
  15022. setRecording(!oldState,
  15023. recordingToken,
  15024. function (state) {
  15025. console.log("New recording state: ", state);
  15026. if (state === oldState) {
  15027. // FIXME: new focus:
  15028. // this will not work when moderator changes
  15029. // during active session. Then it will assume that
  15030. // recording status has changed to true, but it might have
  15031. // been already true(and we only received actual status from
  15032. // the focus).
  15033. //
  15034. // SO we start with status null, so that it is initialized
  15035. // here and will fail only after second click, so if invalid
  15036. // token was used we have to press the button twice before
  15037. // current status will be fetched and token will be reset.
  15038. //
  15039. // Reliable way would be to return authentication error.
  15040. // Or status update when moderator connects.
  15041. // Or we have to stop recording session when current
  15042. // moderator leaves the room.
  15043. // Failed to change, reset the token because it might
  15044. // have been wrong
  15045. setRecordingToken(null);
  15046. }
  15047. startedCallback(state);
  15048. },
  15049. connection
  15050. );
  15051. }
  15052. }
  15053. module.exports = Recording;
  15054. },{"./moderator":60}],62:[function(require,module,exports){
  15055. /* jshint -W117 */
  15056. /* a simple MUC connection plugin
  15057. * can only handle a single MUC room
  15058. */
  15059. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15060. var Moderator = require("./moderator");
  15061. var JingleSession = require("./JingleSession");
  15062. var bridgeIsDown = false;
  15063. module.exports = function(XMPP, eventEmitter) {
  15064. Strophe.addConnectionPlugin('emuc', {
  15065. connection: null,
  15066. roomjid: null,
  15067. myroomjid: null,
  15068. members: {},
  15069. list_members: [], // so we can elect a new focus
  15070. presMap: {},
  15071. preziMap: {},
  15072. joined: false,
  15073. isOwner: false,
  15074. role: null,
  15075. focusMucJid: null,
  15076. init: function (conn) {
  15077. this.connection = conn;
  15078. },
  15079. initPresenceMap: function (myroomjid) {
  15080. this.presMap['to'] = myroomjid;
  15081. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15082. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted())
  15083. {
  15084. this.addAudioInfoToPresence(true);
  15085. }
  15086. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted())
  15087. {
  15088. this.addVideoInfoToPresence(true);
  15089. }
  15090. },
  15091. doJoin: function (jid, password) {
  15092. this.myroomjid = jid;
  15093. console.info("Joined MUC as " + this.myroomjid);
  15094. this.initPresenceMap(this.myroomjid);
  15095. if (!this.roomjid) {
  15096. this.roomjid = Strophe.getBareJidFromJid(jid);
  15097. // add handlers (just once)
  15098. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15099. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15100. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15101. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15102. }
  15103. if (password !== undefined) {
  15104. this.presMap['password'] = password;
  15105. }
  15106. this.sendPresence();
  15107. },
  15108. doLeave: function () {
  15109. console.log("do leave", this.myroomjid);
  15110. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15111. this.presMap.length = 0;
  15112. this.connection.send(pres);
  15113. },
  15114. createNonAnonymousRoom: function () {
  15115. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15116. var getForm = $iq({type: 'get', to: this.roomjid})
  15117. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15118. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15119. var self = this;
  15120. this.connection.sendIQ(getForm, function (form) {
  15121. if (!$(form).find(
  15122. '>query>x[xmlns="jabber:x:data"]' +
  15123. '>field[var="muc#roomconfig_whois"]').length) {
  15124. console.error('non-anonymous rooms not supported');
  15125. return;
  15126. }
  15127. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15128. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15129. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15130. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15131. .c('value')
  15132. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15133. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15134. .c('value').t('anyone').up().up();
  15135. self.connection.sendIQ(formSubmit);
  15136. }, function (error) {
  15137. console.error("Error getting room configuration form");
  15138. });
  15139. },
  15140. onPresence: function (pres) {
  15141. var from = pres.getAttribute('from');
  15142. // What is this for? A workaround for something?
  15143. if (pres.getAttribute('type')) {
  15144. return true;
  15145. }
  15146. // Parse etherpad tag.
  15147. var etherpad = $(pres).find('>etherpad');
  15148. if (etherpad.length) {
  15149. if (config.etherpad_base) {
  15150. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15151. }
  15152. }
  15153. // Parse prezi tag.
  15154. var presentation = $(pres).find('>prezi');
  15155. if (presentation.length) {
  15156. var url = presentation.attr('url');
  15157. var current = presentation.find('>current').text();
  15158. console.log('presentation info received from', from, url);
  15159. if (this.preziMap[from] == null) {
  15160. this.preziMap[from] = url;
  15161. $(document).trigger('presentationadded.muc', [from, url, current]);
  15162. }
  15163. else {
  15164. $(document).trigger('gotoslide.muc', [from, url, current]);
  15165. }
  15166. }
  15167. else if (this.preziMap[from] != null) {
  15168. var url = this.preziMap[from];
  15169. delete this.preziMap[from];
  15170. $(document).trigger('presentationremoved.muc', [from, url]);
  15171. }
  15172. // Parse audio info tag.
  15173. var audioMuted = $(pres).find('>audiomuted');
  15174. if (audioMuted.length) {
  15175. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15176. from, (audioMuted.text() === "true"));
  15177. }
  15178. // Parse video info tag.
  15179. var videoMuted = $(pres).find('>videomuted');
  15180. if (videoMuted.length) {
  15181. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15182. from, (videoMuted.text() === "true"));
  15183. }
  15184. var startMuted = $(pres).find('>startmuted');
  15185. if (startMuted.length)
  15186. {
  15187. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15188. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15189. }
  15190. var devices = $(pres).find('>devices');
  15191. if(devices.length)
  15192. {
  15193. var audio = devices.find('>audio');
  15194. var video = devices.find('>video');
  15195. var devicesValues = {audio: false, video: false};
  15196. if(audio.length && audio.text() === "true")
  15197. {
  15198. devicesValues.audio = true;
  15199. }
  15200. if(video.length && video.text() === "true")
  15201. {
  15202. devicesValues.video = true;
  15203. }
  15204. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15205. Strophe.getResourceFromJid(from), devicesValues);
  15206. }
  15207. var stats = $(pres).find('>stats');
  15208. if (stats.length) {
  15209. var statsObj = {};
  15210. Strophe.forEachChild(stats[0], "stat", function (el) {
  15211. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15212. });
  15213. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15214. }
  15215. // Parse status.
  15216. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15217. this.isOwner = true;
  15218. this.createNonAnonymousRoom();
  15219. }
  15220. // Parse roles.
  15221. var member = {};
  15222. member.show = $(pres).find('>show').text();
  15223. member.status = $(pres).find('>status').text();
  15224. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15225. member.affiliation = tmp.attr('affiliation');
  15226. member.role = tmp.attr('role');
  15227. // Focus recognition
  15228. member.jid = tmp.attr('jid');
  15229. member.isFocus = false;
  15230. if (member.jid
  15231. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15232. member.isFocus = true;
  15233. }
  15234. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15235. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15236. if (from == this.myroomjid) {
  15237. if (member.affiliation == 'owner') this.isOwner = true;
  15238. if (this.role !== member.role) {
  15239. this.role = member.role;
  15240. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15241. from, member, pres, Moderator.isModerator());
  15242. }
  15243. if (!this.joined) {
  15244. this.joined = true;
  15245. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15246. this.list_members.push(from);
  15247. }
  15248. } else if (this.members[from] === undefined) {
  15249. // new participant
  15250. this.members[from] = member;
  15251. this.list_members.push(from);
  15252. console.log('entered', from, member);
  15253. if (member.isFocus) {
  15254. this.focusMucJid = from;
  15255. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15256. }
  15257. else {
  15258. var id = $(pres).find('>userId').text();
  15259. var email = $(pres).find('>email');
  15260. if (email.length > 0) {
  15261. id = email.text();
  15262. }
  15263. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15264. }
  15265. } else {
  15266. // Presence update for existing participant
  15267. // Watch role change:
  15268. if (this.members[from].role != member.role) {
  15269. this.members[from].role = member.role;
  15270. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15271. member.role, member.displayName);
  15272. }
  15273. }
  15274. // Always trigger presence to update bindings
  15275. this.parsePresence(from, member, pres);
  15276. // Trigger status message update
  15277. if (member.status) {
  15278. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15279. }
  15280. return true;
  15281. },
  15282. onPresenceUnavailable: function (pres) {
  15283. var from = pres.getAttribute('from');
  15284. // room destroyed ?
  15285. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15286. '>destroy').length) {
  15287. var reason;
  15288. var reasonSelect = $(pres).find(
  15289. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15290. '>destroy>reason');
  15291. if (reasonSelect.length) {
  15292. reason = reasonSelect.text();
  15293. }
  15294. XMPP.disposeConference(false);
  15295. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15296. return true;
  15297. }
  15298. // Status code 110 indicates that this notification is "self-presence".
  15299. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15300. delete this.members[from];
  15301. this.list_members.splice(this.list_members.indexOf(from), 1);
  15302. this.onParticipantLeft(from);
  15303. }
  15304. // If the status code is 110 this means we're leaving and we would like
  15305. // to remove everyone else from our view, so we trigger the event.
  15306. else if (this.list_members.length > 1) {
  15307. for (var i = 0; i < this.list_members.length; i++) {
  15308. var member = this.list_members[i];
  15309. delete this.members[i];
  15310. this.list_members.splice(i, 1);
  15311. this.onParticipantLeft(member);
  15312. }
  15313. }
  15314. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15315. $(document).trigger('kicked.muc', [from]);
  15316. if (this.myroomjid === from) {
  15317. XMPP.disposeConference(false);
  15318. eventEmitter.emit(XMPPEvents.KICKED);
  15319. }
  15320. }
  15321. return true;
  15322. },
  15323. onPresenceError: function (pres) {
  15324. var from = pres.getAttribute('from');
  15325. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15326. console.log('on password required', from);
  15327. var self = this;
  15328. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15329. self.doJoin(from, value);
  15330. });
  15331. } else if ($(pres).find(
  15332. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15333. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15334. if (toDomain === config.hosts.anonymousdomain) {
  15335. // enter the room by replying with 'not-authorized'. This would
  15336. // result in reconnection from authorized domain.
  15337. // We're either missing Jicofo/Prosody config for anonymous
  15338. // domains or something is wrong.
  15339. // XMPP.promptLogin();
  15340. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15341. } else {
  15342. console.warn('onPresError ', pres);
  15343. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15344. }
  15345. } else {
  15346. console.warn('onPresError ', pres);
  15347. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15348. }
  15349. return true;
  15350. },
  15351. sendMessage: function (body, nickname) {
  15352. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15353. msg.c('body', body).up();
  15354. if (nickname) {
  15355. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15356. }
  15357. this.connection.send(msg);
  15358. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15359. },
  15360. setSubject: function (subject) {
  15361. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15362. msg.c('subject', subject);
  15363. this.connection.send(msg);
  15364. console.log("topic changed to " + subject);
  15365. },
  15366. onMessage: function (msg) {
  15367. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15368. var from = msg.getAttribute('from');
  15369. var nick =
  15370. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15371. .text() ||
  15372. Strophe.getResourceFromJid(from);
  15373. var txt = $(msg).find('>body').text();
  15374. var type = msg.getAttribute("type");
  15375. if (type == "error") {
  15376. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15377. $(msg).find('>text').text(), txt);
  15378. return true;
  15379. }
  15380. var subject = $(msg).find('>subject');
  15381. if (subject.length) {
  15382. var subjectText = subject.text();
  15383. if (subjectText || subjectText == "") {
  15384. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15385. console.log("Subject is changed to " + subjectText);
  15386. }
  15387. }
  15388. // xep-0203 delay
  15389. var stamp = $(msg).find('>delay').attr('stamp');
  15390. if (!stamp) {
  15391. // or xep-0091 delay, UTC timestamp
  15392. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15393. if (stamp) {
  15394. // the format is CCYYMMDDThh:mm:ss
  15395. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15396. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15397. }
  15398. }
  15399. if (txt) {
  15400. console.log('chat', nick, txt);
  15401. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15402. from, nick, txt, this.myroomjid, stamp);
  15403. }
  15404. return true;
  15405. },
  15406. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15407. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15408. var ob = this;
  15409. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15410. function (res) {
  15411. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15412. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15413. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15414. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15415. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15416. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15417. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15418. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15419. ob.connection.sendIQ(formsubmit,
  15420. onSuccess,
  15421. onError);
  15422. } else {
  15423. onNotSupported();
  15424. }
  15425. }, onError);
  15426. },
  15427. kick: function (jid) {
  15428. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15429. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15430. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15431. .c('reason').t('You have been kicked.').up().up().up();
  15432. this.connection.sendIQ(
  15433. kickIQ,
  15434. function (result) {
  15435. console.log('Kick participant with jid: ', jid, result);
  15436. },
  15437. function (error) {
  15438. console.log('Kick participant error: ', error);
  15439. });
  15440. },
  15441. sendPresence: function () {
  15442. if (!this.presMap['to']) {
  15443. // Too early to send presence - not initialized
  15444. return;
  15445. }
  15446. var pres = $pres({to: this.presMap['to'] });
  15447. pres.c('x', {xmlns: this.presMap['xns']});
  15448. if (this.presMap['password']) {
  15449. pres.c('password').t(this.presMap['password']).up();
  15450. }
  15451. pres.up();
  15452. // Send XEP-0115 'c' stanza that contains our capabilities info
  15453. if (this.connection.caps) {
  15454. this.connection.caps.node = config.clientNode;
  15455. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15456. }
  15457. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15458. .t(navigator.userAgent).up();
  15459. if (this.presMap['bridgeIsDown']) {
  15460. pres.c('bridgeIsDown').up();
  15461. }
  15462. if (this.presMap['email']) {
  15463. pres.c('email').t(this.presMap['email']).up();
  15464. }
  15465. if (this.presMap['userId']) {
  15466. pres.c('userId').t(this.presMap['userId']).up();
  15467. }
  15468. if (this.presMap['displayName']) {
  15469. // XEP-0172
  15470. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15471. .t(this.presMap['displayName']).up();
  15472. }
  15473. if(this.presMap["devices"])
  15474. {
  15475. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15476. .c('video').t(this.presMap['devices'].video).up().up();
  15477. }
  15478. if (this.presMap['audions']) {
  15479. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15480. .t(this.presMap['audiomuted']).up();
  15481. }
  15482. if (this.presMap['videons']) {
  15483. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15484. .t(this.presMap['videomuted']).up();
  15485. }
  15486. if (this.presMap['statsns']) {
  15487. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15488. for (var stat in this.presMap["stats"])
  15489. if (this.presMap["stats"][stat] != null)
  15490. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15491. pres.up();
  15492. }
  15493. if (this.presMap['prezins']) {
  15494. pres.c('prezi',
  15495. {xmlns: this.presMap['prezins'],
  15496. 'url': this.presMap['preziurl']})
  15497. .c('current').t(this.presMap['prezicurrent']).up().up();
  15498. }
  15499. if(this.presMap["startMuted"] !== undefined)
  15500. {
  15501. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15502. video: this.presMap["startMuted"].video,
  15503. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15504. delete this.presMap["startMuted"];
  15505. }
  15506. pres.up();
  15507. this.connection.send(pres);
  15508. },
  15509. addDisplayNameToPresence: function (displayName) {
  15510. this.presMap['displayName'] = displayName;
  15511. },
  15512. addDevicesToPresence: function (devices) {
  15513. this.presMap['devices'] = devices;
  15514. },
  15515. addPreziToPresence: function (url, currentSlide) {
  15516. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15517. this.presMap['preziurl'] = url;
  15518. this.presMap['prezicurrent'] = currentSlide;
  15519. },
  15520. removePreziFromPresence: function () {
  15521. delete this.presMap['prezins'];
  15522. delete this.presMap['preziurl'];
  15523. delete this.presMap['prezicurrent'];
  15524. },
  15525. addCurrentSlideToPresence: function (currentSlide) {
  15526. this.presMap['prezicurrent'] = currentSlide;
  15527. },
  15528. getPrezi: function (roomjid) {
  15529. return this.preziMap[roomjid];
  15530. },
  15531. addAudioInfoToPresence: function (isMuted) {
  15532. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15533. this.presMap['audiomuted'] = isMuted.toString();
  15534. },
  15535. addVideoInfoToPresence: function (isMuted) {
  15536. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15537. this.presMap['videomuted'] = isMuted.toString();
  15538. },
  15539. addConnectionInfoToPresence: function (stats) {
  15540. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15541. this.presMap['stats'] = stats;
  15542. },
  15543. findJidFromResource: function (resourceJid) {
  15544. if (resourceJid &&
  15545. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15546. return this.myroomjid;
  15547. }
  15548. var peerJid = null;
  15549. Object.keys(this.members).some(function (jid) {
  15550. peerJid = jid;
  15551. return Strophe.getResourceFromJid(jid) === resourceJid;
  15552. });
  15553. return peerJid;
  15554. },
  15555. addBridgeIsDownToPresence: function () {
  15556. this.presMap['bridgeIsDown'] = true;
  15557. },
  15558. addEmailToPresence: function (email) {
  15559. this.presMap['email'] = email;
  15560. },
  15561. addUserIdToPresence: function (userId) {
  15562. this.presMap['userId'] = userId;
  15563. },
  15564. addStartMutedToPresence: function (audio, video) {
  15565. this.presMap["startMuted"] = {audio: audio, video: video};
  15566. },
  15567. isModerator: function () {
  15568. return this.role === 'moderator';
  15569. },
  15570. getMemberRole: function (peerJid) {
  15571. if (this.members[peerJid]) {
  15572. return this.members[peerJid].role;
  15573. }
  15574. return null;
  15575. },
  15576. onParticipantLeft: function (jid) {
  15577. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15578. this.connection.jingle.terminateByJid(jid);
  15579. if (this.getPrezi(jid)) {
  15580. $(document).trigger('presentationremoved.muc',
  15581. [jid, this.getPrezi(jid)]);
  15582. }
  15583. Moderator.onMucMemberLeft(jid);
  15584. },
  15585. parsePresence: function (from, memeber, pres) {
  15586. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  15587. bridgeIsDown = true;
  15588. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15589. }
  15590. if(memeber.isFocus)
  15591. return;
  15592. var displayName = !config.displayJids
  15593. ? memeber.displayName : Strophe.getResourceFromJid(from);
  15594. if (displayName && displayName.length > 0)
  15595. {
  15596. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15597. }
  15598. var id = $(pres).find('>userID').text();
  15599. var email = $(pres).find('>email');
  15600. if(email.length > 0) {
  15601. id = email.text();
  15602. }
  15603. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15604. }
  15605. });
  15606. };
  15607. },{"../../service/xmpp/XMPPEvents":110,"./JingleSession":55,"./moderator":60}],63:[function(require,module,exports){
  15608. /* jshint -W117 */
  15609. var JingleSession = require("./JingleSession");
  15610. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15611. var RTCBrowserType = require("../RTC/RTCBrowserType");
  15612. module.exports = function(XMPP, eventEmitter)
  15613. {
  15614. function CallIncomingJingle(sid, connection) {
  15615. var sess = connection.jingle.sessions[sid];
  15616. // TODO: do we check activecall == null?
  15617. connection.jingle.activecall = sess;
  15618. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15619. // TODO: check affiliation and/or role
  15620. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15621. sess.usedrip = true; // not-so-naive trickle ice
  15622. sess.sendAnswer();
  15623. sess.accept();
  15624. };
  15625. Strophe.addConnectionPlugin('jingle', {
  15626. connection: null,
  15627. sessions: {},
  15628. jid2session: {},
  15629. ice_config: {iceServers: []},
  15630. pc_constraints: {},
  15631. activecall: null,
  15632. media_constraints: {
  15633. mandatory: {
  15634. 'OfferToReceiveAudio': true,
  15635. 'OfferToReceiveVideo': true
  15636. }
  15637. // MozDontOfferDataChannel: true when this is firefox
  15638. },
  15639. init: function (conn) {
  15640. this.connection = conn;
  15641. if (this.connection.disco) {
  15642. // http://xmpp.org/extensions/xep-0167.html#support
  15643. // http://xmpp.org/extensions/xep-0176.html#support
  15644. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15645. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15646. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15647. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15648. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15649. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15650. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15651. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  15652. || RTCBrowserType.isTemasysPluginUsed()) {
  15653. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  15654. }
  15655. // this is dealt with by SDP O/A so we don't need to annouce this
  15656. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15657. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15658. if (config.useRtcpMux) {
  15659. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15660. }
  15661. if (config.useBundle) {
  15662. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15663. }
  15664. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15665. }
  15666. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15667. },
  15668. onJingle: function (iq) {
  15669. var sid = $(iq).find('jingle').attr('sid');
  15670. var action = $(iq).find('jingle').attr('action');
  15671. var fromJid = iq.getAttribute('from');
  15672. // send ack first
  15673. var ack = $iq({type: 'result',
  15674. to: fromJid,
  15675. id: iq.getAttribute('id')
  15676. });
  15677. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15678. var sess = this.sessions[sid];
  15679. if ('session-initiate' != action) {
  15680. if (sess === null) {
  15681. ack.type = 'error';
  15682. ack.c('error', {type: 'cancel'})
  15683. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15684. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15685. this.connection.send(ack);
  15686. return true;
  15687. }
  15688. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15689. // local jid is not checked
  15690. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15691. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15692. ack.type = 'error';
  15693. ack.c('error', {type: 'cancel'})
  15694. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15695. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15696. this.connection.send(ack);
  15697. return true;
  15698. }
  15699. } else if (sess !== undefined) {
  15700. // existing session with same session id
  15701. // this might be out-of-order if the sess.peerjid is the same as from
  15702. ack.type = 'error';
  15703. ack.c('error', {type: 'cancel'})
  15704. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15705. console.warn('duplicate session id', sid);
  15706. this.connection.send(ack);
  15707. return true;
  15708. }
  15709. // FIXME: check for a defined action
  15710. this.connection.send(ack);
  15711. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15712. switch (action) {
  15713. case 'session-initiate':
  15714. var startMuted = $(iq).find('jingle>startmuted');
  15715. if(startMuted && startMuted.length > 0)
  15716. {
  15717. var audioMuted = startMuted.attr("audio");
  15718. var videoMuted = startMuted.attr("video");
  15719. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  15720. autioMuted === "true", videoMuted === "true");
  15721. }
  15722. sess = new JingleSession(
  15723. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15724. this.connection, XMPP, eventEmitter);
  15725. // configure session
  15726. sess.media_constraints = this.media_constraints;
  15727. sess.pc_constraints = this.pc_constraints;
  15728. sess.ice_config = this.ice_config;
  15729. sess.initiate(fromJid, false);
  15730. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15731. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15732. this.sessions[sess.sid] = sess;
  15733. this.jid2session[sess.peerjid] = sess;
  15734. // the callback should either
  15735. // .sendAnswer and .accept
  15736. // or .sendTerminate -- not necessarily synchronus
  15737. CallIncomingJingle(sess.sid, this.connection);
  15738. break;
  15739. case 'session-accept':
  15740. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15741. sess.accept();
  15742. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15743. break;
  15744. case 'session-terminate':
  15745. // If this is not the focus sending the terminate, we have
  15746. // nothing more to do here.
  15747. if (Object.keys(this.sessions).length < 1
  15748. || !(this.sessions[Object.keys(this.sessions)[0]]
  15749. instanceof JingleSession))
  15750. {
  15751. break;
  15752. }
  15753. console.log('terminating...', sess.sid);
  15754. sess.terminate();
  15755. this.terminate(sess.sid);
  15756. if ($(iq).find('>jingle>reason').length) {
  15757. $(document).trigger('callterminated.jingle', [
  15758. sess.sid,
  15759. sess.peerjid,
  15760. $(iq).find('>jingle>reason>:first')[0].tagName,
  15761. $(iq).find('>jingle>reason>text').text()
  15762. ]);
  15763. } else {
  15764. $(document).trigger('callterminated.jingle',
  15765. [sess.sid, sess.peerjid]);
  15766. }
  15767. break;
  15768. case 'transport-info':
  15769. sess.addIceCandidate($(iq).find('>jingle>content'));
  15770. break;
  15771. case 'session-info':
  15772. var affected;
  15773. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15774. $(document).trigger('ringing.jingle', [sess.sid]);
  15775. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15776. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15777. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15778. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15779. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15780. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15781. }
  15782. break;
  15783. case 'addsource': // FIXME: proprietary, un-jingleish
  15784. case 'source-add': // FIXME: proprietary
  15785. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15786. break;
  15787. case 'removesource': // FIXME: proprietary, un-jingleish
  15788. case 'source-remove': // FIXME: proprietary
  15789. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15790. break;
  15791. default:
  15792. console.warn('jingle action not implemented', action);
  15793. break;
  15794. }
  15795. return true;
  15796. },
  15797. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15798. var sess = new JingleSession(myjid || this.connection.jid,
  15799. Math.random().toString(36).substr(2, 12), // random string
  15800. this.connection, XMPP, eventEmitter);
  15801. // configure session
  15802. sess.media_constraints = this.media_constraints;
  15803. sess.pc_constraints = this.pc_constraints;
  15804. sess.ice_config = this.ice_config;
  15805. sess.initiate(peerjid, true);
  15806. this.sessions[sess.sid] = sess;
  15807. this.jid2session[sess.peerjid] = sess;
  15808. sess.sendOffer();
  15809. return sess;
  15810. },
  15811. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15812. if (sid === null || sid === undefined) {
  15813. for (sid in this.sessions) {
  15814. if (this.sessions[sid].state != 'ended') {
  15815. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15816. this.sessions[sid].terminate();
  15817. }
  15818. delete this.jid2session[this.sessions[sid].peerjid];
  15819. delete this.sessions[sid];
  15820. }
  15821. } else if (this.sessions.hasOwnProperty(sid)) {
  15822. if (this.sessions[sid].state != 'ended') {
  15823. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15824. this.sessions[sid].terminate();
  15825. }
  15826. delete this.jid2session[this.sessions[sid].peerjid];
  15827. delete this.sessions[sid];
  15828. }
  15829. },
  15830. // Used to terminate a session when an unavailable presence is received.
  15831. terminateByJid: function (jid) {
  15832. if (this.jid2session.hasOwnProperty(jid)) {
  15833. var sess = this.jid2session[jid];
  15834. if (sess) {
  15835. sess.terminate();
  15836. console.log('peer went away silently', jid);
  15837. delete this.sessions[sess.sid];
  15838. delete this.jid2session[jid];
  15839. $(document).trigger('callterminated.jingle',
  15840. [sess.sid, jid], 'gone');
  15841. }
  15842. }
  15843. },
  15844. terminateRemoteByJid: function (jid, reason) {
  15845. if (this.jid2session.hasOwnProperty(jid)) {
  15846. var sess = this.jid2session[jid];
  15847. if (sess) {
  15848. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15849. sess.terminate();
  15850. console.log('terminate peer with jid', sess.sid, jid);
  15851. delete this.sessions[sess.sid];
  15852. delete this.jid2session[jid];
  15853. $(document).trigger('callterminated.jingle',
  15854. [sess.sid, jid, 'kicked']);
  15855. }
  15856. }
  15857. },
  15858. getStunAndTurnCredentials: function () {
  15859. // get stun and turn configuration from server via xep-0215
  15860. // uses time-limited credentials as described in
  15861. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15862. //
  15863. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15864. // for a prosody module which implements this
  15865. //
  15866. // currently, this doesn't work with updateIce and therefore credentials with a long
  15867. // validity have to be fetched before creating the peerconnection
  15868. // TODO: implement refresh via updateIce as described in
  15869. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15870. var self = this;
  15871. this.connection.sendIQ(
  15872. $iq({type: 'get', to: this.connection.domain})
  15873. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15874. function (res) {
  15875. var iceservers = [];
  15876. $(res).find('>services>service').each(function (idx, el) {
  15877. el = $(el);
  15878. var dict = {};
  15879. var type = el.attr('type');
  15880. switch (type) {
  15881. case 'stun':
  15882. dict.url = 'stun:' + el.attr('host');
  15883. if (el.attr('port')) {
  15884. dict.url += ':' + el.attr('port');
  15885. }
  15886. iceservers.push(dict);
  15887. break;
  15888. case 'turn':
  15889. case 'turns':
  15890. dict.url = type + ':';
  15891. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15892. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15893. dict.url += el.attr('username') + '@';
  15894. } else {
  15895. dict.username = el.attr('username'); // only works in M28
  15896. }
  15897. }
  15898. dict.url += el.attr('host');
  15899. if (el.attr('port') && el.attr('port') != '3478') {
  15900. dict.url += ':' + el.attr('port');
  15901. }
  15902. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15903. dict.url += '?transport=' + el.attr('transport');
  15904. }
  15905. if (el.attr('password')) {
  15906. dict.credential = el.attr('password');
  15907. }
  15908. iceservers.push(dict);
  15909. break;
  15910. }
  15911. });
  15912. self.ice_config.iceServers = iceservers;
  15913. },
  15914. function (err) {
  15915. console.warn('getting turn credentials failed', err);
  15916. console.warn('is mod_turncredentials or similar installed?');
  15917. }
  15918. );
  15919. // implement push?
  15920. },
  15921. /**
  15922. * Populates the log data
  15923. */
  15924. populateData: function () {
  15925. var data = {};
  15926. var self = this;
  15927. Object.keys(this.sessions).forEach(function (sid) {
  15928. var session = self.sessions[sid];
  15929. if (session.peerconnection && session.peerconnection.updateLog) {
  15930. // FIXME: should probably be a .dump call
  15931. data["jingle_" + session.sid] = {
  15932. updateLog: session.peerconnection.updateLog,
  15933. stats: session.peerconnection.stats,
  15934. url: window.location.href
  15935. };
  15936. }
  15937. });
  15938. return data;
  15939. }
  15940. });
  15941. };
  15942. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTCBrowserType":10,"./JingleSession":55}],64:[function(require,module,exports){
  15943. /* global Strophe */
  15944. module.exports = function () {
  15945. Strophe.addConnectionPlugin('logger', {
  15946. // logs raw stanzas and makes them available for download as JSON
  15947. connection: null,
  15948. log: [],
  15949. init: function (conn) {
  15950. this.connection = conn;
  15951. this.connection.rawInput = this.log_incoming.bind(this);
  15952. this.connection.rawOutput = this.log_outgoing.bind(this);
  15953. },
  15954. log_incoming: function (stanza) {
  15955. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15956. },
  15957. log_outgoing: function (stanza) {
  15958. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15959. }
  15960. });
  15961. };
  15962. },{}],65:[function(require,module,exports){
  15963. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15964. setAudioMuted, Strophe */
  15965. /**
  15966. * Moderate connection plugin.
  15967. */
  15968. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15969. module.exports = function (XMPP, eventEmitter) {
  15970. Strophe.addConnectionPlugin('moderate', {
  15971. connection: null,
  15972. init: function (conn) {
  15973. this.connection = conn;
  15974. this.connection.addHandler(this.onMute.bind(this),
  15975. 'http://jitsi.org/jitmeet/audio',
  15976. 'iq',
  15977. 'set',
  15978. null,
  15979. null);
  15980. },
  15981. setMute: function (jid, mute) {
  15982. console.info("set mute", mute);
  15983. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15984. .c('mute', {
  15985. xmlns: 'http://jitsi.org/jitmeet/audio',
  15986. jid: jid
  15987. })
  15988. .t(mute.toString())
  15989. .up();
  15990. this.connection.sendIQ(
  15991. iqToFocus,
  15992. function (result) {
  15993. console.log('set mute', result);
  15994. },
  15995. function (error) {
  15996. console.log('set mute error', error);
  15997. });
  15998. },
  15999. onMute: function (iq) {
  16000. var from = iq.getAttribute('from');
  16001. if (from !== this.connection.emuc.focusMucJid) {
  16002. console.warn("Ignored mute from non focus peer");
  16003. return false;
  16004. }
  16005. var mute = $(iq).find('mute');
  16006. if (mute.length) {
  16007. var doMuteAudio = mute.text() === "true";
  16008. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16009. XMPP.forceMuted = doMuteAudio;
  16010. }
  16011. return true;
  16012. },
  16013. eject: function (jid) {
  16014. // We're not the focus, so can't terminate
  16015. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16016. this.connection.emuc.kick(jid);
  16017. }
  16018. });
  16019. }
  16020. },{"../../service/xmpp/XMPPEvents":110}],66:[function(require,module,exports){
  16021. /* jshint -W117 */
  16022. module.exports = function() {
  16023. Strophe.addConnectionPlugin('rayo',
  16024. {
  16025. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16026. connection: null,
  16027. init: function (conn) {
  16028. this.connection = conn;
  16029. if (this.connection.disco) {
  16030. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16031. }
  16032. this.connection.addHandler(
  16033. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16034. },
  16035. onRayo: function (iq) {
  16036. console.info("Rayo IQ", iq);
  16037. },
  16038. dial: function (to, from, roomName, roomPass) {
  16039. var self = this;
  16040. var req = $iq(
  16041. {
  16042. type: 'set',
  16043. to: this.connection.emuc.focusMucJid
  16044. }
  16045. );
  16046. req.c('dial',
  16047. {
  16048. xmlns: this.RAYO_XMLNS,
  16049. to: to,
  16050. from: from
  16051. });
  16052. req.c('header',
  16053. {
  16054. name: 'JvbRoomName',
  16055. value: roomName
  16056. }).up();
  16057. if (roomPass !== null && roomPass.length) {
  16058. req.c('header',
  16059. {
  16060. name: 'JvbRoomPassword',
  16061. value: roomPass
  16062. }).up();
  16063. }
  16064. this.connection.sendIQ(
  16065. req,
  16066. function (result) {
  16067. console.info('Dial result ', result);
  16068. var resource = $(result).find('ref').attr('uri');
  16069. this.call_resource = resource.substr('xmpp:'.length);
  16070. console.info(
  16071. "Received call resource: " + this.call_resource);
  16072. },
  16073. function (error) {
  16074. console.info('Dial error ', error);
  16075. }
  16076. );
  16077. },
  16078. hang_up: function () {
  16079. if (!this.call_resource) {
  16080. console.warn("No call in progress");
  16081. return;
  16082. }
  16083. var self = this;
  16084. var req = $iq(
  16085. {
  16086. type: 'set',
  16087. to: this.call_resource
  16088. }
  16089. );
  16090. req.c('hangup',
  16091. {
  16092. xmlns: this.RAYO_XMLNS
  16093. });
  16094. this.connection.sendIQ(
  16095. req,
  16096. function (result) {
  16097. console.info('Hangup result ', result);
  16098. self.call_resource = null;
  16099. },
  16100. function (error) {
  16101. console.info('Hangup error ', error);
  16102. self.call_resource = null;
  16103. }
  16104. );
  16105. }
  16106. }
  16107. );
  16108. };
  16109. },{}],67:[function(require,module,exports){
  16110. /**
  16111. * Strophe logger implementation. Logs from level WARN and above.
  16112. */
  16113. module.exports = function () {
  16114. Strophe.log = function (level, msg) {
  16115. switch (level) {
  16116. case Strophe.LogLevel.WARN:
  16117. console.warn("Strophe: " + msg);
  16118. break;
  16119. case Strophe.LogLevel.ERROR:
  16120. case Strophe.LogLevel.FATAL:
  16121. console.error("Strophe: " + msg);
  16122. break;
  16123. }
  16124. };
  16125. Strophe.getStatusString = function (status) {
  16126. switch (status) {
  16127. case Strophe.Status.ERROR:
  16128. return "ERROR";
  16129. case Strophe.Status.CONNECTING:
  16130. return "CONNECTING";
  16131. case Strophe.Status.CONNFAIL:
  16132. return "CONNFAIL";
  16133. case Strophe.Status.AUTHENTICATING:
  16134. return "AUTHENTICATING";
  16135. case Strophe.Status.AUTHFAIL:
  16136. return "AUTHFAIL";
  16137. case Strophe.Status.CONNECTED:
  16138. return "CONNECTED";
  16139. case Strophe.Status.DISCONNECTED:
  16140. return "DISCONNECTED";
  16141. case Strophe.Status.DISCONNECTING:
  16142. return "DISCONNECTING";
  16143. case Strophe.Status.ATTACHED:
  16144. return "ATTACHED";
  16145. default:
  16146. return "unknown";
  16147. }
  16148. };
  16149. };
  16150. },{}],68:[function(require,module,exports){
  16151. /* global $, APP, config, Strophe*/
  16152. var Moderator = require("./moderator");
  16153. var EventEmitter = require("events");
  16154. var Recording = require("./recording");
  16155. var SDP = require("./SDP");
  16156. var Settings = require("../settings/Settings");
  16157. var Pako = require("pako");
  16158. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16159. var RTCEvents = require("../../service/RTC/RTCEvents");
  16160. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16161. var retry = require('retry');
  16162. var eventEmitter = new EventEmitter();
  16163. var connection = null;
  16164. var authenticatedUser = false;
  16165. function connect(jid, password) {
  16166. var faultTolerantConnect = retry.operation({
  16167. retries: 3
  16168. });
  16169. // fault tolerant connect
  16170. faultTolerantConnect.attempt(function () {
  16171. connection = XMPP.createConnection();
  16172. Moderator.setConnection(connection);
  16173. if (connection.disco) {
  16174. // for chrome, add multistream cap
  16175. }
  16176. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16177. if (config.useIPv6) {
  16178. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16179. if (!connection.jingle.pc_constraints.optional)
  16180. connection.jingle.pc_constraints.optional = [];
  16181. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16182. }
  16183. // Include user info in MUC presence
  16184. var settings = Settings.getSettings();
  16185. if (settings.email) {
  16186. connection.emuc.addEmailToPresence(settings.email);
  16187. }
  16188. if (settings.uid) {
  16189. connection.emuc.addUserIdToPresence(settings.uid);
  16190. }
  16191. if (settings.displayName) {
  16192. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16193. }
  16194. // connection.connect() starts the connection process.
  16195. //
  16196. // As the connection process proceeds, the user supplied callback will
  16197. // be triggered multiple times with status updates. The callback should
  16198. // take two arguments - the status code and the error condition.
  16199. //
  16200. // The status code will be one of the values in the Strophe.Status
  16201. // constants. The error condition will be one of the conditions defined
  16202. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16203. //
  16204. // The Parameters wait, hold and route are optional and only relevant
  16205. // for BOSH connections. Please see XEP 124 for a more detailed
  16206. // explanation of the optional parameters.
  16207. //
  16208. // Connection status constants for use by the connection handler
  16209. // callback.
  16210. //
  16211. // Status.ERROR - An error has occurred (websockets specific)
  16212. // Status.CONNECTING - The connection is currently being made
  16213. // Status.CONNFAIL - The connection attempt failed
  16214. // Status.AUTHENTICATING - The connection is authenticating
  16215. // Status.AUTHFAIL - The authentication attempt failed
  16216. // Status.CONNECTED - The connection has succeeded
  16217. // Status.DISCONNECTED - The connection has been terminated
  16218. // Status.DISCONNECTING - The connection is currently being terminated
  16219. // Status.ATTACHED - The connection has been attached
  16220. var anonymousConnectionFailed = false;
  16221. var connectionFailed = false;
  16222. var lastErrorMsg;
  16223. connection.connect(jid, password, function (status, msg) {
  16224. console.log('Strophe status changed to',
  16225. Strophe.getStatusString(status), msg);
  16226. if (status === Strophe.Status.CONNECTED) {
  16227. if (config.useStunTurn) {
  16228. connection.jingle.getStunAndTurnCredentials();
  16229. }
  16230. console.info("My Jabber ID: " + connection.jid);
  16231. if (password)
  16232. authenticatedUser = true;
  16233. maybeDoJoin();
  16234. } else if (status === Strophe.Status.CONNFAIL) {
  16235. if (msg === 'x-strophe-bad-non-anon-jid') {
  16236. anonymousConnectionFailed = true;
  16237. } else {
  16238. connectionFailed = true;
  16239. }
  16240. lastErrorMsg = msg;
  16241. } else if (status === Strophe.Status.DISCONNECTED) {
  16242. if (anonymousConnectionFailed) {
  16243. // prompt user for username and password
  16244. XMPP.promptLogin();
  16245. } else {
  16246. // Strophe already has built-in HTTP/BOSH error handling and
  16247. // request retry logic. Requests are resent automatically
  16248. // until their error count reaches 5. Strophe.js disconnects
  16249. // if the error count is > 5. We are not replicating this
  16250. // here.
  16251. //
  16252. // The "problem" is that failed HTTP/BOSH requests don't
  16253. // trigger a callback with a status update, so when a
  16254. // callback with status Strophe.Status.DISCONNECTED arrives,
  16255. // we can't be sure if it's a graceful disconnect or if it's
  16256. // triggered by some HTTP/BOSH error.
  16257. //
  16258. // But that's a minor issue in Jitsi Meet as we never
  16259. // disconnect anyway, not even when the user closes the
  16260. // browser window (which is kind of wrong, but the point is
  16261. // that we should never ever get disconnected).
  16262. //
  16263. // On the other hand, failed connections due to XMPP layer
  16264. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16265. //
  16266. // Here we implement retry logic for failed connections due
  16267. // to XMPP layer errors and we display an error to the user
  16268. // if we get disconnected from the XMPP server permanently.
  16269. // If the connection failed, retry.
  16270. if (connectionFailed
  16271. && faultTolerantConnect.retry("connection-failed")) {
  16272. return;
  16273. }
  16274. // If we failed to connect to the XMPP server, fire an event
  16275. // to let all the interested module now about it.
  16276. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16277. msg ? msg : lastErrorMsg);
  16278. }
  16279. } else if (status === Strophe.Status.AUTHFAIL) {
  16280. // wrong password or username, prompt user
  16281. XMPP.promptLogin();
  16282. }
  16283. });
  16284. });
  16285. }
  16286. function maybeDoJoin() {
  16287. if (connection && connection.connected &&
  16288. Strophe.getResourceFromJid(connection.jid)
  16289. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16290. // .connected is true while connecting?
  16291. doJoin();
  16292. }
  16293. }
  16294. function doJoin() {
  16295. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16296. }
  16297. function initStrophePlugins()
  16298. {
  16299. require("./strophe.emuc")(XMPP, eventEmitter);
  16300. require("./strophe.jingle")(XMPP, eventEmitter);
  16301. require("./strophe.moderate")(XMPP, eventEmitter);
  16302. require("./strophe.util")();
  16303. require("./strophe.rayo")();
  16304. require("./strophe.logger")();
  16305. }
  16306. function registerListeners() {
  16307. APP.RTC.addStreamListener(maybeDoJoin,
  16308. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  16309. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16310. XMPP.addToPresence("devices", devices);
  16311. });
  16312. }
  16313. var unload = (function () {
  16314. var unloaded = false;
  16315. return function () {
  16316. if (unloaded) { return; }
  16317. unloaded = true;
  16318. if (connection && connection.connected) {
  16319. // ensure signout
  16320. $.ajax({
  16321. type: 'POST',
  16322. url: config.bosh,
  16323. async: false,
  16324. cache: false,
  16325. contentType: 'application/xml',
  16326. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  16327. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16328. (connection.sid || connection._proto.sid) +
  16329. "' type='terminate'>" +
  16330. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16331. "</body>",
  16332. success: function (data) {
  16333. console.log('signed out');
  16334. console.log(data);
  16335. },
  16336. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16337. console.log('signout error',
  16338. textStatus + ' (' + errorThrown + ')');
  16339. }
  16340. });
  16341. }
  16342. XMPP.disposeConference(true);
  16343. };
  16344. })();
  16345. function setupEvents() {
  16346. // In recent versions of FF the 'beforeunload' event is not fired when the
  16347. // window or the tab is closed. It is only fired when we leave the page
  16348. // (change URL). If this participant doesn't unload properly, then it
  16349. // becomes a ghost for the rest of the participants that stay in the
  16350. // conference. Thankfully handling the 'unload' event in addition to the
  16351. // 'beforeunload' event seems to garante the execution of the 'unload'
  16352. // method at least once.
  16353. //
  16354. // The 'unload' method can safely be run multiple times, it will actually do
  16355. // something only the first time that it's run, so we're don't have to worry
  16356. // about browsers that fire both events.
  16357. $(window).bind('beforeunload', unload);
  16358. $(window).bind('unload', unload);
  16359. }
  16360. var XMPP = {
  16361. getConnection: function(){ return connection; },
  16362. sessionTerminated: false,
  16363. /**
  16364. * XMPP connection status
  16365. */
  16366. Status: Strophe.Status,
  16367. /**
  16368. * Remembers if we were muted by the focus.
  16369. * @type {boolean}
  16370. */
  16371. forceMuted: false,
  16372. start: function () {
  16373. setupEvents();
  16374. initStrophePlugins();
  16375. registerListeners();
  16376. Moderator.init(this, eventEmitter);
  16377. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16378. // Force authenticated domain if room is appended with '?login=true'
  16379. if (config.hosts.anonymousdomain &&
  16380. window.location.search.indexOf("login=true") !== -1) {
  16381. configDomain = config.hosts.domain;
  16382. }
  16383. var jid = configDomain || window.location.hostname;
  16384. connect(jid, null);
  16385. },
  16386. createConnection: function () {
  16387. var bosh = config.bosh || '/http-bind';
  16388. return new Strophe.Connection(bosh);
  16389. },
  16390. getStatusString: function (status) {
  16391. return Strophe.getStatusString(status);
  16392. },
  16393. promptLogin: function () {
  16394. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16395. },
  16396. joinRoom: function(roomName, useNicks, nick)
  16397. {
  16398. var roomjid;
  16399. roomjid = roomName;
  16400. if (useNicks) {
  16401. if (nick) {
  16402. roomjid += '/' + nick;
  16403. } else {
  16404. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16405. }
  16406. } else {
  16407. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16408. if(!authenticatedUser)
  16409. tmpJid = tmpJid.substr(0, 8);
  16410. roomjid += '/' + tmpJid;
  16411. }
  16412. connection.emuc.doJoin(roomjid);
  16413. },
  16414. myJid: function () {
  16415. if(!connection)
  16416. return null;
  16417. return connection.emuc.myroomjid;
  16418. },
  16419. myResource: function () {
  16420. if(!connection || ! connection.emuc.myroomjid)
  16421. return null;
  16422. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16423. },
  16424. disposeConference: function (onUnload) {
  16425. var handler = connection.jingle.activecall;
  16426. if (handler && handler.peerconnection) {
  16427. // FIXME: probably removing streams is not required and close() should
  16428. // be enough
  16429. if (APP.RTC.localAudio) {
  16430. handler.peerconnection.removeStream(
  16431. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16432. }
  16433. if (APP.RTC.localVideo) {
  16434. handler.peerconnection.removeStream(
  16435. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16436. }
  16437. handler.peerconnection.close();
  16438. }
  16439. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16440. connection.jingle.activecall = null;
  16441. if(!onUnload)
  16442. {
  16443. this.sessionTerminated = true;
  16444. connection.emuc.doLeave();
  16445. }
  16446. },
  16447. addListener: function(type, listener)
  16448. {
  16449. eventEmitter.on(type, listener);
  16450. },
  16451. removeListener: function (type, listener) {
  16452. eventEmitter.removeListener(type, listener);
  16453. },
  16454. allocateConferenceFocus: function(roomName, callback) {
  16455. Moderator.allocateConferenceFocus(roomName, callback);
  16456. },
  16457. getLoginUrl: function (roomName, callback) {
  16458. Moderator.getLoginUrl(roomName, callback);
  16459. },
  16460. getPopupLoginUrl: function (roomName, callback) {
  16461. Moderator.getPopupLoginUrl(roomName, callback);
  16462. },
  16463. isModerator: function () {
  16464. return Moderator.isModerator();
  16465. },
  16466. isSipGatewayEnabled: function () {
  16467. return Moderator.isSipGatewayEnabled();
  16468. },
  16469. isExternalAuthEnabled: function () {
  16470. return Moderator.isExternalAuthEnabled();
  16471. },
  16472. isConferenceInProgress: function () {
  16473. return connection && connection.jingle.activecall &&
  16474. connection.jingle.activecall.peerconnection;
  16475. },
  16476. switchStreams: function (stream, oldStream, callback, isAudio) {
  16477. if (this.isConferenceInProgress()) {
  16478. // FIXME: will block switchInProgress on true value in case of exception
  16479. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16480. } else {
  16481. // We are done immediately
  16482. console.warn("No conference handler or conference not started yet");
  16483. callback();
  16484. }
  16485. },
  16486. sendVideoInfoPresence: function (mute) {
  16487. if(!connection)
  16488. return;
  16489. connection.emuc.addVideoInfoToPresence(mute);
  16490. connection.emuc.sendPresence();
  16491. },
  16492. setVideoMute: function (mute, callback, options) {
  16493. if(!connection)
  16494. return;
  16495. var self = this;
  16496. var localCallback = function (mute) {
  16497. self.sendVideoInfoPresence(mute);
  16498. return callback(mute);
  16499. };
  16500. if(connection.jingle.activecall)
  16501. {
  16502. connection.jingle.activecall.setVideoMute(
  16503. mute, localCallback, options);
  16504. }
  16505. else {
  16506. localCallback(mute);
  16507. }
  16508. },
  16509. setAudioMute: function (mute, callback) {
  16510. if (!(connection && APP.RTC.localAudio)) {
  16511. return false;
  16512. }
  16513. if (this.forceMuted && !mute) {
  16514. console.info("Asking focus for unmute");
  16515. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16516. // FIXME: wait for result before resetting muted status
  16517. this.forceMuted = false;
  16518. }
  16519. if (mute == APP.RTC.localAudio.isMuted()) {
  16520. // Nothing to do
  16521. return true;
  16522. }
  16523. // It is not clear what is the right way to handle multiple tracks.
  16524. // So at least make sure that they are all muted or all unmuted and
  16525. // that we send presence just once.
  16526. APP.RTC.localAudio.setMute(!mute);
  16527. // isMuted is the opposite of audioEnabled
  16528. this.sendAudioInfoPresence(mute, callback);
  16529. return true;
  16530. },
  16531. sendAudioInfoPresence: function(mute, callback)
  16532. {
  16533. if(connection) {
  16534. connection.emuc.addAudioInfoToPresence(mute);
  16535. connection.emuc.sendPresence();
  16536. }
  16537. callback();
  16538. return true;
  16539. },
  16540. // Really mute video, i.e. dont even send black frames
  16541. muteVideo: function (pc, unmute) {
  16542. // FIXME: this probably needs another of those lovely state safeguards...
  16543. // which checks for iceconn == connected and sigstate == stable
  16544. pc.setRemoteDescription(pc.remoteDescription,
  16545. function () {
  16546. pc.createAnswer(
  16547. function (answer) {
  16548. var sdp = new SDP(answer.sdp);
  16549. if (sdp.media.length > 1) {
  16550. if (unmute)
  16551. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  16552. else
  16553. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  16554. sdp.raw = sdp.session + sdp.media.join('');
  16555. answer.sdp = sdp.raw;
  16556. }
  16557. pc.setLocalDescription(answer,
  16558. function () {
  16559. console.log('mute SLD ok');
  16560. },
  16561. function (error) {
  16562. console.log('mute SLD error');
  16563. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  16564. }
  16565. );
  16566. },
  16567. function (error) {
  16568. console.log(error);
  16569. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  16570. }
  16571. );
  16572. },
  16573. function (error) {
  16574. console.log('muteVideo SRD error');
  16575. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  16576. }
  16577. );
  16578. },
  16579. toggleRecording: function (tokenEmptyCallback,
  16580. startingCallback, startedCallback) {
  16581. Recording.toggleRecording(tokenEmptyCallback,
  16582. startingCallback, startedCallback, connection);
  16583. },
  16584. addToPresence: function (name, value, dontSend) {
  16585. switch (name)
  16586. {
  16587. case "displayName":
  16588. connection.emuc.addDisplayNameToPresence(value);
  16589. break;
  16590. case "prezi":
  16591. connection.emuc.addPreziToPresence(value, 0);
  16592. break;
  16593. case "preziSlide":
  16594. connection.emuc.addCurrentSlideToPresence(value);
  16595. break;
  16596. case "connectionQuality":
  16597. connection.emuc.addConnectionInfoToPresence(value);
  16598. break;
  16599. case "email":
  16600. connection.emuc.addEmailToPresence(value);
  16601. break;
  16602. case "devices":
  16603. connection.emuc.addDevicesToPresence(value);
  16604. break;
  16605. case "startMuted":
  16606. if(!Moderator.isModerator())
  16607. return;
  16608. connection.emuc.addStartMutedToPresence(value[0],
  16609. value[1]);
  16610. break;
  16611. default :
  16612. console.log("Unknown tag for presence: " + name);
  16613. return;
  16614. }
  16615. if (!dontSend)
  16616. connection.emuc.sendPresence();
  16617. },
  16618. /**
  16619. * Sends 'data' as a log message to the focus. Returns true iff a message
  16620. * was sent.
  16621. * @param data
  16622. * @returns {boolean} true iff a message was sent.
  16623. */
  16624. sendLogs: function (data) {
  16625. if(!connection.emuc.focusMucJid)
  16626. return false;
  16627. var deflate = true;
  16628. var content = JSON.stringify(data);
  16629. if (deflate) {
  16630. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16631. }
  16632. content = Base64.encode(content);
  16633. // XEP-0337-ish
  16634. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16635. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16636. id: 'PeerConnectionStats'});
  16637. message.c('message').t(content).up();
  16638. if (deflate) {
  16639. message.c('tag', {name: "deflated", value: "true"}).up();
  16640. }
  16641. message.up();
  16642. connection.send(message);
  16643. return true;
  16644. },
  16645. populateData: function () {
  16646. var data = {};
  16647. if (connection.jingle) {
  16648. data = connection.jingle.populateData();
  16649. }
  16650. return data;
  16651. },
  16652. getLogger: function () {
  16653. if(connection.logger)
  16654. return connection.logger.log;
  16655. return null;
  16656. },
  16657. getPrezi: function () {
  16658. return connection.emuc.getPrezi(this.myJid());
  16659. },
  16660. removePreziFromPresence: function () {
  16661. connection.emuc.removePreziFromPresence();
  16662. connection.emuc.sendPresence();
  16663. },
  16664. sendChatMessage: function (message, nickname) {
  16665. connection.emuc.sendMessage(message, nickname);
  16666. },
  16667. setSubject: function (topic) {
  16668. connection.emuc.setSubject(topic);
  16669. },
  16670. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16671. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16672. },
  16673. dial: function (to, from, roomName,roomPass) {
  16674. connection.rayo.dial(to, from, roomName,roomPass);
  16675. },
  16676. setMute: function (jid, mute) {
  16677. connection.moderate.setMute(jid, mute);
  16678. },
  16679. eject: function (jid) {
  16680. connection.moderate.eject(jid);
  16681. },
  16682. logout: function (callback) {
  16683. Moderator.logout(callback);
  16684. },
  16685. findJidFromResource: function (resource) {
  16686. return connection.emuc.findJidFromResource(resource);
  16687. },
  16688. getMembers: function () {
  16689. return connection.emuc.members;
  16690. },
  16691. getJidFromSSRC: function (ssrc) {
  16692. if (!this.isConferenceInProgress())
  16693. return null;
  16694. return connection.jingle.activecall.getSsrcOwner(ssrc);
  16695. },
  16696. getMUCJoined: function () {
  16697. return connection.emuc.joined;
  16698. },
  16699. getSessions: function () {
  16700. return connection.jingle.sessions;
  16701. },
  16702. removeStream: function (stream) {
  16703. if (!this.isConferenceInProgress())
  16704. return;
  16705. connection.jingle.activecall.peerconnection.removeStream(stream);
  16706. }
  16707. };
  16708. module.exports = XMPP;
  16709. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes":103,"../../service/xmpp/XMPPEvents":110,"../settings/Settings":49,"./SDP":56,"./moderator":60,"./recording":61,"./strophe.emuc":62,"./strophe.jingle":63,"./strophe.logger":64,"./strophe.moderate":65,"./strophe.rayo":66,"./strophe.util":67,"events":1,"pako":71,"retry":87}],69:[function(require,module,exports){
  16710. (function (process){
  16711. /*!
  16712. * async
  16713. * https://github.com/caolan/async
  16714. *
  16715. * Copyright 2010-2014 Caolan McMahon
  16716. * Released under the MIT license
  16717. */
  16718. /*jshint onevar: false, indent:4 */
  16719. /*global setImmediate: false, setTimeout: false, console: false */
  16720. (function () {
  16721. var async = {};
  16722. // global on the server, window in the browser
  16723. var root, previous_async;
  16724. root = this;
  16725. if (root != null) {
  16726. previous_async = root.async;
  16727. }
  16728. async.noConflict = function () {
  16729. root.async = previous_async;
  16730. return async;
  16731. };
  16732. function only_once(fn) {
  16733. var called = false;
  16734. return function() {
  16735. if (called) throw new Error("Callback was already called.");
  16736. called = true;
  16737. fn.apply(root, arguments);
  16738. }
  16739. }
  16740. //// cross-browser compatiblity functions ////
  16741. var _toString = Object.prototype.toString;
  16742. var _isArray = Array.isArray || function (obj) {
  16743. return _toString.call(obj) === '[object Array]';
  16744. };
  16745. var _each = function (arr, iterator) {
  16746. if (arr.forEach) {
  16747. return arr.forEach(iterator);
  16748. }
  16749. for (var i = 0; i < arr.length; i += 1) {
  16750. iterator(arr[i], i, arr);
  16751. }
  16752. };
  16753. var _map = function (arr, iterator) {
  16754. if (arr.map) {
  16755. return arr.map(iterator);
  16756. }
  16757. var results = [];
  16758. _each(arr, function (x, i, a) {
  16759. results.push(iterator(x, i, a));
  16760. });
  16761. return results;
  16762. };
  16763. var _reduce = function (arr, iterator, memo) {
  16764. if (arr.reduce) {
  16765. return arr.reduce(iterator, memo);
  16766. }
  16767. _each(arr, function (x, i, a) {
  16768. memo = iterator(memo, x, i, a);
  16769. });
  16770. return memo;
  16771. };
  16772. var _keys = function (obj) {
  16773. if (Object.keys) {
  16774. return Object.keys(obj);
  16775. }
  16776. var keys = [];
  16777. for (var k in obj) {
  16778. if (obj.hasOwnProperty(k)) {
  16779. keys.push(k);
  16780. }
  16781. }
  16782. return keys;
  16783. };
  16784. //// exported async module functions ////
  16785. //// nextTick implementation with browser-compatible fallback ////
  16786. if (typeof process === 'undefined' || !(process.nextTick)) {
  16787. if (typeof setImmediate === 'function') {
  16788. async.nextTick = function (fn) {
  16789. // not a direct alias for IE10 compatibility
  16790. setImmediate(fn);
  16791. };
  16792. async.setImmediate = async.nextTick;
  16793. }
  16794. else {
  16795. async.nextTick = function (fn) {
  16796. setTimeout(fn, 0);
  16797. };
  16798. async.setImmediate = async.nextTick;
  16799. }
  16800. }
  16801. else {
  16802. async.nextTick = process.nextTick;
  16803. if (typeof setImmediate !== 'undefined') {
  16804. async.setImmediate = function (fn) {
  16805. // not a direct alias for IE10 compatibility
  16806. setImmediate(fn);
  16807. };
  16808. }
  16809. else {
  16810. async.setImmediate = async.nextTick;
  16811. }
  16812. }
  16813. async.each = function (arr, iterator, callback) {
  16814. callback = callback || function () {};
  16815. if (!arr.length) {
  16816. return callback();
  16817. }
  16818. var completed = 0;
  16819. _each(arr, function (x) {
  16820. iterator(x, only_once(done) );
  16821. });
  16822. function done(err) {
  16823. if (err) {
  16824. callback(err);
  16825. callback = function () {};
  16826. }
  16827. else {
  16828. completed += 1;
  16829. if (completed >= arr.length) {
  16830. callback();
  16831. }
  16832. }
  16833. }
  16834. };
  16835. async.forEach = async.each;
  16836. async.eachSeries = function (arr, iterator, callback) {
  16837. callback = callback || function () {};
  16838. if (!arr.length) {
  16839. return callback();
  16840. }
  16841. var completed = 0;
  16842. var iterate = function () {
  16843. iterator(arr[completed], function (err) {
  16844. if (err) {
  16845. callback(err);
  16846. callback = function () {};
  16847. }
  16848. else {
  16849. completed += 1;
  16850. if (completed >= arr.length) {
  16851. callback();
  16852. }
  16853. else {
  16854. iterate();
  16855. }
  16856. }
  16857. });
  16858. };
  16859. iterate();
  16860. };
  16861. async.forEachSeries = async.eachSeries;
  16862. async.eachLimit = function (arr, limit, iterator, callback) {
  16863. var fn = _eachLimit(limit);
  16864. fn.apply(null, [arr, iterator, callback]);
  16865. };
  16866. async.forEachLimit = async.eachLimit;
  16867. var _eachLimit = function (limit) {
  16868. return function (arr, iterator, callback) {
  16869. callback = callback || function () {};
  16870. if (!arr.length || limit <= 0) {
  16871. return callback();
  16872. }
  16873. var completed = 0;
  16874. var started = 0;
  16875. var running = 0;
  16876. (function replenish () {
  16877. if (completed >= arr.length) {
  16878. return callback();
  16879. }
  16880. while (running < limit && started < arr.length) {
  16881. started += 1;
  16882. running += 1;
  16883. iterator(arr[started - 1], function (err) {
  16884. if (err) {
  16885. callback(err);
  16886. callback = function () {};
  16887. }
  16888. else {
  16889. completed += 1;
  16890. running -= 1;
  16891. if (completed >= arr.length) {
  16892. callback();
  16893. }
  16894. else {
  16895. replenish();
  16896. }
  16897. }
  16898. });
  16899. }
  16900. })();
  16901. };
  16902. };
  16903. var doParallel = function (fn) {
  16904. return function () {
  16905. var args = Array.prototype.slice.call(arguments);
  16906. return fn.apply(null, [async.each].concat(args));
  16907. };
  16908. };
  16909. var doParallelLimit = function(limit, fn) {
  16910. return function () {
  16911. var args = Array.prototype.slice.call(arguments);
  16912. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16913. };
  16914. };
  16915. var doSeries = function (fn) {
  16916. return function () {
  16917. var args = Array.prototype.slice.call(arguments);
  16918. return fn.apply(null, [async.eachSeries].concat(args));
  16919. };
  16920. };
  16921. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16922. arr = _map(arr, function (x, i) {
  16923. return {index: i, value: x};
  16924. });
  16925. if (!callback) {
  16926. eachfn(arr, function (x, callback) {
  16927. iterator(x.value, function (err) {
  16928. callback(err);
  16929. });
  16930. });
  16931. } else {
  16932. var results = [];
  16933. eachfn(arr, function (x, callback) {
  16934. iterator(x.value, function (err, v) {
  16935. results[x.index] = v;
  16936. callback(err);
  16937. });
  16938. }, function (err) {
  16939. callback(err, results);
  16940. });
  16941. }
  16942. };
  16943. async.map = doParallel(_asyncMap);
  16944. async.mapSeries = doSeries(_asyncMap);
  16945. async.mapLimit = function (arr, limit, iterator, callback) {
  16946. return _mapLimit(limit)(arr, iterator, callback);
  16947. };
  16948. var _mapLimit = function(limit) {
  16949. return doParallelLimit(limit, _asyncMap);
  16950. };
  16951. // reduce only has a series version, as doing reduce in parallel won't
  16952. // work in many situations.
  16953. async.reduce = function (arr, memo, iterator, callback) {
  16954. async.eachSeries(arr, function (x, callback) {
  16955. iterator(memo, x, function (err, v) {
  16956. memo = v;
  16957. callback(err);
  16958. });
  16959. }, function (err) {
  16960. callback(err, memo);
  16961. });
  16962. };
  16963. // inject alias
  16964. async.inject = async.reduce;
  16965. // foldl alias
  16966. async.foldl = async.reduce;
  16967. async.reduceRight = function (arr, memo, iterator, callback) {
  16968. var reversed = _map(arr, function (x) {
  16969. return x;
  16970. }).reverse();
  16971. async.reduce(reversed, memo, iterator, callback);
  16972. };
  16973. // foldr alias
  16974. async.foldr = async.reduceRight;
  16975. var _filter = function (eachfn, arr, iterator, callback) {
  16976. var results = [];
  16977. arr = _map(arr, function (x, i) {
  16978. return {index: i, value: x};
  16979. });
  16980. eachfn(arr, function (x, callback) {
  16981. iterator(x.value, function (v) {
  16982. if (v) {
  16983. results.push(x);
  16984. }
  16985. callback();
  16986. });
  16987. }, function (err) {
  16988. callback(_map(results.sort(function (a, b) {
  16989. return a.index - b.index;
  16990. }), function (x) {
  16991. return x.value;
  16992. }));
  16993. });
  16994. };
  16995. async.filter = doParallel(_filter);
  16996. async.filterSeries = doSeries(_filter);
  16997. // select alias
  16998. async.select = async.filter;
  16999. async.selectSeries = async.filterSeries;
  17000. var _reject = function (eachfn, arr, iterator, callback) {
  17001. var results = [];
  17002. arr = _map(arr, function (x, i) {
  17003. return {index: i, value: x};
  17004. });
  17005. eachfn(arr, function (x, callback) {
  17006. iterator(x.value, function (v) {
  17007. if (!v) {
  17008. results.push(x);
  17009. }
  17010. callback();
  17011. });
  17012. }, function (err) {
  17013. callback(_map(results.sort(function (a, b) {
  17014. return a.index - b.index;
  17015. }), function (x) {
  17016. return x.value;
  17017. }));
  17018. });
  17019. };
  17020. async.reject = doParallel(_reject);
  17021. async.rejectSeries = doSeries(_reject);
  17022. var _detect = function (eachfn, arr, iterator, main_callback) {
  17023. eachfn(arr, function (x, callback) {
  17024. iterator(x, function (result) {
  17025. if (result) {
  17026. main_callback(x);
  17027. main_callback = function () {};
  17028. }
  17029. else {
  17030. callback();
  17031. }
  17032. });
  17033. }, function (err) {
  17034. main_callback();
  17035. });
  17036. };
  17037. async.detect = doParallel(_detect);
  17038. async.detectSeries = doSeries(_detect);
  17039. async.some = function (arr, iterator, main_callback) {
  17040. async.each(arr, function (x, callback) {
  17041. iterator(x, function (v) {
  17042. if (v) {
  17043. main_callback(true);
  17044. main_callback = function () {};
  17045. }
  17046. callback();
  17047. });
  17048. }, function (err) {
  17049. main_callback(false);
  17050. });
  17051. };
  17052. // any alias
  17053. async.any = async.some;
  17054. async.every = function (arr, iterator, main_callback) {
  17055. async.each(arr, function (x, callback) {
  17056. iterator(x, function (v) {
  17057. if (!v) {
  17058. main_callback(false);
  17059. main_callback = function () {};
  17060. }
  17061. callback();
  17062. });
  17063. }, function (err) {
  17064. main_callback(true);
  17065. });
  17066. };
  17067. // all alias
  17068. async.all = async.every;
  17069. async.sortBy = function (arr, iterator, callback) {
  17070. async.map(arr, function (x, callback) {
  17071. iterator(x, function (err, criteria) {
  17072. if (err) {
  17073. callback(err);
  17074. }
  17075. else {
  17076. callback(null, {value: x, criteria: criteria});
  17077. }
  17078. });
  17079. }, function (err, results) {
  17080. if (err) {
  17081. return callback(err);
  17082. }
  17083. else {
  17084. var fn = function (left, right) {
  17085. var a = left.criteria, b = right.criteria;
  17086. return a < b ? -1 : a > b ? 1 : 0;
  17087. };
  17088. callback(null, _map(results.sort(fn), function (x) {
  17089. return x.value;
  17090. }));
  17091. }
  17092. });
  17093. };
  17094. async.auto = function (tasks, callback) {
  17095. callback = callback || function () {};
  17096. var keys = _keys(tasks);
  17097. var remainingTasks = keys.length
  17098. if (!remainingTasks) {
  17099. return callback();
  17100. }
  17101. var results = {};
  17102. var listeners = [];
  17103. var addListener = function (fn) {
  17104. listeners.unshift(fn);
  17105. };
  17106. var removeListener = function (fn) {
  17107. for (var i = 0; i < listeners.length; i += 1) {
  17108. if (listeners[i] === fn) {
  17109. listeners.splice(i, 1);
  17110. return;
  17111. }
  17112. }
  17113. };
  17114. var taskComplete = function () {
  17115. remainingTasks--
  17116. _each(listeners.slice(0), function (fn) {
  17117. fn();
  17118. });
  17119. };
  17120. addListener(function () {
  17121. if (!remainingTasks) {
  17122. var theCallback = callback;
  17123. // prevent final callback from calling itself if it errors
  17124. callback = function () {};
  17125. theCallback(null, results);
  17126. }
  17127. });
  17128. _each(keys, function (k) {
  17129. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17130. var taskCallback = function (err) {
  17131. var args = Array.prototype.slice.call(arguments, 1);
  17132. if (args.length <= 1) {
  17133. args = args[0];
  17134. }
  17135. if (err) {
  17136. var safeResults = {};
  17137. _each(_keys(results), function(rkey) {
  17138. safeResults[rkey] = results[rkey];
  17139. });
  17140. safeResults[k] = args;
  17141. callback(err, safeResults);
  17142. // stop subsequent errors hitting callback multiple times
  17143. callback = function () {};
  17144. }
  17145. else {
  17146. results[k] = args;
  17147. async.setImmediate(taskComplete);
  17148. }
  17149. };
  17150. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17151. var ready = function () {
  17152. return _reduce(requires, function (a, x) {
  17153. return (a && results.hasOwnProperty(x));
  17154. }, true) && !results.hasOwnProperty(k);
  17155. };
  17156. if (ready()) {
  17157. task[task.length - 1](taskCallback, results);
  17158. }
  17159. else {
  17160. var listener = function () {
  17161. if (ready()) {
  17162. removeListener(listener);
  17163. task[task.length - 1](taskCallback, results);
  17164. }
  17165. };
  17166. addListener(listener);
  17167. }
  17168. });
  17169. };
  17170. async.retry = function(times, task, callback) {
  17171. var DEFAULT_TIMES = 5;
  17172. var attempts = [];
  17173. // Use defaults if times not passed
  17174. if (typeof times === 'function') {
  17175. callback = task;
  17176. task = times;
  17177. times = DEFAULT_TIMES;
  17178. }
  17179. // Make sure times is a number
  17180. times = parseInt(times, 10) || DEFAULT_TIMES;
  17181. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17182. var retryAttempt = function(task, finalAttempt) {
  17183. return function(seriesCallback) {
  17184. task(function(err, result){
  17185. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17186. }, wrappedResults);
  17187. };
  17188. };
  17189. while (times) {
  17190. attempts.push(retryAttempt(task, !(times-=1)));
  17191. }
  17192. async.series(attempts, function(done, data){
  17193. data = data[data.length - 1];
  17194. (wrappedCallback || callback)(data.err, data.result);
  17195. });
  17196. }
  17197. // If a callback is passed, run this as a controll flow
  17198. return callback ? wrappedTask() : wrappedTask
  17199. };
  17200. async.waterfall = function (tasks, callback) {
  17201. callback = callback || function () {};
  17202. if (!_isArray(tasks)) {
  17203. var err = new Error('First argument to waterfall must be an array of functions');
  17204. return callback(err);
  17205. }
  17206. if (!tasks.length) {
  17207. return callback();
  17208. }
  17209. var wrapIterator = function (iterator) {
  17210. return function (err) {
  17211. if (err) {
  17212. callback.apply(null, arguments);
  17213. callback = function () {};
  17214. }
  17215. else {
  17216. var args = Array.prototype.slice.call(arguments, 1);
  17217. var next = iterator.next();
  17218. if (next) {
  17219. args.push(wrapIterator(next));
  17220. }
  17221. else {
  17222. args.push(callback);
  17223. }
  17224. async.setImmediate(function () {
  17225. iterator.apply(null, args);
  17226. });
  17227. }
  17228. };
  17229. };
  17230. wrapIterator(async.iterator(tasks))();
  17231. };
  17232. var _parallel = function(eachfn, tasks, callback) {
  17233. callback = callback || function () {};
  17234. if (_isArray(tasks)) {
  17235. eachfn.map(tasks, function (fn, callback) {
  17236. if (fn) {
  17237. fn(function (err) {
  17238. var args = Array.prototype.slice.call(arguments, 1);
  17239. if (args.length <= 1) {
  17240. args = args[0];
  17241. }
  17242. callback.call(null, err, args);
  17243. });
  17244. }
  17245. }, callback);
  17246. }
  17247. else {
  17248. var results = {};
  17249. eachfn.each(_keys(tasks), function (k, callback) {
  17250. tasks[k](function (err) {
  17251. var args = Array.prototype.slice.call(arguments, 1);
  17252. if (args.length <= 1) {
  17253. args = args[0];
  17254. }
  17255. results[k] = args;
  17256. callback(err);
  17257. });
  17258. }, function (err) {
  17259. callback(err, results);
  17260. });
  17261. }
  17262. };
  17263. async.parallel = function (tasks, callback) {
  17264. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17265. };
  17266. async.parallelLimit = function(tasks, limit, callback) {
  17267. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17268. };
  17269. async.series = function (tasks, callback) {
  17270. callback = callback || function () {};
  17271. if (_isArray(tasks)) {
  17272. async.mapSeries(tasks, function (fn, callback) {
  17273. if (fn) {
  17274. fn(function (err) {
  17275. var args = Array.prototype.slice.call(arguments, 1);
  17276. if (args.length <= 1) {
  17277. args = args[0];
  17278. }
  17279. callback.call(null, err, args);
  17280. });
  17281. }
  17282. }, callback);
  17283. }
  17284. else {
  17285. var results = {};
  17286. async.eachSeries(_keys(tasks), function (k, callback) {
  17287. tasks[k](function (err) {
  17288. var args = Array.prototype.slice.call(arguments, 1);
  17289. if (args.length <= 1) {
  17290. args = args[0];
  17291. }
  17292. results[k] = args;
  17293. callback(err);
  17294. });
  17295. }, function (err) {
  17296. callback(err, results);
  17297. });
  17298. }
  17299. };
  17300. async.iterator = function (tasks) {
  17301. var makeCallback = function (index) {
  17302. var fn = function () {
  17303. if (tasks.length) {
  17304. tasks[index].apply(null, arguments);
  17305. }
  17306. return fn.next();
  17307. };
  17308. fn.next = function () {
  17309. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17310. };
  17311. return fn;
  17312. };
  17313. return makeCallback(0);
  17314. };
  17315. async.apply = function (fn) {
  17316. var args = Array.prototype.slice.call(arguments, 1);
  17317. return function () {
  17318. return fn.apply(
  17319. null, args.concat(Array.prototype.slice.call(arguments))
  17320. );
  17321. };
  17322. };
  17323. var _concat = function (eachfn, arr, fn, callback) {
  17324. var r = [];
  17325. eachfn(arr, function (x, cb) {
  17326. fn(x, function (err, y) {
  17327. r = r.concat(y || []);
  17328. cb(err);
  17329. });
  17330. }, function (err) {
  17331. callback(err, r);
  17332. });
  17333. };
  17334. async.concat = doParallel(_concat);
  17335. async.concatSeries = doSeries(_concat);
  17336. async.whilst = function (test, iterator, callback) {
  17337. if (test()) {
  17338. iterator(function (err) {
  17339. if (err) {
  17340. return callback(err);
  17341. }
  17342. async.whilst(test, iterator, callback);
  17343. });
  17344. }
  17345. else {
  17346. callback();
  17347. }
  17348. };
  17349. async.doWhilst = function (iterator, test, callback) {
  17350. iterator(function (err) {
  17351. if (err) {
  17352. return callback(err);
  17353. }
  17354. var args = Array.prototype.slice.call(arguments, 1);
  17355. if (test.apply(null, args)) {
  17356. async.doWhilst(iterator, test, callback);
  17357. }
  17358. else {
  17359. callback();
  17360. }
  17361. });
  17362. };
  17363. async.until = function (test, iterator, callback) {
  17364. if (!test()) {
  17365. iterator(function (err) {
  17366. if (err) {
  17367. return callback(err);
  17368. }
  17369. async.until(test, iterator, callback);
  17370. });
  17371. }
  17372. else {
  17373. callback();
  17374. }
  17375. };
  17376. async.doUntil = function (iterator, test, callback) {
  17377. iterator(function (err) {
  17378. if (err) {
  17379. return callback(err);
  17380. }
  17381. var args = Array.prototype.slice.call(arguments, 1);
  17382. if (!test.apply(null, args)) {
  17383. async.doUntil(iterator, test, callback);
  17384. }
  17385. else {
  17386. callback();
  17387. }
  17388. });
  17389. };
  17390. async.queue = function (worker, concurrency) {
  17391. if (concurrency === undefined) {
  17392. concurrency = 1;
  17393. }
  17394. function _insert(q, data, pos, callback) {
  17395. if (!q.started){
  17396. q.started = true;
  17397. }
  17398. if (!_isArray(data)) {
  17399. data = [data];
  17400. }
  17401. if(data.length == 0) {
  17402. // call drain immediately if there are no tasks
  17403. return async.setImmediate(function() {
  17404. if (q.drain) {
  17405. q.drain();
  17406. }
  17407. });
  17408. }
  17409. _each(data, function(task) {
  17410. var item = {
  17411. data: task,
  17412. callback: typeof callback === 'function' ? callback : null
  17413. };
  17414. if (pos) {
  17415. q.tasks.unshift(item);
  17416. } else {
  17417. q.tasks.push(item);
  17418. }
  17419. if (q.saturated && q.tasks.length === q.concurrency) {
  17420. q.saturated();
  17421. }
  17422. async.setImmediate(q.process);
  17423. });
  17424. }
  17425. var workers = 0;
  17426. var q = {
  17427. tasks: [],
  17428. concurrency: concurrency,
  17429. saturated: null,
  17430. empty: null,
  17431. drain: null,
  17432. started: false,
  17433. paused: false,
  17434. push: function (data, callback) {
  17435. _insert(q, data, false, callback);
  17436. },
  17437. kill: function () {
  17438. q.drain = null;
  17439. q.tasks = [];
  17440. },
  17441. unshift: function (data, callback) {
  17442. _insert(q, data, true, callback);
  17443. },
  17444. process: function () {
  17445. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17446. var task = q.tasks.shift();
  17447. if (q.empty && q.tasks.length === 0) {
  17448. q.empty();
  17449. }
  17450. workers += 1;
  17451. var next = function () {
  17452. workers -= 1;
  17453. if (task.callback) {
  17454. task.callback.apply(task, arguments);
  17455. }
  17456. if (q.drain && q.tasks.length + workers === 0) {
  17457. q.drain();
  17458. }
  17459. q.process();
  17460. };
  17461. var cb = only_once(next);
  17462. worker(task.data, cb);
  17463. }
  17464. },
  17465. length: function () {
  17466. return q.tasks.length;
  17467. },
  17468. running: function () {
  17469. return workers;
  17470. },
  17471. idle: function() {
  17472. return q.tasks.length + workers === 0;
  17473. },
  17474. pause: function () {
  17475. if (q.paused === true) { return; }
  17476. q.paused = true;
  17477. q.process();
  17478. },
  17479. resume: function () {
  17480. if (q.paused === false) { return; }
  17481. q.paused = false;
  17482. q.process();
  17483. }
  17484. };
  17485. return q;
  17486. };
  17487. async.priorityQueue = function (worker, concurrency) {
  17488. function _compareTasks(a, b){
  17489. return a.priority - b.priority;
  17490. };
  17491. function _binarySearch(sequence, item, compare) {
  17492. var beg = -1,
  17493. end = sequence.length - 1;
  17494. while (beg < end) {
  17495. var mid = beg + ((end - beg + 1) >>> 1);
  17496. if (compare(item, sequence[mid]) >= 0) {
  17497. beg = mid;
  17498. } else {
  17499. end = mid - 1;
  17500. }
  17501. }
  17502. return beg;
  17503. }
  17504. function _insert(q, data, priority, callback) {
  17505. if (!q.started){
  17506. q.started = true;
  17507. }
  17508. if (!_isArray(data)) {
  17509. data = [data];
  17510. }
  17511. if(data.length == 0) {
  17512. // call drain immediately if there are no tasks
  17513. return async.setImmediate(function() {
  17514. if (q.drain) {
  17515. q.drain();
  17516. }
  17517. });
  17518. }
  17519. _each(data, function(task) {
  17520. var item = {
  17521. data: task,
  17522. priority: priority,
  17523. callback: typeof callback === 'function' ? callback : null
  17524. };
  17525. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17526. if (q.saturated && q.tasks.length === q.concurrency) {
  17527. q.saturated();
  17528. }
  17529. async.setImmediate(q.process);
  17530. });
  17531. }
  17532. // Start with a normal queue
  17533. var q = async.queue(worker, concurrency);
  17534. // Override push to accept second parameter representing priority
  17535. q.push = function (data, priority, callback) {
  17536. _insert(q, data, priority, callback);
  17537. };
  17538. // Remove unshift function
  17539. delete q.unshift;
  17540. return q;
  17541. };
  17542. async.cargo = function (worker, payload) {
  17543. var working = false,
  17544. tasks = [];
  17545. var cargo = {
  17546. tasks: tasks,
  17547. payload: payload,
  17548. saturated: null,
  17549. empty: null,
  17550. drain: null,
  17551. drained: true,
  17552. push: function (data, callback) {
  17553. if (!_isArray(data)) {
  17554. data = [data];
  17555. }
  17556. _each(data, function(task) {
  17557. tasks.push({
  17558. data: task,
  17559. callback: typeof callback === 'function' ? callback : null
  17560. });
  17561. cargo.drained = false;
  17562. if (cargo.saturated && tasks.length === payload) {
  17563. cargo.saturated();
  17564. }
  17565. });
  17566. async.setImmediate(cargo.process);
  17567. },
  17568. process: function process() {
  17569. if (working) return;
  17570. if (tasks.length === 0) {
  17571. if(cargo.drain && !cargo.drained) cargo.drain();
  17572. cargo.drained = true;
  17573. return;
  17574. }
  17575. var ts = typeof payload === 'number'
  17576. ? tasks.splice(0, payload)
  17577. : tasks.splice(0, tasks.length);
  17578. var ds = _map(ts, function (task) {
  17579. return task.data;
  17580. });
  17581. if(cargo.empty) cargo.empty();
  17582. working = true;
  17583. worker(ds, function () {
  17584. working = false;
  17585. var args = arguments;
  17586. _each(ts, function (data) {
  17587. if (data.callback) {
  17588. data.callback.apply(null, args);
  17589. }
  17590. });
  17591. process();
  17592. });
  17593. },
  17594. length: function () {
  17595. return tasks.length;
  17596. },
  17597. running: function () {
  17598. return working;
  17599. }
  17600. };
  17601. return cargo;
  17602. };
  17603. var _console_fn = function (name) {
  17604. return function (fn) {
  17605. var args = Array.prototype.slice.call(arguments, 1);
  17606. fn.apply(null, args.concat([function (err) {
  17607. var args = Array.prototype.slice.call(arguments, 1);
  17608. if (typeof console !== 'undefined') {
  17609. if (err) {
  17610. if (console.error) {
  17611. console.error(err);
  17612. }
  17613. }
  17614. else if (console[name]) {
  17615. _each(args, function (x) {
  17616. console[name](x);
  17617. });
  17618. }
  17619. }
  17620. }]));
  17621. };
  17622. };
  17623. async.log = _console_fn('log');
  17624. async.dir = _console_fn('dir');
  17625. /*async.info = _console_fn('info');
  17626. async.warn = _console_fn('warn');
  17627. async.error = _console_fn('error');*/
  17628. async.memoize = function (fn, hasher) {
  17629. var memo = {};
  17630. var queues = {};
  17631. hasher = hasher || function (x) {
  17632. return x;
  17633. };
  17634. var memoized = function () {
  17635. var args = Array.prototype.slice.call(arguments);
  17636. var callback = args.pop();
  17637. var key = hasher.apply(null, args);
  17638. if (key in memo) {
  17639. async.nextTick(function () {
  17640. callback.apply(null, memo[key]);
  17641. });
  17642. }
  17643. else if (key in queues) {
  17644. queues[key].push(callback);
  17645. }
  17646. else {
  17647. queues[key] = [callback];
  17648. fn.apply(null, args.concat([function () {
  17649. memo[key] = arguments;
  17650. var q = queues[key];
  17651. delete queues[key];
  17652. for (var i = 0, l = q.length; i < l; i++) {
  17653. q[i].apply(null, arguments);
  17654. }
  17655. }]));
  17656. }
  17657. };
  17658. memoized.memo = memo;
  17659. memoized.unmemoized = fn;
  17660. return memoized;
  17661. };
  17662. async.unmemoize = function (fn) {
  17663. return function () {
  17664. return (fn.unmemoized || fn).apply(null, arguments);
  17665. };
  17666. };
  17667. async.times = function (count, iterator, callback) {
  17668. var counter = [];
  17669. for (var i = 0; i < count; i++) {
  17670. counter.push(i);
  17671. }
  17672. return async.map(counter, iterator, callback);
  17673. };
  17674. async.timesSeries = function (count, iterator, callback) {
  17675. var counter = [];
  17676. for (var i = 0; i < count; i++) {
  17677. counter.push(i);
  17678. }
  17679. return async.mapSeries(counter, iterator, callback);
  17680. };
  17681. async.seq = function (/* functions... */) {
  17682. var fns = arguments;
  17683. return function () {
  17684. var that = this;
  17685. var args = Array.prototype.slice.call(arguments);
  17686. var callback = args.pop();
  17687. async.reduce(fns, args, function (newargs, fn, cb) {
  17688. fn.apply(that, newargs.concat([function () {
  17689. var err = arguments[0];
  17690. var nextargs = Array.prototype.slice.call(arguments, 1);
  17691. cb(err, nextargs);
  17692. }]))
  17693. },
  17694. function (err, results) {
  17695. callback.apply(that, [err].concat(results));
  17696. });
  17697. };
  17698. };
  17699. async.compose = function (/* functions... */) {
  17700. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17701. };
  17702. var _applyEach = function (eachfn, fns /*args...*/) {
  17703. var go = function () {
  17704. var that = this;
  17705. var args = Array.prototype.slice.call(arguments);
  17706. var callback = args.pop();
  17707. return eachfn(fns, function (fn, cb) {
  17708. fn.apply(that, args.concat([cb]));
  17709. },
  17710. callback);
  17711. };
  17712. if (arguments.length > 2) {
  17713. var args = Array.prototype.slice.call(arguments, 2);
  17714. return go.apply(this, args);
  17715. }
  17716. else {
  17717. return go;
  17718. }
  17719. };
  17720. async.applyEach = doParallel(_applyEach);
  17721. async.applyEachSeries = doSeries(_applyEach);
  17722. async.forever = function (fn, callback) {
  17723. function next(err) {
  17724. if (err) {
  17725. if (callback) {
  17726. return callback(err);
  17727. }
  17728. throw err;
  17729. }
  17730. fn(next);
  17731. }
  17732. next();
  17733. };
  17734. // Node.js
  17735. if (typeof module !== 'undefined' && module.exports) {
  17736. module.exports = async;
  17737. }
  17738. // AMD / RequireJS
  17739. else if (typeof define !== 'undefined' && define.amd) {
  17740. define([], function () {
  17741. return async;
  17742. });
  17743. }
  17744. // included directly via <script> tag
  17745. else {
  17746. root.async = async;
  17747. }
  17748. }());
  17749. }).call(this,require('_process'))
  17750. },{"_process":2}],70:[function(require,module,exports){
  17751. // i18next, v1.7.7
  17752. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17753. // Distributed under MIT license
  17754. // http://i18next.com
  17755. (function() {
  17756. // add indexOf to non ECMA-262 standard compliant browsers
  17757. if (!Array.prototype.indexOf) {
  17758. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17759. "use strict";
  17760. if (this == null) {
  17761. throw new TypeError();
  17762. }
  17763. var t = Object(this);
  17764. var len = t.length >>> 0;
  17765. if (len === 0) {
  17766. return -1;
  17767. }
  17768. var n = 0;
  17769. if (arguments.length > 0) {
  17770. n = Number(arguments[1]);
  17771. if (n != n) { // shortcut for verifying if it's NaN
  17772. n = 0;
  17773. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17774. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17775. }
  17776. }
  17777. if (n >= len) {
  17778. return -1;
  17779. }
  17780. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17781. for (; k < len; k++) {
  17782. if (k in t && t[k] === searchElement) {
  17783. return k;
  17784. }
  17785. }
  17786. return -1;
  17787. }
  17788. }
  17789. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17790. if (!Array.prototype.lastIndexOf) {
  17791. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17792. "use strict";
  17793. if (this == null) {
  17794. throw new TypeError();
  17795. }
  17796. var t = Object(this);
  17797. var len = t.length >>> 0;
  17798. if (len === 0) {
  17799. return -1;
  17800. }
  17801. var n = len;
  17802. if (arguments.length > 1) {
  17803. n = Number(arguments[1]);
  17804. if (n != n) {
  17805. n = 0;
  17806. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17807. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17808. }
  17809. }
  17810. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17811. for (; k >= 0; k--) {
  17812. if (k in t && t[k] === searchElement) {
  17813. return k;
  17814. }
  17815. }
  17816. return -1;
  17817. };
  17818. }
  17819. // Add string trim for IE8.
  17820. if (typeof String.prototype.trim !== 'function') {
  17821. String.prototype.trim = function() {
  17822. return this.replace(/^\s+|\s+$/g, '');
  17823. }
  17824. }
  17825. var root = this
  17826. , $ = root.jQuery || root.Zepto
  17827. , i18n = {}
  17828. , resStore = {}
  17829. , currentLng
  17830. , replacementCounter = 0
  17831. , languages = []
  17832. , initialized = false
  17833. , sync = {};
  17834. // Export the i18next object for **CommonJS**.
  17835. // If we're not in CommonJS, add `i18n` to the
  17836. // global object or to jquery.
  17837. if (typeof module !== 'undefined' && module.exports) {
  17838. if (!$) {
  17839. try {
  17840. $ = require('jquery');
  17841. } catch(e) {
  17842. // just ignore
  17843. }
  17844. }
  17845. if ($) {
  17846. $.i18n = $.i18n || i18n;
  17847. }
  17848. module.exports = i18n;
  17849. } else {
  17850. if ($) {
  17851. $.i18n = $.i18n || i18n;
  17852. }
  17853. root.i18n = root.i18n || i18n;
  17854. }
  17855. sync = {
  17856. load: function(lngs, options, cb) {
  17857. if (options.useLocalStorage) {
  17858. sync._loadLocal(lngs, options, function(err, store) {
  17859. var missingLngs = [];
  17860. for (var i = 0, len = lngs.length; i < len; i++) {
  17861. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17862. }
  17863. if (missingLngs.length > 0) {
  17864. sync._fetch(missingLngs, options, function(err, fetched) {
  17865. f.extend(store, fetched);
  17866. sync._storeLocal(fetched);
  17867. cb(null, store);
  17868. });
  17869. } else {
  17870. cb(null, store);
  17871. }
  17872. });
  17873. } else {
  17874. sync._fetch(lngs, options, function(err, store){
  17875. cb(null, store);
  17876. });
  17877. }
  17878. },
  17879. _loadLocal: function(lngs, options, cb) {
  17880. var store = {}
  17881. , nowMS = new Date().getTime();
  17882. if(window.localStorage) {
  17883. var todo = lngs.length;
  17884. f.each(lngs, function(key, lng) {
  17885. var local = window.localStorage.getItem('res_' + lng);
  17886. if (local) {
  17887. local = JSON.parse(local);
  17888. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17889. store[lng] = local;
  17890. }
  17891. }
  17892. todo--; // wait for all done befor callback
  17893. if (todo === 0) cb(null, store);
  17894. });
  17895. }
  17896. },
  17897. _storeLocal: function(store) {
  17898. if(window.localStorage) {
  17899. for (var m in store) {
  17900. store[m].i18nStamp = new Date().getTime();
  17901. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17902. }
  17903. }
  17904. return;
  17905. },
  17906. _fetch: function(lngs, options, cb) {
  17907. var ns = options.ns
  17908. , store = {};
  17909. if (!options.dynamicLoad) {
  17910. var todo = ns.namespaces.length * lngs.length
  17911. , errors;
  17912. // load each file individual
  17913. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17914. f.each(lngs, function(lngIndex, lngValue) {
  17915. // Call this once our translation has returned.
  17916. var loadComplete = function(err, data) {
  17917. if (err) {
  17918. errors = errors || [];
  17919. errors.push(err);
  17920. }
  17921. store[lngValue] = store[lngValue] || {};
  17922. store[lngValue][nsValue] = data;
  17923. todo--; // wait for all done befor callback
  17924. if (todo === 0) cb(errors, store);
  17925. };
  17926. if(typeof options.customLoad == 'function'){
  17927. // Use the specified custom callback.
  17928. options.customLoad(lngValue, nsValue, options, loadComplete);
  17929. } else {
  17930. //~ // Use our inbuilt sync.
  17931. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17932. }
  17933. });
  17934. });
  17935. } else {
  17936. // Call this once our translation has returned.
  17937. var loadComplete = function(err, data) {
  17938. cb(null, data);
  17939. };
  17940. if(typeof options.customLoad == 'function'){
  17941. // Use the specified custom callback.
  17942. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17943. } else {
  17944. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17945. // load all needed stuff once
  17946. f.ajax({
  17947. url: url,
  17948. success: function(data, status, xhr) {
  17949. f.log('loaded: ' + url);
  17950. loadComplete(null, data);
  17951. },
  17952. error : function(xhr, status, error) {
  17953. f.log('failed loading: ' + url);
  17954. loadComplete('failed loading resource.json error: ' + error);
  17955. },
  17956. dataType: "json",
  17957. async : options.getAsync
  17958. });
  17959. }
  17960. }
  17961. },
  17962. _fetchOne: function(lng, ns, options, done) {
  17963. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17964. f.ajax({
  17965. url: url,
  17966. success: function(data, status, xhr) {
  17967. f.log('loaded: ' + url);
  17968. done(null, data);
  17969. },
  17970. error : function(xhr, status, error) {
  17971. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17972. // file loaded but invalid json, stop waste time !
  17973. f.error('There is a typo in: ' + url);
  17974. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17975. f.log('Does not exist: ' + url);
  17976. } else {
  17977. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17978. f.log(theStatus + ' when loading ' + url);
  17979. }
  17980. done(error, {});
  17981. },
  17982. dataType: "json",
  17983. async : options.getAsync
  17984. });
  17985. },
  17986. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17987. var payload = {};
  17988. payload[key] = defaultValue;
  17989. var urls = [];
  17990. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17991. for (var i = 0; i < o.fallbackLng.length; i++) {
  17992. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17993. }
  17994. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17995. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17996. } else if (o.sendMissingTo === 'all') {
  17997. for (var i = 0, l = lngs.length; i < l; i++) {
  17998. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17999. }
  18000. }
  18001. for (var y = 0, len = urls.length; y < len; y++) {
  18002. var item = urls[y];
  18003. f.ajax({
  18004. url: item.url,
  18005. type: o.sendType,
  18006. data: payload,
  18007. success: function(data, status, xhr) {
  18008. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18009. // add key to resStore
  18010. var keys = key.split('.');
  18011. var x = 0;
  18012. var value = resStore[item.lng][ns];
  18013. while (keys[x]) {
  18014. if (x === keys.length - 1) {
  18015. value = value[keys[x]] = defaultValue;
  18016. } else {
  18017. value = value[keys[x]] = value[keys[x]] || {};
  18018. }
  18019. x++;
  18020. }
  18021. },
  18022. error : function(xhr, status, error) {
  18023. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18024. },
  18025. dataType: "json",
  18026. async : o.postAsync
  18027. });
  18028. }
  18029. },
  18030. reload: reload
  18031. };
  18032. // defaults
  18033. var o = {
  18034. lng: undefined,
  18035. load: 'all',
  18036. preload: [],
  18037. lowerCaseLng: false,
  18038. returnObjectTrees: false,
  18039. fallbackLng: ['dev'],
  18040. fallbackNS: [],
  18041. detectLngQS: 'setLng',
  18042. detectLngFromLocalStorage: false,
  18043. ns: 'translation',
  18044. fallbackOnNull: true,
  18045. fallbackOnEmpty: false,
  18046. fallbackToDefaultNS: false,
  18047. nsseparator: ':',
  18048. keyseparator: '.',
  18049. selectorAttr: 'data-i18n',
  18050. debug: false,
  18051. resGetPath: 'locales/__lng__/__ns__.json',
  18052. resPostPath: 'locales/add/__lng__/__ns__',
  18053. getAsync: true,
  18054. postAsync: true,
  18055. resStore: undefined,
  18056. useLocalStorage: false,
  18057. localStorageExpirationTime: 7*24*60*60*1000,
  18058. dynamicLoad: false,
  18059. sendMissing: false,
  18060. sendMissingTo: 'fallback', // current | all
  18061. sendType: 'POST',
  18062. interpolationPrefix: '__',
  18063. interpolationSuffix: '__',
  18064. defaultVariables: false,
  18065. reusePrefix: '$t(',
  18066. reuseSuffix: ')',
  18067. pluralSuffix: '_plural',
  18068. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18069. contextNotFound: ['context_not_found', Math.random()].join(''),
  18070. escapeInterpolation: false,
  18071. indefiniteSuffix: '_indefinite',
  18072. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18073. setJqueryExt: true,
  18074. defaultValueFromContent: true,
  18075. useDataAttrOptions: false,
  18076. cookieExpirationTime: undefined,
  18077. useCookie: true,
  18078. cookieName: 'i18next',
  18079. cookieDomain: undefined,
  18080. objectTreeKeyHandler: undefined,
  18081. postProcess: undefined,
  18082. parseMissingKey: undefined,
  18083. missingKeyHandler: sync.postMissing,
  18084. shortcutFunction: 'sprintf' // or: defaultValue
  18085. };
  18086. function _extend(target, source) {
  18087. if (!source || typeof source === 'function') {
  18088. return target;
  18089. }
  18090. for (var attr in source) { target[attr] = source[attr]; }
  18091. return target;
  18092. }
  18093. function _deepExtend(target, source) {
  18094. for (var prop in source)
  18095. if (prop in target)
  18096. _deepExtend(target[prop], source[prop]);
  18097. else
  18098. target[prop] = source[prop];
  18099. return target;
  18100. }
  18101. function _each(object, callback, args) {
  18102. var name, i = 0,
  18103. length = object.length,
  18104. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18105. if (args) {
  18106. if (isObj) {
  18107. for (name in object) {
  18108. if (callback.apply(object[name], args) === false) {
  18109. break;
  18110. }
  18111. }
  18112. } else {
  18113. for ( ; i < length; ) {
  18114. if (callback.apply(object[i++], args) === false) {
  18115. break;
  18116. }
  18117. }
  18118. }
  18119. // A special, fast, case for the most common use of each
  18120. } else {
  18121. if (isObj) {
  18122. for (name in object) {
  18123. if (callback.call(object[name], name, object[name]) === false) {
  18124. break;
  18125. }
  18126. }
  18127. } else {
  18128. for ( ; i < length; ) {
  18129. if (callback.call(object[i], i, object[i++]) === false) {
  18130. break;
  18131. }
  18132. }
  18133. }
  18134. }
  18135. return object;
  18136. }
  18137. var _entityMap = {
  18138. "&": "&amp;",
  18139. "<": "&lt;",
  18140. ">": "&gt;",
  18141. '"': '&quot;',
  18142. "'": '&#39;',
  18143. "/": '&#x2F;'
  18144. };
  18145. function _escape(data) {
  18146. if (typeof data === 'string') {
  18147. return data.replace(/[&<>"'\/]/g, function (s) {
  18148. return _entityMap[s];
  18149. });
  18150. }else{
  18151. return data;
  18152. }
  18153. }
  18154. function _ajax(options) {
  18155. // v0.5.0 of https://github.com/goloroden/http.js
  18156. var getXhr = function (callback) {
  18157. // Use the native XHR object if the browser supports it.
  18158. if (window.XMLHttpRequest) {
  18159. return callback(null, new XMLHttpRequest());
  18160. } else if (window.ActiveXObject) {
  18161. // In Internet Explorer check for ActiveX versions of the XHR object.
  18162. try {
  18163. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18164. } catch (e) {
  18165. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18166. }
  18167. }
  18168. // If no XHR support was found, throw an error.
  18169. return callback(new Error());
  18170. };
  18171. var encodeUsingUrlEncoding = function (data) {
  18172. if(typeof data === 'string') {
  18173. return data;
  18174. }
  18175. var result = [];
  18176. for(var dataItem in data) {
  18177. if(data.hasOwnProperty(dataItem)) {
  18178. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18179. }
  18180. }
  18181. return result.join('&');
  18182. };
  18183. var utf8 = function (text) {
  18184. text = text.replace(/\r\n/g, '\n');
  18185. var result = '';
  18186. for(var i = 0; i < text.length; i++) {
  18187. var c = text.charCodeAt(i);
  18188. if(c < 128) {
  18189. result += String.fromCharCode(c);
  18190. } else if((c > 127) && (c < 2048)) {
  18191. result += String.fromCharCode((c >> 6) | 192);
  18192. result += String.fromCharCode((c & 63) | 128);
  18193. } else {
  18194. result += String.fromCharCode((c >> 12) | 224);
  18195. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18196. result += String.fromCharCode((c & 63) | 128);
  18197. }
  18198. }
  18199. return result;
  18200. };
  18201. var base64 = function (text) {
  18202. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18203. text = utf8(text);
  18204. var result = '',
  18205. chr1, chr2, chr3,
  18206. enc1, enc2, enc3, enc4,
  18207. i = 0;
  18208. do {
  18209. chr1 = text.charCodeAt(i++);
  18210. chr2 = text.charCodeAt(i++);
  18211. chr3 = text.charCodeAt(i++);
  18212. enc1 = chr1 >> 2;
  18213. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18214. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18215. enc4 = chr3 & 63;
  18216. if(isNaN(chr2)) {
  18217. enc3 = enc4 = 64;
  18218. } else if(isNaN(chr3)) {
  18219. enc4 = 64;
  18220. }
  18221. result +=
  18222. keyStr.charAt(enc1) +
  18223. keyStr.charAt(enc2) +
  18224. keyStr.charAt(enc3) +
  18225. keyStr.charAt(enc4);
  18226. chr1 = chr2 = chr3 = '';
  18227. enc1 = enc2 = enc3 = enc4 = '';
  18228. } while(i < text.length);
  18229. return result;
  18230. };
  18231. var mergeHeaders = function () {
  18232. // Use the first header object as base.
  18233. var result = arguments[0];
  18234. // Iterate through the remaining header objects and add them.
  18235. for(var i = 1; i < arguments.length; i++) {
  18236. var currentHeaders = arguments[i];
  18237. for(var header in currentHeaders) {
  18238. if(currentHeaders.hasOwnProperty(header)) {
  18239. result[header] = currentHeaders[header];
  18240. }
  18241. }
  18242. }
  18243. // Return the merged headers.
  18244. return result;
  18245. };
  18246. var ajax = function (method, url, options, callback) {
  18247. // Adjust parameters.
  18248. if(typeof options === 'function') {
  18249. callback = options;
  18250. options = {};
  18251. }
  18252. // Set default parameter values.
  18253. options.cache = options.cache || false;
  18254. options.data = options.data || {};
  18255. options.headers = options.headers || {};
  18256. options.jsonp = options.jsonp || false;
  18257. options.async = options.async === undefined ? true : options.async;
  18258. // Merge the various header objects.
  18259. var headers = mergeHeaders({
  18260. 'accept': '*/*',
  18261. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18262. }, ajax.headers, options.headers);
  18263. // Encode the data according to the content-type.
  18264. var payload;
  18265. if (headers['content-type'] === 'application/json') {
  18266. payload = JSON.stringify(options.data);
  18267. } else {
  18268. payload = encodeUsingUrlEncoding(options.data);
  18269. }
  18270. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18271. // if neccessary.
  18272. if(method === 'GET') {
  18273. // Setup the query string.
  18274. var queryString = [];
  18275. if(payload) {
  18276. queryString.push(payload);
  18277. payload = null;
  18278. }
  18279. // Handle caching.
  18280. if(!options.cache) {
  18281. queryString.push('_=' + (new Date()).getTime());
  18282. }
  18283. // If neccessary prepare the query string for a JSONP call.
  18284. if(options.jsonp) {
  18285. queryString.push('callback=' + options.jsonp);
  18286. queryString.push('jsonp=' + options.jsonp);
  18287. }
  18288. // Merge the query string and attach it to the url.
  18289. queryString = queryString.join('&');
  18290. if (queryString.length > 1) {
  18291. if (url.indexOf('?') > -1) {
  18292. url += '&' + queryString;
  18293. } else {
  18294. url += '?' + queryString;
  18295. }
  18296. }
  18297. // Make a JSONP call if neccessary.
  18298. if(options.jsonp) {
  18299. var head = document.getElementsByTagName('head')[0];
  18300. var script = document.createElement('script');
  18301. script.type = 'text/javascript';
  18302. script.src = url;
  18303. head.appendChild(script);
  18304. return;
  18305. }
  18306. }
  18307. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18308. getXhr(function (err, xhr) {
  18309. if(err) return callback(err);
  18310. // Open the request.
  18311. xhr.open(method, url, options.async);
  18312. // Set the request headers.
  18313. for(var header in headers) {
  18314. if(headers.hasOwnProperty(header)) {
  18315. xhr.setRequestHeader(header, headers[header]);
  18316. }
  18317. }
  18318. // Handle the request events.
  18319. xhr.onreadystatechange = function () {
  18320. if(xhr.readyState === 4) {
  18321. var data = xhr.responseText || '';
  18322. // If no callback is given, return.
  18323. if(!callback) {
  18324. return;
  18325. }
  18326. // Return an object that provides access to the data as text and JSON.
  18327. callback(xhr.status, {
  18328. text: function () {
  18329. return data;
  18330. },
  18331. json: function () {
  18332. try {
  18333. return JSON.parse(data)
  18334. } catch (e) {
  18335. f.error('Can not parse JSON. URL: ' + url);
  18336. return {};
  18337. }
  18338. }
  18339. });
  18340. }
  18341. };
  18342. // Actually send the XHR request.
  18343. xhr.send(payload);
  18344. });
  18345. };
  18346. // Define the external interface.
  18347. var http = {
  18348. authBasic: function (username, password) {
  18349. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18350. },
  18351. connect: function (url, options, callback) {
  18352. return ajax('CONNECT', url, options, callback);
  18353. },
  18354. del: function (url, options, callback) {
  18355. return ajax('DELETE', url, options, callback);
  18356. },
  18357. get: function (url, options, callback) {
  18358. return ajax('GET', url, options, callback);
  18359. },
  18360. head: function (url, options, callback) {
  18361. return ajax('HEAD', url, options, callback);
  18362. },
  18363. headers: function (headers) {
  18364. ajax.headers = headers || {};
  18365. },
  18366. isAllowed: function (url, verb, callback) {
  18367. this.options(url, function (status, data) {
  18368. callback(data.text().indexOf(verb) !== -1);
  18369. });
  18370. },
  18371. options: function (url, options, callback) {
  18372. return ajax('OPTIONS', url, options, callback);
  18373. },
  18374. patch: function (url, options, callback) {
  18375. return ajax('PATCH', url, options, callback);
  18376. },
  18377. post: function (url, options, callback) {
  18378. return ajax('POST', url, options, callback);
  18379. },
  18380. put: function (url, options, callback) {
  18381. return ajax('PUT', url, options, callback);
  18382. },
  18383. trace: function (url, options, callback) {
  18384. return ajax('TRACE', url, options, callback);
  18385. }
  18386. };
  18387. var methode = options.type ? options.type.toLowerCase() : 'get';
  18388. http[methode](options.url, options, function (status, data) {
  18389. // file: protocol always gives status code 0, so check for data
  18390. if (status === 200 || (status === 0 && data.text())) {
  18391. options.success(data.json(), status, null);
  18392. } else {
  18393. options.error(data.text(), status, null);
  18394. }
  18395. });
  18396. }
  18397. var _cookie = {
  18398. create: function(name,value,minutes,domain) {
  18399. var expires;
  18400. if (minutes) {
  18401. var date = new Date();
  18402. date.setTime(date.getTime()+(minutes*60*1000));
  18403. expires = "; expires="+date.toGMTString();
  18404. }
  18405. else expires = "";
  18406. domain = (domain)? "domain="+domain+";" : "";
  18407. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18408. },
  18409. read: function(name) {
  18410. var nameEQ = name + "=";
  18411. var ca = document.cookie.split(';');
  18412. for(var i=0;i < ca.length;i++) {
  18413. var c = ca[i];
  18414. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18415. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18416. }
  18417. return null;
  18418. },
  18419. remove: function(name) {
  18420. this.create(name,"",-1);
  18421. }
  18422. };
  18423. var cookie_noop = {
  18424. create: function(name,value,minutes,domain) {},
  18425. read: function(name) { return null; },
  18426. remove: function(name) {}
  18427. };
  18428. // move dependent functions to a container so that
  18429. // they can be overriden easier in no jquery environment (node.js)
  18430. var f = {
  18431. extend: $ ? $.extend : _extend,
  18432. deepExtend: _deepExtend,
  18433. each: $ ? $.each : _each,
  18434. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18435. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18436. detectLanguage: detectLanguage,
  18437. escape: _escape,
  18438. log: function(str) {
  18439. if (o.debug && typeof console !== "undefined") console.log(str);
  18440. },
  18441. error: function(str) {
  18442. if (typeof console !== "undefined") console.error(str);
  18443. },
  18444. getCountyIndexOfLng: function(lng) {
  18445. var lng_index = 0;
  18446. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18447. return lng_index;
  18448. },
  18449. toLanguages: function(lng) {
  18450. var log = this.log;
  18451. function applyCase(l) {
  18452. var ret = l;
  18453. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18454. var parts = l.split('-');
  18455. ret = o.lowerCaseLng ?
  18456. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18457. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18458. } else {
  18459. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18460. }
  18461. return ret;
  18462. }
  18463. var languages = [];
  18464. var whitelist = o.lngWhitelist || false;
  18465. var addLanguage = function(language){
  18466. //reject langs not whitelisted
  18467. if(!whitelist || whitelist.indexOf(language) > -1){
  18468. languages.push(language);
  18469. }else{
  18470. log('rejecting non-whitelisted language: ' + language);
  18471. }
  18472. };
  18473. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18474. var parts = lng.split('-');
  18475. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18476. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18477. } else {
  18478. addLanguage(applyCase(lng));
  18479. }
  18480. for (var i = 0; i < o.fallbackLng.length; i++) {
  18481. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18482. }
  18483. return languages;
  18484. },
  18485. regexEscape: function(str) {
  18486. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18487. },
  18488. regexReplacementEscape: function(strOrFn) {
  18489. if (typeof strOrFn === 'string') {
  18490. return strOrFn.replace(/\$/g, "$$$$");
  18491. } else {
  18492. return strOrFn;
  18493. }
  18494. },
  18495. localStorage: {
  18496. setItem: function(key, value) {
  18497. if (window.localStorage) {
  18498. try {
  18499. window.localStorage.setItem(key, value);
  18500. } catch (e) {
  18501. f.log('failed to set value for key "' + key + '" to localStorage.');
  18502. }
  18503. }
  18504. }
  18505. }
  18506. };
  18507. function init(options, cb) {
  18508. if (typeof options === 'function') {
  18509. cb = options;
  18510. options = {};
  18511. }
  18512. options = options || {};
  18513. // override defaults with passed in options
  18514. f.extend(o, options);
  18515. delete o.fixLng; /* passed in each time */
  18516. // override functions: .log(), .detectLanguage(), etc
  18517. if (o.functions) {
  18518. delete o.functions;
  18519. f.extend(f, options.functions);
  18520. }
  18521. // create namespace object if namespace is passed in as string
  18522. if (typeof o.ns == 'string') {
  18523. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18524. }
  18525. // fallback namespaces
  18526. if (typeof o.fallbackNS == 'string') {
  18527. o.fallbackNS = [o.fallbackNS];
  18528. }
  18529. // fallback languages
  18530. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18531. o.fallbackLng = [o.fallbackLng];
  18532. }
  18533. // escape prefix/suffix
  18534. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18535. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18536. if (!o.lng) o.lng = f.detectLanguage();
  18537. languages = f.toLanguages(o.lng);
  18538. currentLng = languages[0];
  18539. f.log('currentLng set to: ' + currentLng);
  18540. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18541. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18542. }
  18543. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18544. f.localStorage.setItem('i18next_lng', currentLng);
  18545. }
  18546. var lngTranslate = translate;
  18547. if (options.fixLng) {
  18548. lngTranslate = function(key, options) {
  18549. options = options || {};
  18550. options.lng = options.lng || lngTranslate.lng;
  18551. return translate(key, options);
  18552. };
  18553. lngTranslate.lng = currentLng;
  18554. }
  18555. pluralExtensions.setCurrentLng(currentLng);
  18556. // add JQuery extensions
  18557. if ($ && o.setJqueryExt) addJqueryFunct();
  18558. // jQuery deferred
  18559. var deferred;
  18560. if ($ && $.Deferred) {
  18561. deferred = $.Deferred();
  18562. }
  18563. // return immidiatly if res are passed in
  18564. if (o.resStore) {
  18565. resStore = o.resStore;
  18566. initialized = true;
  18567. if (cb) cb(lngTranslate);
  18568. if (deferred) deferred.resolve(lngTranslate);
  18569. if (deferred) return deferred.promise();
  18570. return;
  18571. }
  18572. // languages to load
  18573. var lngsToLoad = f.toLanguages(o.lng);
  18574. if (typeof o.preload === 'string') o.preload = [o.preload];
  18575. for (var i = 0, l = o.preload.length; i < l; i++) {
  18576. var pres = f.toLanguages(o.preload[i]);
  18577. for (var y = 0, len = pres.length; y < len; y++) {
  18578. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18579. lngsToLoad.push(pres[y]);
  18580. }
  18581. }
  18582. }
  18583. // else load them
  18584. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18585. resStore = store;
  18586. initialized = true;
  18587. if (cb) cb(lngTranslate);
  18588. if (deferred) deferred.resolve(lngTranslate);
  18589. });
  18590. if (deferred) return deferred.promise();
  18591. }
  18592. function preload(lngs, cb) {
  18593. if (typeof lngs === 'string') lngs = [lngs];
  18594. for (var i = 0, l = lngs.length; i < l; i++) {
  18595. if (o.preload.indexOf(lngs[i]) < 0) {
  18596. o.preload.push(lngs[i]);
  18597. }
  18598. }
  18599. return init(cb);
  18600. }
  18601. function addResourceBundle(lng, ns, resources, deep) {
  18602. if (typeof ns !== 'string') {
  18603. resources = ns;
  18604. ns = o.ns.defaultNs;
  18605. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18606. o.ns.namespaces.push(ns);
  18607. }
  18608. resStore[lng] = resStore[lng] || {};
  18609. resStore[lng][ns] = resStore[lng][ns] || {};
  18610. if (deep) {
  18611. f.deepExtend(resStore[lng][ns], resources);
  18612. } else {
  18613. f.extend(resStore[lng][ns], resources);
  18614. }
  18615. }
  18616. function hasResourceBundle(lng, ns) {
  18617. if (typeof ns !== 'string') {
  18618. ns = o.ns.defaultNs;
  18619. }
  18620. resStore[lng] = resStore[lng] || {};
  18621. var res = resStore[lng][ns] || {};
  18622. var hasValues = false;
  18623. for(var prop in res) {
  18624. if (res.hasOwnProperty(prop)) {
  18625. hasValues = true;
  18626. }
  18627. }
  18628. return hasValues;
  18629. }
  18630. function removeResourceBundle(lng, ns) {
  18631. if (typeof ns !== 'string') {
  18632. ns = o.ns.defaultNs;
  18633. }
  18634. resStore[lng] = resStore[lng] || {};
  18635. resStore[lng][ns] = {};
  18636. }
  18637. function addResource(lng, ns, key, value) {
  18638. if (typeof ns !== 'string') {
  18639. resource = ns;
  18640. ns = o.ns.defaultNs;
  18641. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18642. o.ns.namespaces.push(ns);
  18643. }
  18644. resStore[lng] = resStore[lng] || {};
  18645. resStore[lng][ns] = resStore[lng][ns] || {};
  18646. var keys = key.split(o.keyseparator);
  18647. var x = 0;
  18648. var node = resStore[lng][ns];
  18649. var origRef = node;
  18650. while (keys[x]) {
  18651. if (x == keys.length - 1)
  18652. node[keys[x]] = value;
  18653. else {
  18654. if (node[keys[x]] == null)
  18655. node[keys[x]] = {};
  18656. node = node[keys[x]];
  18657. }
  18658. x++;
  18659. }
  18660. }
  18661. function addResources(lng, ns, resources) {
  18662. if (typeof ns !== 'string') {
  18663. resource = ns;
  18664. ns = o.ns.defaultNs;
  18665. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18666. o.ns.namespaces.push(ns);
  18667. }
  18668. for (var m in resources) {
  18669. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18670. }
  18671. }
  18672. function setDefaultNamespace(ns) {
  18673. o.ns.defaultNs = ns;
  18674. }
  18675. function loadNamespace(namespace, cb) {
  18676. loadNamespaces([namespace], cb);
  18677. }
  18678. function loadNamespaces(namespaces, cb) {
  18679. var opts = {
  18680. dynamicLoad: o.dynamicLoad,
  18681. resGetPath: o.resGetPath,
  18682. getAsync: o.getAsync,
  18683. customLoad: o.customLoad,
  18684. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18685. };
  18686. // languages to load
  18687. var lngsToLoad = f.toLanguages(o.lng);
  18688. if (typeof o.preload === 'string') o.preload = [o.preload];
  18689. for (var i = 0, l = o.preload.length; i < l; i++) {
  18690. var pres = f.toLanguages(o.preload[i]);
  18691. for (var y = 0, len = pres.length; y < len; y++) {
  18692. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18693. lngsToLoad.push(pres[y]);
  18694. }
  18695. }
  18696. }
  18697. // check if we have to load
  18698. var lngNeedLoad = [];
  18699. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18700. var needLoad = false;
  18701. var resSet = resStore[lngsToLoad[a]];
  18702. if (resSet) {
  18703. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18704. if (!resSet[namespaces[b]]) needLoad = true;
  18705. }
  18706. } else {
  18707. needLoad = true;
  18708. }
  18709. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18710. }
  18711. if (lngNeedLoad.length) {
  18712. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18713. var todo = namespaces.length * lngNeedLoad.length;
  18714. // load each file individual
  18715. f.each(namespaces, function(nsIndex, nsValue) {
  18716. // append namespace to namespace array
  18717. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18718. o.ns.namespaces.push(nsValue);
  18719. }
  18720. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18721. resStore[lngValue] = resStore[lngValue] || {};
  18722. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18723. todo--; // wait for all done befor callback
  18724. if (todo === 0 && cb) {
  18725. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18726. cb();
  18727. }
  18728. });
  18729. });
  18730. });
  18731. } else {
  18732. if (cb) cb();
  18733. }
  18734. }
  18735. function setLng(lng, options, cb) {
  18736. if (typeof options === 'function') {
  18737. cb = options;
  18738. options = {};
  18739. } else if (!options) {
  18740. options = {};
  18741. }
  18742. options.lng = lng;
  18743. return init(options, cb);
  18744. }
  18745. function lng() {
  18746. return currentLng;
  18747. }
  18748. function reload(cb) {
  18749. resStore = {};
  18750. setLng(currentLng, cb);
  18751. }
  18752. function addJqueryFunct() {
  18753. // $.t shortcut
  18754. $.t = $.t || translate;
  18755. function parse(ele, key, options) {
  18756. if (key.length === 0) return;
  18757. var attr = 'text';
  18758. if (key.indexOf('[') === 0) {
  18759. var parts = key.split(']');
  18760. key = parts[1];
  18761. attr = parts[0].substr(1, parts[0].length-1);
  18762. }
  18763. if (key.indexOf(';') === key.length-1) {
  18764. key = key.substr(0, key.length-2);
  18765. }
  18766. var optionsToUse;
  18767. if (attr === 'html') {
  18768. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18769. ele.html($.t(key, optionsToUse));
  18770. } else if (attr === 'text') {
  18771. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18772. ele.text($.t(key, optionsToUse));
  18773. } else if (attr === 'prepend') {
  18774. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18775. ele.prepend($.t(key, optionsToUse));
  18776. } else if (attr === 'append') {
  18777. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18778. ele.append($.t(key, optionsToUse));
  18779. } else if (attr.indexOf("data-") === 0) {
  18780. var dataAttr = attr.substr(("data-").length);
  18781. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18782. var translated = $.t(key, optionsToUse);
  18783. //we change into the data cache
  18784. ele.data(dataAttr, translated);
  18785. //we change into the dom
  18786. ele.attr(attr, translated);
  18787. } else {
  18788. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18789. ele.attr(attr, $.t(key, optionsToUse));
  18790. }
  18791. }
  18792. function localize(ele, options) {
  18793. var key = ele.attr(o.selectorAttr);
  18794. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18795. if (!key) return;
  18796. var target = ele
  18797. , targetSelector = ele.data("i18n-target");
  18798. if (targetSelector) {
  18799. target = ele.find(targetSelector) || ele;
  18800. }
  18801. if (!options && o.useDataAttrOptions === true) {
  18802. options = ele.data("i18n-options");
  18803. }
  18804. options = options || {};
  18805. if (key.indexOf(';') >= 0) {
  18806. var keys = key.split(';');
  18807. $.each(keys, function(m, k) {
  18808. if (k !== '') parse(target, k, options);
  18809. });
  18810. } else {
  18811. parse(target, key, options);
  18812. }
  18813. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18814. }
  18815. // fn
  18816. $.fn.i18n = function (options) {
  18817. return this.each(function() {
  18818. // localize element itself
  18819. localize($(this), options);
  18820. // localize childs
  18821. var elements = $(this).find('[' + o.selectorAttr + ']');
  18822. elements.each(function() {
  18823. localize($(this), options);
  18824. });
  18825. });
  18826. };
  18827. }
  18828. function applyReplacement(str, replacementHash, nestedKey, options) {
  18829. if (!str) return str;
  18830. options = options || replacementHash; // first call uses replacement hash combined with options
  18831. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18832. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18833. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18834. , unEscapingSuffix = 'HTML'+suffix;
  18835. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18836. f.each(hash, function(key, value) {
  18837. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18838. if (typeof value === 'object' && value !== null) {
  18839. str = applyReplacement(str, value, nextKey, options);
  18840. } else {
  18841. if (options.escapeInterpolation || o.escapeInterpolation) {
  18842. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18843. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18844. } else {
  18845. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18846. }
  18847. // str = options.escapeInterpolation;
  18848. }
  18849. });
  18850. return str;
  18851. }
  18852. // append it to functions
  18853. f.applyReplacement = applyReplacement;
  18854. function applyReuse(translated, options) {
  18855. var comma = ',';
  18856. var options_open = '{';
  18857. var options_close = '}';
  18858. var opts = f.extend({}, options);
  18859. delete opts.postProcess;
  18860. while (translated.indexOf(o.reusePrefix) != -1) {
  18861. replacementCounter++;
  18862. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18863. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18864. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18865. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18866. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18867. if (index_of_end_of_closing <= index_of_opening) {
  18868. f.error('there is an missing closing in following translation value', translated);
  18869. return '';
  18870. }
  18871. if (token_without_symbols.indexOf(comma) != -1) {
  18872. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18873. 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) {
  18874. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18875. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18876. try {
  18877. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18878. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18879. } catch (e) {
  18880. }
  18881. }
  18882. }
  18883. var translated_token = _translate(token_without_symbols, opts);
  18884. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18885. }
  18886. return translated;
  18887. }
  18888. function hasContext(options) {
  18889. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18890. }
  18891. function needsPlural(options, lng) {
  18892. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18893. }
  18894. function needsIndefiniteArticle(options) {
  18895. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18896. }
  18897. function exists(key, options) {
  18898. options = options || {};
  18899. var notFound = _getDefaultValue(key, options)
  18900. , found = _find(key, options);
  18901. return found !== undefined || found === notFound;
  18902. }
  18903. function translate(key, options) {
  18904. options = options || {};
  18905. if (!initialized) {
  18906. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18907. return options.defaultValue || '';
  18908. };
  18909. replacementCounter = 0;
  18910. return _translate.apply(null, arguments);
  18911. }
  18912. function _getDefaultValue(key, options) {
  18913. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18914. }
  18915. function _injectSprintfProcessor() {
  18916. var values = [];
  18917. // mh: build array from second argument onwards
  18918. for (var i = 1; i < arguments.length; i++) {
  18919. values.push(arguments[i]);
  18920. }
  18921. return {
  18922. postProcess: 'sprintf',
  18923. sprintf: values
  18924. };
  18925. }
  18926. function _translate(potentialKeys, options) {
  18927. if (options && typeof options !== 'object') {
  18928. if (o.shortcutFunction === 'sprintf') {
  18929. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18930. options = _injectSprintfProcessor.apply(null, arguments);
  18931. } else if (o.shortcutFunction === 'defaultValue') {
  18932. options = {
  18933. defaultValue: options
  18934. }
  18935. }
  18936. } else {
  18937. options = options || {};
  18938. }
  18939. if (typeof o.defaultVariables === 'object') {
  18940. options = f.extend({}, o.defaultVariables, options);
  18941. }
  18942. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18943. if (typeof potentialKeys === 'string') {
  18944. potentialKeys = [potentialKeys];
  18945. }
  18946. var key = potentialKeys[0];
  18947. if (potentialKeys.length > 1) {
  18948. for (var i = 0; i < potentialKeys.length; i++) {
  18949. key = potentialKeys[i];
  18950. if (exists(key, options)) {
  18951. break;
  18952. }
  18953. }
  18954. }
  18955. var notFound = _getDefaultValue(key, options)
  18956. , found = _find(key, options)
  18957. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18958. , ns = options.ns || o.ns.defaultNs
  18959. , parts;
  18960. // split ns and key
  18961. if (key.indexOf(o.nsseparator) > -1) {
  18962. parts = key.split(o.nsseparator);
  18963. ns = parts[0];
  18964. key = parts[1];
  18965. }
  18966. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18967. if (options.lng) {
  18968. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18969. } else {
  18970. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18971. }
  18972. }
  18973. var postProcessor = options.postProcess || o.postProcess;
  18974. if (found !== undefined && postProcessor) {
  18975. if (postProcessors[postProcessor]) {
  18976. found = postProcessors[postProcessor](found, key, options);
  18977. }
  18978. }
  18979. // process notFound if function exists
  18980. var splitNotFound = notFound;
  18981. if (notFound.indexOf(o.nsseparator) > -1) {
  18982. parts = notFound.split(o.nsseparator);
  18983. splitNotFound = parts[1];
  18984. }
  18985. if (splitNotFound === key && o.parseMissingKey) {
  18986. notFound = o.parseMissingKey(notFound);
  18987. }
  18988. if (found === undefined) {
  18989. notFound = applyReplacement(notFound, options);
  18990. notFound = applyReuse(notFound, options);
  18991. if (postProcessor && postProcessors[postProcessor]) {
  18992. var val = _getDefaultValue(key, options);
  18993. found = postProcessors[postProcessor](val, key, options);
  18994. }
  18995. }
  18996. return (found !== undefined) ? found : notFound;
  18997. }
  18998. function _find(key, options) {
  18999. options = options || {};
  19000. var optionWithoutCount, translated
  19001. , notFound = _getDefaultValue(key, options)
  19002. , lngs = languages;
  19003. if (!resStore) { return notFound; } // no resStore to translate from
  19004. // CI mode
  19005. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19006. // passed in lng
  19007. if (options.lngs) lngs = options.lngs;
  19008. if (options.lng) {
  19009. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19010. if (!resStore[lngs[0]]) {
  19011. var oldAsync = o.getAsync;
  19012. o.getAsync = false;
  19013. i18n.sync.load(lngs, o, function(err, store) {
  19014. f.extend(resStore, store);
  19015. o.getAsync = oldAsync;
  19016. });
  19017. }
  19018. }
  19019. var ns = options.ns || o.ns.defaultNs;
  19020. if (key.indexOf(o.nsseparator) > -1) {
  19021. var parts = key.split(o.nsseparator);
  19022. ns = parts[0];
  19023. key = parts[1];
  19024. }
  19025. if (hasContext(options)) {
  19026. optionWithoutCount = f.extend({}, options);
  19027. delete optionWithoutCount.context;
  19028. optionWithoutCount.defaultValue = o.contextNotFound;
  19029. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19030. translated = translate(contextKey, optionWithoutCount);
  19031. if (translated != o.contextNotFound) {
  19032. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19033. } // else continue translation with original/nonContext key
  19034. }
  19035. if (needsPlural(options, lngs[0])) {
  19036. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19037. delete optionWithoutCount.count;
  19038. delete optionWithoutCount.lng;
  19039. optionWithoutCount.defaultValue = o.pluralNotFound;
  19040. var pluralKey;
  19041. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19042. pluralKey = ns + o.nsseparator + key;
  19043. } else {
  19044. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19045. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19046. if (pluralExtension >= 0) {
  19047. pluralKey = pluralKey + '_' + pluralExtension;
  19048. } else if (pluralExtension === 1) {
  19049. pluralKey = ns + o.nsseparator + key; // singular
  19050. }
  19051. }
  19052. translated = translate(pluralKey, optionWithoutCount);
  19053. if (translated != o.pluralNotFound) {
  19054. return applyReplacement(translated, {
  19055. count: options.count,
  19056. interpolationPrefix: options.interpolationPrefix,
  19057. interpolationSuffix: options.interpolationSuffix
  19058. }); // apply replacement for count only
  19059. } else if (lngs.length > 1) {
  19060. // remove failed lng
  19061. var clone = lngs.slice();
  19062. clone.shift();
  19063. options = f.extend(options, { lngs: clone });
  19064. delete options.lng;
  19065. // retry with fallbacks
  19066. translated = translate(ns + o.nsseparator + key, options);
  19067. if (translated != o.pluralNotFound) return translated;
  19068. } else {
  19069. return translated;
  19070. }
  19071. }
  19072. if (needsIndefiniteArticle(options)) {
  19073. var optionsWithoutIndef = f.extend({}, options);
  19074. delete optionsWithoutIndef.indefinite_article;
  19075. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19076. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19077. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19078. translated = translate(indefiniteKey, optionsWithoutIndef);
  19079. if (translated != o.indefiniteNotFound) {
  19080. return translated;
  19081. }
  19082. }
  19083. var found;
  19084. var keys = key.split(o.keyseparator);
  19085. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19086. if (found !== undefined) break;
  19087. var l = lngs[i];
  19088. var x = 0;
  19089. var value = resStore[l] && resStore[l][ns];
  19090. while (keys[x]) {
  19091. value = value && value[keys[x]];
  19092. x++;
  19093. }
  19094. if (value !== undefined) {
  19095. var valueType = Object.prototype.toString.apply(value);
  19096. if (typeof value === 'string') {
  19097. value = applyReplacement(value, options);
  19098. value = applyReuse(value, options);
  19099. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19100. value = value.join('\n');
  19101. value = applyReplacement(value, options);
  19102. value = applyReuse(value, options);
  19103. } else if (value === null && o.fallbackOnNull === true) {
  19104. value = undefined;
  19105. } else if (value !== null) {
  19106. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19107. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19108. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19109. } else {
  19110. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19111. 'returned an object instead of string.';
  19112. f.log(value);
  19113. }
  19114. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19115. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19116. f.each(value, function(m) {
  19117. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19118. });
  19119. value = copy;
  19120. }
  19121. }
  19122. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19123. value = undefined;
  19124. found = value;
  19125. }
  19126. }
  19127. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19128. // set flag for fallback lookup - avoid recursion
  19129. options.isFallbackLookup = true;
  19130. if (o.fallbackNS.length) {
  19131. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19132. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19133. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19134. /* compare value without namespace */
  19135. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19136. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19137. if (foundValue !== notFoundValue) break;
  19138. }
  19139. }
  19140. } else {
  19141. found = _find(key, options); // fallback to default NS
  19142. }
  19143. options.isFallbackLookup = false;
  19144. }
  19145. return found;
  19146. }
  19147. function detectLanguage() {
  19148. var detectedLng;
  19149. var whitelist = o.lngWhitelist || [];
  19150. var userLngChoices = [];
  19151. // get from qs
  19152. var qsParm = [];
  19153. if (typeof window !== 'undefined') {
  19154. (function() {
  19155. var query = window.location.search.substring(1);
  19156. var params = query.split('&');
  19157. for (var i=0; i<params.length; i++) {
  19158. var pos = params[i].indexOf('=');
  19159. if (pos > 0) {
  19160. var key = params[i].substring(0,pos);
  19161. if (key == o.detectLngQS) {
  19162. userLngChoices.push(params[i].substring(pos+1));
  19163. }
  19164. }
  19165. }
  19166. })();
  19167. }
  19168. // get from cookie
  19169. if (o.useCookie && typeof document !== 'undefined') {
  19170. var c = f.cookie.read(o.cookieName);
  19171. if (c) userLngChoices.push(c);
  19172. }
  19173. // get from localStorage
  19174. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19175. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19176. }
  19177. // get from navigator
  19178. if (typeof navigator !== 'undefined') {
  19179. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19180. for (var i=0;i<navigator.languages.length;i++) {
  19181. userLngChoices.push(navigator.languages[i]);
  19182. }
  19183. }
  19184. if (navigator.userLanguage) {
  19185. userLngChoices.push(navigator.userLanguage);
  19186. }
  19187. if (navigator.language) {
  19188. userLngChoices.push(navigator.language);
  19189. }
  19190. }
  19191. (function() {
  19192. for (var i=0;i<userLngChoices.length;i++) {
  19193. var lng = userLngChoices[i];
  19194. if (lng.indexOf('-') > -1) {
  19195. var parts = lng.split('-');
  19196. lng = o.lowerCaseLng ?
  19197. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19198. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19199. }
  19200. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19201. detectedLng = lng;
  19202. break;
  19203. }
  19204. }
  19205. })();
  19206. //fallback
  19207. if (!detectedLng){
  19208. detectedLng = o.fallbackLng[0];
  19209. }
  19210. return detectedLng;
  19211. }
  19212. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19213. /* [code, name, numbers, pluralsType] */
  19214. var _rules = [
  19215. ["ach", "Acholi", [1,2], 1],
  19216. ["af", "Afrikaans",[1,2], 2],
  19217. ["ak", "Akan", [1,2], 1],
  19218. ["am", "Amharic", [1,2], 1],
  19219. ["an", "Aragonese",[1,2], 2],
  19220. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19221. ["arn", "Mapudungun",[1,2], 1],
  19222. ["ast", "Asturian", [1,2], 2],
  19223. ["ay", "Aymará", [1], 3],
  19224. ["az", "Azerbaijani",[1,2],2],
  19225. ["be", "Belarusian",[1,2,5],4],
  19226. ["bg", "Bulgarian",[1,2], 2],
  19227. ["bn", "Bengali", [1,2], 2],
  19228. ["bo", "Tibetan", [1], 3],
  19229. ["br", "Breton", [1,2], 1],
  19230. ["bs", "Bosnian", [1,2,5],4],
  19231. ["ca", "Catalan", [1,2], 2],
  19232. ["cgg", "Chiga", [1], 3],
  19233. ["cs", "Czech", [1,2,5],6],
  19234. ["csb", "Kashubian",[1,2,5],7],
  19235. ["cy", "Welsh", [1,2,3,8],8],
  19236. ["da", "Danish", [1,2], 2],
  19237. ["de", "German", [1,2], 2],
  19238. ["dev", "Development Fallback", [1,2], 2],
  19239. ["dz", "Dzongkha", [1], 3],
  19240. ["el", "Greek", [1,2], 2],
  19241. ["en", "English", [1,2], 2],
  19242. ["eo", "Esperanto",[1,2], 2],
  19243. ["es", "Spanish", [1,2], 2],
  19244. ["es_ar","Argentinean Spanish", [1,2], 2],
  19245. ["et", "Estonian", [1,2], 2],
  19246. ["eu", "Basque", [1,2], 2],
  19247. ["fa", "Persian", [1], 3],
  19248. ["fi", "Finnish", [1,2], 2],
  19249. ["fil", "Filipino", [1,2], 1],
  19250. ["fo", "Faroese", [1,2], 2],
  19251. ["fr", "French", [1,2], 9],
  19252. ["fur", "Friulian", [1,2], 2],
  19253. ["fy", "Frisian", [1,2], 2],
  19254. ["ga", "Irish", [1,2,3,7,11],10],
  19255. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19256. ["gl", "Galician", [1,2], 2],
  19257. ["gu", "Gujarati", [1,2], 2],
  19258. ["gun", "Gun", [1,2], 1],
  19259. ["ha", "Hausa", [1,2], 2],
  19260. ["he", "Hebrew", [1,2], 2],
  19261. ["hi", "Hindi", [1,2], 2],
  19262. ["hr", "Croatian", [1,2,5],4],
  19263. ["hu", "Hungarian",[1,2], 2],
  19264. ["hy", "Armenian", [1,2], 2],
  19265. ["ia", "Interlingua",[1,2],2],
  19266. ["id", "Indonesian",[1], 3],
  19267. ["is", "Icelandic",[1,2], 12],
  19268. ["it", "Italian", [1,2], 2],
  19269. ["ja", "Japanese", [1], 3],
  19270. ["jbo", "Lojban", [1], 3],
  19271. ["jv", "Javanese", [0,1], 13],
  19272. ["ka", "Georgian", [1], 3],
  19273. ["kk", "Kazakh", [1], 3],
  19274. ["km", "Khmer", [1], 3],
  19275. ["kn", "Kannada", [1,2], 2],
  19276. ["ko", "Korean", [1], 3],
  19277. ["ku", "Kurdish", [1,2], 2],
  19278. ["kw", "Cornish", [1,2,3,4],14],
  19279. ["ky", "Kyrgyz", [1], 3],
  19280. ["lb", "Letzeburgesch",[1,2],2],
  19281. ["ln", "Lingala", [1,2], 1],
  19282. ["lo", "Lao", [1], 3],
  19283. ["lt", "Lithuanian",[1,2,10],15],
  19284. ["lv", "Latvian", [1,2,0],16],
  19285. ["mai", "Maithili", [1,2], 2],
  19286. ["mfe", "Mauritian Creole",[1,2],1],
  19287. ["mg", "Malagasy", [1,2], 1],
  19288. ["mi", "Maori", [1,2], 1],
  19289. ["mk", "Macedonian",[1,2],17],
  19290. ["ml", "Malayalam",[1,2], 2],
  19291. ["mn", "Mongolian",[1,2], 2],
  19292. ["mnk", "Mandinka", [0,1,2],18],
  19293. ["mr", "Marathi", [1,2], 2],
  19294. ["ms", "Malay", [1], 3],
  19295. ["mt", "Maltese", [1,2,11,20],19],
  19296. ["nah", "Nahuatl", [1,2], 2],
  19297. ["nap", "Neapolitan",[1,2], 2],
  19298. ["nb", "Norwegian Bokmal",[1,2],2],
  19299. ["ne", "Nepali", [1,2], 2],
  19300. ["nl", "Dutch", [1,2], 2],
  19301. ["nn", "Norwegian Nynorsk",[1,2],2],
  19302. ["no", "Norwegian",[1,2], 2],
  19303. ["nso", "Northern Sotho",[1,2],2],
  19304. ["oc", "Occitan", [1,2], 1],
  19305. ["or", "Oriya", [2,1], 2],
  19306. ["pa", "Punjabi", [1,2], 2],
  19307. ["pap", "Papiamento",[1,2], 2],
  19308. ["pl", "Polish", [1,2,5],7],
  19309. ["pms", "Piemontese",[1,2], 2],
  19310. ["ps", "Pashto", [1,2], 2],
  19311. ["pt", "Portuguese",[1,2], 2],
  19312. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19313. ["rm", "Romansh", [1,2], 2],
  19314. ["ro", "Romanian", [1,2,20],20],
  19315. ["ru", "Russian", [1,2,5],4],
  19316. ["sah", "Yakut", [1], 3],
  19317. ["sco", "Scots", [1,2], 2],
  19318. ["se", "Northern Sami",[1,2], 2],
  19319. ["si", "Sinhala", [1,2], 2],
  19320. ["sk", "Slovak", [1,2,5],6],
  19321. ["sl", "Slovenian",[5,1,2,3],21],
  19322. ["so", "Somali", [1,2], 2],
  19323. ["son", "Songhay", [1,2], 2],
  19324. ["sq", "Albanian", [1,2], 2],
  19325. ["sr", "Serbian", [1,2,5],4],
  19326. ["su", "Sundanese",[1], 3],
  19327. ["sv", "Swedish", [1,2], 2],
  19328. ["sw", "Swahili", [1,2], 2],
  19329. ["ta", "Tamil", [1,2], 2],
  19330. ["te", "Telugu", [1,2], 2],
  19331. ["tg", "Tajik", [1,2], 1],
  19332. ["th", "Thai", [1], 3],
  19333. ["ti", "Tigrinya", [1,2], 1],
  19334. ["tk", "Turkmen", [1,2], 2],
  19335. ["tr", "Turkish", [1,2], 1],
  19336. ["tt", "Tatar", [1], 3],
  19337. ["ug", "Uyghur", [1], 3],
  19338. ["uk", "Ukrainian",[1,2,5],4],
  19339. ["ur", "Urdu", [1,2], 2],
  19340. ["uz", "Uzbek", [1,2], 1],
  19341. ["vi", "Vietnamese",[1], 3],
  19342. ["wa", "Walloon", [1,2], 1],
  19343. ["wo", "Wolof", [1], 3],
  19344. ["yo", "Yoruba", [1,2], 2],
  19345. ["zh", "Chinese", [1], 3]
  19346. ];
  19347. var _rulesPluralsTypes = {
  19348. 1: function(n) {return Number(n > 1);},
  19349. 2: function(n) {return Number(n != 1);},
  19350. 3: function(n) {return 0;},
  19351. 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);},
  19352. 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);},
  19353. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19354. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19355. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19356. 9: function(n) {return Number(n >= 2);},
  19357. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19358. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19359. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19360. 13: function(n) {return Number(n !== 0);},
  19361. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19362. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19363. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19364. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19365. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19366. 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);},
  19367. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19368. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19369. };
  19370. var pluralExtensions = {
  19371. rules: (function () {
  19372. var l, rules = {};
  19373. for (l=_rules.length; l-- ;) {
  19374. rules[_rules[l][0]] = {
  19375. name: _rules[l][1],
  19376. numbers: _rules[l][2],
  19377. plurals: _rulesPluralsTypes[_rules[l][3]]
  19378. }
  19379. }
  19380. return rules;
  19381. }()),
  19382. // you can add your own pluralExtensions
  19383. addRule: function(lng, obj) {
  19384. pluralExtensions.rules[lng] = obj;
  19385. },
  19386. setCurrentLng: function(lng) {
  19387. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19388. var parts = lng.split('-');
  19389. pluralExtensions.currentRule = {
  19390. lng: lng,
  19391. rule: pluralExtensions.rules[parts[0]]
  19392. };
  19393. }
  19394. },
  19395. needsPlural: function(lng, count) {
  19396. var parts = lng.split('-');
  19397. var ext;
  19398. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19399. ext = pluralExtensions.currentRule.rule;
  19400. } else {
  19401. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19402. }
  19403. if (ext && ext.numbers.length <= 1) {
  19404. return false;
  19405. } else {
  19406. return this.get(lng, count) !== 1;
  19407. }
  19408. },
  19409. get: function(lng, count) {
  19410. var parts = lng.split('-');
  19411. function getResult(l, c) {
  19412. var ext;
  19413. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19414. ext = pluralExtensions.currentRule.rule;
  19415. } else {
  19416. ext = pluralExtensions.rules[l];
  19417. }
  19418. if (ext) {
  19419. var i;
  19420. if (ext.noAbs) {
  19421. i = ext.plurals(c);
  19422. } else {
  19423. i = ext.plurals(Math.abs(c));
  19424. }
  19425. var number = ext.numbers[i];
  19426. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19427. if (number === 2) {
  19428. number = -1; // regular plural
  19429. } else if (number === 1) {
  19430. number = 1; // singular
  19431. }
  19432. }//console.log(count + '-' + number);
  19433. return number;
  19434. } else {
  19435. return c === 1 ? '1' : '-1';
  19436. }
  19437. }
  19438. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19439. }
  19440. };
  19441. var postProcessors = {};
  19442. var addPostProcessor = function(name, fc) {
  19443. postProcessors[name] = fc;
  19444. };
  19445. // sprintf support
  19446. var sprintf = (function() {
  19447. function get_type(variable) {
  19448. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19449. }
  19450. function str_repeat(input, multiplier) {
  19451. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19452. return output.join('');
  19453. }
  19454. var str_format = function() {
  19455. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19456. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19457. }
  19458. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19459. };
  19460. str_format.format = function(parse_tree, argv) {
  19461. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19462. for (i = 0; i < tree_length; i++) {
  19463. node_type = get_type(parse_tree[i]);
  19464. if (node_type === 'string') {
  19465. output.push(parse_tree[i]);
  19466. }
  19467. else if (node_type === 'array') {
  19468. match = parse_tree[i]; // convenience purposes only
  19469. if (match[2]) { // keyword argument
  19470. arg = argv[cursor];
  19471. for (k = 0; k < match[2].length; k++) {
  19472. if (!arg.hasOwnProperty(match[2][k])) {
  19473. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19474. }
  19475. arg = arg[match[2][k]];
  19476. }
  19477. }
  19478. else if (match[1]) { // positional argument (explicit)
  19479. arg = argv[match[1]];
  19480. }
  19481. else { // positional argument (implicit)
  19482. arg = argv[cursor++];
  19483. }
  19484. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19485. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19486. }
  19487. switch (match[8]) {
  19488. case 'b': arg = arg.toString(2); break;
  19489. case 'c': arg = String.fromCharCode(arg); break;
  19490. case 'd': arg = parseInt(arg, 10); break;
  19491. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19492. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19493. case 'o': arg = arg.toString(8); break;
  19494. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19495. case 'u': arg = Math.abs(arg); break;
  19496. case 'x': arg = arg.toString(16); break;
  19497. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19498. }
  19499. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19500. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19501. pad_length = match[6] - String(arg).length;
  19502. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19503. output.push(match[5] ? arg + pad : pad + arg);
  19504. }
  19505. }
  19506. return output.join('');
  19507. };
  19508. str_format.cache = {};
  19509. str_format.parse = function(fmt) {
  19510. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19511. while (_fmt) {
  19512. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19513. parse_tree.push(match[0]);
  19514. }
  19515. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19516. parse_tree.push('%');
  19517. }
  19518. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19519. if (match[2]) {
  19520. arg_names |= 1;
  19521. var field_list = [], replacement_field = match[2], field_match = [];
  19522. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19523. field_list.push(field_match[1]);
  19524. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19525. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19526. field_list.push(field_match[1]);
  19527. }
  19528. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19529. field_list.push(field_match[1]);
  19530. }
  19531. else {
  19532. throw('[sprintf] huh?');
  19533. }
  19534. }
  19535. }
  19536. else {
  19537. throw('[sprintf] huh?');
  19538. }
  19539. match[2] = field_list;
  19540. }
  19541. else {
  19542. arg_names |= 2;
  19543. }
  19544. if (arg_names === 3) {
  19545. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19546. }
  19547. parse_tree.push(match);
  19548. }
  19549. else {
  19550. throw('[sprintf] huh?');
  19551. }
  19552. _fmt = _fmt.substring(match[0].length);
  19553. }
  19554. return parse_tree;
  19555. };
  19556. return str_format;
  19557. })();
  19558. var vsprintf = function(fmt, argv) {
  19559. argv.unshift(fmt);
  19560. return sprintf.apply(null, argv);
  19561. };
  19562. addPostProcessor("sprintf", function(val, key, opts) {
  19563. if (!opts.sprintf) return val;
  19564. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19565. return vsprintf(val, opts.sprintf);
  19566. } else if (typeof opts.sprintf === 'object') {
  19567. return sprintf(val, opts.sprintf);
  19568. }
  19569. return val;
  19570. });
  19571. // public api interface
  19572. i18n.init = init;
  19573. i18n.setLng = setLng;
  19574. i18n.preload = preload;
  19575. i18n.addResourceBundle = addResourceBundle;
  19576. i18n.hasResourceBundle = hasResourceBundle;
  19577. i18n.addResource = addResource;
  19578. i18n.addResources = addResources;
  19579. i18n.removeResourceBundle = removeResourceBundle;
  19580. i18n.loadNamespace = loadNamespace;
  19581. i18n.loadNamespaces = loadNamespaces;
  19582. i18n.setDefaultNamespace = setDefaultNamespace;
  19583. i18n.t = translate;
  19584. i18n.translate = translate;
  19585. i18n.exists = exists;
  19586. i18n.detectLanguage = f.detectLanguage;
  19587. i18n.pluralExtensions = pluralExtensions;
  19588. i18n.sync = sync;
  19589. i18n.functions = f;
  19590. i18n.lng = lng;
  19591. i18n.addPostProcessor = addPostProcessor;
  19592. i18n.options = o;
  19593. })();
  19594. },{"jquery":"jquery"}],71:[function(require,module,exports){
  19595. // Top level file is just a mixin of submodules & constants
  19596. 'use strict';
  19597. var assign = require('./lib/utils/common').assign;
  19598. var deflate = require('./lib/deflate');
  19599. var inflate = require('./lib/inflate');
  19600. var constants = require('./lib/zlib/constants');
  19601. var pako = {};
  19602. assign(pako, deflate, inflate, constants);
  19603. module.exports = pako;
  19604. },{"./lib/deflate":72,"./lib/inflate":73,"./lib/utils/common":74,"./lib/zlib/constants":77}],72:[function(require,module,exports){
  19605. 'use strict';
  19606. var zlib_deflate = require('./zlib/deflate.js');
  19607. var utils = require('./utils/common');
  19608. var strings = require('./utils/strings');
  19609. var msg = require('./zlib/messages');
  19610. var zstream = require('./zlib/zstream');
  19611. var toString = Object.prototype.toString;
  19612. /* Public constants ==========================================================*/
  19613. /* ===========================================================================*/
  19614. var Z_NO_FLUSH = 0;
  19615. var Z_FINISH = 4;
  19616. var Z_OK = 0;
  19617. var Z_STREAM_END = 1;
  19618. var Z_SYNC_FLUSH = 2;
  19619. var Z_DEFAULT_COMPRESSION = -1;
  19620. var Z_DEFAULT_STRATEGY = 0;
  19621. var Z_DEFLATED = 8;
  19622. /* ===========================================================================*/
  19623. /**
  19624. * class Deflate
  19625. *
  19626. * Generic JS-style wrapper for zlib calls. If you don't need
  19627. * streaming behaviour - use more simple functions: [[deflate]],
  19628. * [[deflateRaw]] and [[gzip]].
  19629. **/
  19630. /* internal
  19631. * Deflate.chunks -> Array
  19632. *
  19633. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19634. **/
  19635. /**
  19636. * Deflate.result -> Uint8Array|Array
  19637. *
  19638. * Compressed result, generated by default [[Deflate#onData]]
  19639. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19640. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19641. * push a chunk with explicit flush (call [[Deflate#push]] with
  19642. * `Z_SYNC_FLUSH` param).
  19643. **/
  19644. /**
  19645. * Deflate.err -> Number
  19646. *
  19647. * Error code after deflate finished. 0 (Z_OK) on success.
  19648. * You will not need it in real life, because deflate errors
  19649. * are possible only on wrong options or bad `onData` / `onEnd`
  19650. * custom handlers.
  19651. **/
  19652. /**
  19653. * Deflate.msg -> String
  19654. *
  19655. * Error message, if [[Deflate.err]] != 0
  19656. **/
  19657. /**
  19658. * new Deflate(options)
  19659. * - options (Object): zlib deflate options.
  19660. *
  19661. * Creates new deflator instance with specified params. Throws exception
  19662. * on bad params. Supported options:
  19663. *
  19664. * - `level`
  19665. * - `windowBits`
  19666. * - `memLevel`
  19667. * - `strategy`
  19668. *
  19669. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19670. * for more information on these.
  19671. *
  19672. * Additional options, for internal needs:
  19673. *
  19674. * - `chunkSize` - size of generated data chunks (16K by default)
  19675. * - `raw` (Boolean) - do raw deflate
  19676. * - `gzip` (Boolean) - create gzip wrapper
  19677. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19678. * (each char code [0..255])
  19679. * - `header` (Object) - custom header for gzip
  19680. * - `text` (Boolean) - true if compressed data believed to be text
  19681. * - `time` (Number) - modification time, unix timestamp
  19682. * - `os` (Number) - operation system code
  19683. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19684. * - `name` (String) - file name (binary string)
  19685. * - `comment` (String) - comment (binary string)
  19686. * - `hcrc` (Boolean) - true if header crc should be added
  19687. *
  19688. * ##### Example:
  19689. *
  19690. * ```javascript
  19691. * var pako = require('pako')
  19692. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19693. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19694. *
  19695. * var deflate = new pako.Deflate({ level: 3});
  19696. *
  19697. * deflate.push(chunk1, false);
  19698. * deflate.push(chunk2, true); // true -> last chunk
  19699. *
  19700. * if (deflate.err) { throw new Error(deflate.err); }
  19701. *
  19702. * console.log(deflate.result);
  19703. * ```
  19704. **/
  19705. var Deflate = function(options) {
  19706. this.options = utils.assign({
  19707. level: Z_DEFAULT_COMPRESSION,
  19708. method: Z_DEFLATED,
  19709. chunkSize: 16384,
  19710. windowBits: 15,
  19711. memLevel: 8,
  19712. strategy: Z_DEFAULT_STRATEGY,
  19713. to: ''
  19714. }, options || {});
  19715. var opt = this.options;
  19716. if (opt.raw && (opt.windowBits > 0)) {
  19717. opt.windowBits = -opt.windowBits;
  19718. }
  19719. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19720. opt.windowBits += 16;
  19721. }
  19722. this.err = 0; // error code, if happens (0 = Z_OK)
  19723. this.msg = ''; // error message
  19724. this.ended = false; // used to avoid multiple onEnd() calls
  19725. this.chunks = []; // chunks of compressed data
  19726. this.strm = new zstream();
  19727. this.strm.avail_out = 0;
  19728. var status = zlib_deflate.deflateInit2(
  19729. this.strm,
  19730. opt.level,
  19731. opt.method,
  19732. opt.windowBits,
  19733. opt.memLevel,
  19734. opt.strategy
  19735. );
  19736. if (status !== Z_OK) {
  19737. throw new Error(msg[status]);
  19738. }
  19739. if (opt.header) {
  19740. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19741. }
  19742. };
  19743. /**
  19744. * Deflate#push(data[, mode]) -> Boolean
  19745. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19746. * converted to utf8 byte sequence.
  19747. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19748. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19749. *
  19750. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19751. * new compressed chunks. Returns `true` on success. The last data block must have
  19752. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19753. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19754. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19755. *
  19756. * On fail call [[Deflate#onEnd]] with error code and return false.
  19757. *
  19758. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19759. * array format is detected automatically). Also, don't skip last param and always
  19760. * use the same type in your code (boolean or number). That will improve JS speed.
  19761. *
  19762. * For regular `Array`-s make sure all elements are [0..255].
  19763. *
  19764. * ##### Example
  19765. *
  19766. * ```javascript
  19767. * push(chunk, false); // push one of data chunks
  19768. * ...
  19769. * push(chunk, true); // push last chunk
  19770. * ```
  19771. **/
  19772. Deflate.prototype.push = function(data, mode) {
  19773. var strm = this.strm;
  19774. var chunkSize = this.options.chunkSize;
  19775. var status, _mode;
  19776. if (this.ended) { return false; }
  19777. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19778. // Convert data if needed
  19779. if (typeof data === 'string') {
  19780. // If we need to compress text, change encoding to utf8.
  19781. strm.input = strings.string2buf(data);
  19782. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19783. strm.input = new Uint8Array(data);
  19784. } else {
  19785. strm.input = data;
  19786. }
  19787. strm.next_in = 0;
  19788. strm.avail_in = strm.input.length;
  19789. do {
  19790. if (strm.avail_out === 0) {
  19791. strm.output = new utils.Buf8(chunkSize);
  19792. strm.next_out = 0;
  19793. strm.avail_out = chunkSize;
  19794. }
  19795. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19796. if (status !== Z_STREAM_END && status !== Z_OK) {
  19797. this.onEnd(status);
  19798. this.ended = true;
  19799. return false;
  19800. }
  19801. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19802. if (this.options.to === 'string') {
  19803. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19804. } else {
  19805. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19806. }
  19807. }
  19808. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19809. // Finalize on the last chunk.
  19810. if (_mode === Z_FINISH) {
  19811. status = zlib_deflate.deflateEnd(this.strm);
  19812. this.onEnd(status);
  19813. this.ended = true;
  19814. return status === Z_OK;
  19815. }
  19816. // callback interim results if Z_SYNC_FLUSH.
  19817. if (_mode === Z_SYNC_FLUSH) {
  19818. this.onEnd(Z_OK);
  19819. strm.avail_out = 0;
  19820. return true;
  19821. }
  19822. return true;
  19823. };
  19824. /**
  19825. * Deflate#onData(chunk) -> Void
  19826. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19827. * on js engine support. When string output requested, each chunk
  19828. * will be string.
  19829. *
  19830. * By default, stores data blocks in `chunks[]` property and glue
  19831. * those in `onEnd`. Override this handler, if you need another behaviour.
  19832. **/
  19833. Deflate.prototype.onData = function(chunk) {
  19834. this.chunks.push(chunk);
  19835. };
  19836. /**
  19837. * Deflate#onEnd(status) -> Void
  19838. * - status (Number): deflate status. 0 (Z_OK) on success,
  19839. * other if not.
  19840. *
  19841. * Called once after you tell deflate that the input stream is
  19842. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19843. * or if an error happened. By default - join collected chunks,
  19844. * free memory and fill `results` / `err` properties.
  19845. **/
  19846. Deflate.prototype.onEnd = function(status) {
  19847. // On success - join
  19848. if (status === Z_OK) {
  19849. if (this.options.to === 'string') {
  19850. this.result = this.chunks.join('');
  19851. } else {
  19852. this.result = utils.flattenChunks(this.chunks);
  19853. }
  19854. }
  19855. this.chunks = [];
  19856. this.err = status;
  19857. this.msg = this.strm.msg;
  19858. };
  19859. /**
  19860. * deflate(data[, options]) -> Uint8Array|Array|String
  19861. * - data (Uint8Array|Array|String): input data to compress.
  19862. * - options (Object): zlib deflate options.
  19863. *
  19864. * Compress `data` with deflate alrorythm and `options`.
  19865. *
  19866. * Supported options are:
  19867. *
  19868. * - level
  19869. * - windowBits
  19870. * - memLevel
  19871. * - strategy
  19872. *
  19873. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19874. * for more information on these.
  19875. *
  19876. * Sugar (options):
  19877. *
  19878. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19879. * negative windowBits implicitly.
  19880. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19881. * (each char code [0..255])
  19882. *
  19883. * ##### Example:
  19884. *
  19885. * ```javascript
  19886. * var pako = require('pako')
  19887. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19888. *
  19889. * console.log(pako.deflate(data));
  19890. * ```
  19891. **/
  19892. function deflate(input, options) {
  19893. var deflator = new Deflate(options);
  19894. deflator.push(input, true);
  19895. // That will never happens, if you don't cheat with options :)
  19896. if (deflator.err) { throw deflator.msg; }
  19897. return deflator.result;
  19898. }
  19899. /**
  19900. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19901. * - data (Uint8Array|Array|String): input data to compress.
  19902. * - options (Object): zlib deflate options.
  19903. *
  19904. * The same as [[deflate]], but creates raw data, without wrapper
  19905. * (header and adler32 crc).
  19906. **/
  19907. function deflateRaw(input, options) {
  19908. options = options || {};
  19909. options.raw = true;
  19910. return deflate(input, options);
  19911. }
  19912. /**
  19913. * gzip(data[, options]) -> Uint8Array|Array|String
  19914. * - data (Uint8Array|Array|String): input data to compress.
  19915. * - options (Object): zlib deflate options.
  19916. *
  19917. * The same as [[deflate]], but create gzip wrapper instead of
  19918. * deflate one.
  19919. **/
  19920. function gzip(input, options) {
  19921. options = options || {};
  19922. options.gzip = true;
  19923. return deflate(input, options);
  19924. }
  19925. exports.Deflate = Deflate;
  19926. exports.deflate = deflate;
  19927. exports.deflateRaw = deflateRaw;
  19928. exports.gzip = gzip;
  19929. },{"./utils/common":74,"./utils/strings":75,"./zlib/deflate.js":79,"./zlib/messages":84,"./zlib/zstream":86}],73:[function(require,module,exports){
  19930. 'use strict';
  19931. var zlib_inflate = require('./zlib/inflate.js');
  19932. var utils = require('./utils/common');
  19933. var strings = require('./utils/strings');
  19934. var c = require('./zlib/constants');
  19935. var msg = require('./zlib/messages');
  19936. var zstream = require('./zlib/zstream');
  19937. var gzheader = require('./zlib/gzheader');
  19938. var toString = Object.prototype.toString;
  19939. /**
  19940. * class Inflate
  19941. *
  19942. * Generic JS-style wrapper for zlib calls. If you don't need
  19943. * streaming behaviour - use more simple functions: [[inflate]]
  19944. * and [[inflateRaw]].
  19945. **/
  19946. /* internal
  19947. * inflate.chunks -> Array
  19948. *
  19949. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19950. **/
  19951. /**
  19952. * Inflate.result -> Uint8Array|Array|String
  19953. *
  19954. * Uncompressed result, generated by default [[Inflate#onData]]
  19955. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19956. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19957. * push a chunk with explicit flush (call [[Inflate#push]] with
  19958. * `Z_SYNC_FLUSH` param).
  19959. **/
  19960. /**
  19961. * Inflate.err -> Number
  19962. *
  19963. * Error code after inflate finished. 0 (Z_OK) on success.
  19964. * Should be checked if broken data possible.
  19965. **/
  19966. /**
  19967. * Inflate.msg -> String
  19968. *
  19969. * Error message, if [[Inflate.err]] != 0
  19970. **/
  19971. /**
  19972. * new Inflate(options)
  19973. * - options (Object): zlib inflate options.
  19974. *
  19975. * Creates new inflator instance with specified params. Throws exception
  19976. * on bad params. Supported options:
  19977. *
  19978. * - `windowBits`
  19979. *
  19980. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19981. * for more information on these.
  19982. *
  19983. * Additional options, for internal needs:
  19984. *
  19985. * - `chunkSize` - size of generated data chunks (16K by default)
  19986. * - `raw` (Boolean) - do raw inflate
  19987. * - `to` (String) - if equal to 'string', then result will be converted
  19988. * from utf8 to utf16 (javascript) string. When string output requested,
  19989. * chunk length can differ from `chunkSize`, depending on content.
  19990. *
  19991. * By default, when no options set, autodetect deflate/gzip data format via
  19992. * wrapper header.
  19993. *
  19994. * ##### Example:
  19995. *
  19996. * ```javascript
  19997. * var pako = require('pako')
  19998. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19999. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20000. *
  20001. * var inflate = new pako.Inflate({ level: 3});
  20002. *
  20003. * inflate.push(chunk1, false);
  20004. * inflate.push(chunk2, true); // true -> last chunk
  20005. *
  20006. * if (inflate.err) { throw new Error(inflate.err); }
  20007. *
  20008. * console.log(inflate.result);
  20009. * ```
  20010. **/
  20011. var Inflate = function(options) {
  20012. this.options = utils.assign({
  20013. chunkSize: 16384,
  20014. windowBits: 0,
  20015. to: ''
  20016. }, options || {});
  20017. var opt = this.options;
  20018. // Force window size for `raw` data, if not set directly,
  20019. // because we have no header for autodetect.
  20020. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20021. opt.windowBits = -opt.windowBits;
  20022. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20023. }
  20024. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20025. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20026. !(options && options.windowBits)) {
  20027. opt.windowBits += 32;
  20028. }
  20029. // Gzip header has no info about windows size, we can do autodetect only
  20030. // for deflate. So, if window size not set, force it to max when gzip possible
  20031. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20032. // bit 3 (16) -> gzipped data
  20033. // bit 4 (32) -> autodetect gzip/deflate
  20034. if ((opt.windowBits & 15) === 0) {
  20035. opt.windowBits |= 15;
  20036. }
  20037. }
  20038. this.err = 0; // error code, if happens (0 = Z_OK)
  20039. this.msg = ''; // error message
  20040. this.ended = false; // used to avoid multiple onEnd() calls
  20041. this.chunks = []; // chunks of compressed data
  20042. this.strm = new zstream();
  20043. this.strm.avail_out = 0;
  20044. var status = zlib_inflate.inflateInit2(
  20045. this.strm,
  20046. opt.windowBits
  20047. );
  20048. if (status !== c.Z_OK) {
  20049. throw new Error(msg[status]);
  20050. }
  20051. this.header = new gzheader();
  20052. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20053. };
  20054. /**
  20055. * Inflate#push(data[, mode]) -> Boolean
  20056. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20057. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20058. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20059. *
  20060. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20061. * new output chunks. Returns `true` on success. The last data block must have
  20062. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20063. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20064. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20065. *
  20066. * On fail call [[Inflate#onEnd]] with error code and return false.
  20067. *
  20068. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20069. * format is detected automatically). Also, don't skip last param and always
  20070. * use the same type in your code (boolean or number). That will improve JS speed.
  20071. *
  20072. * For regular `Array`-s make sure all elements are [0..255].
  20073. *
  20074. * ##### Example
  20075. *
  20076. * ```javascript
  20077. * push(chunk, false); // push one of data chunks
  20078. * ...
  20079. * push(chunk, true); // push last chunk
  20080. * ```
  20081. **/
  20082. Inflate.prototype.push = function(data, mode) {
  20083. var strm = this.strm;
  20084. var chunkSize = this.options.chunkSize;
  20085. var status, _mode;
  20086. var next_out_utf8, tail, utf8str;
  20087. if (this.ended) { return false; }
  20088. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20089. // Convert data if needed
  20090. if (typeof data === 'string') {
  20091. // Only binary strings can be decompressed on practice
  20092. strm.input = strings.binstring2buf(data);
  20093. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20094. strm.input = new Uint8Array(data);
  20095. } else {
  20096. strm.input = data;
  20097. }
  20098. strm.next_in = 0;
  20099. strm.avail_in = strm.input.length;
  20100. do {
  20101. if (strm.avail_out === 0) {
  20102. strm.output = new utils.Buf8(chunkSize);
  20103. strm.next_out = 0;
  20104. strm.avail_out = chunkSize;
  20105. }
  20106. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20107. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20108. this.onEnd(status);
  20109. this.ended = true;
  20110. return false;
  20111. }
  20112. if (strm.next_out) {
  20113. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20114. if (this.options.to === 'string') {
  20115. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20116. tail = strm.next_out - next_out_utf8;
  20117. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20118. // move tail
  20119. strm.next_out = tail;
  20120. strm.avail_out = chunkSize - tail;
  20121. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20122. this.onData(utf8str);
  20123. } else {
  20124. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20125. }
  20126. }
  20127. }
  20128. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20129. if (status === c.Z_STREAM_END) {
  20130. _mode = c.Z_FINISH;
  20131. }
  20132. // Finalize on the last chunk.
  20133. if (_mode === c.Z_FINISH) {
  20134. status = zlib_inflate.inflateEnd(this.strm);
  20135. this.onEnd(status);
  20136. this.ended = true;
  20137. return status === c.Z_OK;
  20138. }
  20139. // callback interim results if Z_SYNC_FLUSH.
  20140. if (_mode === c.Z_SYNC_FLUSH) {
  20141. this.onEnd(c.Z_OK);
  20142. strm.avail_out = 0;
  20143. return true;
  20144. }
  20145. return true;
  20146. };
  20147. /**
  20148. * Inflate#onData(chunk) -> Void
  20149. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20150. * on js engine support. When string output requested, each chunk
  20151. * will be string.
  20152. *
  20153. * By default, stores data blocks in `chunks[]` property and glue
  20154. * those in `onEnd`. Override this handler, if you need another behaviour.
  20155. **/
  20156. Inflate.prototype.onData = function(chunk) {
  20157. this.chunks.push(chunk);
  20158. };
  20159. /**
  20160. * Inflate#onEnd(status) -> Void
  20161. * - status (Number): inflate status. 0 (Z_OK) on success,
  20162. * other if not.
  20163. *
  20164. * Called either after you tell inflate that the input stream is
  20165. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20166. * or if an error happened. By default - join collected chunks,
  20167. * free memory and fill `results` / `err` properties.
  20168. **/
  20169. Inflate.prototype.onEnd = function(status) {
  20170. // On success - join
  20171. if (status === c.Z_OK) {
  20172. if (this.options.to === 'string') {
  20173. // Glue & convert here, until we teach pako to send
  20174. // utf8 alligned strings to onData
  20175. this.result = this.chunks.join('');
  20176. } else {
  20177. this.result = utils.flattenChunks(this.chunks);
  20178. }
  20179. }
  20180. this.chunks = [];
  20181. this.err = status;
  20182. this.msg = this.strm.msg;
  20183. };
  20184. /**
  20185. * inflate(data[, options]) -> Uint8Array|Array|String
  20186. * - data (Uint8Array|Array|String): input data to decompress.
  20187. * - options (Object): zlib inflate options.
  20188. *
  20189. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20190. * format via wrapper header by default. That's why we don't provide
  20191. * separate `ungzip` method.
  20192. *
  20193. * Supported options are:
  20194. *
  20195. * - windowBits
  20196. *
  20197. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20198. * for more information.
  20199. *
  20200. * Sugar (options):
  20201. *
  20202. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20203. * negative windowBits implicitly.
  20204. * - `to` (String) - if equal to 'string', then result will be converted
  20205. * from utf8 to utf16 (javascript) string. When string output requested,
  20206. * chunk length can differ from `chunkSize`, depending on content.
  20207. *
  20208. *
  20209. * ##### Example:
  20210. *
  20211. * ```javascript
  20212. * var pako = require('pako')
  20213. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20214. * , output;
  20215. *
  20216. * try {
  20217. * output = pako.inflate(input);
  20218. * } catch (err)
  20219. * console.log(err);
  20220. * }
  20221. * ```
  20222. **/
  20223. function inflate(input, options) {
  20224. var inflator = new Inflate(options);
  20225. inflator.push(input, true);
  20226. // That will never happens, if you don't cheat with options :)
  20227. if (inflator.err) { throw inflator.msg; }
  20228. return inflator.result;
  20229. }
  20230. /**
  20231. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20232. * - data (Uint8Array|Array|String): input data to decompress.
  20233. * - options (Object): zlib inflate options.
  20234. *
  20235. * The same as [[inflate]], but creates raw data, without wrapper
  20236. * (header and adler32 crc).
  20237. **/
  20238. function inflateRaw(input, options) {
  20239. options = options || {};
  20240. options.raw = true;
  20241. return inflate(input, options);
  20242. }
  20243. /**
  20244. * ungzip(data[, options]) -> Uint8Array|Array|String
  20245. * - data (Uint8Array|Array|String): input data to decompress.
  20246. * - options (Object): zlib inflate options.
  20247. *
  20248. * Just shortcut to [[inflate]], because it autodetects format
  20249. * by header.content. Done for convenience.
  20250. **/
  20251. exports.Inflate = Inflate;
  20252. exports.inflate = inflate;
  20253. exports.inflateRaw = inflateRaw;
  20254. exports.ungzip = inflate;
  20255. },{"./utils/common":74,"./utils/strings":75,"./zlib/constants":77,"./zlib/gzheader":80,"./zlib/inflate.js":82,"./zlib/messages":84,"./zlib/zstream":86}],74:[function(require,module,exports){
  20256. 'use strict';
  20257. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20258. (typeof Uint16Array !== 'undefined') &&
  20259. (typeof Int32Array !== 'undefined');
  20260. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20261. var sources = Array.prototype.slice.call(arguments, 1);
  20262. while (sources.length) {
  20263. var source = sources.shift();
  20264. if (!source) { continue; }
  20265. if (typeof source !== 'object') {
  20266. throw new TypeError(source + 'must be non-object');
  20267. }
  20268. for (var p in source) {
  20269. if (source.hasOwnProperty(p)) {
  20270. obj[p] = source[p];
  20271. }
  20272. }
  20273. }
  20274. return obj;
  20275. };
  20276. // reduce buffer size, avoiding mem copy
  20277. exports.shrinkBuf = function (buf, size) {
  20278. if (buf.length === size) { return buf; }
  20279. if (buf.subarray) { return buf.subarray(0, size); }
  20280. buf.length = size;
  20281. return buf;
  20282. };
  20283. var fnTyped = {
  20284. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20285. if (src.subarray && dest.subarray) {
  20286. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20287. return;
  20288. }
  20289. // Fallback to ordinary array
  20290. for (var i=0; i<len; i++) {
  20291. dest[dest_offs + i] = src[src_offs + i];
  20292. }
  20293. },
  20294. // Join array of chunks to single array.
  20295. flattenChunks: function(chunks) {
  20296. var i, l, len, pos, chunk, result;
  20297. // calculate data length
  20298. len = 0;
  20299. for (i=0, l=chunks.length; i<l; i++) {
  20300. len += chunks[i].length;
  20301. }
  20302. // join chunks
  20303. result = new Uint8Array(len);
  20304. pos = 0;
  20305. for (i=0, l=chunks.length; i<l; i++) {
  20306. chunk = chunks[i];
  20307. result.set(chunk, pos);
  20308. pos += chunk.length;
  20309. }
  20310. return result;
  20311. }
  20312. };
  20313. var fnUntyped = {
  20314. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20315. for (var i=0; i<len; i++) {
  20316. dest[dest_offs + i] = src[src_offs + i];
  20317. }
  20318. },
  20319. // Join array of chunks to single array.
  20320. flattenChunks: function(chunks) {
  20321. return [].concat.apply([], chunks);
  20322. }
  20323. };
  20324. // Enable/Disable typed arrays use, for testing
  20325. //
  20326. exports.setTyped = function (on) {
  20327. if (on) {
  20328. exports.Buf8 = Uint8Array;
  20329. exports.Buf16 = Uint16Array;
  20330. exports.Buf32 = Int32Array;
  20331. exports.assign(exports, fnTyped);
  20332. } else {
  20333. exports.Buf8 = Array;
  20334. exports.Buf16 = Array;
  20335. exports.Buf32 = Array;
  20336. exports.assign(exports, fnUntyped);
  20337. }
  20338. };
  20339. exports.setTyped(TYPED_OK);
  20340. },{}],75:[function(require,module,exports){
  20341. // String encode/decode helpers
  20342. 'use strict';
  20343. var utils = require('./common');
  20344. // Quick check if we can use fast array to bin string conversion
  20345. //
  20346. // - apply(Array) can fail on Android 2.2
  20347. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20348. //
  20349. var STR_APPLY_OK = true;
  20350. var STR_APPLY_UIA_OK = true;
  20351. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20352. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20353. // Table with utf8 lengths (calculated by first byte of sequence)
  20354. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20355. // because max possible codepoint is 0x10ffff
  20356. var _utf8len = new utils.Buf8(256);
  20357. for (var q=0; q<256; q++) {
  20358. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20359. }
  20360. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20361. // convert string to array (typed, when possible)
  20362. exports.string2buf = function (str) {
  20363. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20364. // count binary size
  20365. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20366. c = str.charCodeAt(m_pos);
  20367. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20368. c2 = str.charCodeAt(m_pos+1);
  20369. if ((c2 & 0xfc00) === 0xdc00) {
  20370. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20371. m_pos++;
  20372. }
  20373. }
  20374. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20375. }
  20376. // allocate buffer
  20377. buf = new utils.Buf8(buf_len);
  20378. // convert
  20379. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20380. c = str.charCodeAt(m_pos);
  20381. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20382. c2 = str.charCodeAt(m_pos+1);
  20383. if ((c2 & 0xfc00) === 0xdc00) {
  20384. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20385. m_pos++;
  20386. }
  20387. }
  20388. if (c < 0x80) {
  20389. /* one byte */
  20390. buf[i++] = c;
  20391. } else if (c < 0x800) {
  20392. /* two bytes */
  20393. buf[i++] = 0xC0 | (c >>> 6);
  20394. buf[i++] = 0x80 | (c & 0x3f);
  20395. } else if (c < 0x10000) {
  20396. /* three bytes */
  20397. buf[i++] = 0xE0 | (c >>> 12);
  20398. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20399. buf[i++] = 0x80 | (c & 0x3f);
  20400. } else {
  20401. /* four bytes */
  20402. buf[i++] = 0xf0 | (c >>> 18);
  20403. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20404. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20405. buf[i++] = 0x80 | (c & 0x3f);
  20406. }
  20407. }
  20408. return buf;
  20409. };
  20410. // Helper (used in 2 places)
  20411. function buf2binstring(buf, len) {
  20412. // use fallback for big arrays to avoid stack overflow
  20413. if (len < 65537) {
  20414. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20415. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20416. }
  20417. }
  20418. var result = '';
  20419. for (var i=0; i < len; i++) {
  20420. result += String.fromCharCode(buf[i]);
  20421. }
  20422. return result;
  20423. }
  20424. // Convert byte array to binary string
  20425. exports.buf2binstring = function(buf) {
  20426. return buf2binstring(buf, buf.length);
  20427. };
  20428. // Convert binary string (typed, when possible)
  20429. exports.binstring2buf = function(str) {
  20430. var buf = new utils.Buf8(str.length);
  20431. for (var i=0, len=buf.length; i < len; i++) {
  20432. buf[i] = str.charCodeAt(i);
  20433. }
  20434. return buf;
  20435. };
  20436. // convert array to string
  20437. exports.buf2string = function (buf, max) {
  20438. var i, out, c, c_len;
  20439. var len = max || buf.length;
  20440. // Reserve max possible length (2 words per char)
  20441. // NB: by unknown reasons, Array is significantly faster for
  20442. // String.fromCharCode.apply than Uint16Array.
  20443. var utf16buf = new Array(len*2);
  20444. for (out=0, i=0; i<len;) {
  20445. c = buf[i++];
  20446. // quick process ascii
  20447. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20448. c_len = _utf8len[c];
  20449. // skip 5 & 6 byte codes
  20450. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20451. // apply mask on first byte
  20452. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20453. // join the rest
  20454. while (c_len > 1 && i < len) {
  20455. c = (c << 6) | (buf[i++] & 0x3f);
  20456. c_len--;
  20457. }
  20458. // terminated by end of string?
  20459. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20460. if (c < 0x10000) {
  20461. utf16buf[out++] = c;
  20462. } else {
  20463. c -= 0x10000;
  20464. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20465. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20466. }
  20467. }
  20468. return buf2binstring(utf16buf, out);
  20469. };
  20470. // Calculate max possible position in utf8 buffer,
  20471. // that will not break sequence. If that's not possible
  20472. // - (very small limits) return max size as is.
  20473. //
  20474. // buf[] - utf8 bytes array
  20475. // max - length limit (mandatory);
  20476. exports.utf8border = function(buf, max) {
  20477. var pos;
  20478. max = max || buf.length;
  20479. if (max > buf.length) { max = buf.length; }
  20480. // go back from last position, until start of sequence found
  20481. pos = max-1;
  20482. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20483. // Fuckup - very small and broken sequence,
  20484. // return max, because we should return something anyway.
  20485. if (pos < 0) { return max; }
  20486. // If we came to start of buffer - that means vuffer is too small,
  20487. // return max too.
  20488. if (pos === 0) { return max; }
  20489. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20490. };
  20491. },{"./common":74}],76:[function(require,module,exports){
  20492. 'use strict';
  20493. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20494. // It doesn't worth to make additional optimizationa as in original.
  20495. // Small size is preferable.
  20496. function adler32(adler, buf, len, pos) {
  20497. var s1 = (adler & 0xffff) |0,
  20498. s2 = ((adler >>> 16) & 0xffff) |0,
  20499. n = 0;
  20500. while (len !== 0) {
  20501. // Set limit ~ twice less than 5552, to keep
  20502. // s2 in 31-bits, because we force signed ints.
  20503. // in other case %= will fail.
  20504. n = len > 2000 ? 2000 : len;
  20505. len -= n;
  20506. do {
  20507. s1 = (s1 + buf[pos++]) |0;
  20508. s2 = (s2 + s1) |0;
  20509. } while (--n);
  20510. s1 %= 65521;
  20511. s2 %= 65521;
  20512. }
  20513. return (s1 | (s2 << 16)) |0;
  20514. }
  20515. module.exports = adler32;
  20516. },{}],77:[function(require,module,exports){
  20517. module.exports = {
  20518. /* Allowed flush values; see deflate() and inflate() below for details */
  20519. Z_NO_FLUSH: 0,
  20520. Z_PARTIAL_FLUSH: 1,
  20521. Z_SYNC_FLUSH: 2,
  20522. Z_FULL_FLUSH: 3,
  20523. Z_FINISH: 4,
  20524. Z_BLOCK: 5,
  20525. Z_TREES: 6,
  20526. /* Return codes for the compression/decompression functions. Negative values
  20527. * are errors, positive values are used for special but normal events.
  20528. */
  20529. Z_OK: 0,
  20530. Z_STREAM_END: 1,
  20531. Z_NEED_DICT: 2,
  20532. Z_ERRNO: -1,
  20533. Z_STREAM_ERROR: -2,
  20534. Z_DATA_ERROR: -3,
  20535. //Z_MEM_ERROR: -4,
  20536. Z_BUF_ERROR: -5,
  20537. //Z_VERSION_ERROR: -6,
  20538. /* compression levels */
  20539. Z_NO_COMPRESSION: 0,
  20540. Z_BEST_SPEED: 1,
  20541. Z_BEST_COMPRESSION: 9,
  20542. Z_DEFAULT_COMPRESSION: -1,
  20543. Z_FILTERED: 1,
  20544. Z_HUFFMAN_ONLY: 2,
  20545. Z_RLE: 3,
  20546. Z_FIXED: 4,
  20547. Z_DEFAULT_STRATEGY: 0,
  20548. /* Possible values of the data_type field (though see inflate()) */
  20549. Z_BINARY: 0,
  20550. Z_TEXT: 1,
  20551. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20552. Z_UNKNOWN: 2,
  20553. /* The deflate compression method */
  20554. Z_DEFLATED: 8
  20555. //Z_NULL: null // Use -1 or null inline, depending on var type
  20556. };
  20557. },{}],78:[function(require,module,exports){
  20558. 'use strict';
  20559. // Note: we can't get significant speed boost here.
  20560. // So write code to minimize size - no pregenerated tables
  20561. // and array tools dependencies.
  20562. // Use ordinary array, since untyped makes no boost here
  20563. function makeTable() {
  20564. var c, table = [];
  20565. for (var n =0; n < 256; n++) {
  20566. c = n;
  20567. for (var k =0; k < 8; k++) {
  20568. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20569. }
  20570. table[n] = c;
  20571. }
  20572. return table;
  20573. }
  20574. // Create table on load. Just 255 signed longs. Not a problem.
  20575. var crcTable = makeTable();
  20576. function crc32(crc, buf, len, pos) {
  20577. var t = crcTable,
  20578. end = pos + len;
  20579. crc = crc ^ (-1);
  20580. for (var i = pos; i < end; i++) {
  20581. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20582. }
  20583. return (crc ^ (-1)); // >>> 0;
  20584. }
  20585. module.exports = crc32;
  20586. },{}],79:[function(require,module,exports){
  20587. 'use strict';
  20588. var utils = require('../utils/common');
  20589. var trees = require('./trees');
  20590. var adler32 = require('./adler32');
  20591. var crc32 = require('./crc32');
  20592. var msg = require('./messages');
  20593. /* Public constants ==========================================================*/
  20594. /* ===========================================================================*/
  20595. /* Allowed flush values; see deflate() and inflate() below for details */
  20596. var Z_NO_FLUSH = 0;
  20597. var Z_PARTIAL_FLUSH = 1;
  20598. //var Z_SYNC_FLUSH = 2;
  20599. var Z_FULL_FLUSH = 3;
  20600. var Z_FINISH = 4;
  20601. var Z_BLOCK = 5;
  20602. //var Z_TREES = 6;
  20603. /* Return codes for the compression/decompression functions. Negative values
  20604. * are errors, positive values are used for special but normal events.
  20605. */
  20606. var Z_OK = 0;
  20607. var Z_STREAM_END = 1;
  20608. //var Z_NEED_DICT = 2;
  20609. //var Z_ERRNO = -1;
  20610. var Z_STREAM_ERROR = -2;
  20611. var Z_DATA_ERROR = -3;
  20612. //var Z_MEM_ERROR = -4;
  20613. var Z_BUF_ERROR = -5;
  20614. //var Z_VERSION_ERROR = -6;
  20615. /* compression levels */
  20616. //var Z_NO_COMPRESSION = 0;
  20617. //var Z_BEST_SPEED = 1;
  20618. //var Z_BEST_COMPRESSION = 9;
  20619. var Z_DEFAULT_COMPRESSION = -1;
  20620. var Z_FILTERED = 1;
  20621. var Z_HUFFMAN_ONLY = 2;
  20622. var Z_RLE = 3;
  20623. var Z_FIXED = 4;
  20624. var Z_DEFAULT_STRATEGY = 0;
  20625. /* Possible values of the data_type field (though see inflate()) */
  20626. //var Z_BINARY = 0;
  20627. //var Z_TEXT = 1;
  20628. //var Z_ASCII = 1; // = Z_TEXT
  20629. var Z_UNKNOWN = 2;
  20630. /* The deflate compression method */
  20631. var Z_DEFLATED = 8;
  20632. /*============================================================================*/
  20633. var MAX_MEM_LEVEL = 9;
  20634. /* Maximum value for memLevel in deflateInit2 */
  20635. var MAX_WBITS = 15;
  20636. /* 32K LZ77 window */
  20637. var DEF_MEM_LEVEL = 8;
  20638. var LENGTH_CODES = 29;
  20639. /* number of length codes, not counting the special END_BLOCK code */
  20640. var LITERALS = 256;
  20641. /* number of literal bytes 0..255 */
  20642. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20643. /* number of Literal or Length codes, including the END_BLOCK code */
  20644. var D_CODES = 30;
  20645. /* number of distance codes */
  20646. var BL_CODES = 19;
  20647. /* number of codes used to transfer the bit lengths */
  20648. var HEAP_SIZE = 2*L_CODES + 1;
  20649. /* maximum heap size */
  20650. var MAX_BITS = 15;
  20651. /* All codes must not exceed MAX_BITS bits */
  20652. var MIN_MATCH = 3;
  20653. var MAX_MATCH = 258;
  20654. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20655. var PRESET_DICT = 0x20;
  20656. var INIT_STATE = 42;
  20657. var EXTRA_STATE = 69;
  20658. var NAME_STATE = 73;
  20659. var COMMENT_STATE = 91;
  20660. var HCRC_STATE = 103;
  20661. var BUSY_STATE = 113;
  20662. var FINISH_STATE = 666;
  20663. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20664. var BS_BLOCK_DONE = 2; /* block flush performed */
  20665. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20666. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20667. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20668. function err(strm, errorCode) {
  20669. strm.msg = msg[errorCode];
  20670. return errorCode;
  20671. }
  20672. function rank(f) {
  20673. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20674. }
  20675. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20676. /* =========================================================================
  20677. * Flush as much pending output as possible. All deflate() output goes
  20678. * through this function so some applications may wish to modify it
  20679. * to avoid allocating a large strm->output buffer and copying into it.
  20680. * (See also read_buf()).
  20681. */
  20682. function flush_pending(strm) {
  20683. var s = strm.state;
  20684. //_tr_flush_bits(s);
  20685. var len = s.pending;
  20686. if (len > strm.avail_out) {
  20687. len = strm.avail_out;
  20688. }
  20689. if (len === 0) { return; }
  20690. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20691. strm.next_out += len;
  20692. s.pending_out += len;
  20693. strm.total_out += len;
  20694. strm.avail_out -= len;
  20695. s.pending -= len;
  20696. if (s.pending === 0) {
  20697. s.pending_out = 0;
  20698. }
  20699. }
  20700. function flush_block_only (s, last) {
  20701. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20702. s.block_start = s.strstart;
  20703. flush_pending(s.strm);
  20704. }
  20705. function put_byte(s, b) {
  20706. s.pending_buf[s.pending++] = b;
  20707. }
  20708. /* =========================================================================
  20709. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20710. * IN assertion: the stream state is correct and there is enough room in
  20711. * pending_buf.
  20712. */
  20713. function putShortMSB(s, b) {
  20714. // put_byte(s, (Byte)(b >> 8));
  20715. // put_byte(s, (Byte)(b & 0xff));
  20716. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20717. s.pending_buf[s.pending++] = b & 0xff;
  20718. }
  20719. /* ===========================================================================
  20720. * Read a new buffer from the current input stream, update the adler32
  20721. * and total number of bytes read. All deflate() input goes through
  20722. * this function so some applications may wish to modify it to avoid
  20723. * allocating a large strm->input buffer and copying from it.
  20724. * (See also flush_pending()).
  20725. */
  20726. function read_buf(strm, buf, start, size) {
  20727. var len = strm.avail_in;
  20728. if (len > size) { len = size; }
  20729. if (len === 0) { return 0; }
  20730. strm.avail_in -= len;
  20731. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20732. if (strm.state.wrap === 1) {
  20733. strm.adler = adler32(strm.adler, buf, len, start);
  20734. }
  20735. else if (strm.state.wrap === 2) {
  20736. strm.adler = crc32(strm.adler, buf, len, start);
  20737. }
  20738. strm.next_in += len;
  20739. strm.total_in += len;
  20740. return len;
  20741. }
  20742. /* ===========================================================================
  20743. * Set match_start to the longest match starting at the given string and
  20744. * return its length. Matches shorter or equal to prev_length are discarded,
  20745. * in which case the result is equal to prev_length and match_start is
  20746. * garbage.
  20747. * IN assertions: cur_match is the head of the hash chain for the current
  20748. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20749. * OUT assertion: the match length is not greater than s->lookahead.
  20750. */
  20751. function longest_match(s, cur_match) {
  20752. var chain_length = s.max_chain_length; /* max hash chain length */
  20753. var scan = s.strstart; /* current string */
  20754. var match; /* matched string */
  20755. var len; /* length of current match */
  20756. var best_len = s.prev_length; /* best match length so far */
  20757. var nice_match = s.nice_match; /* stop if match long enough */
  20758. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20759. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20760. var _win = s.window; // shortcut
  20761. var wmask = s.w_mask;
  20762. var prev = s.prev;
  20763. /* Stop when cur_match becomes <= limit. To simplify the code,
  20764. * we prevent matches with the string of window index 0.
  20765. */
  20766. var strend = s.strstart + MAX_MATCH;
  20767. var scan_end1 = _win[scan + best_len - 1];
  20768. var scan_end = _win[scan + best_len];
  20769. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20770. * It is easy to get rid of this optimization if necessary.
  20771. */
  20772. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20773. /* Do not waste too much time if we already have a good match: */
  20774. if (s.prev_length >= s.good_match) {
  20775. chain_length >>= 2;
  20776. }
  20777. /* Do not look for matches beyond the end of the input. This is necessary
  20778. * to make deflate deterministic.
  20779. */
  20780. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20781. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20782. do {
  20783. // Assert(cur_match < s->strstart, "no future");
  20784. match = cur_match;
  20785. /* Skip to next match if the match length cannot increase
  20786. * or if the match length is less than 2. Note that the checks below
  20787. * for insufficient lookahead only occur occasionally for performance
  20788. * reasons. Therefore uninitialized memory will be accessed, and
  20789. * conditional jumps will be made that depend on those values.
  20790. * However the length of the match is limited to the lookahead, so
  20791. * the output of deflate is not affected by the uninitialized values.
  20792. */
  20793. if (_win[match + best_len] !== scan_end ||
  20794. _win[match + best_len - 1] !== scan_end1 ||
  20795. _win[match] !== _win[scan] ||
  20796. _win[++match] !== _win[scan + 1]) {
  20797. continue;
  20798. }
  20799. /* The check at best_len-1 can be removed because it will be made
  20800. * again later. (This heuristic is not always a win.)
  20801. * It is not necessary to compare scan[2] and match[2] since they
  20802. * are always equal when the other bytes match, given that
  20803. * the hash keys are equal and that HASH_BITS >= 8.
  20804. */
  20805. scan += 2;
  20806. match++;
  20807. // Assert(*scan == *match, "match[2]?");
  20808. /* We check for insufficient lookahead only every 8th comparison;
  20809. * the 256th check will be made at strstart+258.
  20810. */
  20811. do {
  20812. /*jshint noempty:false*/
  20813. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20814. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20815. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20816. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20817. scan < strend);
  20818. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20819. len = MAX_MATCH - (strend - scan);
  20820. scan = strend - MAX_MATCH;
  20821. if (len > best_len) {
  20822. s.match_start = cur_match;
  20823. best_len = len;
  20824. if (len >= nice_match) {
  20825. break;
  20826. }
  20827. scan_end1 = _win[scan + best_len - 1];
  20828. scan_end = _win[scan + best_len];
  20829. }
  20830. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20831. if (best_len <= s.lookahead) {
  20832. return best_len;
  20833. }
  20834. return s.lookahead;
  20835. }
  20836. /* ===========================================================================
  20837. * Fill the window when the lookahead becomes insufficient.
  20838. * Updates strstart and lookahead.
  20839. *
  20840. * IN assertion: lookahead < MIN_LOOKAHEAD
  20841. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20842. * At least one byte has been read, or avail_in == 0; reads are
  20843. * performed for at least two bytes (required for the zip translate_eol
  20844. * option -- not supported here).
  20845. */
  20846. function fill_window(s) {
  20847. var _w_size = s.w_size;
  20848. var p, n, m, more, str;
  20849. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20850. do {
  20851. more = s.window_size - s.lookahead - s.strstart;
  20852. // JS ints have 32 bit, block below not needed
  20853. /* Deal with !@#$% 64K limit: */
  20854. //if (sizeof(int) <= 2) {
  20855. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20856. // more = wsize;
  20857. //
  20858. // } else if (more == (unsigned)(-1)) {
  20859. // /* Very unlikely, but possible on 16 bit machine if
  20860. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20861. // */
  20862. // more--;
  20863. // }
  20864. //}
  20865. /* If the window is almost full and there is insufficient lookahead,
  20866. * move the upper half to the lower one to make room in the upper half.
  20867. */
  20868. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20869. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20870. s.match_start -= _w_size;
  20871. s.strstart -= _w_size;
  20872. /* we now have strstart >= MAX_DIST */
  20873. s.block_start -= _w_size;
  20874. /* Slide the hash table (could be avoided with 32 bit values
  20875. at the expense of memory usage). We slide even when level == 0
  20876. to keep the hash table consistent if we switch back to level > 0
  20877. later. (Using level 0 permanently is not an optimal usage of
  20878. zlib, so we don't care about this pathological case.)
  20879. */
  20880. n = s.hash_size;
  20881. p = n;
  20882. do {
  20883. m = s.head[--p];
  20884. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20885. } while (--n);
  20886. n = _w_size;
  20887. p = n;
  20888. do {
  20889. m = s.prev[--p];
  20890. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20891. /* If n is not on any hash chain, prev[n] is garbage but
  20892. * its value will never be used.
  20893. */
  20894. } while (--n);
  20895. more += _w_size;
  20896. }
  20897. if (s.strm.avail_in === 0) {
  20898. break;
  20899. }
  20900. /* If there was no sliding:
  20901. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20902. * more == window_size - lookahead - strstart
  20903. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20904. * => more >= window_size - 2*WSIZE + 2
  20905. * In the BIG_MEM or MMAP case (not yet supported),
  20906. * window_size == input_size + MIN_LOOKAHEAD &&
  20907. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20908. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20909. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20910. */
  20911. //Assert(more >= 2, "more < 2");
  20912. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20913. s.lookahead += n;
  20914. /* Initialize the hash value now that we have some input: */
  20915. if (s.lookahead + s.insert >= MIN_MATCH) {
  20916. str = s.strstart - s.insert;
  20917. s.ins_h = s.window[str];
  20918. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20919. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20920. //#if MIN_MATCH != 3
  20921. // Call update_hash() MIN_MATCH-3 more times
  20922. //#endif
  20923. while (s.insert) {
  20924. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20925. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20926. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20927. s.head[s.ins_h] = str;
  20928. str++;
  20929. s.insert--;
  20930. if (s.lookahead + s.insert < MIN_MATCH) {
  20931. break;
  20932. }
  20933. }
  20934. }
  20935. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20936. * but this is not important since only literal bytes will be emitted.
  20937. */
  20938. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20939. /* If the WIN_INIT bytes after the end of the current data have never been
  20940. * written, then zero those bytes in order to avoid memory check reports of
  20941. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20942. * the longest match routines. Update the high water mark for the next
  20943. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20944. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20945. */
  20946. // if (s.high_water < s.window_size) {
  20947. // var curr = s.strstart + s.lookahead;
  20948. // var init = 0;
  20949. //
  20950. // if (s.high_water < curr) {
  20951. // /* Previous high water mark below current data -- zero WIN_INIT
  20952. // * bytes or up to end of window, whichever is less.
  20953. // */
  20954. // init = s.window_size - curr;
  20955. // if (init > WIN_INIT)
  20956. // init = WIN_INIT;
  20957. // zmemzero(s->window + curr, (unsigned)init);
  20958. // s->high_water = curr + init;
  20959. // }
  20960. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20961. // /* High water mark at or above current data, but below current data
  20962. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20963. // * to end of window, whichever is less.
  20964. // */
  20965. // init = (ulg)curr + WIN_INIT - s->high_water;
  20966. // if (init > s->window_size - s->high_water)
  20967. // init = s->window_size - s->high_water;
  20968. // zmemzero(s->window + s->high_water, (unsigned)init);
  20969. // s->high_water += init;
  20970. // }
  20971. // }
  20972. //
  20973. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20974. // "not enough room for search");
  20975. }
  20976. /* ===========================================================================
  20977. * Copy without compression as much as possible from the input stream, return
  20978. * the current block state.
  20979. * This function does not insert new strings in the dictionary since
  20980. * uncompressible data is probably not useful. This function is used
  20981. * only for the level=0 compression option.
  20982. * NOTE: this function should be optimized to avoid extra copying from
  20983. * window to pending_buf.
  20984. */
  20985. function deflate_stored(s, flush) {
  20986. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20987. * to pending_buf_size, and each stored block has a 5 byte header:
  20988. */
  20989. var max_block_size = 0xffff;
  20990. if (max_block_size > s.pending_buf_size - 5) {
  20991. max_block_size = s.pending_buf_size - 5;
  20992. }
  20993. /* Copy as much as possible from input to output: */
  20994. for (;;) {
  20995. /* Fill the window as much as possible: */
  20996. if (s.lookahead <= 1) {
  20997. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20998. // s->block_start >= (long)s->w_size, "slide too late");
  20999. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21000. // s.block_start >= s.w_size)) {
  21001. // throw new Error("slide too late");
  21002. // }
  21003. fill_window(s);
  21004. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21005. return BS_NEED_MORE;
  21006. }
  21007. if (s.lookahead === 0) {
  21008. break;
  21009. }
  21010. /* flush the current block */
  21011. }
  21012. //Assert(s->block_start >= 0L, "block gone");
  21013. // if (s.block_start < 0) throw new Error("block gone");
  21014. s.strstart += s.lookahead;
  21015. s.lookahead = 0;
  21016. /* Emit a stored block if pending_buf will be full: */
  21017. var max_start = s.block_start + max_block_size;
  21018. if (s.strstart === 0 || s.strstart >= max_start) {
  21019. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21020. s.lookahead = s.strstart - max_start;
  21021. s.strstart = max_start;
  21022. /*** FLUSH_BLOCK(s, 0); ***/
  21023. flush_block_only(s, false);
  21024. if (s.strm.avail_out === 0) {
  21025. return BS_NEED_MORE;
  21026. }
  21027. /***/
  21028. }
  21029. /* Flush if we may have to slide, otherwise block_start may become
  21030. * negative and the data will be gone:
  21031. */
  21032. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21033. /*** FLUSH_BLOCK(s, 0); ***/
  21034. flush_block_only(s, false);
  21035. if (s.strm.avail_out === 0) {
  21036. return BS_NEED_MORE;
  21037. }
  21038. /***/
  21039. }
  21040. }
  21041. s.insert = 0;
  21042. if (flush === Z_FINISH) {
  21043. /*** FLUSH_BLOCK(s, 1); ***/
  21044. flush_block_only(s, true);
  21045. if (s.strm.avail_out === 0) {
  21046. return BS_FINISH_STARTED;
  21047. }
  21048. /***/
  21049. return BS_FINISH_DONE;
  21050. }
  21051. if (s.strstart > s.block_start) {
  21052. /*** FLUSH_BLOCK(s, 0); ***/
  21053. flush_block_only(s, false);
  21054. if (s.strm.avail_out === 0) {
  21055. return BS_NEED_MORE;
  21056. }
  21057. /***/
  21058. }
  21059. return BS_NEED_MORE;
  21060. }
  21061. /* ===========================================================================
  21062. * Compress as much as possible from the input stream, return the current
  21063. * block state.
  21064. * This function does not perform lazy evaluation of matches and inserts
  21065. * new strings in the dictionary only for unmatched strings or for short
  21066. * matches. It is used only for the fast compression options.
  21067. */
  21068. function deflate_fast(s, flush) {
  21069. var hash_head; /* head of the hash chain */
  21070. var bflush; /* set if current block must be flushed */
  21071. for (;;) {
  21072. /* Make sure that we always have enough lookahead, except
  21073. * at the end of the input file. We need MAX_MATCH bytes
  21074. * for the next match, plus MIN_MATCH bytes to insert the
  21075. * string following the next match.
  21076. */
  21077. if (s.lookahead < MIN_LOOKAHEAD) {
  21078. fill_window(s);
  21079. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21080. return BS_NEED_MORE;
  21081. }
  21082. if (s.lookahead === 0) {
  21083. break; /* flush the current block */
  21084. }
  21085. }
  21086. /* Insert the string window[strstart .. strstart+2] in the
  21087. * dictionary, and set hash_head to the head of the hash chain:
  21088. */
  21089. hash_head = 0/*NIL*/;
  21090. if (s.lookahead >= MIN_MATCH) {
  21091. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21092. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21093. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21094. s.head[s.ins_h] = s.strstart;
  21095. /***/
  21096. }
  21097. /* Find the longest match, discarding those <= prev_length.
  21098. * At this point we have always match_length < MIN_MATCH
  21099. */
  21100. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21101. /* To simplify the code, we prevent matches with the string
  21102. * of window index 0 (in particular we have to avoid a match
  21103. * of the string with itself at the start of the input file).
  21104. */
  21105. s.match_length = longest_match(s, hash_head);
  21106. /* longest_match() sets match_start */
  21107. }
  21108. if (s.match_length >= MIN_MATCH) {
  21109. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21110. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21111. s.match_length - MIN_MATCH, bflush); ***/
  21112. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21113. s.lookahead -= s.match_length;
  21114. /* Insert new strings in the hash table only if the match length
  21115. * is not too large. This saves time but degrades compression.
  21116. */
  21117. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21118. s.match_length--; /* string at strstart already in table */
  21119. do {
  21120. s.strstart++;
  21121. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21122. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21123. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21124. s.head[s.ins_h] = s.strstart;
  21125. /***/
  21126. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21127. * always MIN_MATCH bytes ahead.
  21128. */
  21129. } while (--s.match_length !== 0);
  21130. s.strstart++;
  21131. } else
  21132. {
  21133. s.strstart += s.match_length;
  21134. s.match_length = 0;
  21135. s.ins_h = s.window[s.strstart];
  21136. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21137. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21138. //#if MIN_MATCH != 3
  21139. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21140. //#endif
  21141. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21142. * matter since it will be recomputed at next deflate call.
  21143. */
  21144. }
  21145. } else {
  21146. /* No match, output a literal byte */
  21147. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21148. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21149. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21150. s.lookahead--;
  21151. s.strstart++;
  21152. }
  21153. if (bflush) {
  21154. /*** FLUSH_BLOCK(s, 0); ***/
  21155. flush_block_only(s, false);
  21156. if (s.strm.avail_out === 0) {
  21157. return BS_NEED_MORE;
  21158. }
  21159. /***/
  21160. }
  21161. }
  21162. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21163. if (flush === Z_FINISH) {
  21164. /*** FLUSH_BLOCK(s, 1); ***/
  21165. flush_block_only(s, true);
  21166. if (s.strm.avail_out === 0) {
  21167. return BS_FINISH_STARTED;
  21168. }
  21169. /***/
  21170. return BS_FINISH_DONE;
  21171. }
  21172. if (s.last_lit) {
  21173. /*** FLUSH_BLOCK(s, 0); ***/
  21174. flush_block_only(s, false);
  21175. if (s.strm.avail_out === 0) {
  21176. return BS_NEED_MORE;
  21177. }
  21178. /***/
  21179. }
  21180. return BS_BLOCK_DONE;
  21181. }
  21182. /* ===========================================================================
  21183. * Same as above, but achieves better compression. We use a lazy
  21184. * evaluation for matches: a match is finally adopted only if there is
  21185. * no better match at the next window position.
  21186. */
  21187. function deflate_slow(s, flush) {
  21188. var hash_head; /* head of hash chain */
  21189. var bflush; /* set if current block must be flushed */
  21190. var max_insert;
  21191. /* Process the input block. */
  21192. for (;;) {
  21193. /* Make sure that we always have enough lookahead, except
  21194. * at the end of the input file. We need MAX_MATCH bytes
  21195. * for the next match, plus MIN_MATCH bytes to insert the
  21196. * string following the next match.
  21197. */
  21198. if (s.lookahead < MIN_LOOKAHEAD) {
  21199. fill_window(s);
  21200. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21201. return BS_NEED_MORE;
  21202. }
  21203. if (s.lookahead === 0) { break; } /* flush the current block */
  21204. }
  21205. /* Insert the string window[strstart .. strstart+2] in the
  21206. * dictionary, and set hash_head to the head of the hash chain:
  21207. */
  21208. hash_head = 0/*NIL*/;
  21209. if (s.lookahead >= MIN_MATCH) {
  21210. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21211. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21212. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21213. s.head[s.ins_h] = s.strstart;
  21214. /***/
  21215. }
  21216. /* Find the longest match, discarding those <= prev_length.
  21217. */
  21218. s.prev_length = s.match_length;
  21219. s.prev_match = s.match_start;
  21220. s.match_length = MIN_MATCH-1;
  21221. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21222. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21223. /* To simplify the code, we prevent matches with the string
  21224. * of window index 0 (in particular we have to avoid a match
  21225. * of the string with itself at the start of the input file).
  21226. */
  21227. s.match_length = longest_match(s, hash_head);
  21228. /* longest_match() sets match_start */
  21229. if (s.match_length <= 5 &&
  21230. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21231. /* If prev_match is also MIN_MATCH, match_start is garbage
  21232. * but we will ignore the current match anyway.
  21233. */
  21234. s.match_length = MIN_MATCH-1;
  21235. }
  21236. }
  21237. /* If there was a match at the previous step and the current
  21238. * match is not better, output the previous match:
  21239. */
  21240. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21241. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21242. /* Do not insert strings in hash table beyond this. */
  21243. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21244. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21245. s.prev_length - MIN_MATCH, bflush);***/
  21246. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21247. /* Insert in hash table all strings up to the end of the match.
  21248. * strstart-1 and strstart are already inserted. If there is not
  21249. * enough lookahead, the last two strings are not inserted in
  21250. * the hash table.
  21251. */
  21252. s.lookahead -= s.prev_length-1;
  21253. s.prev_length -= 2;
  21254. do {
  21255. if (++s.strstart <= max_insert) {
  21256. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21257. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21258. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21259. s.head[s.ins_h] = s.strstart;
  21260. /***/
  21261. }
  21262. } while (--s.prev_length !== 0);
  21263. s.match_available = 0;
  21264. s.match_length = MIN_MATCH-1;
  21265. s.strstart++;
  21266. if (bflush) {
  21267. /*** FLUSH_BLOCK(s, 0); ***/
  21268. flush_block_only(s, false);
  21269. if (s.strm.avail_out === 0) {
  21270. return BS_NEED_MORE;
  21271. }
  21272. /***/
  21273. }
  21274. } else if (s.match_available) {
  21275. /* If there was no match at the previous position, output a
  21276. * single literal. If there was a match but the current match
  21277. * is longer, truncate the previous match to a single literal.
  21278. */
  21279. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21280. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21281. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21282. if (bflush) {
  21283. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21284. flush_block_only(s, false);
  21285. /***/
  21286. }
  21287. s.strstart++;
  21288. s.lookahead--;
  21289. if (s.strm.avail_out === 0) {
  21290. return BS_NEED_MORE;
  21291. }
  21292. } else {
  21293. /* There is no previous match to compare with, wait for
  21294. * the next step to decide.
  21295. */
  21296. s.match_available = 1;
  21297. s.strstart++;
  21298. s.lookahead--;
  21299. }
  21300. }
  21301. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21302. if (s.match_available) {
  21303. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21304. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21305. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21306. s.match_available = 0;
  21307. }
  21308. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21309. if (flush === Z_FINISH) {
  21310. /*** FLUSH_BLOCK(s, 1); ***/
  21311. flush_block_only(s, true);
  21312. if (s.strm.avail_out === 0) {
  21313. return BS_FINISH_STARTED;
  21314. }
  21315. /***/
  21316. return BS_FINISH_DONE;
  21317. }
  21318. if (s.last_lit) {
  21319. /*** FLUSH_BLOCK(s, 0); ***/
  21320. flush_block_only(s, false);
  21321. if (s.strm.avail_out === 0) {
  21322. return BS_NEED_MORE;
  21323. }
  21324. /***/
  21325. }
  21326. return BS_BLOCK_DONE;
  21327. }
  21328. /* ===========================================================================
  21329. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21330. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21331. * deflate switches away from Z_RLE.)
  21332. */
  21333. function deflate_rle(s, flush) {
  21334. var bflush; /* set if current block must be flushed */
  21335. var prev; /* byte at distance one to match */
  21336. var scan, strend; /* scan goes up to strend for length of run */
  21337. var _win = s.window;
  21338. for (;;) {
  21339. /* Make sure that we always have enough lookahead, except
  21340. * at the end of the input file. We need MAX_MATCH bytes
  21341. * for the longest run, plus one for the unrolled loop.
  21342. */
  21343. if (s.lookahead <= MAX_MATCH) {
  21344. fill_window(s);
  21345. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21346. return BS_NEED_MORE;
  21347. }
  21348. if (s.lookahead === 0) { break; } /* flush the current block */
  21349. }
  21350. /* See how many times the previous byte repeats */
  21351. s.match_length = 0;
  21352. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21353. scan = s.strstart - 1;
  21354. prev = _win[scan];
  21355. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21356. strend = s.strstart + MAX_MATCH;
  21357. do {
  21358. /*jshint noempty:false*/
  21359. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21360. prev === _win[++scan] && prev === _win[++scan] &&
  21361. prev === _win[++scan] && prev === _win[++scan] &&
  21362. prev === _win[++scan] && prev === _win[++scan] &&
  21363. scan < strend);
  21364. s.match_length = MAX_MATCH - (strend - scan);
  21365. if (s.match_length > s.lookahead) {
  21366. s.match_length = s.lookahead;
  21367. }
  21368. }
  21369. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21370. }
  21371. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21372. if (s.match_length >= MIN_MATCH) {
  21373. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21374. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21375. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21376. s.lookahead -= s.match_length;
  21377. s.strstart += s.match_length;
  21378. s.match_length = 0;
  21379. } else {
  21380. /* No match, output a literal byte */
  21381. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21382. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21383. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21384. s.lookahead--;
  21385. s.strstart++;
  21386. }
  21387. if (bflush) {
  21388. /*** FLUSH_BLOCK(s, 0); ***/
  21389. flush_block_only(s, false);
  21390. if (s.strm.avail_out === 0) {
  21391. return BS_NEED_MORE;
  21392. }
  21393. /***/
  21394. }
  21395. }
  21396. s.insert = 0;
  21397. if (flush === Z_FINISH) {
  21398. /*** FLUSH_BLOCK(s, 1); ***/
  21399. flush_block_only(s, true);
  21400. if (s.strm.avail_out === 0) {
  21401. return BS_FINISH_STARTED;
  21402. }
  21403. /***/
  21404. return BS_FINISH_DONE;
  21405. }
  21406. if (s.last_lit) {
  21407. /*** FLUSH_BLOCK(s, 0); ***/
  21408. flush_block_only(s, false);
  21409. if (s.strm.avail_out === 0) {
  21410. return BS_NEED_MORE;
  21411. }
  21412. /***/
  21413. }
  21414. return BS_BLOCK_DONE;
  21415. }
  21416. /* ===========================================================================
  21417. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21418. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21419. */
  21420. function deflate_huff(s, flush) {
  21421. var bflush; /* set if current block must be flushed */
  21422. for (;;) {
  21423. /* Make sure that we have a literal to write. */
  21424. if (s.lookahead === 0) {
  21425. fill_window(s);
  21426. if (s.lookahead === 0) {
  21427. if (flush === Z_NO_FLUSH) {
  21428. return BS_NEED_MORE;
  21429. }
  21430. break; /* flush the current block */
  21431. }
  21432. }
  21433. /* Output a literal byte */
  21434. s.match_length = 0;
  21435. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21436. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21437. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21438. s.lookahead--;
  21439. s.strstart++;
  21440. if (bflush) {
  21441. /*** FLUSH_BLOCK(s, 0); ***/
  21442. flush_block_only(s, false);
  21443. if (s.strm.avail_out === 0) {
  21444. return BS_NEED_MORE;
  21445. }
  21446. /***/
  21447. }
  21448. }
  21449. s.insert = 0;
  21450. if (flush === Z_FINISH) {
  21451. /*** FLUSH_BLOCK(s, 1); ***/
  21452. flush_block_only(s, true);
  21453. if (s.strm.avail_out === 0) {
  21454. return BS_FINISH_STARTED;
  21455. }
  21456. /***/
  21457. return BS_FINISH_DONE;
  21458. }
  21459. if (s.last_lit) {
  21460. /*** FLUSH_BLOCK(s, 0); ***/
  21461. flush_block_only(s, false);
  21462. if (s.strm.avail_out === 0) {
  21463. return BS_NEED_MORE;
  21464. }
  21465. /***/
  21466. }
  21467. return BS_BLOCK_DONE;
  21468. }
  21469. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21470. * the desired pack level (0..9). The values given below have been tuned to
  21471. * exclude worst case performance for pathological files. Better values may be
  21472. * found for specific files.
  21473. */
  21474. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21475. this.good_length = good_length;
  21476. this.max_lazy = max_lazy;
  21477. this.nice_length = nice_length;
  21478. this.max_chain = max_chain;
  21479. this.func = func;
  21480. };
  21481. var configuration_table;
  21482. configuration_table = [
  21483. /* good lazy nice chain */
  21484. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21485. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21486. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21487. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21488. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21489. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21490. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21491. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21492. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21493. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21494. ];
  21495. /* ===========================================================================
  21496. * Initialize the "longest match" routines for a new zlib stream
  21497. */
  21498. function lm_init(s) {
  21499. s.window_size = 2 * s.w_size;
  21500. /*** CLEAR_HASH(s); ***/
  21501. zero(s.head); // Fill with NIL (= 0);
  21502. /* Set the default configuration parameters:
  21503. */
  21504. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21505. s.good_match = configuration_table[s.level].good_length;
  21506. s.nice_match = configuration_table[s.level].nice_length;
  21507. s.max_chain_length = configuration_table[s.level].max_chain;
  21508. s.strstart = 0;
  21509. s.block_start = 0;
  21510. s.lookahead = 0;
  21511. s.insert = 0;
  21512. s.match_length = s.prev_length = MIN_MATCH - 1;
  21513. s.match_available = 0;
  21514. s.ins_h = 0;
  21515. }
  21516. function DeflateState() {
  21517. this.strm = null; /* pointer back to this zlib stream */
  21518. this.status = 0; /* as the name implies */
  21519. this.pending_buf = null; /* output still pending */
  21520. this.pending_buf_size = 0; /* size of pending_buf */
  21521. this.pending_out = 0; /* next pending byte to output to the stream */
  21522. this.pending = 0; /* nb of bytes in the pending buffer */
  21523. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21524. this.gzhead = null; /* gzip header information to write */
  21525. this.gzindex = 0; /* where in extra, name, or comment */
  21526. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21527. this.last_flush = -1; /* value of flush param for previous deflate call */
  21528. this.w_size = 0; /* LZ77 window size (32K by default) */
  21529. this.w_bits = 0; /* log2(w_size) (8..16) */
  21530. this.w_mask = 0; /* w_size - 1 */
  21531. this.window = null;
  21532. /* Sliding window. Input bytes are read into the second half of the window,
  21533. * and move to the first half later to keep a dictionary of at least wSize
  21534. * bytes. With this organization, matches are limited to a distance of
  21535. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21536. * performed with a length multiple of the block size.
  21537. */
  21538. this.window_size = 0;
  21539. /* Actual size of window: 2*wSize, except when the user input buffer
  21540. * is directly used as sliding window.
  21541. */
  21542. this.prev = null;
  21543. /* Link to older string with same hash index. To limit the size of this
  21544. * array to 64K, this link is maintained only for the last 32K strings.
  21545. * An index in this array is thus a window index modulo 32K.
  21546. */
  21547. this.head = null; /* Heads of the hash chains or NIL. */
  21548. this.ins_h = 0; /* hash index of string to be inserted */
  21549. this.hash_size = 0; /* number of elements in hash table */
  21550. this.hash_bits = 0; /* log2(hash_size) */
  21551. this.hash_mask = 0; /* hash_size-1 */
  21552. this.hash_shift = 0;
  21553. /* Number of bits by which ins_h must be shifted at each input
  21554. * step. It must be such that after MIN_MATCH steps, the oldest
  21555. * byte no longer takes part in the hash key, that is:
  21556. * hash_shift * MIN_MATCH >= hash_bits
  21557. */
  21558. this.block_start = 0;
  21559. /* Window position at the beginning of the current output block. Gets
  21560. * negative when the window is moved backwards.
  21561. */
  21562. this.match_length = 0; /* length of best match */
  21563. this.prev_match = 0; /* previous match */
  21564. this.match_available = 0; /* set if previous match exists */
  21565. this.strstart = 0; /* start of string to insert */
  21566. this.match_start = 0; /* start of matching string */
  21567. this.lookahead = 0; /* number of valid bytes ahead in window */
  21568. this.prev_length = 0;
  21569. /* Length of the best match at previous step. Matches not greater than this
  21570. * are discarded. This is used in the lazy match evaluation.
  21571. */
  21572. this.max_chain_length = 0;
  21573. /* To speed up deflation, hash chains are never searched beyond this
  21574. * length. A higher limit improves compression ratio but degrades the
  21575. * speed.
  21576. */
  21577. this.max_lazy_match = 0;
  21578. /* Attempt to find a better match only when the current match is strictly
  21579. * smaller than this value. This mechanism is used only for compression
  21580. * levels >= 4.
  21581. */
  21582. // That's alias to max_lazy_match, don't use directly
  21583. //this.max_insert_length = 0;
  21584. /* Insert new strings in the hash table only if the match length is not
  21585. * greater than this length. This saves time but degrades compression.
  21586. * max_insert_length is used only for compression levels <= 3.
  21587. */
  21588. this.level = 0; /* compression level (1..9) */
  21589. this.strategy = 0; /* favor or force Huffman coding*/
  21590. this.good_match = 0;
  21591. /* Use a faster search when the previous match is longer than this */
  21592. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21593. /* used by trees.c: */
  21594. /* Didn't use ct_data typedef below to suppress compiler warning */
  21595. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21596. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21597. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21598. // Use flat array of DOUBLE size, with interleaved fata,
  21599. // because JS does not support effective
  21600. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21601. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21602. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21603. zero(this.dyn_ltree);
  21604. zero(this.dyn_dtree);
  21605. zero(this.bl_tree);
  21606. this.l_desc = null; /* desc. for literal tree */
  21607. this.d_desc = null; /* desc. for distance tree */
  21608. this.bl_desc = null; /* desc. for bit length tree */
  21609. //ush bl_count[MAX_BITS+1];
  21610. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21611. /* number of codes at each bit length for an optimal tree */
  21612. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21613. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21614. zero(this.heap);
  21615. this.heap_len = 0; /* number of elements in the heap */
  21616. this.heap_max = 0; /* element of largest frequency */
  21617. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21618. * The same heap array is used to build all trees.
  21619. */
  21620. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21621. zero(this.depth);
  21622. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21623. */
  21624. this.l_buf = 0; /* buffer index for literals or lengths */
  21625. this.lit_bufsize = 0;
  21626. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21627. * limiting lit_bufsize to 64K:
  21628. * - frequencies can be kept in 16 bit counters
  21629. * - if compression is not successful for the first block, all input
  21630. * data is still in the window so we can still emit a stored block even
  21631. * when input comes from standard input. (This can also be done for
  21632. * all blocks if lit_bufsize is not greater than 32K.)
  21633. * - if compression is not successful for a file smaller than 64K, we can
  21634. * even emit a stored file instead of a stored block (saving 5 bytes).
  21635. * This is applicable only for zip (not gzip or zlib).
  21636. * - creating new Huffman trees less frequently may not provide fast
  21637. * adaptation to changes in the input data statistics. (Take for
  21638. * example a binary file with poorly compressible code followed by
  21639. * a highly compressible string table.) Smaller buffer sizes give
  21640. * fast adaptation but have of course the overhead of transmitting
  21641. * trees more frequently.
  21642. * - I can't count above 4
  21643. */
  21644. this.last_lit = 0; /* running index in l_buf */
  21645. this.d_buf = 0;
  21646. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21647. * the same number of elements. To use different lengths, an extra flag
  21648. * array would be necessary.
  21649. */
  21650. this.opt_len = 0; /* bit length of current block with optimal trees */
  21651. this.static_len = 0; /* bit length of current block with static trees */
  21652. this.matches = 0; /* number of string matches in current block */
  21653. this.insert = 0; /* bytes at end of window left to insert */
  21654. this.bi_buf = 0;
  21655. /* Output buffer. bits are inserted starting at the bottom (least
  21656. * significant bits).
  21657. */
  21658. this.bi_valid = 0;
  21659. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21660. * are always zero.
  21661. */
  21662. // Used for window memory init. We safely ignore it for JS. That makes
  21663. // sense only for pointers and memory check tools.
  21664. //this.high_water = 0;
  21665. /* High water mark offset in window for initialized bytes -- bytes above
  21666. * this are set to zero in order to avoid memory check warnings when
  21667. * longest match routines access bytes past the input. This is then
  21668. * updated to the new high water mark.
  21669. */
  21670. }
  21671. function deflateResetKeep(strm) {
  21672. var s;
  21673. if (!strm || !strm.state) {
  21674. return err(strm, Z_STREAM_ERROR);
  21675. }
  21676. strm.total_in = strm.total_out = 0;
  21677. strm.data_type = Z_UNKNOWN;
  21678. s = strm.state;
  21679. s.pending = 0;
  21680. s.pending_out = 0;
  21681. if (s.wrap < 0) {
  21682. s.wrap = -s.wrap;
  21683. /* was made negative by deflate(..., Z_FINISH); */
  21684. }
  21685. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21686. strm.adler = (s.wrap === 2) ?
  21687. 0 // crc32(0, Z_NULL, 0)
  21688. :
  21689. 1; // adler32(0, Z_NULL, 0)
  21690. s.last_flush = Z_NO_FLUSH;
  21691. trees._tr_init(s);
  21692. return Z_OK;
  21693. }
  21694. function deflateReset(strm) {
  21695. var ret = deflateResetKeep(strm);
  21696. if (ret === Z_OK) {
  21697. lm_init(strm.state);
  21698. }
  21699. return ret;
  21700. }
  21701. function deflateSetHeader(strm, head) {
  21702. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21703. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21704. strm.state.gzhead = head;
  21705. return Z_OK;
  21706. }
  21707. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21708. if (!strm) { // === Z_NULL
  21709. return Z_STREAM_ERROR;
  21710. }
  21711. var wrap = 1;
  21712. if (level === Z_DEFAULT_COMPRESSION) {
  21713. level = 6;
  21714. }
  21715. if (windowBits < 0) { /* suppress zlib wrapper */
  21716. wrap = 0;
  21717. windowBits = -windowBits;
  21718. }
  21719. else if (windowBits > 15) {
  21720. wrap = 2; /* write gzip wrapper instead */
  21721. windowBits -= 16;
  21722. }
  21723. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21724. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21725. strategy < 0 || strategy > Z_FIXED) {
  21726. return err(strm, Z_STREAM_ERROR);
  21727. }
  21728. if (windowBits === 8) {
  21729. windowBits = 9;
  21730. }
  21731. /* until 256-byte window bug fixed */
  21732. var s = new DeflateState();
  21733. strm.state = s;
  21734. s.strm = strm;
  21735. s.wrap = wrap;
  21736. s.gzhead = null;
  21737. s.w_bits = windowBits;
  21738. s.w_size = 1 << s.w_bits;
  21739. s.w_mask = s.w_size - 1;
  21740. s.hash_bits = memLevel + 7;
  21741. s.hash_size = 1 << s.hash_bits;
  21742. s.hash_mask = s.hash_size - 1;
  21743. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21744. s.window = new utils.Buf8(s.w_size * 2);
  21745. s.head = new utils.Buf16(s.hash_size);
  21746. s.prev = new utils.Buf16(s.w_size);
  21747. // Don't need mem init magic for JS.
  21748. //s.high_water = 0; /* nothing written to s->window yet */
  21749. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21750. s.pending_buf_size = s.lit_bufsize * 4;
  21751. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21752. s.d_buf = s.lit_bufsize >> 1;
  21753. s.l_buf = (1 + 2) * s.lit_bufsize;
  21754. s.level = level;
  21755. s.strategy = strategy;
  21756. s.method = method;
  21757. return deflateReset(strm);
  21758. }
  21759. function deflateInit(strm, level) {
  21760. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21761. }
  21762. function deflate(strm, flush) {
  21763. var old_flush, s;
  21764. var beg, val; // for gzip header write only
  21765. if (!strm || !strm.state ||
  21766. flush > Z_BLOCK || flush < 0) {
  21767. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21768. }
  21769. s = strm.state;
  21770. if (!strm.output ||
  21771. (!strm.input && strm.avail_in !== 0) ||
  21772. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21773. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21774. }
  21775. s.strm = strm; /* just in case */
  21776. old_flush = s.last_flush;
  21777. s.last_flush = flush;
  21778. /* Write the header */
  21779. if (s.status === INIT_STATE) {
  21780. if (s.wrap === 2) { // GZIP header
  21781. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21782. put_byte(s, 31);
  21783. put_byte(s, 139);
  21784. put_byte(s, 8);
  21785. if (!s.gzhead) { // s->gzhead == Z_NULL
  21786. put_byte(s, 0);
  21787. put_byte(s, 0);
  21788. put_byte(s, 0);
  21789. put_byte(s, 0);
  21790. put_byte(s, 0);
  21791. put_byte(s, s.level === 9 ? 2 :
  21792. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21793. 4 : 0));
  21794. put_byte(s, OS_CODE);
  21795. s.status = BUSY_STATE;
  21796. }
  21797. else {
  21798. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21799. (s.gzhead.hcrc ? 2 : 0) +
  21800. (!s.gzhead.extra ? 0 : 4) +
  21801. (!s.gzhead.name ? 0 : 8) +
  21802. (!s.gzhead.comment ? 0 : 16)
  21803. );
  21804. put_byte(s, s.gzhead.time & 0xff);
  21805. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21806. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21807. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21808. put_byte(s, s.level === 9 ? 2 :
  21809. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21810. 4 : 0));
  21811. put_byte(s, s.gzhead.os & 0xff);
  21812. if (s.gzhead.extra && s.gzhead.extra.length) {
  21813. put_byte(s, s.gzhead.extra.length & 0xff);
  21814. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21815. }
  21816. if (s.gzhead.hcrc) {
  21817. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21818. }
  21819. s.gzindex = 0;
  21820. s.status = EXTRA_STATE;
  21821. }
  21822. }
  21823. else // DEFLATE header
  21824. {
  21825. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21826. var level_flags = -1;
  21827. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21828. level_flags = 0;
  21829. } else if (s.level < 6) {
  21830. level_flags = 1;
  21831. } else if (s.level === 6) {
  21832. level_flags = 2;
  21833. } else {
  21834. level_flags = 3;
  21835. }
  21836. header |= (level_flags << 6);
  21837. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21838. header += 31 - (header % 31);
  21839. s.status = BUSY_STATE;
  21840. putShortMSB(s, header);
  21841. /* Save the adler32 of the preset dictionary: */
  21842. if (s.strstart !== 0) {
  21843. putShortMSB(s, strm.adler >>> 16);
  21844. putShortMSB(s, strm.adler & 0xffff);
  21845. }
  21846. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21847. }
  21848. }
  21849. //#ifdef GZIP
  21850. if (s.status === EXTRA_STATE) {
  21851. if (s.gzhead.extra/* != Z_NULL*/) {
  21852. beg = s.pending; /* start of bytes to update crc */
  21853. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21854. if (s.pending === s.pending_buf_size) {
  21855. if (s.gzhead.hcrc && s.pending > beg) {
  21856. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21857. }
  21858. flush_pending(strm);
  21859. beg = s.pending;
  21860. if (s.pending === s.pending_buf_size) {
  21861. break;
  21862. }
  21863. }
  21864. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21865. s.gzindex++;
  21866. }
  21867. if (s.gzhead.hcrc && s.pending > beg) {
  21868. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21869. }
  21870. if (s.gzindex === s.gzhead.extra.length) {
  21871. s.gzindex = 0;
  21872. s.status = NAME_STATE;
  21873. }
  21874. }
  21875. else {
  21876. s.status = NAME_STATE;
  21877. }
  21878. }
  21879. if (s.status === NAME_STATE) {
  21880. if (s.gzhead.name/* != Z_NULL*/) {
  21881. beg = s.pending; /* start of bytes to update crc */
  21882. //int val;
  21883. do {
  21884. if (s.pending === s.pending_buf_size) {
  21885. if (s.gzhead.hcrc && s.pending > beg) {
  21886. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21887. }
  21888. flush_pending(strm);
  21889. beg = s.pending;
  21890. if (s.pending === s.pending_buf_size) {
  21891. val = 1;
  21892. break;
  21893. }
  21894. }
  21895. // JS specific: little magic to add zero terminator to end of string
  21896. if (s.gzindex < s.gzhead.name.length) {
  21897. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21898. } else {
  21899. val = 0;
  21900. }
  21901. put_byte(s, val);
  21902. } while (val !== 0);
  21903. if (s.gzhead.hcrc && s.pending > beg) {
  21904. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21905. }
  21906. if (val === 0) {
  21907. s.gzindex = 0;
  21908. s.status = COMMENT_STATE;
  21909. }
  21910. }
  21911. else {
  21912. s.status = COMMENT_STATE;
  21913. }
  21914. }
  21915. if (s.status === COMMENT_STATE) {
  21916. if (s.gzhead.comment/* != Z_NULL*/) {
  21917. beg = s.pending; /* start of bytes to update crc */
  21918. //int val;
  21919. do {
  21920. if (s.pending === s.pending_buf_size) {
  21921. if (s.gzhead.hcrc && s.pending > beg) {
  21922. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21923. }
  21924. flush_pending(strm);
  21925. beg = s.pending;
  21926. if (s.pending === s.pending_buf_size) {
  21927. val = 1;
  21928. break;
  21929. }
  21930. }
  21931. // JS specific: little magic to add zero terminator to end of string
  21932. if (s.gzindex < s.gzhead.comment.length) {
  21933. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21934. } else {
  21935. val = 0;
  21936. }
  21937. put_byte(s, val);
  21938. } while (val !== 0);
  21939. if (s.gzhead.hcrc && s.pending > beg) {
  21940. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21941. }
  21942. if (val === 0) {
  21943. s.status = HCRC_STATE;
  21944. }
  21945. }
  21946. else {
  21947. s.status = HCRC_STATE;
  21948. }
  21949. }
  21950. if (s.status === HCRC_STATE) {
  21951. if (s.gzhead.hcrc) {
  21952. if (s.pending + 2 > s.pending_buf_size) {
  21953. flush_pending(strm);
  21954. }
  21955. if (s.pending + 2 <= s.pending_buf_size) {
  21956. put_byte(s, strm.adler & 0xff);
  21957. put_byte(s, (strm.adler >> 8) & 0xff);
  21958. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21959. s.status = BUSY_STATE;
  21960. }
  21961. }
  21962. else {
  21963. s.status = BUSY_STATE;
  21964. }
  21965. }
  21966. //#endif
  21967. /* Flush as much pending output as possible */
  21968. if (s.pending !== 0) {
  21969. flush_pending(strm);
  21970. if (strm.avail_out === 0) {
  21971. /* Since avail_out is 0, deflate will be called again with
  21972. * more output space, but possibly with both pending and
  21973. * avail_in equal to zero. There won't be anything to do,
  21974. * but this is not an error situation so make sure we
  21975. * return OK instead of BUF_ERROR at next call of deflate:
  21976. */
  21977. s.last_flush = -1;
  21978. return Z_OK;
  21979. }
  21980. /* Make sure there is something to do and avoid duplicate consecutive
  21981. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21982. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21983. */
  21984. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21985. flush !== Z_FINISH) {
  21986. return err(strm, Z_BUF_ERROR);
  21987. }
  21988. /* User must not provide more input after the first FINISH: */
  21989. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21990. return err(strm, Z_BUF_ERROR);
  21991. }
  21992. /* Start a new block or continue the current one.
  21993. */
  21994. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21995. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21996. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21997. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21998. configuration_table[s.level].func(s, flush));
  21999. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22000. s.status = FINISH_STATE;
  22001. }
  22002. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22003. if (strm.avail_out === 0) {
  22004. s.last_flush = -1;
  22005. /* avoid BUF_ERROR next call, see above */
  22006. }
  22007. return Z_OK;
  22008. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22009. * of deflate should use the same flush parameter to make sure
  22010. * that the flush is complete. So we don't have to output an
  22011. * empty block here, this will be done at next call. This also
  22012. * ensures that for a very small output buffer, we emit at most
  22013. * one empty block.
  22014. */
  22015. }
  22016. if (bstate === BS_BLOCK_DONE) {
  22017. if (flush === Z_PARTIAL_FLUSH) {
  22018. trees._tr_align(s);
  22019. }
  22020. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22021. trees._tr_stored_block(s, 0, 0, false);
  22022. /* For a full flush, this empty block will be recognized
  22023. * as a special marker by inflate_sync().
  22024. */
  22025. if (flush === Z_FULL_FLUSH) {
  22026. /*** CLEAR_HASH(s); ***/ /* forget history */
  22027. zero(s.head); // Fill with NIL (= 0);
  22028. if (s.lookahead === 0) {
  22029. s.strstart = 0;
  22030. s.block_start = 0;
  22031. s.insert = 0;
  22032. }
  22033. }
  22034. }
  22035. flush_pending(strm);
  22036. if (strm.avail_out === 0) {
  22037. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22038. return Z_OK;
  22039. }
  22040. }
  22041. }
  22042. //Assert(strm->avail_out > 0, "bug2");
  22043. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22044. if (flush !== Z_FINISH) { return Z_OK; }
  22045. if (s.wrap <= 0) { return Z_STREAM_END; }
  22046. /* Write the trailer */
  22047. if (s.wrap === 2) {
  22048. put_byte(s, strm.adler & 0xff);
  22049. put_byte(s, (strm.adler >> 8) & 0xff);
  22050. put_byte(s, (strm.adler >> 16) & 0xff);
  22051. put_byte(s, (strm.adler >> 24) & 0xff);
  22052. put_byte(s, strm.total_in & 0xff);
  22053. put_byte(s, (strm.total_in >> 8) & 0xff);
  22054. put_byte(s, (strm.total_in >> 16) & 0xff);
  22055. put_byte(s, (strm.total_in >> 24) & 0xff);
  22056. }
  22057. else
  22058. {
  22059. putShortMSB(s, strm.adler >>> 16);
  22060. putShortMSB(s, strm.adler & 0xffff);
  22061. }
  22062. flush_pending(strm);
  22063. /* If avail_out is zero, the application will call deflate again
  22064. * to flush the rest.
  22065. */
  22066. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22067. /* write the trailer only once! */
  22068. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22069. }
  22070. function deflateEnd(strm) {
  22071. var status;
  22072. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22073. return Z_STREAM_ERROR;
  22074. }
  22075. status = strm.state.status;
  22076. if (status !== INIT_STATE &&
  22077. status !== EXTRA_STATE &&
  22078. status !== NAME_STATE &&
  22079. status !== COMMENT_STATE &&
  22080. status !== HCRC_STATE &&
  22081. status !== BUSY_STATE &&
  22082. status !== FINISH_STATE
  22083. ) {
  22084. return err(strm, Z_STREAM_ERROR);
  22085. }
  22086. strm.state = null;
  22087. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22088. }
  22089. /* =========================================================================
  22090. * Copy the source state to the destination state
  22091. */
  22092. //function deflateCopy(dest, source) {
  22093. //
  22094. //}
  22095. exports.deflateInit = deflateInit;
  22096. exports.deflateInit2 = deflateInit2;
  22097. exports.deflateReset = deflateReset;
  22098. exports.deflateResetKeep = deflateResetKeep;
  22099. exports.deflateSetHeader = deflateSetHeader;
  22100. exports.deflate = deflate;
  22101. exports.deflateEnd = deflateEnd;
  22102. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22103. /* Not implemented
  22104. exports.deflateBound = deflateBound;
  22105. exports.deflateCopy = deflateCopy;
  22106. exports.deflateSetDictionary = deflateSetDictionary;
  22107. exports.deflateParams = deflateParams;
  22108. exports.deflatePending = deflatePending;
  22109. exports.deflatePrime = deflatePrime;
  22110. exports.deflateTune = deflateTune;
  22111. */
  22112. },{"../utils/common":74,"./adler32":76,"./crc32":78,"./messages":84,"./trees":85}],80:[function(require,module,exports){
  22113. 'use strict';
  22114. function GZheader() {
  22115. /* true if compressed data believed to be text */
  22116. this.text = 0;
  22117. /* modification time */
  22118. this.time = 0;
  22119. /* extra flags (not used when writing a gzip file) */
  22120. this.xflags = 0;
  22121. /* operating system */
  22122. this.os = 0;
  22123. /* pointer to extra field or Z_NULL if none */
  22124. this.extra = null;
  22125. /* extra field length (valid if extra != Z_NULL) */
  22126. this.extra_len = 0; // Actually, we don't need it in JS,
  22127. // but leave for few code modifications
  22128. //
  22129. // Setup limits is not necessary because in js we should not preallocate memory
  22130. // for inflate use constant limit in 65536 bytes
  22131. //
  22132. /* space at extra (only when reading header) */
  22133. // this.extra_max = 0;
  22134. /* pointer to zero-terminated file name or Z_NULL */
  22135. this.name = '';
  22136. /* space at name (only when reading header) */
  22137. // this.name_max = 0;
  22138. /* pointer to zero-terminated comment or Z_NULL */
  22139. this.comment = '';
  22140. /* space at comment (only when reading header) */
  22141. // this.comm_max = 0;
  22142. /* true if there was or will be a header crc */
  22143. this.hcrc = 0;
  22144. /* true when done reading gzip header (not used when writing a gzip file) */
  22145. this.done = false;
  22146. }
  22147. module.exports = GZheader;
  22148. },{}],81:[function(require,module,exports){
  22149. 'use strict';
  22150. // See state defs from inflate.js
  22151. var BAD = 30; /* got a data error -- remain here until reset */
  22152. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22153. /*
  22154. Decode literal, length, and distance codes and write out the resulting
  22155. literal and match bytes until either not enough input or output is
  22156. available, an end-of-block is encountered, or a data error is encountered.
  22157. When large enough input and output buffers are supplied to inflate(), for
  22158. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22159. inflate execution time is spent in this routine.
  22160. Entry assumptions:
  22161. state.mode === LEN
  22162. strm.avail_in >= 6
  22163. strm.avail_out >= 258
  22164. start >= strm.avail_out
  22165. state.bits < 8
  22166. On return, state.mode is one of:
  22167. LEN -- ran out of enough output space or enough available input
  22168. TYPE -- reached end of block code, inflate() to interpret next block
  22169. BAD -- error in block data
  22170. Notes:
  22171. - The maximum input bits used by a length/distance pair is 15 bits for the
  22172. length code, 5 bits for the length extra, 15 bits for the distance code,
  22173. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22174. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22175. checking for available input while decoding.
  22176. - The maximum bytes that a single length/distance pair can output is 258
  22177. bytes, which is the maximum length that can be coded. inflate_fast()
  22178. requires strm.avail_out >= 258 for each loop to avoid checking for
  22179. output space.
  22180. */
  22181. module.exports = function inflate_fast(strm, start) {
  22182. var state;
  22183. var _in; /* local strm.input */
  22184. var last; /* have enough input while in < last */
  22185. var _out; /* local strm.output */
  22186. var beg; /* inflate()'s initial strm.output */
  22187. var end; /* while out < end, enough space available */
  22188. //#ifdef INFLATE_STRICT
  22189. var dmax; /* maximum distance from zlib header */
  22190. //#endif
  22191. var wsize; /* window size or zero if not using window */
  22192. var whave; /* valid bytes in the window */
  22193. var wnext; /* window write index */
  22194. var window; /* allocated sliding window, if wsize != 0 */
  22195. var hold; /* local strm.hold */
  22196. var bits; /* local strm.bits */
  22197. var lcode; /* local strm.lencode */
  22198. var dcode; /* local strm.distcode */
  22199. var lmask; /* mask for first level of length codes */
  22200. var dmask; /* mask for first level of distance codes */
  22201. var here; /* retrieved table entry */
  22202. var op; /* code bits, operation, extra bits, or */
  22203. /* window position, window bytes to copy */
  22204. var len; /* match length, unused bytes */
  22205. var dist; /* match distance */
  22206. var from; /* where to copy match from */
  22207. var from_source;
  22208. var input, output; // JS specific, because we have no pointers
  22209. /* copy state to local variables */
  22210. state = strm.state;
  22211. //here = state.here;
  22212. _in = strm.next_in;
  22213. input = strm.input;
  22214. last = _in + (strm.avail_in - 5);
  22215. _out = strm.next_out;
  22216. output = strm.output;
  22217. beg = _out - (start - strm.avail_out);
  22218. end = _out + (strm.avail_out - 257);
  22219. //#ifdef INFLATE_STRICT
  22220. dmax = state.dmax;
  22221. //#endif
  22222. wsize = state.wsize;
  22223. whave = state.whave;
  22224. wnext = state.wnext;
  22225. window = state.window;
  22226. hold = state.hold;
  22227. bits = state.bits;
  22228. lcode = state.lencode;
  22229. dcode = state.distcode;
  22230. lmask = (1 << state.lenbits) - 1;
  22231. dmask = (1 << state.distbits) - 1;
  22232. /* decode literals and length/distances until end-of-block or not enough
  22233. input data or output space */
  22234. top:
  22235. do {
  22236. if (bits < 15) {
  22237. hold += input[_in++] << bits;
  22238. bits += 8;
  22239. hold += input[_in++] << bits;
  22240. bits += 8;
  22241. }
  22242. here = lcode[hold & lmask];
  22243. dolen:
  22244. for (;;) { // Goto emulation
  22245. op = here >>> 24/*here.bits*/;
  22246. hold >>>= op;
  22247. bits -= op;
  22248. op = (here >>> 16) & 0xff/*here.op*/;
  22249. if (op === 0) { /* literal */
  22250. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22251. // "inflate: literal '%c'\n" :
  22252. // "inflate: literal 0x%02x\n", here.val));
  22253. output[_out++] = here & 0xffff/*here.val*/;
  22254. }
  22255. else if (op & 16) { /* length base */
  22256. len = here & 0xffff/*here.val*/;
  22257. op &= 15; /* number of extra bits */
  22258. if (op) {
  22259. if (bits < op) {
  22260. hold += input[_in++] << bits;
  22261. bits += 8;
  22262. }
  22263. len += hold & ((1 << op) - 1);
  22264. hold >>>= op;
  22265. bits -= op;
  22266. }
  22267. //Tracevv((stderr, "inflate: length %u\n", len));
  22268. if (bits < 15) {
  22269. hold += input[_in++] << bits;
  22270. bits += 8;
  22271. hold += input[_in++] << bits;
  22272. bits += 8;
  22273. }
  22274. here = dcode[hold & dmask];
  22275. dodist:
  22276. for (;;) { // goto emulation
  22277. op = here >>> 24/*here.bits*/;
  22278. hold >>>= op;
  22279. bits -= op;
  22280. op = (here >>> 16) & 0xff/*here.op*/;
  22281. if (op & 16) { /* distance base */
  22282. dist = here & 0xffff/*here.val*/;
  22283. op &= 15; /* number of extra bits */
  22284. if (bits < op) {
  22285. hold += input[_in++] << bits;
  22286. bits += 8;
  22287. if (bits < op) {
  22288. hold += input[_in++] << bits;
  22289. bits += 8;
  22290. }
  22291. }
  22292. dist += hold & ((1 << op) - 1);
  22293. //#ifdef INFLATE_STRICT
  22294. if (dist > dmax) {
  22295. strm.msg = 'invalid distance too far back';
  22296. state.mode = BAD;
  22297. break top;
  22298. }
  22299. //#endif
  22300. hold >>>= op;
  22301. bits -= op;
  22302. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22303. op = _out - beg; /* max distance in output */
  22304. if (dist > op) { /* see if copy from window */
  22305. op = dist - op; /* distance back in window */
  22306. if (op > whave) {
  22307. if (state.sane) {
  22308. strm.msg = 'invalid distance too far back';
  22309. state.mode = BAD;
  22310. break top;
  22311. }
  22312. // (!) This block is disabled in zlib defailts,
  22313. // don't enable it for binary compatibility
  22314. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22315. // if (len <= op - whave) {
  22316. // do {
  22317. // output[_out++] = 0;
  22318. // } while (--len);
  22319. // continue top;
  22320. // }
  22321. // len -= op - whave;
  22322. // do {
  22323. // output[_out++] = 0;
  22324. // } while (--op > whave);
  22325. // if (op === 0) {
  22326. // from = _out - dist;
  22327. // do {
  22328. // output[_out++] = output[from++];
  22329. // } while (--len);
  22330. // continue top;
  22331. // }
  22332. //#endif
  22333. }
  22334. from = 0; // window index
  22335. from_source = window;
  22336. if (wnext === 0) { /* very common case */
  22337. from += wsize - op;
  22338. if (op < len) { /* some from window */
  22339. len -= op;
  22340. do {
  22341. output[_out++] = window[from++];
  22342. } while (--op);
  22343. from = _out - dist; /* rest from output */
  22344. from_source = output;
  22345. }
  22346. }
  22347. else if (wnext < op) { /* wrap around window */
  22348. from += wsize + wnext - op;
  22349. op -= wnext;
  22350. if (op < len) { /* some from end of window */
  22351. len -= op;
  22352. do {
  22353. output[_out++] = window[from++];
  22354. } while (--op);
  22355. from = 0;
  22356. if (wnext < len) { /* some from start of window */
  22357. op = wnext;
  22358. len -= op;
  22359. do {
  22360. output[_out++] = window[from++];
  22361. } while (--op);
  22362. from = _out - dist; /* rest from output */
  22363. from_source = output;
  22364. }
  22365. }
  22366. }
  22367. else { /* contiguous in window */
  22368. from += wnext - op;
  22369. if (op < len) { /* some from window */
  22370. len -= op;
  22371. do {
  22372. output[_out++] = window[from++];
  22373. } while (--op);
  22374. from = _out - dist; /* rest from output */
  22375. from_source = output;
  22376. }
  22377. }
  22378. while (len > 2) {
  22379. output[_out++] = from_source[from++];
  22380. output[_out++] = from_source[from++];
  22381. output[_out++] = from_source[from++];
  22382. len -= 3;
  22383. }
  22384. if (len) {
  22385. output[_out++] = from_source[from++];
  22386. if (len > 1) {
  22387. output[_out++] = from_source[from++];
  22388. }
  22389. }
  22390. }
  22391. else {
  22392. from = _out - dist; /* copy direct from output */
  22393. do { /* minimum length is three */
  22394. output[_out++] = output[from++];
  22395. output[_out++] = output[from++];
  22396. output[_out++] = output[from++];
  22397. len -= 3;
  22398. } while (len > 2);
  22399. if (len) {
  22400. output[_out++] = output[from++];
  22401. if (len > 1) {
  22402. output[_out++] = output[from++];
  22403. }
  22404. }
  22405. }
  22406. }
  22407. else if ((op & 64) === 0) { /* 2nd level distance code */
  22408. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22409. continue dodist;
  22410. }
  22411. else {
  22412. strm.msg = 'invalid distance code';
  22413. state.mode = BAD;
  22414. break top;
  22415. }
  22416. break; // need to emulate goto via "continue"
  22417. }
  22418. }
  22419. else if ((op & 64) === 0) { /* 2nd level length code */
  22420. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22421. continue dolen;
  22422. }
  22423. else if (op & 32) { /* end-of-block */
  22424. //Tracevv((stderr, "inflate: end of block\n"));
  22425. state.mode = TYPE;
  22426. break top;
  22427. }
  22428. else {
  22429. strm.msg = 'invalid literal/length code';
  22430. state.mode = BAD;
  22431. break top;
  22432. }
  22433. break; // need to emulate goto via "continue"
  22434. }
  22435. } while (_in < last && _out < end);
  22436. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22437. len = bits >> 3;
  22438. _in -= len;
  22439. bits -= len << 3;
  22440. hold &= (1 << bits) - 1;
  22441. /* update state and return */
  22442. strm.next_in = _in;
  22443. strm.next_out = _out;
  22444. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22445. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22446. state.hold = hold;
  22447. state.bits = bits;
  22448. return;
  22449. };
  22450. },{}],82:[function(require,module,exports){
  22451. 'use strict';
  22452. var utils = require('../utils/common');
  22453. var adler32 = require('./adler32');
  22454. var crc32 = require('./crc32');
  22455. var inflate_fast = require('./inffast');
  22456. var inflate_table = require('./inftrees');
  22457. var CODES = 0;
  22458. var LENS = 1;
  22459. var DISTS = 2;
  22460. /* Public constants ==========================================================*/
  22461. /* ===========================================================================*/
  22462. /* Allowed flush values; see deflate() and inflate() below for details */
  22463. //var Z_NO_FLUSH = 0;
  22464. //var Z_PARTIAL_FLUSH = 1;
  22465. //var Z_SYNC_FLUSH = 2;
  22466. //var Z_FULL_FLUSH = 3;
  22467. var Z_FINISH = 4;
  22468. var Z_BLOCK = 5;
  22469. var Z_TREES = 6;
  22470. /* Return codes for the compression/decompression functions. Negative values
  22471. * are errors, positive values are used for special but normal events.
  22472. */
  22473. var Z_OK = 0;
  22474. var Z_STREAM_END = 1;
  22475. var Z_NEED_DICT = 2;
  22476. //var Z_ERRNO = -1;
  22477. var Z_STREAM_ERROR = -2;
  22478. var Z_DATA_ERROR = -3;
  22479. var Z_MEM_ERROR = -4;
  22480. var Z_BUF_ERROR = -5;
  22481. //var Z_VERSION_ERROR = -6;
  22482. /* The deflate compression method */
  22483. var Z_DEFLATED = 8;
  22484. /* STATES ====================================================================*/
  22485. /* ===========================================================================*/
  22486. var HEAD = 1; /* i: waiting for magic header */
  22487. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22488. var TIME = 3; /* i: waiting for modification time (gzip) */
  22489. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22490. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22491. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22492. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22493. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22494. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22495. var DICTID = 10; /* i: waiting for dictionary check value */
  22496. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22497. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22498. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22499. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22500. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22501. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22502. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22503. var LENLENS = 18; /* i: waiting for code length code lengths */
  22504. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22505. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22506. var LEN = 21; /* i: waiting for length/lit/eob code */
  22507. var LENEXT = 22; /* i: waiting for length extra bits */
  22508. var DIST = 23; /* i: waiting for distance code */
  22509. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22510. var MATCH = 25; /* o: waiting for output space to copy string */
  22511. var LIT = 26; /* o: waiting for output space to write literal */
  22512. var CHECK = 27; /* i: waiting for 32-bit check value */
  22513. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22514. var DONE = 29; /* finished check, done -- remain here until reset */
  22515. var BAD = 30; /* got a data error -- remain here until reset */
  22516. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22517. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22518. /* ===========================================================================*/
  22519. var ENOUGH_LENS = 852;
  22520. var ENOUGH_DISTS = 592;
  22521. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22522. var MAX_WBITS = 15;
  22523. /* 32K LZ77 window */
  22524. var DEF_WBITS = MAX_WBITS;
  22525. function ZSWAP32(q) {
  22526. return (((q >>> 24) & 0xff) +
  22527. ((q >>> 8) & 0xff00) +
  22528. ((q & 0xff00) << 8) +
  22529. ((q & 0xff) << 24));
  22530. }
  22531. function InflateState() {
  22532. this.mode = 0; /* current inflate mode */
  22533. this.last = false; /* true if processing last block */
  22534. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22535. this.havedict = false; /* true if dictionary provided */
  22536. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22537. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22538. this.check = 0; /* protected copy of check value */
  22539. this.total = 0; /* protected copy of output count */
  22540. // TODO: may be {}
  22541. this.head = null; /* where to save gzip header information */
  22542. /* sliding window */
  22543. this.wbits = 0; /* log base 2 of requested window size */
  22544. this.wsize = 0; /* window size or zero if not using window */
  22545. this.whave = 0; /* valid bytes in the window */
  22546. this.wnext = 0; /* window write index */
  22547. this.window = null; /* allocated sliding window, if needed */
  22548. /* bit accumulator */
  22549. this.hold = 0; /* input bit accumulator */
  22550. this.bits = 0; /* number of bits in "in" */
  22551. /* for string and stored block copying */
  22552. this.length = 0; /* literal or length of data to copy */
  22553. this.offset = 0; /* distance back to copy string from */
  22554. /* for table and code decoding */
  22555. this.extra = 0; /* extra bits needed */
  22556. /* fixed and dynamic code tables */
  22557. this.lencode = null; /* starting table for length/literal codes */
  22558. this.distcode = null; /* starting table for distance codes */
  22559. this.lenbits = 0; /* index bits for lencode */
  22560. this.distbits = 0; /* index bits for distcode */
  22561. /* dynamic table building */
  22562. this.ncode = 0; /* number of code length code lengths */
  22563. this.nlen = 0; /* number of length code lengths */
  22564. this.ndist = 0; /* number of distance code lengths */
  22565. this.have = 0; /* number of code lengths in lens[] */
  22566. this.next = null; /* next available space in codes[] */
  22567. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22568. this.work = new utils.Buf16(288); /* work area for code table building */
  22569. /*
  22570. because we don't have pointers in js, we use lencode and distcode directly
  22571. as buffers so we don't need codes
  22572. */
  22573. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22574. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22575. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22576. this.sane = 0; /* if false, allow invalid distance too far */
  22577. this.back = 0; /* bits back of last unprocessed length/lit */
  22578. this.was = 0; /* initial length of match */
  22579. }
  22580. function inflateResetKeep(strm) {
  22581. var state;
  22582. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22583. state = strm.state;
  22584. strm.total_in = strm.total_out = state.total = 0;
  22585. strm.msg = ''; /*Z_NULL*/
  22586. if (state.wrap) { /* to support ill-conceived Java test suite */
  22587. strm.adler = state.wrap & 1;
  22588. }
  22589. state.mode = HEAD;
  22590. state.last = 0;
  22591. state.havedict = 0;
  22592. state.dmax = 32768;
  22593. state.head = null/*Z_NULL*/;
  22594. state.hold = 0;
  22595. state.bits = 0;
  22596. //state.lencode = state.distcode = state.next = state.codes;
  22597. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22598. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22599. state.sane = 1;
  22600. state.back = -1;
  22601. //Tracev((stderr, "inflate: reset\n"));
  22602. return Z_OK;
  22603. }
  22604. function inflateReset(strm) {
  22605. var state;
  22606. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22607. state = strm.state;
  22608. state.wsize = 0;
  22609. state.whave = 0;
  22610. state.wnext = 0;
  22611. return inflateResetKeep(strm);
  22612. }
  22613. function inflateReset2(strm, windowBits) {
  22614. var wrap;
  22615. var state;
  22616. /* get the state */
  22617. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22618. state = strm.state;
  22619. /* extract wrap request from windowBits parameter */
  22620. if (windowBits < 0) {
  22621. wrap = 0;
  22622. windowBits = -windowBits;
  22623. }
  22624. else {
  22625. wrap = (windowBits >> 4) + 1;
  22626. if (windowBits < 48) {
  22627. windowBits &= 15;
  22628. }
  22629. }
  22630. /* set number of window bits, free window if different */
  22631. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22632. return Z_STREAM_ERROR;
  22633. }
  22634. if (state.window !== null && state.wbits !== windowBits) {
  22635. state.window = null;
  22636. }
  22637. /* update state and reset the rest of it */
  22638. state.wrap = wrap;
  22639. state.wbits = windowBits;
  22640. return inflateReset(strm);
  22641. }
  22642. function inflateInit2(strm, windowBits) {
  22643. var ret;
  22644. var state;
  22645. if (!strm) { return Z_STREAM_ERROR; }
  22646. //strm.msg = Z_NULL; /* in case we return an error */
  22647. state = new InflateState();
  22648. //if (state === Z_NULL) return Z_MEM_ERROR;
  22649. //Tracev((stderr, "inflate: allocated\n"));
  22650. strm.state = state;
  22651. state.window = null/*Z_NULL*/;
  22652. ret = inflateReset2(strm, windowBits);
  22653. if (ret !== Z_OK) {
  22654. strm.state = null/*Z_NULL*/;
  22655. }
  22656. return ret;
  22657. }
  22658. function inflateInit(strm) {
  22659. return inflateInit2(strm, DEF_WBITS);
  22660. }
  22661. /*
  22662. Return state with length and distance decoding tables and index sizes set to
  22663. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22664. If BUILDFIXED is defined, then instead this routine builds the tables the
  22665. first time it's called, and returns those tables the first time and
  22666. thereafter. This reduces the size of the code by about 2K bytes, in
  22667. exchange for a little execution time. However, BUILDFIXED should not be
  22668. used for threaded applications, since the rewriting of the tables and virgin
  22669. may not be thread-safe.
  22670. */
  22671. var virgin = true;
  22672. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22673. function fixedtables(state) {
  22674. /* build fixed huffman tables if first call (may not be thread safe) */
  22675. if (virgin) {
  22676. var sym;
  22677. lenfix = new utils.Buf32(512);
  22678. distfix = new utils.Buf32(32);
  22679. /* literal/length table */
  22680. sym = 0;
  22681. while (sym < 144) { state.lens[sym++] = 8; }
  22682. while (sym < 256) { state.lens[sym++] = 9; }
  22683. while (sym < 280) { state.lens[sym++] = 7; }
  22684. while (sym < 288) { state.lens[sym++] = 8; }
  22685. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22686. /* distance table */
  22687. sym = 0;
  22688. while (sym < 32) { state.lens[sym++] = 5; }
  22689. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22690. /* do this just once */
  22691. virgin = false;
  22692. }
  22693. state.lencode = lenfix;
  22694. state.lenbits = 9;
  22695. state.distcode = distfix;
  22696. state.distbits = 5;
  22697. }
  22698. /*
  22699. Update the window with the last wsize (normally 32K) bytes written before
  22700. returning. If window does not exist yet, create it. This is only called
  22701. when a window is already in use, or when output has been written during this
  22702. inflate call, but the end of the deflate stream has not been reached yet.
  22703. It is also called to create a window for dictionary data when a dictionary
  22704. is loaded.
  22705. Providing output buffers larger than 32K to inflate() should provide a speed
  22706. advantage, since only the last 32K of output is copied to the sliding window
  22707. upon return from inflate(), and since all distances after the first 32K of
  22708. output will fall in the output data, making match copies simpler and faster.
  22709. The advantage may be dependent on the size of the processor's data caches.
  22710. */
  22711. function updatewindow(strm, src, end, copy) {
  22712. var dist;
  22713. var state = strm.state;
  22714. /* if it hasn't been done already, allocate space for the window */
  22715. if (state.window === null) {
  22716. state.wsize = 1 << state.wbits;
  22717. state.wnext = 0;
  22718. state.whave = 0;
  22719. state.window = new utils.Buf8(state.wsize);
  22720. }
  22721. /* copy state->wsize or less output bytes into the circular window */
  22722. if (copy >= state.wsize) {
  22723. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22724. state.wnext = 0;
  22725. state.whave = state.wsize;
  22726. }
  22727. else {
  22728. dist = state.wsize - state.wnext;
  22729. if (dist > copy) {
  22730. dist = copy;
  22731. }
  22732. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22733. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22734. copy -= dist;
  22735. if (copy) {
  22736. //zmemcpy(state->window, end - copy, copy);
  22737. utils.arraySet(state.window,src, end - copy, copy, 0);
  22738. state.wnext = copy;
  22739. state.whave = state.wsize;
  22740. }
  22741. else {
  22742. state.wnext += dist;
  22743. if (state.wnext === state.wsize) { state.wnext = 0; }
  22744. if (state.whave < state.wsize) { state.whave += dist; }
  22745. }
  22746. }
  22747. return 0;
  22748. }
  22749. function inflate(strm, flush) {
  22750. var state;
  22751. var input, output; // input/output buffers
  22752. var next; /* next input INDEX */
  22753. var put; /* next output INDEX */
  22754. var have, left; /* available input and output */
  22755. var hold; /* bit buffer */
  22756. var bits; /* bits in bit buffer */
  22757. var _in, _out; /* save starting available input and output */
  22758. var copy; /* number of stored or match bytes to copy */
  22759. var from; /* where to copy match bytes from */
  22760. var from_source;
  22761. var here = 0; /* current decoding table entry */
  22762. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22763. //var last; /* parent table entry */
  22764. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22765. var len; /* length to copy for repeats, bits to drop */
  22766. var ret; /* return code */
  22767. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22768. var opts;
  22769. var n; // temporary var for NEED_BITS
  22770. var order = /* permutation of code lengths */
  22771. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22772. if (!strm || !strm.state || !strm.output ||
  22773. (!strm.input && strm.avail_in !== 0)) {
  22774. return Z_STREAM_ERROR;
  22775. }
  22776. state = strm.state;
  22777. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22778. //--- LOAD() ---
  22779. put = strm.next_out;
  22780. output = strm.output;
  22781. left = strm.avail_out;
  22782. next = strm.next_in;
  22783. input = strm.input;
  22784. have = strm.avail_in;
  22785. hold = state.hold;
  22786. bits = state.bits;
  22787. //---
  22788. _in = have;
  22789. _out = left;
  22790. ret = Z_OK;
  22791. inf_leave: // goto emulation
  22792. for (;;) {
  22793. switch (state.mode) {
  22794. case HEAD:
  22795. if (state.wrap === 0) {
  22796. state.mode = TYPEDO;
  22797. break;
  22798. }
  22799. //=== NEEDBITS(16);
  22800. while (bits < 16) {
  22801. if (have === 0) { break inf_leave; }
  22802. have--;
  22803. hold += input[next++] << bits;
  22804. bits += 8;
  22805. }
  22806. //===//
  22807. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22808. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22809. //=== CRC2(state.check, hold);
  22810. hbuf[0] = hold & 0xff;
  22811. hbuf[1] = (hold >>> 8) & 0xff;
  22812. state.check = crc32(state.check, hbuf, 2, 0);
  22813. //===//
  22814. //=== INITBITS();
  22815. hold = 0;
  22816. bits = 0;
  22817. //===//
  22818. state.mode = FLAGS;
  22819. break;
  22820. }
  22821. state.flags = 0; /* expect zlib header */
  22822. if (state.head) {
  22823. state.head.done = false;
  22824. }
  22825. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22826. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22827. strm.msg = 'incorrect header check';
  22828. state.mode = BAD;
  22829. break;
  22830. }
  22831. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22832. strm.msg = 'unknown compression method';
  22833. state.mode = BAD;
  22834. break;
  22835. }
  22836. //--- DROPBITS(4) ---//
  22837. hold >>>= 4;
  22838. bits -= 4;
  22839. //---//
  22840. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22841. if (state.wbits === 0) {
  22842. state.wbits = len;
  22843. }
  22844. else if (len > state.wbits) {
  22845. strm.msg = 'invalid window size';
  22846. state.mode = BAD;
  22847. break;
  22848. }
  22849. state.dmax = 1 << len;
  22850. //Tracev((stderr, "inflate: zlib header ok\n"));
  22851. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22852. state.mode = hold & 0x200 ? DICTID : TYPE;
  22853. //=== INITBITS();
  22854. hold = 0;
  22855. bits = 0;
  22856. //===//
  22857. break;
  22858. case FLAGS:
  22859. //=== NEEDBITS(16); */
  22860. while (bits < 16) {
  22861. if (have === 0) { break inf_leave; }
  22862. have--;
  22863. hold += input[next++] << bits;
  22864. bits += 8;
  22865. }
  22866. //===//
  22867. state.flags = hold;
  22868. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22869. strm.msg = 'unknown compression method';
  22870. state.mode = BAD;
  22871. break;
  22872. }
  22873. if (state.flags & 0xe000) {
  22874. strm.msg = 'unknown header flags set';
  22875. state.mode = BAD;
  22876. break;
  22877. }
  22878. if (state.head) {
  22879. state.head.text = ((hold >> 8) & 1);
  22880. }
  22881. if (state.flags & 0x0200) {
  22882. //=== CRC2(state.check, hold);
  22883. hbuf[0] = hold & 0xff;
  22884. hbuf[1] = (hold >>> 8) & 0xff;
  22885. state.check = crc32(state.check, hbuf, 2, 0);
  22886. //===//
  22887. }
  22888. //=== INITBITS();
  22889. hold = 0;
  22890. bits = 0;
  22891. //===//
  22892. state.mode = TIME;
  22893. /* falls through */
  22894. case TIME:
  22895. //=== NEEDBITS(32); */
  22896. while (bits < 32) {
  22897. if (have === 0) { break inf_leave; }
  22898. have--;
  22899. hold += input[next++] << bits;
  22900. bits += 8;
  22901. }
  22902. //===//
  22903. if (state.head) {
  22904. state.head.time = hold;
  22905. }
  22906. if (state.flags & 0x0200) {
  22907. //=== CRC4(state.check, hold)
  22908. hbuf[0] = hold & 0xff;
  22909. hbuf[1] = (hold >>> 8) & 0xff;
  22910. hbuf[2] = (hold >>> 16) & 0xff;
  22911. hbuf[3] = (hold >>> 24) & 0xff;
  22912. state.check = crc32(state.check, hbuf, 4, 0);
  22913. //===
  22914. }
  22915. //=== INITBITS();
  22916. hold = 0;
  22917. bits = 0;
  22918. //===//
  22919. state.mode = OS;
  22920. /* falls through */
  22921. case OS:
  22922. //=== NEEDBITS(16); */
  22923. while (bits < 16) {
  22924. if (have === 0) { break inf_leave; }
  22925. have--;
  22926. hold += input[next++] << bits;
  22927. bits += 8;
  22928. }
  22929. //===//
  22930. if (state.head) {
  22931. state.head.xflags = (hold & 0xff);
  22932. state.head.os = (hold >> 8);
  22933. }
  22934. if (state.flags & 0x0200) {
  22935. //=== CRC2(state.check, hold);
  22936. hbuf[0] = hold & 0xff;
  22937. hbuf[1] = (hold >>> 8) & 0xff;
  22938. state.check = crc32(state.check, hbuf, 2, 0);
  22939. //===//
  22940. }
  22941. //=== INITBITS();
  22942. hold = 0;
  22943. bits = 0;
  22944. //===//
  22945. state.mode = EXLEN;
  22946. /* falls through */
  22947. case EXLEN:
  22948. if (state.flags & 0x0400) {
  22949. //=== NEEDBITS(16); */
  22950. while (bits < 16) {
  22951. if (have === 0) { break inf_leave; }
  22952. have--;
  22953. hold += input[next++] << bits;
  22954. bits += 8;
  22955. }
  22956. //===//
  22957. state.length = hold;
  22958. if (state.head) {
  22959. state.head.extra_len = hold;
  22960. }
  22961. if (state.flags & 0x0200) {
  22962. //=== CRC2(state.check, hold);
  22963. hbuf[0] = hold & 0xff;
  22964. hbuf[1] = (hold >>> 8) & 0xff;
  22965. state.check = crc32(state.check, hbuf, 2, 0);
  22966. //===//
  22967. }
  22968. //=== INITBITS();
  22969. hold = 0;
  22970. bits = 0;
  22971. //===//
  22972. }
  22973. else if (state.head) {
  22974. state.head.extra = null/*Z_NULL*/;
  22975. }
  22976. state.mode = EXTRA;
  22977. /* falls through */
  22978. case EXTRA:
  22979. if (state.flags & 0x0400) {
  22980. copy = state.length;
  22981. if (copy > have) { copy = have; }
  22982. if (copy) {
  22983. if (state.head) {
  22984. len = state.head.extra_len - state.length;
  22985. if (!state.head.extra) {
  22986. // Use untyped array for more conveniend processing later
  22987. state.head.extra = new Array(state.head.extra_len);
  22988. }
  22989. utils.arraySet(
  22990. state.head.extra,
  22991. input,
  22992. next,
  22993. // extra field is limited to 65536 bytes
  22994. // - no need for additional size check
  22995. copy,
  22996. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22997. len
  22998. );
  22999. //zmemcpy(state.head.extra + len, next,
  23000. // len + copy > state.head.extra_max ?
  23001. // state.head.extra_max - len : copy);
  23002. }
  23003. if (state.flags & 0x0200) {
  23004. state.check = crc32(state.check, input, copy, next);
  23005. }
  23006. have -= copy;
  23007. next += copy;
  23008. state.length -= copy;
  23009. }
  23010. if (state.length) { break inf_leave; }
  23011. }
  23012. state.length = 0;
  23013. state.mode = NAME;
  23014. /* falls through */
  23015. case NAME:
  23016. if (state.flags & 0x0800) {
  23017. if (have === 0) { break inf_leave; }
  23018. copy = 0;
  23019. do {
  23020. // TODO: 2 or 1 bytes?
  23021. len = input[next + copy++];
  23022. /* use constant limit because in js we should not preallocate memory */
  23023. if (state.head && len &&
  23024. (state.length < 65536 /*state.head.name_max*/)) {
  23025. state.head.name += String.fromCharCode(len);
  23026. }
  23027. } while (len && copy < have);
  23028. if (state.flags & 0x0200) {
  23029. state.check = crc32(state.check, input, copy, next);
  23030. }
  23031. have -= copy;
  23032. next += copy;
  23033. if (len) { break inf_leave; }
  23034. }
  23035. else if (state.head) {
  23036. state.head.name = null;
  23037. }
  23038. state.length = 0;
  23039. state.mode = COMMENT;
  23040. /* falls through */
  23041. case COMMENT:
  23042. if (state.flags & 0x1000) {
  23043. if (have === 0) { break inf_leave; }
  23044. copy = 0;
  23045. do {
  23046. len = input[next + copy++];
  23047. /* use constant limit because in js we should not preallocate memory */
  23048. if (state.head && len &&
  23049. (state.length < 65536 /*state.head.comm_max*/)) {
  23050. state.head.comment += String.fromCharCode(len);
  23051. }
  23052. } while (len && copy < have);
  23053. if (state.flags & 0x0200) {
  23054. state.check = crc32(state.check, input, copy, next);
  23055. }
  23056. have -= copy;
  23057. next += copy;
  23058. if (len) { break inf_leave; }
  23059. }
  23060. else if (state.head) {
  23061. state.head.comment = null;
  23062. }
  23063. state.mode = HCRC;
  23064. /* falls through */
  23065. case HCRC:
  23066. if (state.flags & 0x0200) {
  23067. //=== NEEDBITS(16); */
  23068. while (bits < 16) {
  23069. if (have === 0) { break inf_leave; }
  23070. have--;
  23071. hold += input[next++] << bits;
  23072. bits += 8;
  23073. }
  23074. //===//
  23075. if (hold !== (state.check & 0xffff)) {
  23076. strm.msg = 'header crc mismatch';
  23077. state.mode = BAD;
  23078. break;
  23079. }
  23080. //=== INITBITS();
  23081. hold = 0;
  23082. bits = 0;
  23083. //===//
  23084. }
  23085. if (state.head) {
  23086. state.head.hcrc = ((state.flags >> 9) & 1);
  23087. state.head.done = true;
  23088. }
  23089. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23090. state.mode = TYPE;
  23091. break;
  23092. case DICTID:
  23093. //=== NEEDBITS(32); */
  23094. while (bits < 32) {
  23095. if (have === 0) { break inf_leave; }
  23096. have--;
  23097. hold += input[next++] << bits;
  23098. bits += 8;
  23099. }
  23100. //===//
  23101. strm.adler = state.check = ZSWAP32(hold);
  23102. //=== INITBITS();
  23103. hold = 0;
  23104. bits = 0;
  23105. //===//
  23106. state.mode = DICT;
  23107. /* falls through */
  23108. case DICT:
  23109. if (state.havedict === 0) {
  23110. //--- RESTORE() ---
  23111. strm.next_out = put;
  23112. strm.avail_out = left;
  23113. strm.next_in = next;
  23114. strm.avail_in = have;
  23115. state.hold = hold;
  23116. state.bits = bits;
  23117. //---
  23118. return Z_NEED_DICT;
  23119. }
  23120. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23121. state.mode = TYPE;
  23122. /* falls through */
  23123. case TYPE:
  23124. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23125. /* falls through */
  23126. case TYPEDO:
  23127. if (state.last) {
  23128. //--- BYTEBITS() ---//
  23129. hold >>>= bits & 7;
  23130. bits -= bits & 7;
  23131. //---//
  23132. state.mode = CHECK;
  23133. break;
  23134. }
  23135. //=== NEEDBITS(3); */
  23136. while (bits < 3) {
  23137. if (have === 0) { break inf_leave; }
  23138. have--;
  23139. hold += input[next++] << bits;
  23140. bits += 8;
  23141. }
  23142. //===//
  23143. state.last = (hold & 0x01)/*BITS(1)*/;
  23144. //--- DROPBITS(1) ---//
  23145. hold >>>= 1;
  23146. bits -= 1;
  23147. //---//
  23148. switch ((hold & 0x03)/*BITS(2)*/) {
  23149. case 0: /* stored block */
  23150. //Tracev((stderr, "inflate: stored block%s\n",
  23151. // state.last ? " (last)" : ""));
  23152. state.mode = STORED;
  23153. break;
  23154. case 1: /* fixed block */
  23155. fixedtables(state);
  23156. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23157. // state.last ? " (last)" : ""));
  23158. state.mode = LEN_; /* decode codes */
  23159. if (flush === Z_TREES) {
  23160. //--- DROPBITS(2) ---//
  23161. hold >>>= 2;
  23162. bits -= 2;
  23163. //---//
  23164. break inf_leave;
  23165. }
  23166. break;
  23167. case 2: /* dynamic block */
  23168. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23169. // state.last ? " (last)" : ""));
  23170. state.mode = TABLE;
  23171. break;
  23172. case 3:
  23173. strm.msg = 'invalid block type';
  23174. state.mode = BAD;
  23175. }
  23176. //--- DROPBITS(2) ---//
  23177. hold >>>= 2;
  23178. bits -= 2;
  23179. //---//
  23180. break;
  23181. case STORED:
  23182. //--- BYTEBITS() ---// /* go to byte boundary */
  23183. hold >>>= bits & 7;
  23184. bits -= bits & 7;
  23185. //---//
  23186. //=== NEEDBITS(32); */
  23187. while (bits < 32) {
  23188. if (have === 0) { break inf_leave; }
  23189. have--;
  23190. hold += input[next++] << bits;
  23191. bits += 8;
  23192. }
  23193. //===//
  23194. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23195. strm.msg = 'invalid stored block lengths';
  23196. state.mode = BAD;
  23197. break;
  23198. }
  23199. state.length = hold & 0xffff;
  23200. //Tracev((stderr, "inflate: stored length %u\n",
  23201. // state.length));
  23202. //=== INITBITS();
  23203. hold = 0;
  23204. bits = 0;
  23205. //===//
  23206. state.mode = COPY_;
  23207. if (flush === Z_TREES) { break inf_leave; }
  23208. /* falls through */
  23209. case COPY_:
  23210. state.mode = COPY;
  23211. /* falls through */
  23212. case COPY:
  23213. copy = state.length;
  23214. if (copy) {
  23215. if (copy > have) { copy = have; }
  23216. if (copy > left) { copy = left; }
  23217. if (copy === 0) { break inf_leave; }
  23218. //--- zmemcpy(put, next, copy); ---
  23219. utils.arraySet(output, input, next, copy, put);
  23220. //---//
  23221. have -= copy;
  23222. next += copy;
  23223. left -= copy;
  23224. put += copy;
  23225. state.length -= copy;
  23226. break;
  23227. }
  23228. //Tracev((stderr, "inflate: stored end\n"));
  23229. state.mode = TYPE;
  23230. break;
  23231. case TABLE:
  23232. //=== NEEDBITS(14); */
  23233. while (bits < 14) {
  23234. if (have === 0) { break inf_leave; }
  23235. have--;
  23236. hold += input[next++] << bits;
  23237. bits += 8;
  23238. }
  23239. //===//
  23240. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23241. //--- DROPBITS(5) ---//
  23242. hold >>>= 5;
  23243. bits -= 5;
  23244. //---//
  23245. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23246. //--- DROPBITS(5) ---//
  23247. hold >>>= 5;
  23248. bits -= 5;
  23249. //---//
  23250. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23251. //--- DROPBITS(4) ---//
  23252. hold >>>= 4;
  23253. bits -= 4;
  23254. //---//
  23255. //#ifndef PKZIP_BUG_WORKAROUND
  23256. if (state.nlen > 286 || state.ndist > 30) {
  23257. strm.msg = 'too many length or distance symbols';
  23258. state.mode = BAD;
  23259. break;
  23260. }
  23261. //#endif
  23262. //Tracev((stderr, "inflate: table sizes ok\n"));
  23263. state.have = 0;
  23264. state.mode = LENLENS;
  23265. /* falls through */
  23266. case LENLENS:
  23267. while (state.have < state.ncode) {
  23268. //=== NEEDBITS(3);
  23269. while (bits < 3) {
  23270. if (have === 0) { break inf_leave; }
  23271. have--;
  23272. hold += input[next++] << bits;
  23273. bits += 8;
  23274. }
  23275. //===//
  23276. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23277. //--- DROPBITS(3) ---//
  23278. hold >>>= 3;
  23279. bits -= 3;
  23280. //---//
  23281. }
  23282. while (state.have < 19) {
  23283. state.lens[order[state.have++]] = 0;
  23284. }
  23285. // We have separate tables & no pointers. 2 commented lines below not needed.
  23286. //state.next = state.codes;
  23287. //state.lencode = state.next;
  23288. // Switch to use dynamic table
  23289. state.lencode = state.lendyn;
  23290. state.lenbits = 7;
  23291. opts = {bits: state.lenbits};
  23292. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23293. state.lenbits = opts.bits;
  23294. if (ret) {
  23295. strm.msg = 'invalid code lengths set';
  23296. state.mode = BAD;
  23297. break;
  23298. }
  23299. //Tracev((stderr, "inflate: code lengths ok\n"));
  23300. state.have = 0;
  23301. state.mode = CODELENS;
  23302. /* falls through */
  23303. case CODELENS:
  23304. while (state.have < state.nlen + state.ndist) {
  23305. for (;;) {
  23306. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23307. here_bits = here >>> 24;
  23308. here_op = (here >>> 16) & 0xff;
  23309. here_val = here & 0xffff;
  23310. if ((here_bits) <= bits) { break; }
  23311. //--- PULLBYTE() ---//
  23312. if (have === 0) { break inf_leave; }
  23313. have--;
  23314. hold += input[next++] << bits;
  23315. bits += 8;
  23316. //---//
  23317. }
  23318. if (here_val < 16) {
  23319. //--- DROPBITS(here.bits) ---//
  23320. hold >>>= here_bits;
  23321. bits -= here_bits;
  23322. //---//
  23323. state.lens[state.have++] = here_val;
  23324. }
  23325. else {
  23326. if (here_val === 16) {
  23327. //=== NEEDBITS(here.bits + 2);
  23328. n = here_bits + 2;
  23329. while (bits < n) {
  23330. if (have === 0) { break inf_leave; }
  23331. have--;
  23332. hold += input[next++] << bits;
  23333. bits += 8;
  23334. }
  23335. //===//
  23336. //--- DROPBITS(here.bits) ---//
  23337. hold >>>= here_bits;
  23338. bits -= here_bits;
  23339. //---//
  23340. if (state.have === 0) {
  23341. strm.msg = 'invalid bit length repeat';
  23342. state.mode = BAD;
  23343. break;
  23344. }
  23345. len = state.lens[state.have - 1];
  23346. copy = 3 + (hold & 0x03);//BITS(2);
  23347. //--- DROPBITS(2) ---//
  23348. hold >>>= 2;
  23349. bits -= 2;
  23350. //---//
  23351. }
  23352. else if (here_val === 17) {
  23353. //=== NEEDBITS(here.bits + 3);
  23354. n = here_bits + 3;
  23355. while (bits < n) {
  23356. if (have === 0) { break inf_leave; }
  23357. have--;
  23358. hold += input[next++] << bits;
  23359. bits += 8;
  23360. }
  23361. //===//
  23362. //--- DROPBITS(here.bits) ---//
  23363. hold >>>= here_bits;
  23364. bits -= here_bits;
  23365. //---//
  23366. len = 0;
  23367. copy = 3 + (hold & 0x07);//BITS(3);
  23368. //--- DROPBITS(3) ---//
  23369. hold >>>= 3;
  23370. bits -= 3;
  23371. //---//
  23372. }
  23373. else {
  23374. //=== NEEDBITS(here.bits + 7);
  23375. n = here_bits + 7;
  23376. while (bits < n) {
  23377. if (have === 0) { break inf_leave; }
  23378. have--;
  23379. hold += input[next++] << bits;
  23380. bits += 8;
  23381. }
  23382. //===//
  23383. //--- DROPBITS(here.bits) ---//
  23384. hold >>>= here_bits;
  23385. bits -= here_bits;
  23386. //---//
  23387. len = 0;
  23388. copy = 11 + (hold & 0x7f);//BITS(7);
  23389. //--- DROPBITS(7) ---//
  23390. hold >>>= 7;
  23391. bits -= 7;
  23392. //---//
  23393. }
  23394. if (state.have + copy > state.nlen + state.ndist) {
  23395. strm.msg = 'invalid bit length repeat';
  23396. state.mode = BAD;
  23397. break;
  23398. }
  23399. while (copy--) {
  23400. state.lens[state.have++] = len;
  23401. }
  23402. }
  23403. }
  23404. /* handle error breaks in while */
  23405. if (state.mode === BAD) { break; }
  23406. /* check for end-of-block code (better have one) */
  23407. if (state.lens[256] === 0) {
  23408. strm.msg = 'invalid code -- missing end-of-block';
  23409. state.mode = BAD;
  23410. break;
  23411. }
  23412. /* build code tables -- note: do not change the lenbits or distbits
  23413. values here (9 and 6) without reading the comments in inftrees.h
  23414. concerning the ENOUGH constants, which depend on those values */
  23415. state.lenbits = 9;
  23416. opts = {bits: state.lenbits};
  23417. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23418. // We have separate tables & no pointers. 2 commented lines below not needed.
  23419. // state.next_index = opts.table_index;
  23420. state.lenbits = opts.bits;
  23421. // state.lencode = state.next;
  23422. if (ret) {
  23423. strm.msg = 'invalid literal/lengths set';
  23424. state.mode = BAD;
  23425. break;
  23426. }
  23427. state.distbits = 6;
  23428. //state.distcode.copy(state.codes);
  23429. // Switch to use dynamic table
  23430. state.distcode = state.distdyn;
  23431. opts = {bits: state.distbits};
  23432. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23433. // We have separate tables & no pointers. 2 commented lines below not needed.
  23434. // state.next_index = opts.table_index;
  23435. state.distbits = opts.bits;
  23436. // state.distcode = state.next;
  23437. if (ret) {
  23438. strm.msg = 'invalid distances set';
  23439. state.mode = BAD;
  23440. break;
  23441. }
  23442. //Tracev((stderr, 'inflate: codes ok\n'));
  23443. state.mode = LEN_;
  23444. if (flush === Z_TREES) { break inf_leave; }
  23445. /* falls through */
  23446. case LEN_:
  23447. state.mode = LEN;
  23448. /* falls through */
  23449. case LEN:
  23450. if (have >= 6 && left >= 258) {
  23451. //--- RESTORE() ---
  23452. strm.next_out = put;
  23453. strm.avail_out = left;
  23454. strm.next_in = next;
  23455. strm.avail_in = have;
  23456. state.hold = hold;
  23457. state.bits = bits;
  23458. //---
  23459. inflate_fast(strm, _out);
  23460. //--- LOAD() ---
  23461. put = strm.next_out;
  23462. output = strm.output;
  23463. left = strm.avail_out;
  23464. next = strm.next_in;
  23465. input = strm.input;
  23466. have = strm.avail_in;
  23467. hold = state.hold;
  23468. bits = state.bits;
  23469. //---
  23470. if (state.mode === TYPE) {
  23471. state.back = -1;
  23472. }
  23473. break;
  23474. }
  23475. state.back = 0;
  23476. for (;;) {
  23477. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23478. here_bits = here >>> 24;
  23479. here_op = (here >>> 16) & 0xff;
  23480. here_val = here & 0xffff;
  23481. if (here_bits <= bits) { break; }
  23482. //--- PULLBYTE() ---//
  23483. if (have === 0) { break inf_leave; }
  23484. have--;
  23485. hold += input[next++] << bits;
  23486. bits += 8;
  23487. //---//
  23488. }
  23489. if (here_op && (here_op & 0xf0) === 0) {
  23490. last_bits = here_bits;
  23491. last_op = here_op;
  23492. last_val = here_val;
  23493. for (;;) {
  23494. here = state.lencode[last_val +
  23495. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23496. here_bits = here >>> 24;
  23497. here_op = (here >>> 16) & 0xff;
  23498. here_val = here & 0xffff;
  23499. if ((last_bits + here_bits) <= bits) { break; }
  23500. //--- PULLBYTE() ---//
  23501. if (have === 0) { break inf_leave; }
  23502. have--;
  23503. hold += input[next++] << bits;
  23504. bits += 8;
  23505. //---//
  23506. }
  23507. //--- DROPBITS(last.bits) ---//
  23508. hold >>>= last_bits;
  23509. bits -= last_bits;
  23510. //---//
  23511. state.back += last_bits;
  23512. }
  23513. //--- DROPBITS(here.bits) ---//
  23514. hold >>>= here_bits;
  23515. bits -= here_bits;
  23516. //---//
  23517. state.back += here_bits;
  23518. state.length = here_val;
  23519. if (here_op === 0) {
  23520. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23521. // "inflate: literal '%c'\n" :
  23522. // "inflate: literal 0x%02x\n", here.val));
  23523. state.mode = LIT;
  23524. break;
  23525. }
  23526. if (here_op & 32) {
  23527. //Tracevv((stderr, "inflate: end of block\n"));
  23528. state.back = -1;
  23529. state.mode = TYPE;
  23530. break;
  23531. }
  23532. if (here_op & 64) {
  23533. strm.msg = 'invalid literal/length code';
  23534. state.mode = BAD;
  23535. break;
  23536. }
  23537. state.extra = here_op & 15;
  23538. state.mode = LENEXT;
  23539. /* falls through */
  23540. case LENEXT:
  23541. if (state.extra) {
  23542. //=== NEEDBITS(state.extra);
  23543. n = state.extra;
  23544. while (bits < n) {
  23545. if (have === 0) { break inf_leave; }
  23546. have--;
  23547. hold += input[next++] << bits;
  23548. bits += 8;
  23549. }
  23550. //===//
  23551. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23552. //--- DROPBITS(state.extra) ---//
  23553. hold >>>= state.extra;
  23554. bits -= state.extra;
  23555. //---//
  23556. state.back += state.extra;
  23557. }
  23558. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23559. state.was = state.length;
  23560. state.mode = DIST;
  23561. /* falls through */
  23562. case DIST:
  23563. for (;;) {
  23564. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23565. here_bits = here >>> 24;
  23566. here_op = (here >>> 16) & 0xff;
  23567. here_val = here & 0xffff;
  23568. if ((here_bits) <= bits) { break; }
  23569. //--- PULLBYTE() ---//
  23570. if (have === 0) { break inf_leave; }
  23571. have--;
  23572. hold += input[next++] << bits;
  23573. bits += 8;
  23574. //---//
  23575. }
  23576. if ((here_op & 0xf0) === 0) {
  23577. last_bits = here_bits;
  23578. last_op = here_op;
  23579. last_val = here_val;
  23580. for (;;) {
  23581. here = state.distcode[last_val +
  23582. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23583. here_bits = here >>> 24;
  23584. here_op = (here >>> 16) & 0xff;
  23585. here_val = here & 0xffff;
  23586. if ((last_bits + here_bits) <= bits) { break; }
  23587. //--- PULLBYTE() ---//
  23588. if (have === 0) { break inf_leave; }
  23589. have--;
  23590. hold += input[next++] << bits;
  23591. bits += 8;
  23592. //---//
  23593. }
  23594. //--- DROPBITS(last.bits) ---//
  23595. hold >>>= last_bits;
  23596. bits -= last_bits;
  23597. //---//
  23598. state.back += last_bits;
  23599. }
  23600. //--- DROPBITS(here.bits) ---//
  23601. hold >>>= here_bits;
  23602. bits -= here_bits;
  23603. //---//
  23604. state.back += here_bits;
  23605. if (here_op & 64) {
  23606. strm.msg = 'invalid distance code';
  23607. state.mode = BAD;
  23608. break;
  23609. }
  23610. state.offset = here_val;
  23611. state.extra = (here_op) & 15;
  23612. state.mode = DISTEXT;
  23613. /* falls through */
  23614. case DISTEXT:
  23615. if (state.extra) {
  23616. //=== NEEDBITS(state.extra);
  23617. n = state.extra;
  23618. while (bits < n) {
  23619. if (have === 0) { break inf_leave; }
  23620. have--;
  23621. hold += input[next++] << bits;
  23622. bits += 8;
  23623. }
  23624. //===//
  23625. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23626. //--- DROPBITS(state.extra) ---//
  23627. hold >>>= state.extra;
  23628. bits -= state.extra;
  23629. //---//
  23630. state.back += state.extra;
  23631. }
  23632. //#ifdef INFLATE_STRICT
  23633. if (state.offset > state.dmax) {
  23634. strm.msg = 'invalid distance too far back';
  23635. state.mode = BAD;
  23636. break;
  23637. }
  23638. //#endif
  23639. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23640. state.mode = MATCH;
  23641. /* falls through */
  23642. case MATCH:
  23643. if (left === 0) { break inf_leave; }
  23644. copy = _out - left;
  23645. if (state.offset > copy) { /* copy from window */
  23646. copy = state.offset - copy;
  23647. if (copy > state.whave) {
  23648. if (state.sane) {
  23649. strm.msg = 'invalid distance too far back';
  23650. state.mode = BAD;
  23651. break;
  23652. }
  23653. // (!) This block is disabled in zlib defailts,
  23654. // don't enable it for binary compatibility
  23655. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23656. // Trace((stderr, "inflate.c too far\n"));
  23657. // copy -= state.whave;
  23658. // if (copy > state.length) { copy = state.length; }
  23659. // if (copy > left) { copy = left; }
  23660. // left -= copy;
  23661. // state.length -= copy;
  23662. // do {
  23663. // output[put++] = 0;
  23664. // } while (--copy);
  23665. // if (state.length === 0) { state.mode = LEN; }
  23666. // break;
  23667. //#endif
  23668. }
  23669. if (copy > state.wnext) {
  23670. copy -= state.wnext;
  23671. from = state.wsize - copy;
  23672. }
  23673. else {
  23674. from = state.wnext - copy;
  23675. }
  23676. if (copy > state.length) { copy = state.length; }
  23677. from_source = state.window;
  23678. }
  23679. else { /* copy from output */
  23680. from_source = output;
  23681. from = put - state.offset;
  23682. copy = state.length;
  23683. }
  23684. if (copy > left) { copy = left; }
  23685. left -= copy;
  23686. state.length -= copy;
  23687. do {
  23688. output[put++] = from_source[from++];
  23689. } while (--copy);
  23690. if (state.length === 0) { state.mode = LEN; }
  23691. break;
  23692. case LIT:
  23693. if (left === 0) { break inf_leave; }
  23694. output[put++] = state.length;
  23695. left--;
  23696. state.mode = LEN;
  23697. break;
  23698. case CHECK:
  23699. if (state.wrap) {
  23700. //=== NEEDBITS(32);
  23701. while (bits < 32) {
  23702. if (have === 0) { break inf_leave; }
  23703. have--;
  23704. // Use '|' insdead of '+' to make sure that result is signed
  23705. hold |= input[next++] << bits;
  23706. bits += 8;
  23707. }
  23708. //===//
  23709. _out -= left;
  23710. strm.total_out += _out;
  23711. state.total += _out;
  23712. if (_out) {
  23713. strm.adler = state.check =
  23714. /*UPDATE(state.check, put - _out, _out);*/
  23715. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23716. }
  23717. _out = left;
  23718. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23719. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23720. strm.msg = 'incorrect data check';
  23721. state.mode = BAD;
  23722. break;
  23723. }
  23724. //=== INITBITS();
  23725. hold = 0;
  23726. bits = 0;
  23727. //===//
  23728. //Tracev((stderr, "inflate: check matches trailer\n"));
  23729. }
  23730. state.mode = LENGTH;
  23731. /* falls through */
  23732. case LENGTH:
  23733. if (state.wrap && state.flags) {
  23734. //=== NEEDBITS(32);
  23735. while (bits < 32) {
  23736. if (have === 0) { break inf_leave; }
  23737. have--;
  23738. hold += input[next++] << bits;
  23739. bits += 8;
  23740. }
  23741. //===//
  23742. if (hold !== (state.total & 0xffffffff)) {
  23743. strm.msg = 'incorrect length check';
  23744. state.mode = BAD;
  23745. break;
  23746. }
  23747. //=== INITBITS();
  23748. hold = 0;
  23749. bits = 0;
  23750. //===//
  23751. //Tracev((stderr, "inflate: length matches trailer\n"));
  23752. }
  23753. state.mode = DONE;
  23754. /* falls through */
  23755. case DONE:
  23756. ret = Z_STREAM_END;
  23757. break inf_leave;
  23758. case BAD:
  23759. ret = Z_DATA_ERROR;
  23760. break inf_leave;
  23761. case MEM:
  23762. return Z_MEM_ERROR;
  23763. case SYNC:
  23764. /* falls through */
  23765. default:
  23766. return Z_STREAM_ERROR;
  23767. }
  23768. }
  23769. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23770. /*
  23771. Return from inflate(), updating the total counts and the check value.
  23772. If there was no progress during the inflate() call, return a buffer
  23773. error. Call updatewindow() to create and/or update the window state.
  23774. Note: a memory error from inflate() is non-recoverable.
  23775. */
  23776. //--- RESTORE() ---
  23777. strm.next_out = put;
  23778. strm.avail_out = left;
  23779. strm.next_in = next;
  23780. strm.avail_in = have;
  23781. state.hold = hold;
  23782. state.bits = bits;
  23783. //---
  23784. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23785. (state.mode < CHECK || flush !== Z_FINISH))) {
  23786. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23787. state.mode = MEM;
  23788. return Z_MEM_ERROR;
  23789. }
  23790. }
  23791. _in -= strm.avail_in;
  23792. _out -= strm.avail_out;
  23793. strm.total_in += _in;
  23794. strm.total_out += _out;
  23795. state.total += _out;
  23796. if (state.wrap && _out) {
  23797. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23798. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23799. }
  23800. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23801. (state.mode === TYPE ? 128 : 0) +
  23802. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23803. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23804. ret = Z_BUF_ERROR;
  23805. }
  23806. return ret;
  23807. }
  23808. function inflateEnd(strm) {
  23809. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23810. return Z_STREAM_ERROR;
  23811. }
  23812. var state = strm.state;
  23813. if (state.window) {
  23814. state.window = null;
  23815. }
  23816. strm.state = null;
  23817. return Z_OK;
  23818. }
  23819. function inflateGetHeader(strm, head) {
  23820. var state;
  23821. /* check state */
  23822. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23823. state = strm.state;
  23824. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23825. /* save header structure */
  23826. state.head = head;
  23827. head.done = false;
  23828. return Z_OK;
  23829. }
  23830. exports.inflateReset = inflateReset;
  23831. exports.inflateReset2 = inflateReset2;
  23832. exports.inflateResetKeep = inflateResetKeep;
  23833. exports.inflateInit = inflateInit;
  23834. exports.inflateInit2 = inflateInit2;
  23835. exports.inflate = inflate;
  23836. exports.inflateEnd = inflateEnd;
  23837. exports.inflateGetHeader = inflateGetHeader;
  23838. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23839. /* Not implemented
  23840. exports.inflateCopy = inflateCopy;
  23841. exports.inflateGetDictionary = inflateGetDictionary;
  23842. exports.inflateMark = inflateMark;
  23843. exports.inflatePrime = inflatePrime;
  23844. exports.inflateSetDictionary = inflateSetDictionary;
  23845. exports.inflateSync = inflateSync;
  23846. exports.inflateSyncPoint = inflateSyncPoint;
  23847. exports.inflateUndermine = inflateUndermine;
  23848. */
  23849. },{"../utils/common":74,"./adler32":76,"./crc32":78,"./inffast":81,"./inftrees":83}],83:[function(require,module,exports){
  23850. 'use strict';
  23851. var utils = require('../utils/common');
  23852. var MAXBITS = 15;
  23853. var ENOUGH_LENS = 852;
  23854. var ENOUGH_DISTS = 592;
  23855. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23856. var CODES = 0;
  23857. var LENS = 1;
  23858. var DISTS = 2;
  23859. var lbase = [ /* Length codes 257..285 base */
  23860. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23861. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23862. ];
  23863. var lext = [ /* Length codes 257..285 extra */
  23864. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23865. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23866. ];
  23867. var dbase = [ /* Distance codes 0..29 base */
  23868. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23869. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23870. 8193, 12289, 16385, 24577, 0, 0
  23871. ];
  23872. var dext = [ /* Distance codes 0..29 extra */
  23873. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23874. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23875. 28, 28, 29, 29, 64, 64
  23876. ];
  23877. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23878. {
  23879. var bits = opts.bits;
  23880. //here = opts.here; /* table entry for duplication */
  23881. var len = 0; /* a code's length in bits */
  23882. var sym = 0; /* index of code symbols */
  23883. var min = 0, max = 0; /* minimum and maximum code lengths */
  23884. var root = 0; /* number of index bits for root table */
  23885. var curr = 0; /* number of index bits for current table */
  23886. var drop = 0; /* code bits to drop for sub-table */
  23887. var left = 0; /* number of prefix codes available */
  23888. var used = 0; /* code entries in table used */
  23889. var huff = 0; /* Huffman code */
  23890. var incr; /* for incrementing code, index */
  23891. var fill; /* index for replicating entries */
  23892. var low; /* low bits for current root entry */
  23893. var mask; /* mask for low root bits */
  23894. var next; /* next available space in table */
  23895. var base = null; /* base value table to use */
  23896. var base_index = 0;
  23897. // var shoextra; /* extra bits table to use */
  23898. var end; /* use base and extra for symbol > end */
  23899. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23900. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23901. var extra = null;
  23902. var extra_index = 0;
  23903. var here_bits, here_op, here_val;
  23904. /*
  23905. Process a set of code lengths to create a canonical Huffman code. The
  23906. code lengths are lens[0..codes-1]. Each length corresponds to the
  23907. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23908. symbols by length from short to long, and retaining the symbol order
  23909. for codes with equal lengths. Then the code starts with all zero bits
  23910. for the first code of the shortest length, and the codes are integer
  23911. increments for the same length, and zeros are appended as the length
  23912. increases. For the deflate format, these bits are stored backwards
  23913. from their more natural integer increment ordering, and so when the
  23914. decoding tables are built in the large loop below, the integer codes
  23915. are incremented backwards.
  23916. This routine assumes, but does not check, that all of the entries in
  23917. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23918. 1..MAXBITS is interpreted as that code length. zero means that that
  23919. symbol does not occur in this code.
  23920. The codes are sorted by computing a count of codes for each length,
  23921. creating from that a table of starting indices for each length in the
  23922. sorted table, and then entering the symbols in order in the sorted
  23923. table. The sorted table is work[], with that space being provided by
  23924. the caller.
  23925. The length counts are used for other purposes as well, i.e. finding
  23926. the minimum and maximum length codes, determining if there are any
  23927. codes at all, checking for a valid set of lengths, and looking ahead
  23928. at length counts to determine sub-table sizes when building the
  23929. decoding tables.
  23930. */
  23931. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23932. for (len = 0; len <= MAXBITS; len++) {
  23933. count[len] = 0;
  23934. }
  23935. for (sym = 0; sym < codes; sym++) {
  23936. count[lens[lens_index + sym]]++;
  23937. }
  23938. /* bound code lengths, force root to be within code lengths */
  23939. root = bits;
  23940. for (max = MAXBITS; max >= 1; max--) {
  23941. if (count[max] !== 0) { break; }
  23942. }
  23943. if (root > max) {
  23944. root = max;
  23945. }
  23946. if (max === 0) { /* no symbols to code at all */
  23947. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23948. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23949. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23950. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23951. //table.op[opts.table_index] = 64;
  23952. //table.bits[opts.table_index] = 1;
  23953. //table.val[opts.table_index++] = 0;
  23954. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23955. opts.bits = 1;
  23956. return 0; /* no symbols, but wait for decoding to report error */
  23957. }
  23958. for (min = 1; min < max; min++) {
  23959. if (count[min] !== 0) { break; }
  23960. }
  23961. if (root < min) {
  23962. root = min;
  23963. }
  23964. /* check for an over-subscribed or incomplete set of lengths */
  23965. left = 1;
  23966. for (len = 1; len <= MAXBITS; len++) {
  23967. left <<= 1;
  23968. left -= count[len];
  23969. if (left < 0) {
  23970. return -1;
  23971. } /* over-subscribed */
  23972. }
  23973. if (left > 0 && (type === CODES || max !== 1)) {
  23974. return -1; /* incomplete set */
  23975. }
  23976. /* generate offsets into symbol table for each length for sorting */
  23977. offs[1] = 0;
  23978. for (len = 1; len < MAXBITS; len++) {
  23979. offs[len + 1] = offs[len] + count[len];
  23980. }
  23981. /* sort symbols by length, by symbol order within each length */
  23982. for (sym = 0; sym < codes; sym++) {
  23983. if (lens[lens_index + sym] !== 0) {
  23984. work[offs[lens[lens_index + sym]]++] = sym;
  23985. }
  23986. }
  23987. /*
  23988. Create and fill in decoding tables. In this loop, the table being
  23989. filled is at next and has curr index bits. The code being used is huff
  23990. with length len. That code is converted to an index by dropping drop
  23991. bits off of the bottom. For codes where len is less than drop + curr,
  23992. those top drop + curr - len bits are incremented through all values to
  23993. fill the table with replicated entries.
  23994. root is the number of index bits for the root table. When len exceeds
  23995. root, sub-tables are created pointed to by the root entry with an index
  23996. of the low root bits of huff. This is saved in low to check for when a
  23997. new sub-table should be started. drop is zero when the root table is
  23998. being filled, and drop is root when sub-tables are being filled.
  23999. When a new sub-table is needed, it is necessary to look ahead in the
  24000. code lengths to determine what size sub-table is needed. The length
  24001. counts are used for this, and so count[] is decremented as codes are
  24002. entered in the tables.
  24003. used keeps track of how many table entries have been allocated from the
  24004. provided *table space. It is checked for LENS and DIST tables against
  24005. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24006. the initial root table size constants. See the comments in inftrees.h
  24007. for more information.
  24008. sym increments through all symbols, and the loop terminates when
  24009. all codes of length max, i.e. all codes, have been processed. This
  24010. routine permits incomplete codes, so another loop after this one fills
  24011. in the rest of the decoding tables with invalid code markers.
  24012. */
  24013. /* set up for code type */
  24014. // poor man optimization - use if-else instead of switch,
  24015. // to avoid deopts in old v8
  24016. if (type === CODES) {
  24017. base = extra = work; /* dummy value--not used */
  24018. end = 19;
  24019. } else if (type === LENS) {
  24020. base = lbase;
  24021. base_index -= 257;
  24022. extra = lext;
  24023. extra_index -= 257;
  24024. end = 256;
  24025. } else { /* DISTS */
  24026. base = dbase;
  24027. extra = dext;
  24028. end = -1;
  24029. }
  24030. /* initialize opts for loop */
  24031. huff = 0; /* starting code */
  24032. sym = 0; /* starting code symbol */
  24033. len = min; /* starting code length */
  24034. next = table_index; /* current table to fill in */
  24035. curr = root; /* current table index bits */
  24036. drop = 0; /* current bits to drop from code for index */
  24037. low = -1; /* trigger new sub-table when len > root */
  24038. used = 1 << root; /* use root table entries */
  24039. mask = used - 1; /* mask for comparing low */
  24040. /* check available table space */
  24041. if ((type === LENS && used > ENOUGH_LENS) ||
  24042. (type === DISTS && used > ENOUGH_DISTS)) {
  24043. return 1;
  24044. }
  24045. var i=0;
  24046. /* process all codes and make table entries */
  24047. for (;;) {
  24048. i++;
  24049. /* create table entry */
  24050. here_bits = len - drop;
  24051. if (work[sym] < end) {
  24052. here_op = 0;
  24053. here_val = work[sym];
  24054. }
  24055. else if (work[sym] > end) {
  24056. here_op = extra[extra_index + work[sym]];
  24057. here_val = base[base_index + work[sym]];
  24058. }
  24059. else {
  24060. here_op = 32 + 64; /* end of block */
  24061. here_val = 0;
  24062. }
  24063. /* replicate for those indices with low len bits equal to huff */
  24064. incr = 1 << (len - drop);
  24065. fill = 1 << curr;
  24066. min = fill; /* save offset to next table */
  24067. do {
  24068. fill -= incr;
  24069. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24070. } while (fill !== 0);
  24071. /* backwards increment the len-bit code huff */
  24072. incr = 1 << (len - 1);
  24073. while (huff & incr) {
  24074. incr >>= 1;
  24075. }
  24076. if (incr !== 0) {
  24077. huff &= incr - 1;
  24078. huff += incr;
  24079. } else {
  24080. huff = 0;
  24081. }
  24082. /* go to next symbol, update count, len */
  24083. sym++;
  24084. if (--count[len] === 0) {
  24085. if (len === max) { break; }
  24086. len = lens[lens_index + work[sym]];
  24087. }
  24088. /* create new sub-table if needed */
  24089. if (len > root && (huff & mask) !== low) {
  24090. /* if first time, transition to sub-tables */
  24091. if (drop === 0) {
  24092. drop = root;
  24093. }
  24094. /* increment past last table */
  24095. next += min; /* here min is 1 << curr */
  24096. /* determine length of next table */
  24097. curr = len - drop;
  24098. left = 1 << curr;
  24099. while (curr + drop < max) {
  24100. left -= count[curr + drop];
  24101. if (left <= 0) { break; }
  24102. curr++;
  24103. left <<= 1;
  24104. }
  24105. /* check for enough space */
  24106. used += 1 << curr;
  24107. if ((type === LENS && used > ENOUGH_LENS) ||
  24108. (type === DISTS && used > ENOUGH_DISTS)) {
  24109. return 1;
  24110. }
  24111. /* point entry in root table to sub-table */
  24112. low = huff & mask;
  24113. /*table.op[low] = curr;
  24114. table.bits[low] = root;
  24115. table.val[low] = next - opts.table_index;*/
  24116. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24117. }
  24118. }
  24119. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24120. at most one remaining entry, since if the code is incomplete, the
  24121. maximum code length that was allowed to get this far is one bit) */
  24122. if (huff !== 0) {
  24123. //table.op[next + huff] = 64; /* invalid code marker */
  24124. //table.bits[next + huff] = len - drop;
  24125. //table.val[next + huff] = 0;
  24126. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24127. }
  24128. /* set return parameters */
  24129. //opts.table_index += used;
  24130. opts.bits = root;
  24131. return 0;
  24132. };
  24133. },{"../utils/common":74}],84:[function(require,module,exports){
  24134. 'use strict';
  24135. module.exports = {
  24136. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24137. '1': 'stream end', /* Z_STREAM_END 1 */
  24138. '0': '', /* Z_OK 0 */
  24139. '-1': 'file error', /* Z_ERRNO (-1) */
  24140. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24141. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24142. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24143. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24144. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24145. };
  24146. },{}],85:[function(require,module,exports){
  24147. 'use strict';
  24148. var utils = require('../utils/common');
  24149. /* Public constants ==========================================================*/
  24150. /* ===========================================================================*/
  24151. //var Z_FILTERED = 1;
  24152. //var Z_HUFFMAN_ONLY = 2;
  24153. //var Z_RLE = 3;
  24154. var Z_FIXED = 4;
  24155. //var Z_DEFAULT_STRATEGY = 0;
  24156. /* Possible values of the data_type field (though see inflate()) */
  24157. var Z_BINARY = 0;
  24158. var Z_TEXT = 1;
  24159. //var Z_ASCII = 1; // = Z_TEXT
  24160. var Z_UNKNOWN = 2;
  24161. /*============================================================================*/
  24162. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24163. // From zutil.h
  24164. var STORED_BLOCK = 0;
  24165. var STATIC_TREES = 1;
  24166. var DYN_TREES = 2;
  24167. /* The three kinds of block type */
  24168. var MIN_MATCH = 3;
  24169. var MAX_MATCH = 258;
  24170. /* The minimum and maximum match lengths */
  24171. // From deflate.h
  24172. /* ===========================================================================
  24173. * Internal compression state.
  24174. */
  24175. var LENGTH_CODES = 29;
  24176. /* number of length codes, not counting the special END_BLOCK code */
  24177. var LITERALS = 256;
  24178. /* number of literal bytes 0..255 */
  24179. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24180. /* number of Literal or Length codes, including the END_BLOCK code */
  24181. var D_CODES = 30;
  24182. /* number of distance codes */
  24183. var BL_CODES = 19;
  24184. /* number of codes used to transfer the bit lengths */
  24185. var HEAP_SIZE = 2*L_CODES + 1;
  24186. /* maximum heap size */
  24187. var MAX_BITS = 15;
  24188. /* All codes must not exceed MAX_BITS bits */
  24189. var Buf_size = 16;
  24190. /* size of bit buffer in bi_buf */
  24191. /* ===========================================================================
  24192. * Constants
  24193. */
  24194. var MAX_BL_BITS = 7;
  24195. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24196. var END_BLOCK = 256;
  24197. /* end of block literal code */
  24198. var REP_3_6 = 16;
  24199. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24200. var REPZ_3_10 = 17;
  24201. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24202. var REPZ_11_138 = 18;
  24203. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24204. var extra_lbits = /* extra bits for each length code */
  24205. [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];
  24206. var extra_dbits = /* extra bits for each distance code */
  24207. [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];
  24208. var extra_blbits = /* extra bits for each bit length code */
  24209. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24210. var bl_order =
  24211. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24212. /* The lengths of the bit length codes are sent in order of decreasing
  24213. * probability, to avoid transmitting the lengths for unused bit length codes.
  24214. */
  24215. /* ===========================================================================
  24216. * Local data. These are initialized only once.
  24217. */
  24218. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24219. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24220. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24221. var static_ltree = new Array((L_CODES+2) * 2);
  24222. zero(static_ltree);
  24223. /* The static literal tree. Since the bit lengths are imposed, there is no
  24224. * need for the L_CODES extra codes used during heap construction. However
  24225. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24226. * below).
  24227. */
  24228. var static_dtree = new Array(D_CODES * 2);
  24229. zero(static_dtree);
  24230. /* The static distance tree. (Actually a trivial tree since all codes use
  24231. * 5 bits.)
  24232. */
  24233. var _dist_code = new Array(DIST_CODE_LEN);
  24234. zero(_dist_code);
  24235. /* Distance codes. The first 256 values correspond to the distances
  24236. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24237. * the 15 bit distances.
  24238. */
  24239. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24240. zero(_length_code);
  24241. /* length code for each normalized match length (0 == MIN_MATCH) */
  24242. var base_length = new Array(LENGTH_CODES);
  24243. zero(base_length);
  24244. /* First normalized length for each code (0 = MIN_MATCH) */
  24245. var base_dist = new Array(D_CODES);
  24246. zero(base_dist);
  24247. /* First normalized distance for each code (0 = distance of 1) */
  24248. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24249. this.static_tree = static_tree; /* static tree or NULL */
  24250. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24251. this.extra_base = extra_base; /* base index for extra_bits */
  24252. this.elems = elems; /* max number of elements in the tree */
  24253. this.max_length = max_length; /* max bit length for the codes */
  24254. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24255. this.has_stree = static_tree && static_tree.length;
  24256. };
  24257. var static_l_desc;
  24258. var static_d_desc;
  24259. var static_bl_desc;
  24260. var TreeDesc = function(dyn_tree, stat_desc) {
  24261. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24262. this.max_code = 0; /* largest code with non zero frequency */
  24263. this.stat_desc = stat_desc; /* the corresponding static tree */
  24264. };
  24265. function d_code(dist) {
  24266. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24267. }
  24268. /* ===========================================================================
  24269. * Output a short LSB first on the stream.
  24270. * IN assertion: there is enough room in pendingBuf.
  24271. */
  24272. function put_short (s, w) {
  24273. // put_byte(s, (uch)((w) & 0xff));
  24274. // put_byte(s, (uch)((ush)(w) >> 8));
  24275. s.pending_buf[s.pending++] = (w) & 0xff;
  24276. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24277. }
  24278. /* ===========================================================================
  24279. * Send a value on a given number of bits.
  24280. * IN assertion: length <= 16 and value fits in length bits.
  24281. */
  24282. function send_bits(s, value, length) {
  24283. if (s.bi_valid > (Buf_size - length)) {
  24284. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24285. put_short(s, s.bi_buf);
  24286. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24287. s.bi_valid += length - Buf_size;
  24288. } else {
  24289. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24290. s.bi_valid += length;
  24291. }
  24292. }
  24293. function send_code(s, c, tree) {
  24294. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24295. }
  24296. /* ===========================================================================
  24297. * Reverse the first len bits of a code, using straightforward code (a faster
  24298. * method would use a table)
  24299. * IN assertion: 1 <= len <= 15
  24300. */
  24301. function bi_reverse(code, len) {
  24302. var res = 0;
  24303. do {
  24304. res |= code & 1;
  24305. code >>>= 1;
  24306. res <<= 1;
  24307. } while (--len > 0);
  24308. return res >>> 1;
  24309. }
  24310. /* ===========================================================================
  24311. * Flush the bit buffer, keeping at most 7 bits in it.
  24312. */
  24313. function bi_flush(s) {
  24314. if (s.bi_valid === 16) {
  24315. put_short(s, s.bi_buf);
  24316. s.bi_buf = 0;
  24317. s.bi_valid = 0;
  24318. } else if (s.bi_valid >= 8) {
  24319. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24320. s.bi_buf >>= 8;
  24321. s.bi_valid -= 8;
  24322. }
  24323. }
  24324. /* ===========================================================================
  24325. * Compute the optimal bit lengths for a tree and update the total bit length
  24326. * for the current block.
  24327. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24328. * above are the tree nodes sorted by increasing frequency.
  24329. * OUT assertions: the field len is set to the optimal bit length, the
  24330. * array bl_count contains the frequencies for each bit length.
  24331. * The length opt_len is updated; static_len is also updated if stree is
  24332. * not null.
  24333. */
  24334. function gen_bitlen(s, desc)
  24335. // deflate_state *s;
  24336. // tree_desc *desc; /* the tree descriptor */
  24337. {
  24338. var tree = desc.dyn_tree;
  24339. var max_code = desc.max_code;
  24340. var stree = desc.stat_desc.static_tree;
  24341. var has_stree = desc.stat_desc.has_stree;
  24342. var extra = desc.stat_desc.extra_bits;
  24343. var base = desc.stat_desc.extra_base;
  24344. var max_length = desc.stat_desc.max_length;
  24345. var h; /* heap index */
  24346. var n, m; /* iterate over the tree elements */
  24347. var bits; /* bit length */
  24348. var xbits; /* extra bits */
  24349. var f; /* frequency */
  24350. var overflow = 0; /* number of elements with bit length too large */
  24351. for (bits = 0; bits <= MAX_BITS; bits++) {
  24352. s.bl_count[bits] = 0;
  24353. }
  24354. /* In a first pass, compute the optimal bit lengths (which may
  24355. * overflow in the case of the bit length tree).
  24356. */
  24357. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24358. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24359. n = s.heap[h];
  24360. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24361. if (bits > max_length) {
  24362. bits = max_length;
  24363. overflow++;
  24364. }
  24365. tree[n*2 + 1]/*.Len*/ = bits;
  24366. /* We overwrite tree[n].Dad which is no longer needed */
  24367. if (n > max_code) { continue; } /* not a leaf node */
  24368. s.bl_count[bits]++;
  24369. xbits = 0;
  24370. if (n >= base) {
  24371. xbits = extra[n-base];
  24372. }
  24373. f = tree[n * 2]/*.Freq*/;
  24374. s.opt_len += f * (bits + xbits);
  24375. if (has_stree) {
  24376. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24377. }
  24378. }
  24379. if (overflow === 0) { return; }
  24380. // Trace((stderr,"\nbit length overflow\n"));
  24381. /* This happens for example on obj2 and pic of the Calgary corpus */
  24382. /* Find the first bit length which could increase: */
  24383. do {
  24384. bits = max_length-1;
  24385. while (s.bl_count[bits] === 0) { bits--; }
  24386. s.bl_count[bits]--; /* move one leaf down the tree */
  24387. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24388. s.bl_count[max_length]--;
  24389. /* The brother of the overflow item also moves one step up,
  24390. * but this does not affect bl_count[max_length]
  24391. */
  24392. overflow -= 2;
  24393. } while (overflow > 0);
  24394. /* Now recompute all bit lengths, scanning in increasing frequency.
  24395. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24396. * lengths instead of fixing only the wrong ones. This idea is taken
  24397. * from 'ar' written by Haruhiko Okumura.)
  24398. */
  24399. for (bits = max_length; bits !== 0; bits--) {
  24400. n = s.bl_count[bits];
  24401. while (n !== 0) {
  24402. m = s.heap[--h];
  24403. if (m > max_code) { continue; }
  24404. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24405. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24406. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24407. tree[m*2 + 1]/*.Len*/ = bits;
  24408. }
  24409. n--;
  24410. }
  24411. }
  24412. }
  24413. /* ===========================================================================
  24414. * Generate the codes for a given tree and bit counts (which need not be
  24415. * optimal).
  24416. * IN assertion: the array bl_count contains the bit length statistics for
  24417. * the given tree and the field len is set for all tree elements.
  24418. * OUT assertion: the field code is set for all tree elements of non
  24419. * zero code length.
  24420. */
  24421. function gen_codes(tree, max_code, bl_count)
  24422. // ct_data *tree; /* the tree to decorate */
  24423. // int max_code; /* largest code with non zero frequency */
  24424. // ushf *bl_count; /* number of codes at each bit length */
  24425. {
  24426. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24427. var code = 0; /* running code value */
  24428. var bits; /* bit index */
  24429. var n; /* code index */
  24430. /* The distribution counts are first used to generate the code values
  24431. * without bit reversal.
  24432. */
  24433. for (bits = 1; bits <= MAX_BITS; bits++) {
  24434. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24435. }
  24436. /* Check that the bit counts in bl_count are consistent. The last code
  24437. * must be all ones.
  24438. */
  24439. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24440. // "inconsistent bit counts");
  24441. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24442. for (n = 0; n <= max_code; n++) {
  24443. var len = tree[n*2 + 1]/*.Len*/;
  24444. if (len === 0) { continue; }
  24445. /* Now reverse the bits */
  24446. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24447. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24448. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24449. }
  24450. }
  24451. /* ===========================================================================
  24452. * Initialize the various 'constant' tables.
  24453. */
  24454. function tr_static_init() {
  24455. var n; /* iterates over tree elements */
  24456. var bits; /* bit counter */
  24457. var length; /* length value */
  24458. var code; /* code value */
  24459. var dist; /* distance index */
  24460. var bl_count = new Array(MAX_BITS+1);
  24461. /* number of codes at each bit length for an optimal tree */
  24462. // do check in _tr_init()
  24463. //if (static_init_done) return;
  24464. /* For some embedded targets, global variables are not initialized: */
  24465. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24466. static_l_desc.static_tree = static_ltree;
  24467. static_l_desc.extra_bits = extra_lbits;
  24468. static_d_desc.static_tree = static_dtree;
  24469. static_d_desc.extra_bits = extra_dbits;
  24470. static_bl_desc.extra_bits = extra_blbits;
  24471. #endif*/
  24472. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24473. length = 0;
  24474. for (code = 0; code < LENGTH_CODES-1; code++) {
  24475. base_length[code] = length;
  24476. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24477. _length_code[length++] = code;
  24478. }
  24479. }
  24480. //Assert (length == 256, "tr_static_init: length != 256");
  24481. /* Note that the length 255 (match length 258) can be represented
  24482. * in two different ways: code 284 + 5 bits or code 285, so we
  24483. * overwrite length_code[255] to use the best encoding:
  24484. */
  24485. _length_code[length-1] = code;
  24486. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24487. dist = 0;
  24488. for (code = 0 ; code < 16; code++) {
  24489. base_dist[code] = dist;
  24490. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24491. _dist_code[dist++] = code;
  24492. }
  24493. }
  24494. //Assert (dist == 256, "tr_static_init: dist != 256");
  24495. dist >>= 7; /* from now on, all distances are divided by 128 */
  24496. for (; code < D_CODES; code++) {
  24497. base_dist[code] = dist << 7;
  24498. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24499. _dist_code[256 + dist++] = code;
  24500. }
  24501. }
  24502. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24503. /* Construct the codes of the static literal tree */
  24504. for (bits = 0; bits <= MAX_BITS; bits++) {
  24505. bl_count[bits] = 0;
  24506. }
  24507. n = 0;
  24508. while (n <= 143) {
  24509. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24510. n++;
  24511. bl_count[8]++;
  24512. }
  24513. while (n <= 255) {
  24514. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24515. n++;
  24516. bl_count[9]++;
  24517. }
  24518. while (n <= 279) {
  24519. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24520. n++;
  24521. bl_count[7]++;
  24522. }
  24523. while (n <= 287) {
  24524. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24525. n++;
  24526. bl_count[8]++;
  24527. }
  24528. /* Codes 286 and 287 do not exist, but we must include them in the
  24529. * tree construction to get a canonical Huffman tree (longest code
  24530. * all ones)
  24531. */
  24532. gen_codes(static_ltree, L_CODES+1, bl_count);
  24533. /* The static distance tree is trivial: */
  24534. for (n = 0; n < D_CODES; n++) {
  24535. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24536. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24537. }
  24538. // Now data ready and we can init static trees
  24539. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24540. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24541. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24542. //static_init_done = true;
  24543. }
  24544. /* ===========================================================================
  24545. * Initialize a new block.
  24546. */
  24547. function init_block(s) {
  24548. var n; /* iterates over tree elements */
  24549. /* Initialize the trees. */
  24550. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24551. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24552. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24553. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24554. s.opt_len = s.static_len = 0;
  24555. s.last_lit = s.matches = 0;
  24556. }
  24557. /* ===========================================================================
  24558. * Flush the bit buffer and align the output on a byte boundary
  24559. */
  24560. function bi_windup(s)
  24561. {
  24562. if (s.bi_valid > 8) {
  24563. put_short(s, s.bi_buf);
  24564. } else if (s.bi_valid > 0) {
  24565. //put_byte(s, (Byte)s->bi_buf);
  24566. s.pending_buf[s.pending++] = s.bi_buf;
  24567. }
  24568. s.bi_buf = 0;
  24569. s.bi_valid = 0;
  24570. }
  24571. /* ===========================================================================
  24572. * Copy a stored block, storing first the length and its
  24573. * one's complement if requested.
  24574. */
  24575. function copy_block(s, buf, len, header)
  24576. //DeflateState *s;
  24577. //charf *buf; /* the input data */
  24578. //unsigned len; /* its length */
  24579. //int header; /* true if block header must be written */
  24580. {
  24581. bi_windup(s); /* align on byte boundary */
  24582. if (header) {
  24583. put_short(s, len);
  24584. put_short(s, ~len);
  24585. }
  24586. // while (len--) {
  24587. // put_byte(s, *buf++);
  24588. // }
  24589. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24590. s.pending += len;
  24591. }
  24592. /* ===========================================================================
  24593. * Compares to subtrees, using the tree depth as tie breaker when
  24594. * the subtrees have equal frequency. This minimizes the worst case length.
  24595. */
  24596. function smaller(tree, n, m, depth) {
  24597. var _n2 = n*2;
  24598. var _m2 = m*2;
  24599. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24600. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24601. }
  24602. /* ===========================================================================
  24603. * Restore the heap property by moving down the tree starting at node k,
  24604. * exchanging a node with the smallest of its two sons if necessary, stopping
  24605. * when the heap property is re-established (each father smaller than its
  24606. * two sons).
  24607. */
  24608. function pqdownheap(s, tree, k)
  24609. // deflate_state *s;
  24610. // ct_data *tree; /* the tree to restore */
  24611. // int k; /* node to move down */
  24612. {
  24613. var v = s.heap[k];
  24614. var j = k << 1; /* left son of k */
  24615. while (j <= s.heap_len) {
  24616. /* Set j to the smallest of the two sons: */
  24617. if (j < s.heap_len &&
  24618. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24619. j++;
  24620. }
  24621. /* Exit if v is smaller than both sons */
  24622. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24623. /* Exchange v with the smallest son */
  24624. s.heap[k] = s.heap[j];
  24625. k = j;
  24626. /* And continue down the tree, setting j to the left son of k */
  24627. j <<= 1;
  24628. }
  24629. s.heap[k] = v;
  24630. }
  24631. // inlined manually
  24632. // var SMALLEST = 1;
  24633. /* ===========================================================================
  24634. * Send the block data compressed using the given Huffman trees
  24635. */
  24636. function compress_block(s, ltree, dtree)
  24637. // deflate_state *s;
  24638. // const ct_data *ltree; /* literal tree */
  24639. // const ct_data *dtree; /* distance tree */
  24640. {
  24641. var dist; /* distance of matched string */
  24642. var lc; /* match length or unmatched char (if dist == 0) */
  24643. var lx = 0; /* running index in l_buf */
  24644. var code; /* the code to send */
  24645. var extra; /* number of extra bits to send */
  24646. if (s.last_lit !== 0) {
  24647. do {
  24648. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24649. lc = s.pending_buf[s.l_buf + lx];
  24650. lx++;
  24651. if (dist === 0) {
  24652. send_code(s, lc, ltree); /* send a literal byte */
  24653. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24654. } else {
  24655. /* Here, lc is the match length - MIN_MATCH */
  24656. code = _length_code[lc];
  24657. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24658. extra = extra_lbits[code];
  24659. if (extra !== 0) {
  24660. lc -= base_length[code];
  24661. send_bits(s, lc, extra); /* send the extra length bits */
  24662. }
  24663. dist--; /* dist is now the match distance - 1 */
  24664. code = d_code(dist);
  24665. //Assert (code < D_CODES, "bad d_code");
  24666. send_code(s, code, dtree); /* send the distance code */
  24667. extra = extra_dbits[code];
  24668. if (extra !== 0) {
  24669. dist -= base_dist[code];
  24670. send_bits(s, dist, extra); /* send the extra distance bits */
  24671. }
  24672. } /* literal or match pair ? */
  24673. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24674. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24675. // "pendingBuf overflow");
  24676. } while (lx < s.last_lit);
  24677. }
  24678. send_code(s, END_BLOCK, ltree);
  24679. }
  24680. /* ===========================================================================
  24681. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24682. * Update the total bit length for the current block.
  24683. * IN assertion: the field freq is set for all tree elements.
  24684. * OUT assertions: the fields len and code are set to the optimal bit length
  24685. * and corresponding code. The length opt_len is updated; static_len is
  24686. * also updated if stree is not null. The field max_code is set.
  24687. */
  24688. function build_tree(s, desc)
  24689. // deflate_state *s;
  24690. // tree_desc *desc; /* the tree descriptor */
  24691. {
  24692. var tree = desc.dyn_tree;
  24693. var stree = desc.stat_desc.static_tree;
  24694. var has_stree = desc.stat_desc.has_stree;
  24695. var elems = desc.stat_desc.elems;
  24696. var n, m; /* iterate over heap elements */
  24697. var max_code = -1; /* largest code with non zero frequency */
  24698. var node; /* new node being created */
  24699. /* Construct the initial heap, with least frequent element in
  24700. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24701. * heap[0] is not used.
  24702. */
  24703. s.heap_len = 0;
  24704. s.heap_max = HEAP_SIZE;
  24705. for (n = 0; n < elems; n++) {
  24706. if (tree[n * 2]/*.Freq*/ !== 0) {
  24707. s.heap[++s.heap_len] = max_code = n;
  24708. s.depth[n] = 0;
  24709. } else {
  24710. tree[n*2 + 1]/*.Len*/ = 0;
  24711. }
  24712. }
  24713. /* The pkzip format requires that at least one distance code exists,
  24714. * and that at least one bit should be sent even if there is only one
  24715. * possible code. So to avoid special checks later on we force at least
  24716. * two codes of non zero frequency.
  24717. */
  24718. while (s.heap_len < 2) {
  24719. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24720. tree[node * 2]/*.Freq*/ = 1;
  24721. s.depth[node] = 0;
  24722. s.opt_len--;
  24723. if (has_stree) {
  24724. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24725. }
  24726. /* node is 0 or 1 so it does not have extra bits */
  24727. }
  24728. desc.max_code = max_code;
  24729. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24730. * establish sub-heaps of increasing lengths:
  24731. */
  24732. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24733. /* Construct the Huffman tree by repeatedly combining the least two
  24734. * frequent nodes.
  24735. */
  24736. node = elems; /* next internal node of the tree */
  24737. do {
  24738. //pqremove(s, tree, n); /* n = node of least frequency */
  24739. /*** pqremove ***/
  24740. n = s.heap[1/*SMALLEST*/];
  24741. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24742. pqdownheap(s, tree, 1/*SMALLEST*/);
  24743. /***/
  24744. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24745. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24746. s.heap[--s.heap_max] = m;
  24747. /* Create a new node father of n and m */
  24748. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24749. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24750. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24751. /* and insert the new node in the heap */
  24752. s.heap[1/*SMALLEST*/] = node++;
  24753. pqdownheap(s, tree, 1/*SMALLEST*/);
  24754. } while (s.heap_len >= 2);
  24755. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24756. /* At this point, the fields freq and dad are set. We can now
  24757. * generate the bit lengths.
  24758. */
  24759. gen_bitlen(s, desc);
  24760. /* The field len is now set, we can generate the bit codes */
  24761. gen_codes(tree, max_code, s.bl_count);
  24762. }
  24763. /* ===========================================================================
  24764. * Scan a literal or distance tree to determine the frequencies of the codes
  24765. * in the bit length tree.
  24766. */
  24767. function scan_tree(s, tree, max_code)
  24768. // deflate_state *s;
  24769. // ct_data *tree; /* the tree to be scanned */
  24770. // int max_code; /* and its largest code of non zero frequency */
  24771. {
  24772. var n; /* iterates over all tree elements */
  24773. var prevlen = -1; /* last emitted length */
  24774. var curlen; /* length of current code */
  24775. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24776. var count = 0; /* repeat count of the current code */
  24777. var max_count = 7; /* max repeat count */
  24778. var min_count = 4; /* min repeat count */
  24779. if (nextlen === 0) {
  24780. max_count = 138;
  24781. min_count = 3;
  24782. }
  24783. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24784. for (n = 0; n <= max_code; n++) {
  24785. curlen = nextlen;
  24786. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24787. if (++count < max_count && curlen === nextlen) {
  24788. continue;
  24789. } else if (count < min_count) {
  24790. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24791. } else if (curlen !== 0) {
  24792. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24793. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24794. } else if (count <= 10) {
  24795. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24796. } else {
  24797. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24798. }
  24799. count = 0;
  24800. prevlen = curlen;
  24801. if (nextlen === 0) {
  24802. max_count = 138;
  24803. min_count = 3;
  24804. } else if (curlen === nextlen) {
  24805. max_count = 6;
  24806. min_count = 3;
  24807. } else {
  24808. max_count = 7;
  24809. min_count = 4;
  24810. }
  24811. }
  24812. }
  24813. /* ===========================================================================
  24814. * Send a literal or distance tree in compressed form, using the codes in
  24815. * bl_tree.
  24816. */
  24817. function send_tree(s, tree, max_code)
  24818. // deflate_state *s;
  24819. // ct_data *tree; /* the tree to be scanned */
  24820. // int max_code; /* and its largest code of non zero frequency */
  24821. {
  24822. var n; /* iterates over all tree elements */
  24823. var prevlen = -1; /* last emitted length */
  24824. var curlen; /* length of current code */
  24825. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24826. var count = 0; /* repeat count of the current code */
  24827. var max_count = 7; /* max repeat count */
  24828. var min_count = 4; /* min repeat count */
  24829. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24830. if (nextlen === 0) {
  24831. max_count = 138;
  24832. min_count = 3;
  24833. }
  24834. for (n = 0; n <= max_code; n++) {
  24835. curlen = nextlen;
  24836. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24837. if (++count < max_count && curlen === nextlen) {
  24838. continue;
  24839. } else if (count < min_count) {
  24840. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24841. } else if (curlen !== 0) {
  24842. if (curlen !== prevlen) {
  24843. send_code(s, curlen, s.bl_tree);
  24844. count--;
  24845. }
  24846. //Assert(count >= 3 && count <= 6, " 3_6?");
  24847. send_code(s, REP_3_6, s.bl_tree);
  24848. send_bits(s, count-3, 2);
  24849. } else if (count <= 10) {
  24850. send_code(s, REPZ_3_10, s.bl_tree);
  24851. send_bits(s, count-3, 3);
  24852. } else {
  24853. send_code(s, REPZ_11_138, s.bl_tree);
  24854. send_bits(s, count-11, 7);
  24855. }
  24856. count = 0;
  24857. prevlen = curlen;
  24858. if (nextlen === 0) {
  24859. max_count = 138;
  24860. min_count = 3;
  24861. } else if (curlen === nextlen) {
  24862. max_count = 6;
  24863. min_count = 3;
  24864. } else {
  24865. max_count = 7;
  24866. min_count = 4;
  24867. }
  24868. }
  24869. }
  24870. /* ===========================================================================
  24871. * Construct the Huffman tree for the bit lengths and return the index in
  24872. * bl_order of the last bit length code to send.
  24873. */
  24874. function build_bl_tree(s) {
  24875. var max_blindex; /* index of last bit length code of non zero freq */
  24876. /* Determine the bit length frequencies for literal and distance trees */
  24877. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24878. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24879. /* Build the bit length tree: */
  24880. build_tree(s, s.bl_desc);
  24881. /* opt_len now includes the length of the tree representations, except
  24882. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24883. */
  24884. /* Determine the number of bit length codes to send. The pkzip format
  24885. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24886. * 3 but the actual value used is 4.)
  24887. */
  24888. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24889. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24890. break;
  24891. }
  24892. }
  24893. /* Update opt_len to include the bit length tree and counts */
  24894. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24895. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24896. // s->opt_len, s->static_len));
  24897. return max_blindex;
  24898. }
  24899. /* ===========================================================================
  24900. * Send the header for a block using dynamic Huffman trees: the counts, the
  24901. * lengths of the bit length codes, the literal tree and the distance tree.
  24902. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24903. */
  24904. function send_all_trees(s, lcodes, dcodes, blcodes)
  24905. // deflate_state *s;
  24906. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24907. {
  24908. var rank; /* index in bl_order */
  24909. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24910. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24911. // "too many codes");
  24912. //Tracev((stderr, "\nbl counts: "));
  24913. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24914. send_bits(s, dcodes-1, 5);
  24915. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24916. for (rank = 0; rank < blcodes; rank++) {
  24917. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24918. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24919. }
  24920. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24921. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24922. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24923. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24924. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24925. }
  24926. /* ===========================================================================
  24927. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24928. * - TEXT if the two conditions below are satisfied:
  24929. * a) There are no non-portable control characters belonging to the
  24930. * "black list" (0..6, 14..25, 28..31).
  24931. * b) There is at least one printable character belonging to the
  24932. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24933. * - BINARY otherwise.
  24934. * - The following partially-portable control characters form a
  24935. * "gray list" that is ignored in this detection algorithm:
  24936. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24937. * IN assertion: the fields Freq of dyn_ltree are set.
  24938. */
  24939. function detect_data_type(s) {
  24940. /* black_mask is the bit mask of black-listed bytes
  24941. * set bits 0..6, 14..25, and 28..31
  24942. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24943. */
  24944. var black_mask = 0xf3ffc07f;
  24945. var n;
  24946. /* Check for non-textual ("black-listed") bytes. */
  24947. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24948. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24949. return Z_BINARY;
  24950. }
  24951. }
  24952. /* Check for textual ("white-listed") bytes. */
  24953. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24954. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24955. return Z_TEXT;
  24956. }
  24957. for (n = 32; n < LITERALS; n++) {
  24958. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24959. return Z_TEXT;
  24960. }
  24961. }
  24962. /* There are no "black-listed" or "white-listed" bytes:
  24963. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24964. */
  24965. return Z_BINARY;
  24966. }
  24967. var static_init_done = false;
  24968. /* ===========================================================================
  24969. * Initialize the tree data structures for a new zlib stream.
  24970. */
  24971. function _tr_init(s)
  24972. {
  24973. if (!static_init_done) {
  24974. tr_static_init();
  24975. static_init_done = true;
  24976. }
  24977. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24978. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24979. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24980. s.bi_buf = 0;
  24981. s.bi_valid = 0;
  24982. /* Initialize the first block of the first file: */
  24983. init_block(s);
  24984. }
  24985. /* ===========================================================================
  24986. * Send a stored block
  24987. */
  24988. function _tr_stored_block(s, buf, stored_len, last)
  24989. //DeflateState *s;
  24990. //charf *buf; /* input block */
  24991. //ulg stored_len; /* length of input block */
  24992. //int last; /* one if this is the last block for a file */
  24993. {
  24994. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24995. copy_block(s, buf, stored_len, true); /* with header */
  24996. }
  24997. /* ===========================================================================
  24998. * Send one empty static block to give enough lookahead for inflate.
  24999. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25000. */
  25001. function _tr_align(s) {
  25002. send_bits(s, STATIC_TREES<<1, 3);
  25003. send_code(s, END_BLOCK, static_ltree);
  25004. bi_flush(s);
  25005. }
  25006. /* ===========================================================================
  25007. * Determine the best encoding for the current block: dynamic trees, static
  25008. * trees or store, and output the encoded block to the zip file.
  25009. */
  25010. function _tr_flush_block(s, buf, stored_len, last)
  25011. //DeflateState *s;
  25012. //charf *buf; /* input block, or NULL if too old */
  25013. //ulg stored_len; /* length of input block */
  25014. //int last; /* one if this is the last block for a file */
  25015. {
  25016. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25017. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25018. /* Build the Huffman trees unless a stored block is forced */
  25019. if (s.level > 0) {
  25020. /* Check if the file is binary or text */
  25021. if (s.strm.data_type === Z_UNKNOWN) {
  25022. s.strm.data_type = detect_data_type(s);
  25023. }
  25024. /* Construct the literal and distance trees */
  25025. build_tree(s, s.l_desc);
  25026. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25027. // s->static_len));
  25028. build_tree(s, s.d_desc);
  25029. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25030. // s->static_len));
  25031. /* At this point, opt_len and static_len are the total bit lengths of
  25032. * the compressed block data, excluding the tree representations.
  25033. */
  25034. /* Build the bit length tree for the above two trees, and get the index
  25035. * in bl_order of the last bit length code to send.
  25036. */
  25037. max_blindex = build_bl_tree(s);
  25038. /* Determine the best encoding. Compute the block lengths in bytes. */
  25039. opt_lenb = (s.opt_len+3+7) >>> 3;
  25040. static_lenb = (s.static_len+3+7) >>> 3;
  25041. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25042. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25043. // s->last_lit));
  25044. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25045. } else {
  25046. // Assert(buf != (char*)0, "lost buf");
  25047. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25048. }
  25049. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25050. /* 4: two words for the lengths */
  25051. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25052. * Otherwise we can't have processed more than WSIZE input bytes since
  25053. * the last block flush, because compression would have been
  25054. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25055. * transform a block into a stored block.
  25056. */
  25057. _tr_stored_block(s, buf, stored_len, last);
  25058. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25059. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25060. compress_block(s, static_ltree, static_dtree);
  25061. } else {
  25062. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25063. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25064. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25065. }
  25066. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25067. /* The above check is made mod 2^32, for files larger than 512 MB
  25068. * and uLong implemented on 32 bits.
  25069. */
  25070. init_block(s);
  25071. if (last) {
  25072. bi_windup(s);
  25073. }
  25074. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25075. // s->compressed_len-7*last));
  25076. }
  25077. /* ===========================================================================
  25078. * Save the match info and tally the frequency counts. Return true if
  25079. * the current block must be flushed.
  25080. */
  25081. function _tr_tally(s, dist, lc)
  25082. // deflate_state *s;
  25083. // unsigned dist; /* distance of matched string */
  25084. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25085. {
  25086. //var out_length, in_length, dcode;
  25087. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25088. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25089. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25090. s.last_lit++;
  25091. if (dist === 0) {
  25092. /* lc is the unmatched char */
  25093. s.dyn_ltree[lc*2]/*.Freq*/++;
  25094. } else {
  25095. s.matches++;
  25096. /* Here, lc is the match length - MIN_MATCH */
  25097. dist--; /* dist = match distance - 1 */
  25098. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25099. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25100. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25101. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25102. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25103. }
  25104. // (!) This block is disabled in zlib defailts,
  25105. // don't enable it for binary compatibility
  25106. //#ifdef TRUNCATE_BLOCK
  25107. // /* Try to guess if it is profitable to stop the current block here */
  25108. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25109. // /* Compute an upper bound for the compressed length */
  25110. // out_length = s.last_lit*8;
  25111. // in_length = s.strstart - s.block_start;
  25112. //
  25113. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25114. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25115. // }
  25116. // out_length >>>= 3;
  25117. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25118. // // s->last_lit, in_length, out_length,
  25119. // // 100L - out_length*100L/in_length));
  25120. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25121. // return true;
  25122. // }
  25123. // }
  25124. //#endif
  25125. return (s.last_lit === s.lit_bufsize-1);
  25126. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25127. * on 16 bit machines and because stored blocks are restricted to
  25128. * 64K-1 bytes.
  25129. */
  25130. }
  25131. exports._tr_init = _tr_init;
  25132. exports._tr_stored_block = _tr_stored_block;
  25133. exports._tr_flush_block = _tr_flush_block;
  25134. exports._tr_tally = _tr_tally;
  25135. exports._tr_align = _tr_align;
  25136. },{"../utils/common":74}],86:[function(require,module,exports){
  25137. 'use strict';
  25138. function ZStream() {
  25139. /* next input byte */
  25140. this.input = null; // JS specific, because we have no pointers
  25141. this.next_in = 0;
  25142. /* number of bytes available at input */
  25143. this.avail_in = 0;
  25144. /* total number of input bytes read so far */
  25145. this.total_in = 0;
  25146. /* next output byte should be put there */
  25147. this.output = null; // JS specific, because we have no pointers
  25148. this.next_out = 0;
  25149. /* remaining free space at output */
  25150. this.avail_out = 0;
  25151. /* total number of bytes output so far */
  25152. this.total_out = 0;
  25153. /* last error message, NULL if no error */
  25154. this.msg = ''/*Z_NULL*/;
  25155. /* not visible by applications */
  25156. this.state = null;
  25157. /* best guess about the data type: binary or text */
  25158. this.data_type = 2/*Z_UNKNOWN*/;
  25159. /* adler32 value of the uncompressed data */
  25160. this.adler = 0;
  25161. }
  25162. module.exports = ZStream;
  25163. },{}],87:[function(require,module,exports){
  25164. module.exports = require('./lib/retry');
  25165. },{"./lib/retry":88}],88:[function(require,module,exports){
  25166. var RetryOperation = require('./retry_operation');
  25167. exports.operation = function(options) {
  25168. var timeouts = exports.timeouts(options);
  25169. return new RetryOperation(timeouts);
  25170. };
  25171. exports.timeouts = function(options) {
  25172. if (options instanceof Array) {
  25173. return [].concat(options);
  25174. }
  25175. var opts = {
  25176. retries: 10,
  25177. factor: 2,
  25178. minTimeout: 1 * 1000,
  25179. maxTimeout: Infinity,
  25180. randomize: false
  25181. };
  25182. for (var key in options) {
  25183. opts[key] = options[key];
  25184. }
  25185. if (opts.minTimeout > opts.maxTimeout) {
  25186. throw new Error('minTimeout is greater than maxTimeout');
  25187. }
  25188. var timeouts = [];
  25189. for (var i = 0; i < opts.retries; i++) {
  25190. timeouts.push(this._createTimeout(i, opts));
  25191. }
  25192. // sort the array numerically ascending
  25193. timeouts.sort(function(a,b) {
  25194. return a - b;
  25195. });
  25196. return timeouts;
  25197. };
  25198. exports._createTimeout = function(attempt, opts) {
  25199. var random = (opts.randomize)
  25200. ? (Math.random() + 1)
  25201. : 1;
  25202. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25203. timeout = Math.min(timeout, opts.maxTimeout);
  25204. return timeout;
  25205. };
  25206. },{"./retry_operation":89}],89:[function(require,module,exports){
  25207. function RetryOperation(timeouts) {
  25208. this._timeouts = timeouts;
  25209. this._fn = null;
  25210. this._errors = [];
  25211. this._attempts = 1;
  25212. this._operationTimeout = null;
  25213. this._operationTimeoutCb = null;
  25214. this._timeout = null;
  25215. }
  25216. module.exports = RetryOperation;
  25217. RetryOperation.prototype.retry = function(err) {
  25218. if (this._timeout) {
  25219. clearTimeout(this._timeout);
  25220. }
  25221. if (!err) {
  25222. return false;
  25223. }
  25224. this._errors.push(err);
  25225. var timeout = this._timeouts.shift();
  25226. if (timeout === undefined) {
  25227. return false;
  25228. }
  25229. this._attempts++;
  25230. var self = this;
  25231. setTimeout(function() {
  25232. self._fn(self._attempts);
  25233. if (self._operationTimeoutCb) {
  25234. self._timeout = setTimeout(function() {
  25235. self._operationTimeoutCb(self._attempts);
  25236. }, self._operationTimeout);
  25237. }
  25238. }, timeout);
  25239. return true;
  25240. };
  25241. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25242. this._fn = fn;
  25243. if (timeoutOps) {
  25244. if (timeoutOps.timeout) {
  25245. this._operationTimeout = timeoutOps.timeout;
  25246. }
  25247. if (timeoutOps.cb) {
  25248. this._operationTimeoutCb = timeoutOps.cb;
  25249. }
  25250. }
  25251. this._fn(this._attempts);
  25252. var self = this;
  25253. if (this._operationTimeoutCb) {
  25254. this._timeout = setTimeout(function() {
  25255. self._operationTimeoutCb();
  25256. }, self._operationTimeout);
  25257. }
  25258. };
  25259. RetryOperation.prototype.try = function(fn) {
  25260. console.log('Using RetryOperation.try() is deprecated');
  25261. this.attempt(fn);
  25262. };
  25263. RetryOperation.prototype.start = function(fn) {
  25264. console.log('Using RetryOperation.start() is deprecated');
  25265. this.attempt(fn);
  25266. };
  25267. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25268. RetryOperation.prototype.errors = function() {
  25269. return this._errors;
  25270. };
  25271. RetryOperation.prototype.attempts = function() {
  25272. return this._attempts;
  25273. };
  25274. RetryOperation.prototype.mainError = function() {
  25275. if (this._errors.length === 0) {
  25276. return null;
  25277. }
  25278. var counts = {};
  25279. var mainError = null;
  25280. var mainErrorCount = 0;
  25281. for (var i = 0; i < this._errors.length; i++) {
  25282. var error = this._errors[i];
  25283. var message = error.message;
  25284. var count = (counts[message] || 0) + 1;
  25285. counts[message] = count;
  25286. if (count >= mainErrorCount) {
  25287. mainError = error;
  25288. mainErrorCount = count;
  25289. }
  25290. }
  25291. return mainError;
  25292. };
  25293. },{}],90:[function(require,module,exports){
  25294. module.exports = function arrayEquals(array) {
  25295. // if the other array is a falsy value, return
  25296. if (!array)
  25297. return false;
  25298. // compare lengths - can save a lot of time
  25299. if (this.length != array.length)
  25300. return false;
  25301. for (var i = 0, l = this.length; i < l; i++) {
  25302. // Check if we have nested arrays
  25303. if (this[i] instanceof Array && array[i] instanceof Array) {
  25304. // recurse into the nested arrays
  25305. if (!arrayEquals.apply(this[i], [array[i]]))
  25306. return false;
  25307. } else if (this[i] != array[i]) {
  25308. // Warning - two different object instances will never be equal:
  25309. // {x:20} != {x:20}
  25310. return false;
  25311. }
  25312. }
  25313. return true;
  25314. }
  25315. },{}],91:[function(require,module,exports){
  25316. exports.Interop = require('./interop');
  25317. },{"./interop":92}],92:[function(require,module,exports){
  25318. "use strict";
  25319. var transform = require('./transform');
  25320. var arrayEquals = require('./array-equals');
  25321. function Interop() {
  25322. /**
  25323. * This map holds the most recent Unified Plan offer/answer SDP that was
  25324. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25325. * the SDP string as values.
  25326. *
  25327. * @type {{}}
  25328. */
  25329. this.cache = {};
  25330. }
  25331. module.exports = Interop;
  25332. /**
  25333. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25334. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25335. * application.
  25336. *
  25337. * @param desc
  25338. * @returns {*}
  25339. */
  25340. Interop.prototype.toPlanB = function(desc) {
  25341. //#region Preliminary input validation.
  25342. if (typeof desc !== 'object' || desc === null ||
  25343. typeof desc.sdp !== 'string') {
  25344. console.warn('An empty description was passed as an argument.');
  25345. return desc;
  25346. }
  25347. // Objectify the SDP for easier manipulation.
  25348. var session = transform.parse(desc.sdp);
  25349. // If the SDP contains no media, there's nothing to transform.
  25350. if (typeof session.media === 'undefined' ||
  25351. !Array.isArray(session.media) || session.media.length === 0) {
  25352. console.warn('The description has no media.');
  25353. return desc;
  25354. }
  25355. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25356. // SDP has a video, an audio and a data "channel" at most.
  25357. if (session.media.length <= 3 && session.media.every(function(m) {
  25358. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25359. })) {
  25360. console.warn('This description does not look like Unified Plan.');
  25361. return desc;
  25362. }
  25363. //#endregion
  25364. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25365. // -> Unified Plan transformation.
  25366. this.cache[desc.type] = desc.sdp;
  25367. //#region Convert from Unified Plan to Plan B.
  25368. // We rebuild the session.media array.
  25369. var media = session.media;
  25370. session.media = [];
  25371. // Associative array that maps channel types to channel objects for fast
  25372. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25373. // obj.
  25374. var type2bl = {};
  25375. // Used to build the group:BUNDLE value after the channels construction
  25376. // loop.
  25377. var types = [];
  25378. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25379. media.forEach(function(unifiedLine) {
  25380. // rtcp-mux is required in the Plan B SDP.
  25381. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25382. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25383. unifiedLine.direction !== 'inactive') {
  25384. throw new Error('Cannot convert to Plan B because m-lines ' +
  25385. 'without the rtcp-mux attribute were found.');
  25386. }
  25387. if (unifiedLine.type === 'application') {
  25388. session.media.push(unifiedLine);
  25389. types.push(unifiedLine.mid);
  25390. return;
  25391. }
  25392. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25393. // as the channel basis.
  25394. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25395. type2bl[unifiedLine.type] = unifiedLine;
  25396. }
  25397. // Add sources to the channel and handle a=msid.
  25398. if (typeof unifiedLine.sources === 'object') {
  25399. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25400. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25401. type2bl[unifiedLine.type].sources = {};
  25402. // Assign the sources to the channel.
  25403. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25404. if (typeof unifiedLine.msid !== 'undefined') {
  25405. // In Plan B the msid is an SSRC attribute. Also, we don't
  25406. // care about the obsolete label and mslabel attributes.
  25407. //
  25408. // Note that it is not guaranteed that the unifiedLine will have
  25409. // an msid. recvonly channels in particular don't have one.
  25410. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25411. }
  25412. // NOTE ssrcs in ssrc groups will share msids, as
  25413. // draft-uberti-rtcweb-plan-00 mandates.
  25414. });
  25415. }
  25416. // Add ssrc groups to the channel.
  25417. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25418. Array.isArray(unifiedLine.ssrcGroups)) {
  25419. // Create the ssrcGroups array, if it's not defined.
  25420. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25421. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25422. type2bl[unifiedLine.type].ssrcGroups = [];
  25423. }
  25424. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25425. }
  25426. if (type2bl[unifiedLine.type] === unifiedLine) {
  25427. // Copy ICE related stuff from the principal media line.
  25428. unifiedLine.candidates = media[0].candidates;
  25429. unifiedLine.iceUfrag = media[0].iceUfrag;
  25430. unifiedLine.icePwd = media[0].icePwd;
  25431. unifiedLine.fingerprint = media[0].fingerprint;
  25432. // Plan B mids are in ['audio', 'video', 'data']
  25433. unifiedLine.mid = unifiedLine.type;
  25434. // Plan B doesn't support/need the bundle-only attribute.
  25435. delete unifiedLine.bundleOnly;
  25436. // In Plan B the msid is an SSRC attribute.
  25437. delete unifiedLine.msid;
  25438. // Used to build the group:BUNDLE value after this loop.
  25439. types.push(unifiedLine.type);
  25440. // Add the channel to the new media array.
  25441. session.media.push(unifiedLine);
  25442. }
  25443. });
  25444. // We regenerate the BUNDLE group with the new mids.
  25445. session.groups.some(function(group) {
  25446. if (group.type === 'BUNDLE') {
  25447. group.mids = types.join(' ');
  25448. return true;
  25449. }
  25450. });
  25451. // msid semantic
  25452. session.msidSemantic = {
  25453. semantic: 'WMS',
  25454. token: '*'
  25455. };
  25456. var resStr = transform.write(session);
  25457. return new RTCSessionDescription({
  25458. type: desc.type,
  25459. sdp: resStr
  25460. });
  25461. //#endregion
  25462. };
  25463. /**
  25464. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25465. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25466. * to FF.
  25467. *
  25468. * @param desc
  25469. * @returns {*}
  25470. */
  25471. Interop.prototype.toUnifiedPlan = function(desc) {
  25472. //#region Preliminary input validation.
  25473. if (typeof desc !== 'object' || desc === null ||
  25474. typeof desc.sdp !== 'string') {
  25475. console.warn('An empty description was passed as an argument.');
  25476. return desc;
  25477. }
  25478. var session = transform.parse(desc.sdp);
  25479. // If the SDP contains no media, there's nothing to transform.
  25480. if (typeof session.media === 'undefined' ||
  25481. !Array.isArray(session.media) || session.media.length === 0) {
  25482. console.warn('The description has no media.');
  25483. return desc;
  25484. }
  25485. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25486. // a video, an audio and a data "channel" at most.
  25487. if (session.media.length > 3 || !session.media.every(function(m) {
  25488. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25489. })) {
  25490. console.warn('This description does not look like Plan B.');
  25491. return desc;
  25492. }
  25493. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25494. var mids = [];
  25495. session.media.forEach(function(m) {
  25496. mids.push(m.mid);
  25497. });
  25498. var hasBundle = false;
  25499. if (typeof session.groups !== 'undefined' &&
  25500. Array.isArray(session.groups)) {
  25501. hasBundle = session.groups.every(function(g) {
  25502. return g.type !== 'BUNDLE' ||
  25503. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25504. });
  25505. }
  25506. if (!hasBundle) {
  25507. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25508. " are not bundled were found.");
  25509. }
  25510. //#endregion
  25511. //#region Convert from Plan B to Unified Plan.
  25512. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25513. // rebuild an equivalent Unified Plan offer/answer.
  25514. //
  25515. // For example, if this is a local answer (in Unified Plan style) that we
  25516. // convert to Plan B prior to handing it over to the application (the
  25517. // PeerConnection wrapper called us, for instance, after a successful
  25518. // createAnswer), we want to remember the m-line at which we've seen the
  25519. // (local) SSRC. That's because when the application wants to do call the
  25520. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25521. // Unified Plan), we need to know to which m-line to assign the (local)
  25522. // SSRC. We also need to know all the other m-lines that the original
  25523. // answer had and include them in the transformed answer as well.
  25524. //
  25525. // Another example is if this is a remote offer that we convert to Plan B
  25526. // prior to giving it to the application, we want to remember the mid at
  25527. // which we've seen the (remote) SSRC.
  25528. //
  25529. // In the iteration that follows, we use the cached Unified Plan (if it
  25530. // exists) to assign mids to ssrcs.
  25531. var cached;
  25532. if (typeof this.cache[desc.type] !== 'undefined') {
  25533. cached = transform.parse(this.cache[desc.type]);
  25534. }
  25535. // A helper map that sends mids to m-line objects. We use it later to
  25536. // rebuild the Unified Plan style session.media array.
  25537. var mid2ul = {};
  25538. session.media.forEach(function(bLine) {
  25539. if ((typeof bLine.rtcpMux !== 'string' ||
  25540. bLine.rtcpMux !== 'rtcp-mux') &&
  25541. bLine.direction !== 'inactive') {
  25542. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25543. "without the rtcp-mux attribute were found.");
  25544. }
  25545. if (bLine.type === 'application') {
  25546. mid2ul[bLine.mid] = bLine;
  25547. return;
  25548. }
  25549. // With rtcp-mux and bundle all the channels should have the same ICE
  25550. // stuff.
  25551. var sources = bLine.sources;
  25552. var ssrcGroups = bLine.ssrcGroups;
  25553. var candidates = bLine.candidates;
  25554. var iceUfrag = bLine.iceUfrag;
  25555. var icePwd = bLine.icePwd;
  25556. var fingerprint = bLine.fingerprint;
  25557. var port = bLine.port;
  25558. // We'll use the "bLine" object as a prototype for each new "mLine"
  25559. // that we create, but first we need to clean it up a bit.
  25560. delete bLine.sources;
  25561. delete bLine.ssrcGroups;
  25562. delete bLine.candidates;
  25563. delete bLine.iceUfrag;
  25564. delete bLine.icePwd;
  25565. delete bLine.fingerprint;
  25566. delete bLine.port;
  25567. delete bLine.mid;
  25568. // inverted ssrc group map
  25569. var ssrc2group = {};
  25570. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25571. ssrcGroups.forEach(function (ssrcGroup) {
  25572. // TODO(gp) find out how to receive simulcast with FF. For the
  25573. // time being, hide it.
  25574. if (ssrcGroup.semantics === 'SIM') {
  25575. return;
  25576. }
  25577. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25578. Array.isArray(ssrcGroup.ssrcs)) {
  25579. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25580. if (typeof ssrc2group[ssrc] === 'undefined') {
  25581. ssrc2group[ssrc] = [];
  25582. }
  25583. ssrc2group[ssrc].push(ssrcGroup);
  25584. });
  25585. }
  25586. });
  25587. }
  25588. // ssrc to m-line index.
  25589. var ssrc2ml = {};
  25590. if (typeof sources === 'object') {
  25591. // Explode the Plan B channel sources with one m-line per source.
  25592. Object.keys(sources).forEach(function(ssrc) {
  25593. // The (unified) m-line for this SSRC. We either create it from
  25594. // scratch or, if it's a grouped SSRC, we re-use a related
  25595. // mline. In other words, if the source is grouped with another
  25596. // source, put the two together in the same m-line.
  25597. var unifiedLine;
  25598. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25599. Array.isArray(ssrc2group[ssrc])) {
  25600. ssrc2group[ssrc].some(function (ssrcGroup) {
  25601. // ssrcGroup.ssrcs *is* an Array, no need to check
  25602. // again here.
  25603. return ssrcGroup.ssrcs.some(function (related) {
  25604. if (typeof ssrc2ml[related] === 'object') {
  25605. unifiedLine = ssrc2ml[related];
  25606. return true;
  25607. }
  25608. });
  25609. });
  25610. }
  25611. if (typeof unifiedLine === 'object') {
  25612. // the m-line already exists. Just add the source.
  25613. unifiedLine.sources[ssrc] = sources[ssrc];
  25614. delete sources[ssrc].msid;
  25615. } else {
  25616. // Use the "bLine" as a prototype for the "unifiedLine".
  25617. unifiedLine = Object.create(bLine);
  25618. ssrc2ml[ssrc] = unifiedLine;
  25619. if (typeof sources[ssrc].msid !== 'undefined') {
  25620. // Assign the msid of the source to the m-line. Note
  25621. // that it is not guaranteed that the source will have
  25622. // msid. In particular "recvonly" sources don't have an
  25623. // msid. Note that "recvonly" is a term only defined
  25624. // for m-lines.
  25625. unifiedLine.msid = sources[ssrc].msid;
  25626. delete sources[ssrc].msid;
  25627. }
  25628. // We assign one SSRC per media line.
  25629. unifiedLine.sources = {};
  25630. unifiedLine.sources[ssrc] = sources[ssrc];
  25631. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25632. // Use the cached Unified Plan SDP (if it exists) to assign
  25633. // SSRCs to mids.
  25634. if (typeof cached !== 'undefined' &&
  25635. typeof cached.media !== 'undefined' &&
  25636. Array.isArray(cached.media)) {
  25637. cached.media.forEach(function (m) {
  25638. if (typeof m.sources === 'object') {
  25639. Object.keys(m.sources).forEach(function (s) {
  25640. if (s === ssrc) {
  25641. unifiedLine.mid = m.mid;
  25642. }
  25643. });
  25644. }
  25645. });
  25646. }
  25647. if (typeof unifiedLine.mid === 'undefined') {
  25648. // If this is an SSRC that we see for the first time
  25649. // assign it a new mid. This is typically the case when
  25650. // this method is called to transform a remote
  25651. // description for the first time or when there is a
  25652. // new SSRC in the remote description because a new
  25653. // peer has joined the conference. Local SSRCs should
  25654. // have already been added to the map in the toPlanB
  25655. // method.
  25656. //
  25657. // Because FF generates answers in Unified Plan style,
  25658. // we MUST already have a cached answer with all the
  25659. // local SSRCs mapped to some m-line/mid.
  25660. if (desc.type === 'answer') {
  25661. throw new Error("An unmapped SSRC was found.");
  25662. }
  25663. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25664. }
  25665. // Include the candidates in the 1st media line.
  25666. unifiedLine.candidates = candidates;
  25667. unifiedLine.iceUfrag = iceUfrag;
  25668. unifiedLine.icePwd = icePwd;
  25669. unifiedLine.fingerprint = fingerprint;
  25670. unifiedLine.port = port;
  25671. mid2ul[unifiedLine.mid] = unifiedLine;
  25672. }
  25673. });
  25674. }
  25675. });
  25676. // Rebuild the media array in the right order and add the missing mLines
  25677. // (missing from the Plan B SDP).
  25678. session.media = [];
  25679. mids = []; // reuse
  25680. if (desc.type === 'answer') {
  25681. // The media lines in the answer must match the media lines in the
  25682. // offer. The order is important too. Here we assume that Firefox is the
  25683. // answerer, so we merely have to use the reconstructed (unified) answer
  25684. // to update the cached (unified) answer accordingly.
  25685. //
  25686. // In the general case, one would have to use the cached (unified) offer
  25687. // to find the m-lines that are missing from the reconstructed answer,
  25688. // potentially grabbing them from the cached (unified) answer. One has
  25689. // to be carefull with this approach because inactive m-lines do not
  25690. // always have an mid, making it tricky (impossible?) to find where
  25691. // exactly and which m-lines are missing from the reconstructed answer.
  25692. for (var i = 0; i < cached.media.length; i++) {
  25693. var unifiedLine = cached.media[i];
  25694. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25695. // The mid isn't in the reconstructed (unified) answer.
  25696. // This is either a (unified) m-line containing a remote
  25697. // track only, or a (unified) m-line containing a remote
  25698. // track and a local track that has been removed.
  25699. // In either case, it MUST exist in the cached
  25700. // (unified) answer.
  25701. //
  25702. // In case this is a removed local track, clean-up
  25703. // the (unified) m-line and make sure it's 'recvonly' or
  25704. // 'inactive'.
  25705. delete unifiedLine.msid;
  25706. delete unifiedLine.sources;
  25707. delete unifiedLine.ssrcGroups;
  25708. if (!unifiedLine.direction
  25709. || unifiedLine.direction === 'sendrecv')
  25710. unifiedLine.direction = 'recvonly';
  25711. if (!unifiedLine.direction
  25712. || unifiedLine.direction === 'sendonly')
  25713. unifiedLine.direction = 'inactive';
  25714. } else {
  25715. // This is an (unified) m-line/channel that contains a local
  25716. // track (sendrecv or sendonly channel) or it's a unified
  25717. // recvonly m-line/channel. In either case, since we're
  25718. // going from PlanB -> Unified Plan this m-line MUST
  25719. // exist in the cached answer.
  25720. }
  25721. session.media.push(unifiedLine);
  25722. if (typeof unifiedLine.mid === 'string') {
  25723. // inactive lines don't/may not have an mid.
  25724. mids.push(unifiedLine.mid);
  25725. }
  25726. }
  25727. } else {
  25728. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25729. // under any circumstances. If we are no longer interested in sending a
  25730. // track, we just remove the msid and ssrc attributes and set it to
  25731. // either a=recvonly (as the reofferer, we must use recvonly if the
  25732. // other side was previously sending on the m-section, but we can also
  25733. // leave the possibility open if it wasn't previously in use), or
  25734. // a=inacive.
  25735. if (typeof cached !== 'undefined' &&
  25736. typeof cached.media !== 'undefined' &&
  25737. Array.isArray(cached.media)) {
  25738. cached.media.forEach(function(unifiedLine) {
  25739. mids.push(unifiedLine.mid);
  25740. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25741. session.media.push(mid2ul[unifiedLine.mid]);
  25742. } else {
  25743. delete unifiedLine.msid;
  25744. delete unifiedLine.sources;
  25745. delete unifiedLine.ssrcGroups;
  25746. if (!unifiedLine.direction
  25747. || unifiedLine.direction === 'sendrecv')
  25748. unifiedLine.direction = 'recvonly';
  25749. if (!unifiedLine.direction
  25750. || unifiedLine.direction === 'sendonly')
  25751. unifiedLine.direction = 'inactive';
  25752. session.media.push(unifiedLine);
  25753. }
  25754. });
  25755. }
  25756. // Add all the remaining (new) m-lines of the transformed SDP.
  25757. Object.keys(mid2ul).forEach(function(mid) {
  25758. if (mids.indexOf(mid) === -1) {
  25759. mids.push(mid);
  25760. if (typeof mid2ul[mid].direction === 'recvonly') {
  25761. // This is a remote recvonly channel. Add its SSRC to the
  25762. // appropriate sendrecv or sendonly channel.
  25763. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25764. session.media.some(function (unifiedLine) {
  25765. if ((unifiedLine.direction === 'sendrecv' ||
  25766. unifiedLine.direction === 'sendonly') &&
  25767. unifiedLine.type === mid2ul[mid].type) {
  25768. // mid2ul[mid] shouldn't have any ssrc-groups
  25769. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25770. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25771. });
  25772. return true;
  25773. }
  25774. });
  25775. } else {
  25776. session.media.push(mid2ul[mid]);
  25777. }
  25778. }
  25779. });
  25780. }
  25781. // We regenerate the BUNDLE group (since we regenerated the mids)
  25782. session.groups.some(function(group) {
  25783. if (group.type === 'BUNDLE') {
  25784. group.mids = mids.join(' ');
  25785. return true;
  25786. }
  25787. });
  25788. // msid semantic
  25789. session.msidSemantic = {
  25790. semantic: 'WMS',
  25791. token: '*'
  25792. };
  25793. var resStr = transform.write(session);
  25794. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25795. // function.
  25796. this.cache[desc.type] = resStr;
  25797. return new RTCSessionDescription({
  25798. type: desc.type,
  25799. sdp: resStr
  25800. });
  25801. //#endregion
  25802. };
  25803. },{"./array-equals":90,"./transform":93}],93:[function(require,module,exports){
  25804. var transform = require('sdp-transform');
  25805. exports.write = function(session, opts) {
  25806. if (typeof session !== 'undefined' &&
  25807. typeof session.media !== 'undefined' &&
  25808. Array.isArray(session.media)) {
  25809. session.media.forEach(function (mLine) {
  25810. // expand sources to ssrcs
  25811. if (typeof mLine.sources !== 'undefined' &&
  25812. Object.keys(mLine.sources).length !== 0) {
  25813. mLine.ssrcs = [];
  25814. Object.keys(mLine.sources).forEach(function (ssrc) {
  25815. var source = mLine.sources[ssrc];
  25816. Object.keys(source).forEach(function (attribute) {
  25817. mLine.ssrcs.push({
  25818. id: ssrc,
  25819. attribute: attribute,
  25820. value: source[attribute]
  25821. });
  25822. });
  25823. });
  25824. delete mLine.sources;
  25825. }
  25826. // join ssrcs in ssrc groups
  25827. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25828. Array.isArray(mLine.ssrcGroups)) {
  25829. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25830. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25831. Array.isArray(ssrcGroup.ssrcs)) {
  25832. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25833. }
  25834. });
  25835. }
  25836. });
  25837. }
  25838. // join group mids
  25839. if (typeof session !== 'undefined' &&
  25840. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25841. session.groups.forEach(function (g) {
  25842. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25843. g.mids = g.mids.join(' ');
  25844. }
  25845. });
  25846. }
  25847. return transform.write(session, opts);
  25848. };
  25849. exports.parse = function(sdp) {
  25850. var session = transform.parse(sdp);
  25851. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25852. Array.isArray(session.media)) {
  25853. session.media.forEach(function (mLine) {
  25854. // group sources attributes by ssrc
  25855. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25856. mLine.sources = {};
  25857. mLine.ssrcs.forEach(function (ssrc) {
  25858. if (!mLine.sources[ssrc.id])
  25859. mLine.sources[ssrc.id] = {};
  25860. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25861. });
  25862. delete mLine.ssrcs;
  25863. }
  25864. // split ssrcs in ssrc groups
  25865. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25866. Array.isArray(mLine.ssrcGroups)) {
  25867. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25868. if (typeof ssrcGroup.ssrcs === 'string') {
  25869. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25870. }
  25871. });
  25872. }
  25873. });
  25874. }
  25875. // split group mids
  25876. if (typeof session !== 'undefined' &&
  25877. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25878. session.groups.forEach(function (g) {
  25879. if (typeof g.mids === 'string') {
  25880. g.mids = g.mids.split(' ');
  25881. }
  25882. });
  25883. }
  25884. return session;
  25885. };
  25886. },{"sdp-transform":97}],94:[function(require,module,exports){
  25887. var transform = require('sdp-transform');
  25888. var transformUtils = require('./transform-utils');
  25889. var parseSsrcs = transformUtils.parseSsrcs;
  25890. var writeSsrcs = transformUtils.writeSsrcs;
  25891. //region Constants
  25892. var DEFAULT_NUM_OF_LAYERS = 3;
  25893. //endregion
  25894. //region Ctor
  25895. function Simulcast(options) {
  25896. this.options = options ? options : {};
  25897. if (!this.options.numOfLayers) {
  25898. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25899. }
  25900. this.layers = [];
  25901. }
  25902. //endregion
  25903. //region Stateless private utility functions
  25904. /**
  25905. * Returns a random integer between min (included) and max (excluded)
  25906. * Using Math.round() gives a non-uniform distribution!
  25907. * @returns {number}
  25908. */
  25909. function generateSSRC() {
  25910. var min = 0, max = 0xffffffff;
  25911. return Math.floor(Math.random() * (max - min)) + min;
  25912. };
  25913. function processVideo(session, action) {
  25914. if (session == null || !Array.isArray(session.media)) {
  25915. return;
  25916. }
  25917. session.media.forEach(function (mLine) {
  25918. if (mLine.type === 'video') {
  25919. action(mLine);
  25920. }
  25921. });
  25922. }
  25923. function validateDescription(desc)
  25924. {
  25925. return desc && desc != null
  25926. && desc.type && desc.type != ''
  25927. && desc.sdp && desc.sdp != '';
  25928. }
  25929. function explodeRemoteSimulcast(mLine) {
  25930. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25931. return;
  25932. }
  25933. var sources = parseSsrcs(mLine);
  25934. var order = [];
  25935. // Find the SIM group and explode its sources.
  25936. var j = mLine.ssrcGroups.length;
  25937. while (j--) {
  25938. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25939. continue;
  25940. }
  25941. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25942. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25943. var ssrc = simulcastSsrcs[i];
  25944. order.push(ssrc);
  25945. var parts = sources[ssrc].msid.split(' ');
  25946. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25947. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25948. // Remove all the groups that this SSRC participates in.
  25949. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25950. if (relatedGroup.semantics === 'SIM') {
  25951. return;
  25952. }
  25953. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25954. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25955. return;
  25956. }
  25957. // Nuke all the related SSRCs.
  25958. relatedSsrcs.forEach(function (relatedSSRC) {
  25959. sources[relatedSSRC].msid = sources[ssrc].msid;
  25960. sources[relatedSSRC].cname = sources[ssrc].cname;
  25961. if (relatedSSRC !== ssrc) {
  25962. order.push(relatedSSRC);
  25963. }
  25964. });
  25965. // Schedule the related group for nuking.
  25966. })
  25967. }
  25968. mLine.ssrcs = writeSsrcs(sources, order);
  25969. mLine.ssrcGroups.splice(j, 1);
  25970. };
  25971. }
  25972. function squeezeRemoteSimulcast(mLine) {
  25973. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25974. return;
  25975. }
  25976. var sources = parseSsrcs(mLine);
  25977. // Find the SIM group and nuke it.
  25978. mLine.ssrcGroups.some(function (simulcastGroup) {
  25979. if (simulcastGroup.semantics !== 'SIM') {
  25980. return false;
  25981. }
  25982. // Schedule the SIM group for nuking.
  25983. simulcastGroup.nuke = true;
  25984. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25985. // Nuke all the higher layer SSRCs.
  25986. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25987. var ssrc = simulcastSsrcs[i];
  25988. delete sources[ssrc];
  25989. // Remove all the groups that this SSRC participates in.
  25990. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25991. if (relatedGroup.semantics === 'SIM') {
  25992. return;
  25993. }
  25994. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25995. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25996. return;
  25997. }
  25998. // Nuke all the related SSRCs.
  25999. relatedSsrcs.forEach(function (relatedSSRC) {
  26000. delete sources[relatedSSRC];
  26001. });
  26002. // Schedule the related group for nuking.
  26003. relatedGroup.nuke = true;
  26004. })
  26005. }
  26006. return true;
  26007. });
  26008. mLine.ssrcs = writeSsrcs(sources);
  26009. // Nuke all the scheduled groups.
  26010. var i = mLine.ssrcGroups.length;
  26011. while (i--) {
  26012. if (mLine.ssrcGroups[i].nuke) {
  26013. mLine.ssrcGroups.splice(i, 1);
  26014. }
  26015. }
  26016. }
  26017. function removeGoogConference(mLine) {
  26018. if (!mLine || !Array.isArray(mLine.invalid)) {
  26019. return;
  26020. }
  26021. var i = mLine.invalid.length;
  26022. while (i--) {
  26023. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26024. mLine.invalid.splice(i, 1);
  26025. }
  26026. }
  26027. }
  26028. function assertGoogConference(mLine) {
  26029. if (!mLine) {
  26030. return;
  26031. }
  26032. if (!Array.isArray(mLine.invalid)) {
  26033. mLine.invalid = [];
  26034. }
  26035. if (!mLine.invalid.some(
  26036. function (i) { return i.value === 'x-google-flag:conference' })) {
  26037. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26038. }
  26039. }
  26040. //endregion
  26041. //region "Private" functions
  26042. /**
  26043. *
  26044. * @param mLine
  26045. * @private
  26046. */
  26047. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26048. if (!mLine || mLine.type !== 'video') {
  26049. return;
  26050. }
  26051. var sources = parseSsrcs(mLine);
  26052. if (Object.keys(sources).length === 0) {
  26053. // no sources, disable simulcast.
  26054. if (this.layers.length !== 0) {
  26055. this.layers = [];
  26056. }
  26057. return;
  26058. }
  26059. // find the base layer (we'll reuse its msid and cname).
  26060. var baseLayerSSRC = Object.keys(sources)[0];
  26061. var baseLayer = sources[baseLayerSSRC];
  26062. // todo(gp) handle screen sharing.
  26063. // check if base CNAME has changed and reinitialise layers.
  26064. if (this.layers.length > 0
  26065. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26066. this.layers = [];
  26067. }
  26068. // (re)initialise layers
  26069. if (this.layers.length < 1) {
  26070. // first push the base layer.
  26071. this.layers.push({
  26072. ssrc: baseLayerSSRC,
  26073. msid: baseLayer.msid,
  26074. cname: baseLayer.cname
  26075. });
  26076. var rtx = false; // RFC 4588
  26077. if (Array.isArray(mLine.rtp)) {
  26078. rtx = mLine.rtp.some(
  26079. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26080. }
  26081. if (rtx) {
  26082. this.layers[0].rtx = generateSSRC();
  26083. }
  26084. // now push additional layers.
  26085. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26086. var layer = { ssrc: generateSSRC() };
  26087. if (rtx) {
  26088. layer.rtx = generateSSRC();
  26089. }
  26090. this.layers.push(layer);
  26091. }
  26092. }
  26093. };
  26094. /**
  26095. *
  26096. * @param mLine
  26097. * @private
  26098. */
  26099. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26100. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26101. var sources = {};
  26102. var msid = this.layers[0].msid;
  26103. var cname = this.layers[0].cname;
  26104. var simulcastSsrcs = [];
  26105. var ssrcGroups = [];
  26106. for (var i = 0; i < this.layers.length; i++) {
  26107. var layer = this.layers[i];
  26108. sources[layer.ssrc] = { msid: msid, cname: cname };
  26109. simulcastSsrcs.push(layer.ssrc);
  26110. if (layer.rtx) {
  26111. sources[layer.rtx] = {
  26112. msid: msid,
  26113. cname: cname
  26114. }
  26115. ssrcGroups.push({
  26116. semantics: 'FID',
  26117. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26118. });
  26119. }
  26120. }
  26121. ssrcGroups.push({
  26122. semantics: 'SIM',
  26123. ssrcs: simulcastSsrcs.join(' ')
  26124. });
  26125. mLine.ssrcGroups = ssrcGroups;
  26126. mLine.ssrcs = writeSsrcs(sources);
  26127. }
  26128. }
  26129. //endregion
  26130. //region "Public" functions
  26131. Simulcast.prototype.isSupported = function () {
  26132. return window.chrome;
  26133. // TODO this needs improvements. For example I doubt that Chrome in Android
  26134. // has simulcast support. Also, only recent versions of Chromium have native
  26135. // simulcast support.
  26136. }
  26137. /**
  26138. *
  26139. * @param desc
  26140. * @returns {RTCSessionDescription}
  26141. */
  26142. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26143. if (!validateDescription(desc)) {
  26144. return desc;
  26145. }
  26146. var session = transform.parse(desc.sdp);
  26147. var self = this;
  26148. processVideo(session, function (mLine) {
  26149. // Handle simulcast reception.
  26150. if (self.options.explodeRemoteSimulcast) {
  26151. explodeRemoteSimulcast(mLine);
  26152. } else {
  26153. squeezeRemoteSimulcast(mLine);
  26154. }
  26155. // If native simulcast is enabled, we must append the x-goog-conference
  26156. // attribute to the SDP.
  26157. if (self.layers.length < 1) {
  26158. removeGoogConference(mLine);
  26159. } else {
  26160. assertGoogConference(mLine);
  26161. }
  26162. });
  26163. return new RTCSessionDescription({
  26164. type: desc.type,
  26165. sdp: transform.write(session)
  26166. });
  26167. };
  26168. /**
  26169. *
  26170. * @param desc
  26171. * @returns {RTCSessionDescription}
  26172. */
  26173. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26174. if (!validateDescription(desc) || !this.isSupported()) {
  26175. return desc;
  26176. }
  26177. var session = transform.parse(desc.sdp);
  26178. var self = this;
  26179. processVideo(session, function (mLine) {
  26180. // Initialize native simulcast layers, if not already done.
  26181. self._maybeInitializeLayers(mLine);
  26182. // Update the SDP with the simulcast layers.
  26183. self._restoreSimulcastView(mLine);
  26184. });
  26185. return new RTCSessionDescription({
  26186. type: desc.type,
  26187. sdp: transform.write(session)
  26188. });
  26189. };
  26190. //endregion
  26191. module.exports = Simulcast;
  26192. },{"./transform-utils":95,"sdp-transform":97}],95:[function(require,module,exports){
  26193. exports.writeSsrcs = function(sources, order) {
  26194. var ssrcs = [];
  26195. // expand sources to ssrcs
  26196. if (typeof sources !== 'undefined' &&
  26197. Object.keys(sources).length !== 0) {
  26198. if (Array.isArray(order)) {
  26199. for (var i = 0; i < order.length; i++) {
  26200. var ssrc = order[i];
  26201. var source = sources[ssrc];
  26202. Object.keys(source).forEach(function (attribute) {
  26203. ssrcs.push({
  26204. id: ssrc,
  26205. attribute: attribute,
  26206. value: source[attribute]
  26207. });
  26208. });
  26209. }
  26210. } else {
  26211. Object.keys(sources).forEach(function (ssrc) {
  26212. var source = sources[ssrc];
  26213. Object.keys(source).forEach(function (attribute) {
  26214. ssrcs.push({
  26215. id: ssrc,
  26216. attribute: attribute,
  26217. value: source[attribute]
  26218. });
  26219. });
  26220. });
  26221. }
  26222. }
  26223. return ssrcs;
  26224. };
  26225. exports.parseSsrcs = function (mLine) {
  26226. var sources = {};
  26227. // group sources attributes by ssrc.
  26228. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26229. mLine.ssrcs.forEach(function (ssrc) {
  26230. if (!sources[ssrc.id])
  26231. sources[ssrc.id] = {};
  26232. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26233. });
  26234. }
  26235. return sources;
  26236. };
  26237. },{}],96:[function(require,module,exports){
  26238. var grammar = module.exports = {
  26239. v: [{
  26240. name: 'version',
  26241. reg: /^(\d*)$/
  26242. }],
  26243. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26244. // NB: sessionId will be a String in most cases because it is huge
  26245. name: 'origin',
  26246. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26247. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26248. format: "%s %s %d %s IP%d %s"
  26249. }],
  26250. // default parsing of these only (though some of these feel outdated)
  26251. s: [{ name: 'name' }],
  26252. i: [{ name: 'description' }],
  26253. u: [{ name: 'uri' }],
  26254. e: [{ name: 'email' }],
  26255. p: [{ name: 'phone' }],
  26256. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26257. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26258. //k: [{}], // outdated thing ignored
  26259. t: [{ //t=0 0
  26260. name: 'timing',
  26261. reg: /^(\d*) (\d*)/,
  26262. names: ['start', 'stop'],
  26263. format: "%d %d"
  26264. }],
  26265. c: [{ //c=IN IP4 10.47.197.26
  26266. name: 'connection',
  26267. reg: /^IN IP(\d) (\S*)/,
  26268. names: ['version', 'ip'],
  26269. format: "IN IP%d %s"
  26270. }],
  26271. b: [{ //b=AS:4000
  26272. push: 'bandwidth',
  26273. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26274. names: ['type', 'limit'],
  26275. format: "%s:%s"
  26276. }],
  26277. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26278. // NB: special - pushes to session
  26279. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26280. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26281. names: ['type', 'port', 'protocol', 'payloads'],
  26282. format: "%s %d %s %s"
  26283. }],
  26284. a: [
  26285. { //a=rtpmap:110 opus/48000/2
  26286. push: 'rtp',
  26287. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26288. names: ['payload', 'codec', 'rate', 'encoding'],
  26289. format: function (o) {
  26290. return (o.encoding) ?
  26291. "rtpmap:%d %s/%s/%s":
  26292. "rtpmap:%d %s/%s";
  26293. }
  26294. },
  26295. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26296. push: 'fmtp',
  26297. reg: /^fmtp:(\d*) (\S*)/,
  26298. names: ['payload', 'config'],
  26299. format: "fmtp:%d %s"
  26300. },
  26301. { //a=control:streamid=0
  26302. name: 'control',
  26303. reg: /^control:(.*)/,
  26304. format: "control:%s"
  26305. },
  26306. { //a=rtcp:65179 IN IP4 193.84.77.194
  26307. name: 'rtcp',
  26308. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26309. names: ['port', 'netType', 'ipVer', 'address'],
  26310. format: function (o) {
  26311. return (o.address != null) ?
  26312. "rtcp:%d %s IP%d %s":
  26313. "rtcp:%d";
  26314. }
  26315. },
  26316. { //a=rtcp-fb:98 trr-int 100
  26317. push: 'rtcpFbTrrInt',
  26318. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26319. names: ['payload', 'value'],
  26320. format: "rtcp-fb:%d trr-int %d"
  26321. },
  26322. { //a=rtcp-fb:98 nack rpsi
  26323. push: 'rtcpFb',
  26324. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26325. names: ['payload', 'type', 'subtype'],
  26326. format: function (o) {
  26327. return (o.subtype != null) ?
  26328. "rtcp-fb:%s %s %s":
  26329. "rtcp-fb:%s %s";
  26330. }
  26331. },
  26332. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26333. //a=extmap:1/recvonly URI-gps-string
  26334. push: 'ext',
  26335. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26336. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26337. format: function (o) {
  26338. return (o.config != null) ?
  26339. "extmap:%s %s %s":
  26340. "extmap:%s %s";
  26341. }
  26342. },
  26343. {
  26344. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26345. push: 'crypto',
  26346. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26347. names: ['id', 'suite', 'config', 'sessionConfig'],
  26348. format: function (o) {
  26349. return (o.sessionConfig != null) ?
  26350. "crypto:%d %s %s %s":
  26351. "crypto:%d %s %s";
  26352. }
  26353. },
  26354. { //a=setup:actpass
  26355. name: 'setup',
  26356. reg: /^setup:(\w*)/,
  26357. format: "setup:%s"
  26358. },
  26359. { //a=mid:1
  26360. name: 'mid',
  26361. reg: /^mid:([^\s]*)/,
  26362. format: "mid:%s"
  26363. },
  26364. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26365. name: 'msid',
  26366. reg: /^msid:(.*)/,
  26367. format: "msid:%s"
  26368. },
  26369. { //a=ptime:20
  26370. name: 'ptime',
  26371. reg: /^ptime:(\d*)/,
  26372. format: "ptime:%d"
  26373. },
  26374. { //a=maxptime:60
  26375. name: 'maxptime',
  26376. reg: /^maxptime:(\d*)/,
  26377. format: "maxptime:%d"
  26378. },
  26379. { //a=sendrecv
  26380. name: 'direction',
  26381. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26382. },
  26383. { //a=ice-lite
  26384. name: 'icelite',
  26385. reg: /^(ice-lite)/
  26386. },
  26387. { //a=ice-ufrag:F7gI
  26388. name: 'iceUfrag',
  26389. reg: /^ice-ufrag:(\S*)/,
  26390. format: "ice-ufrag:%s"
  26391. },
  26392. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26393. name: 'icePwd',
  26394. reg: /^ice-pwd:(\S*)/,
  26395. format: "ice-pwd:%s"
  26396. },
  26397. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26398. name: 'fingerprint',
  26399. reg: /^fingerprint:(\S*) (\S*)/,
  26400. names: ['type', 'hash'],
  26401. format: "fingerprint:%s %s"
  26402. },
  26403. {
  26404. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26405. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26406. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26407. push:'candidates',
  26408. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26409. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26410. format: function (o) {
  26411. var str = "candidate:%s %d %s %d %s %d typ %s";
  26412. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26413. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26414. if (o.generation != null) {
  26415. str += " generation %d";
  26416. }
  26417. return str;
  26418. }
  26419. },
  26420. { //a=end-of-candidates (keep after the candidates line for readability)
  26421. name: 'endOfCandidates',
  26422. reg: /^(end-of-candidates)/
  26423. },
  26424. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26425. name: 'remoteCandidates',
  26426. reg: /^remote-candidates:(.*)/,
  26427. format: "remote-candidates:%s"
  26428. },
  26429. { //a=ice-options:google-ice
  26430. name: 'iceOptions',
  26431. reg: /^ice-options:(\S*)/,
  26432. format: "ice-options:%s"
  26433. },
  26434. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26435. push: "ssrcs",
  26436. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26437. names: ['id', 'attribute', 'value'],
  26438. format: "ssrc:%d %s:%s"
  26439. },
  26440. { //a=ssrc-group:FEC 1 2
  26441. push: "ssrcGroups",
  26442. reg: /^ssrc-group:(\w*) (.*)/,
  26443. names: ['semantics', 'ssrcs'],
  26444. format: "ssrc-group:%s %s"
  26445. },
  26446. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26447. name: "msidSemantic",
  26448. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26449. names: ['semantic', 'token'],
  26450. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26451. },
  26452. { //a=group:BUNDLE audio video
  26453. push: 'groups',
  26454. reg: /^group:(\w*) (.*)/,
  26455. names: ['type', 'mids'],
  26456. format: "group:%s %s"
  26457. },
  26458. { //a=rtcp-mux
  26459. name: 'rtcpMux',
  26460. reg: /^(rtcp-mux)/
  26461. },
  26462. { //a=rtcp-rsize
  26463. name: 'rtcpRsize',
  26464. reg: /^(rtcp-rsize)/
  26465. },
  26466. { // any a= that we don't understand is kepts verbatim on media.invalid
  26467. push: 'invalid',
  26468. names: ["value"]
  26469. }
  26470. ]
  26471. };
  26472. // set sensible defaults to avoid polluting the grammar with boring details
  26473. Object.keys(grammar).forEach(function (key) {
  26474. var objs = grammar[key];
  26475. objs.forEach(function (obj) {
  26476. if (!obj.reg) {
  26477. obj.reg = /(.*)/;
  26478. }
  26479. if (!obj.format) {
  26480. obj.format = "%s";
  26481. }
  26482. });
  26483. });
  26484. },{}],97:[function(require,module,exports){
  26485. var parser = require('./parser');
  26486. var writer = require('./writer');
  26487. exports.write = writer;
  26488. exports.parse = parser.parse;
  26489. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26490. exports.parsePayloads = parser.parsePayloads;
  26491. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26492. },{"./parser":98,"./writer":99}],98:[function(require,module,exports){
  26493. var toIntIfInt = function (v) {
  26494. return String(Number(v)) === v ? Number(v) : v;
  26495. };
  26496. var attachProperties = function (match, location, names, rawName) {
  26497. if (rawName && !names) {
  26498. location[rawName] = toIntIfInt(match[1]);
  26499. }
  26500. else {
  26501. for (var i = 0; i < names.length; i += 1) {
  26502. if (match[i+1] != null) {
  26503. location[names[i]] = toIntIfInt(match[i+1]);
  26504. }
  26505. }
  26506. }
  26507. };
  26508. var parseReg = function (obj, location, content) {
  26509. var needsBlank = obj.name && obj.names;
  26510. if (obj.push && !location[obj.push]) {
  26511. location[obj.push] = [];
  26512. }
  26513. else if (needsBlank && !location[obj.name]) {
  26514. location[obj.name] = {};
  26515. }
  26516. var keyLocation = obj.push ?
  26517. {} : // blank object that will be pushed
  26518. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26519. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26520. if (obj.push) {
  26521. location[obj.push].push(keyLocation);
  26522. }
  26523. };
  26524. var grammar = require('./grammar');
  26525. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26526. exports.parse = function (sdp) {
  26527. var session = {}
  26528. , media = []
  26529. , location = session; // points at where properties go under (one of the above)
  26530. // parse lines we understand
  26531. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26532. var type = l[0];
  26533. var content = l.slice(2);
  26534. if (type === 'm') {
  26535. media.push({rtp: [], fmtp: []});
  26536. location = media[media.length-1]; // point at latest media line
  26537. }
  26538. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26539. var obj = grammar[type][j];
  26540. if (obj.reg.test(content)) {
  26541. return parseReg(obj, location, content);
  26542. }
  26543. }
  26544. });
  26545. session.media = media; // link it up
  26546. return session;
  26547. };
  26548. var fmtpReducer = function (acc, expr) {
  26549. var s = expr.split('=');
  26550. if (s.length === 2) {
  26551. acc[s[0]] = toIntIfInt(s[1]);
  26552. }
  26553. return acc;
  26554. };
  26555. exports.parseFmtpConfig = function (str) {
  26556. return str.split(';').reduce(fmtpReducer, {});
  26557. };
  26558. exports.parsePayloads = function (str) {
  26559. return str.split(' ').map(Number);
  26560. };
  26561. exports.parseRemoteCandidates = function (str) {
  26562. var candidates = [];
  26563. var parts = str.split(' ').map(toIntIfInt);
  26564. for (var i = 0; i < parts.length; i += 3) {
  26565. candidates.push({
  26566. component: parts[i],
  26567. ip: parts[i + 1],
  26568. port: parts[i + 2]
  26569. });
  26570. }
  26571. return candidates;
  26572. };
  26573. },{"./grammar":96}],99:[function(require,module,exports){
  26574. var grammar = require('./grammar');
  26575. // customized util.format - discards excess arguments and can void middle ones
  26576. var formatRegExp = /%[sdv%]/g;
  26577. var format = function (formatStr) {
  26578. var i = 1;
  26579. var args = arguments;
  26580. var len = args.length;
  26581. return formatStr.replace(formatRegExp, function (x) {
  26582. if (i >= len) {
  26583. return x; // missing argument
  26584. }
  26585. var arg = args[i];
  26586. i += 1;
  26587. switch (x) {
  26588. case '%%':
  26589. return '%';
  26590. case '%s':
  26591. return String(arg);
  26592. case '%d':
  26593. return Number(arg);
  26594. case '%v':
  26595. return '';
  26596. }
  26597. });
  26598. // NB: we discard excess arguments - they are typically undefined from makeLine
  26599. };
  26600. var makeLine = function (type, obj, location) {
  26601. var str = obj.format instanceof Function ?
  26602. (obj.format(obj.push ? location : location[obj.name])) :
  26603. obj.format;
  26604. var args = [type + '=' + str];
  26605. if (obj.names) {
  26606. for (var i = 0; i < obj.names.length; i += 1) {
  26607. var n = obj.names[i];
  26608. if (obj.name) {
  26609. args.push(location[obj.name][n]);
  26610. }
  26611. else { // for mLine and push attributes
  26612. args.push(location[obj.names[i]]);
  26613. }
  26614. }
  26615. }
  26616. else {
  26617. args.push(location[obj.name]);
  26618. }
  26619. return format.apply(null, args);
  26620. };
  26621. // RFC specified order
  26622. // TODO: extend this with all the rest
  26623. var defaultOuterOrder = [
  26624. 'v', 'o', 's', 'i',
  26625. 'u', 'e', 'p', 'c',
  26626. 'b', 't', 'r', 'z', 'a'
  26627. ];
  26628. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26629. module.exports = function (session, opts) {
  26630. opts = opts || {};
  26631. // ensure certain properties exist
  26632. if (session.version == null) {
  26633. session.version = 0; // "v=0" must be there (only defined version atm)
  26634. }
  26635. if (session.name == null) {
  26636. session.name = " "; // "s= " must be there if no meaningful name set
  26637. }
  26638. session.media.forEach(function (mLine) {
  26639. if (mLine.payloads == null) {
  26640. mLine.payloads = "";
  26641. }
  26642. });
  26643. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26644. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26645. var sdp = [];
  26646. // loop through outerOrder for matching properties on session
  26647. outerOrder.forEach(function (type) {
  26648. grammar[type].forEach(function (obj) {
  26649. if (obj.name in session && session[obj.name] != null) {
  26650. sdp.push(makeLine(type, obj, session));
  26651. }
  26652. else if (obj.push in session && session[obj.push] != null) {
  26653. session[obj.push].forEach(function (el) {
  26654. sdp.push(makeLine(type, obj, el));
  26655. });
  26656. }
  26657. });
  26658. });
  26659. // then for each media line, follow the innerOrder
  26660. session.media.forEach(function (mLine) {
  26661. sdp.push(makeLine('m', grammar.m[0], mLine));
  26662. innerOrder.forEach(function (type) {
  26663. grammar[type].forEach(function (obj) {
  26664. if (obj.name in mLine && mLine[obj.name] != null) {
  26665. sdp.push(makeLine(type, obj, mLine));
  26666. }
  26667. else if (obj.push in mLine && mLine[obj.push] != null) {
  26668. mLine[obj.push].forEach(function (el) {
  26669. sdp.push(makeLine(type, obj, el));
  26670. });
  26671. }
  26672. });
  26673. });
  26674. });
  26675. return sdp.join('\r\n') + '\r\n';
  26676. };
  26677. },{"./grammar":96}],100:[function(require,module,exports){
  26678. var MediaStreamType = {
  26679. VIDEO_TYPE: "Video",
  26680. AUDIO_TYPE: "Audio"
  26681. };
  26682. module.exports = MediaStreamType;
  26683. },{}],101:[function(require,module,exports){
  26684. var RTCEvents = {
  26685. RTC_READY: "rtc.ready",
  26686. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  26687. LASTN_CHANGED: "rtc.lastn_changed",
  26688. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26689. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26690. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26691. AUDIO_MUTE: "rtc.audio_mute",
  26692. VIDEO_MUTE: "rtc.video_mute"
  26693. };
  26694. module.exports = RTCEvents;
  26695. },{}],102:[function(require,module,exports){
  26696. var Resolutions = {
  26697. "1080": {
  26698. width: 1920,
  26699. height: 1080,
  26700. order: 7
  26701. },
  26702. "fullhd": {
  26703. width: 1920,
  26704. height: 1080,
  26705. order: 7
  26706. },
  26707. "720": {
  26708. width: 1280,
  26709. height: 720,
  26710. order: 6
  26711. },
  26712. "hd": {
  26713. width: 1280,
  26714. height: 720,
  26715. order: 6
  26716. },
  26717. "960": {
  26718. width: 960,
  26719. height: 720,
  26720. order: 5
  26721. },
  26722. "640": {
  26723. width: 640,
  26724. height: 480,
  26725. order: 4
  26726. },
  26727. "vga": {
  26728. width: 640,
  26729. height: 480,
  26730. order: 4
  26731. },
  26732. "360": {
  26733. width: 640,
  26734. height: 360,
  26735. order: 3
  26736. },
  26737. "320": {
  26738. width: 320,
  26739. height: 240,
  26740. order: 2
  26741. },
  26742. "180": {
  26743. width: 320,
  26744. height: 180,
  26745. order: 1
  26746. }
  26747. };
  26748. module.exports = Resolutions;
  26749. },{}],103:[function(require,module,exports){
  26750. var StreamEventTypes = {
  26751. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26752. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26753. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26754. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26755. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26756. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26757. };
  26758. module.exports = StreamEventTypes;
  26759. },{}],104:[function(require,module,exports){
  26760. var UIEvents = {
  26761. NICKNAME_CHANGED: "UI.nickname_changed",
  26762. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26763. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26764. };
  26765. module.exports = UIEvents;
  26766. },{}],105:[function(require,module,exports){
  26767. var AuthenticationEvents = {
  26768. /**
  26769. * Event callback arguments:
  26770. * function(authenticationEnabled, userIdentity)
  26771. * authenticationEnabled - indicates whether authentication has been enabled
  26772. * in this session
  26773. * userIdentity - if user has been logged in then it contains user name. If
  26774. * contains 'null' or 'undefined' then user is not logged in.
  26775. */
  26776. IDENTITY_UPDATED: "authentication.identity_updated"
  26777. };
  26778. module.exports = AuthenticationEvents;
  26779. },{}],106:[function(require,module,exports){
  26780. var CQEvents = {
  26781. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26782. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26783. STOP: "cq.stop"
  26784. };
  26785. module.exports = CQEvents;
  26786. },{}],107:[function(require,module,exports){
  26787. var DesktopSharingEventTypes = {
  26788. INIT: "ds.init",
  26789. SWITCHING_DONE: "ds.switching_done",
  26790. NEW_STREAM_CREATED: "ds.new_stream_created"
  26791. };
  26792. module.exports = DesktopSharingEventTypes;
  26793. },{}],108:[function(require,module,exports){
  26794. var Events = {
  26795. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26796. };
  26797. module.exports = Events;
  26798. },{}],109:[function(require,module,exports){
  26799. module.exports = {
  26800. getLanguages : function () {
  26801. var languages = [];
  26802. for(var lang in this)
  26803. {
  26804. if(typeof this[lang] === "string")
  26805. languages.push(this[lang]);
  26806. }
  26807. return languages;
  26808. },
  26809. EN: "en",
  26810. BG: "bg",
  26811. DE: "de",
  26812. TR: "tr",
  26813. FR: "fr"
  26814. }
  26815. },{}],110:[function(require,module,exports){
  26816. var XMPPEvents = {
  26817. CONNECTION_FAILED: "xmpp.connection.failed",
  26818. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26819. CALL_INCOMING: "xmpp.callincoming.jingle",
  26820. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26821. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26822. KICKED: "xmpp.kicked",
  26823. BRIDGE_DOWN: "xmpp.bridge_down",
  26824. USER_ID_CHANGED: "xmpp.user_id_changed",
  26825. // We joined the MUC
  26826. MUC_JOINED: "xmpp.muc_joined",
  26827. // A member joined the MUC
  26828. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26829. // A member left the MUC
  26830. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26831. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26832. MUC_DESTROYED: "xmpp.muc_destroyed",
  26833. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26834. REMOTE_STATS: "xmpp.remote_stats",
  26835. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26836. PRESENCE_STATUS: "xmpp.presence_status",
  26837. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26838. SUBJECT_CHANGED: "xmpp.subject_changed",
  26839. MESSAGE_RECEIVED: "xmpp.message_received",
  26840. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26841. PASSWORD_REQUIRED: "xmpp.password_required",
  26842. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26843. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26844. ETHERPAD: "xmpp.etherpad",
  26845. DEVICE_AVAILABLE: "xmpp.device_available",
  26846. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26847. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26848. AUDIO_MUTED: "xmpp.audio_muted",
  26849. VIDEO_MUTED: "xmpp.video_muted",
  26850. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  26851. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  26852. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  26853. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  26854. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  26855. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  26856. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  26857. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  26858. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  26859. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  26860. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  26861. // xmpp is connected and obtained user media
  26862. READY_TO_JOIN: 'xmpp.ready_to_join'
  26863. };
  26864. module.exports = XMPPEvents;
  26865. },{}]},{},[3])(3)
  26866. });