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 1012KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468
  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. {
  365. displayName: APP.UI.inputDisplayNameHandler,
  366. muteAudio: APP.UI.toggleAudio,
  367. muteVideo: APP.UI.toggleVideo,
  368. toggleFilmStrip: APP.UI.toggleFilmStrip,
  369. toggleChat: APP.UI.toggleChat,
  370. toggleContactList: APP.UI.toggleContactList
  371. };
  372. /**
  373. * Maps the supported events and their status
  374. * (true it the event is enabled and false if it is disabled)
  375. * @type {{
  376. * incomingMessage: boolean,
  377. * outgoingMessage: boolean,
  378. * displayNameChange: boolean,
  379. * participantJoined: boolean,
  380. * participantLeft: boolean
  381. * }}
  382. */
  383. var events =
  384. {
  385. incomingMessage: false,
  386. outgoingMessage:false,
  387. displayNameChange: false,
  388. participantJoined: false,
  389. participantLeft: false
  390. };
  391. var displayName = {};
  392. /**
  393. * Processes commands from external applicaiton.
  394. * @param message the object with the command
  395. */
  396. function processCommand(message)
  397. {
  398. if(message.action != "execute")
  399. {
  400. console.error("Unknown action of the message");
  401. return;
  402. }
  403. for(var key in message)
  404. {
  405. if(commands[key])
  406. commands[key].apply(null, message[key]);
  407. }
  408. }
  409. /**
  410. * Processes events objects from external applications
  411. * @param event the event
  412. */
  413. function processEvent(event) {
  414. if(!event.action)
  415. {
  416. console.error("Event with no action is received.");
  417. return;
  418. }
  419. var i = 0;
  420. switch(event.action)
  421. {
  422. case "add":
  423. for(; i < event.events.length; i++)
  424. {
  425. events[event.events[i]] = true;
  426. }
  427. break;
  428. case "remove":
  429. for(; i < event.events.length; i++)
  430. {
  431. events[event.events[i]] = false;
  432. }
  433. break;
  434. default:
  435. console.error("Unknown action for event.");
  436. }
  437. }
  438. /**
  439. * Sends message to the external application.
  440. * @param object
  441. */
  442. function sendMessage(object) {
  443. window.parent.postMessage(JSON.stringify(object), "*");
  444. }
  445. /**
  446. * Processes a message event from the external application
  447. * @param event the message event
  448. */
  449. function processMessage(event)
  450. {
  451. var message;
  452. try {
  453. message = JSON.parse(event.data);
  454. } catch (e) {}
  455. if(!message.type)
  456. return;
  457. switch (message.type)
  458. {
  459. case "command":
  460. processCommand(message);
  461. break;
  462. case "event":
  463. processEvent(message);
  464. break;
  465. default:
  466. console.error("Unknown type of the message");
  467. return;
  468. }
  469. }
  470. function setupListeners() {
  471. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  472. API.triggerEvent("participantJoined", {jid: from});
  473. });
  474. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  475. if (from != myjid)
  476. API.triggerEvent("incomingMessage",
  477. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  478. });
  479. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  480. API.triggerEvent("participantLeft", {jid: jid});
  481. });
  482. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  483. name = displayName[jid];
  484. if(!name || name != newDisplayName) {
  485. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  486. displayName[jid] = newDisplayName;
  487. }
  488. });
  489. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  490. APP.API.triggerEvent("outgoingMessage", {"message": body});
  491. });
  492. }
  493. var API = {
  494. /**
  495. * Check whether the API should be enabled or not.
  496. * @returns {boolean}
  497. */
  498. isEnabled: function () {
  499. var hash = location.hash;
  500. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  501. return true;
  502. return false;
  503. },
  504. /**
  505. * Initializes the APIConnector. Setups message event listeners that will
  506. * receive information from external applications that embed Jitsi Meet.
  507. * It also sends a message to the external application that APIConnector
  508. * is initialized.
  509. */
  510. init: function () {
  511. if (window.addEventListener)
  512. {
  513. window.addEventListener('message',
  514. processMessage, false);
  515. }
  516. else
  517. {
  518. window.attachEvent('onmessage', processMessage);
  519. }
  520. sendMessage({type: "system", loaded: true});
  521. setupListeners();
  522. },
  523. /**
  524. * Checks whether the event is enabled ot not.
  525. * @param name the name of the event.
  526. * @returns {*}
  527. */
  528. isEventEnabled: function (name) {
  529. return events[name];
  530. },
  531. /**
  532. * Sends event object to the external application that has been subscribed
  533. * for that event.
  534. * @param name the name event
  535. * @param object data associated with the event
  536. */
  537. triggerEvent: function (name, object) {
  538. if(this.isEnabled() && this.isEventEnabled(name))
  539. sendMessage({
  540. type: "event", action: "result", event: name, result: object});
  541. },
  542. /**
  543. * Removes the listeners.
  544. */
  545. dispose: function () {
  546. if(window.removeEventListener)
  547. {
  548. window.removeEventListener("message",
  549. processMessage, false);
  550. }
  551. else
  552. {
  553. window.detachEvent('onmessage', processMessage);
  554. }
  555. }
  556. };
  557. module.exports = API;
  558. },{"../../service/xmpp/XMPPEvents":110}],5:[function(require,module,exports){
  559. /* global APP */
  560. /**
  561. * A module for sending DTMF tones.
  562. */
  563. var DTMFSender;
  564. var initDtmfSender = function() {
  565. // TODO: This needs to reset this if the peerconnection changes
  566. // (e.g. the call is re-made)
  567. if (DTMFSender)
  568. return;
  569. var localAudio = APP.RTC.localAudio;
  570. if (localAudio && localAudio.getTracks().length > 0)
  571. {
  572. var peerconnection
  573. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  574. if (peerconnection) {
  575. DTMFSender =
  576. peerconnection.peerconnection
  577. .createDTMFSender(localAudio.getTracks()[0]);
  578. console.log("Initialized DTMFSender");
  579. }
  580. else {
  581. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  582. }
  583. }
  584. else {
  585. console.log("Failed to initialize DTMFSender: no audio track.");
  586. }
  587. };
  588. var DTMF = {
  589. sendTones: function (tones, duration, pause) {
  590. if (!DTMFSender)
  591. initDtmfSender();
  592. if (DTMFSender){
  593. DTMFSender.insertDTMF(tones,
  594. (duration || 200),
  595. (pause || 200));
  596. }
  597. }
  598. };
  599. module.exports = DTMF;
  600. },{}],6:[function(require,module,exports){
  601. /* global Strophe, focusedVideoSrc*/
  602. // cache datachannels to avoid garbage collection
  603. // https://code.google.com/p/chromium/issues/detail?id=405545
  604. var RTCEvents = require("../../service/RTC/RTCEvents");
  605. var _dataChannels = [];
  606. var eventEmitter = null;
  607. var DataChannels =
  608. {
  609. /**
  610. * Callback triggered by PeerConnection when new data channel is opened
  611. * on the bridge.
  612. * @param event the event info object.
  613. */
  614. onDataChannel: function (event)
  615. {
  616. var dataChannel = event.channel;
  617. dataChannel.onopen = function () {
  618. console.info("Data channel opened by the Videobridge!", dataChannel);
  619. // Code sample for sending string and/or binary data
  620. // Sends String message to the bridge
  621. //dataChannel.send("Hello bridge!");
  622. // Sends 12 bytes binary message to the bridge
  623. //dataChannel.send(new ArrayBuffer(12));
  624. // when the data channel becomes available, tell the bridge about video
  625. // selections so that it can do adaptive simulcast,
  626. // we want the notification to trigger even if userJid is undefined,
  627. // or null.
  628. var userJid = APP.UI.getLargeVideoJid();
  629. // we want the notification to trigger even if userJid is undefined,
  630. // or null.
  631. onSelectedEndpointChanged(userJid);
  632. };
  633. dataChannel.onerror = function (error) {
  634. console.error("Data Channel Error:", error, dataChannel);
  635. };
  636. dataChannel.onmessage = function (event) {
  637. var data = event.data;
  638. // JSON
  639. var obj;
  640. try {
  641. obj = JSON.parse(data);
  642. }
  643. catch (e) {
  644. console.error(
  645. "Failed to parse data channel message as JSON: ",
  646. data,
  647. dataChannel);
  648. }
  649. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  650. var colibriClass = obj.colibriClass;
  651. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  652. // Endpoint ID from the Videobridge.
  653. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  654. console.info(
  655. "Data channel new dominant speaker event: ",
  656. dominantSpeakerEndpoint);
  657. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  658. }
  659. else if ("InLastNChangeEvent" === colibriClass)
  660. {
  661. var oldValue = obj.oldValue;
  662. var newValue = obj.newValue;
  663. // Make sure that oldValue and newValue are of type boolean.
  664. var type;
  665. if ((type = typeof oldValue) !== 'boolean') {
  666. if (type === 'string') {
  667. oldValue = (oldValue == "true");
  668. } else {
  669. oldValue = new Boolean(oldValue).valueOf();
  670. }
  671. }
  672. if ((type = typeof newValue) !== 'boolean') {
  673. if (type === 'string') {
  674. newValue = (newValue == "true");
  675. } else {
  676. newValue = new Boolean(newValue).valueOf();
  677. }
  678. }
  679. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  680. }
  681. else if ("LastNEndpointsChangeEvent" === colibriClass)
  682. {
  683. // The new/latest list of last-n endpoint IDs.
  684. var lastNEndpoints = obj.lastNEndpoints;
  685. // The list of endpoint IDs which are entering the list of
  686. // last-n at this time i.e. were not in the old list of last-n
  687. // endpoint IDs.
  688. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  689. var stream = obj.stream;
  690. console.log(
  691. "Data channel new last-n event: ",
  692. lastNEndpoints, endpointsEnteringLastN, obj);
  693. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  694. lastNEndpoints, endpointsEnteringLastN, obj);
  695. }
  696. else
  697. {
  698. console.debug("Data channel JSON-formatted message: ", obj);
  699. }
  700. }
  701. };
  702. dataChannel.onclose = function ()
  703. {
  704. console.info("The Data Channel closed", dataChannel);
  705. var idx = _dataChannels.indexOf(dataChannel);
  706. if (idx > -1)
  707. _dataChannels = _dataChannels.splice(idx, 1);
  708. };
  709. _dataChannels.push(dataChannel);
  710. },
  711. /**
  712. * Binds "ondatachannel" event listener to given PeerConnection instance.
  713. * @param peerConnection WebRTC peer connection instance.
  714. */
  715. init: function (peerConnection, emitter) {
  716. if(!config.openSctp)
  717. return;
  718. peerConnection.ondatachannel = this.onDataChannel;
  719. eventEmitter = emitter;
  720. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  721. // Although it's not a requirement to open separate channels from both bridge
  722. // and peer as single channel can be used for sending and receiving data.
  723. // So either channel opened by the bridge or the one opened here is enough
  724. // for communication with the bridge.
  725. /*var dataChannelOptions =
  726. {
  727. reliable: true
  728. };
  729. var dataChannel
  730. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  731. // Can be used only when is in open state
  732. dataChannel.onopen = function ()
  733. {
  734. dataChannel.send("My channel !!!");
  735. };
  736. dataChannel.onmessage = function (event)
  737. {
  738. var msgData = event.data;
  739. console.info("Got My Data Channel Message:", msgData, dataChannel);
  740. };*/
  741. },
  742. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  743. handlePinnedEndpointEvent: onPinnedEndpointChanged
  744. };
  745. function onSelectedEndpointChanged(userResource)
  746. {
  747. console.log('selected endpoint changed: ', userResource);
  748. if (_dataChannels && _dataChannels.length != 0)
  749. {
  750. _dataChannels.some(function (dataChannel) {
  751. if (dataChannel.readyState == 'open')
  752. {
  753. console.log('sending selected endpoint changed '
  754. + 'notification to the bridge: ', userResource);
  755. dataChannel.send(JSON.stringify({
  756. 'colibriClass': 'SelectedEndpointChangedEvent',
  757. 'selectedEndpoint':
  758. (!userResource || userResource === null)?
  759. null : userResource
  760. }));
  761. return true;
  762. }
  763. });
  764. }
  765. }
  766. function onPinnedEndpointChanged(userResource)
  767. {
  768. console.log('pinned endpoint changed: ', userResource);
  769. if (_dataChannels && _dataChannels.length != 0)
  770. {
  771. _dataChannels.some(function (dataChannel) {
  772. if (dataChannel.readyState == 'open')
  773. {
  774. dataChannel.send(JSON.stringify({
  775. 'colibriClass': 'PinnedEndpointChangedEvent',
  776. 'pinnedEndpoint':
  777. (!userResource || userResource == null)?
  778. null : userResource
  779. }));
  780. return true;
  781. }
  782. });
  783. }
  784. }
  785. module.exports = DataChannels;
  786. },{"../../service/RTC/RTCEvents":101}],7:[function(require,module,exports){
  787. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  788. var RTCEvents = require("../../service/RTC/RTCEvents");
  789. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  790. {
  791. this.stream = stream;
  792. this.eventEmitter = eventEmitter;
  793. this.type = type;
  794. this.videoType = videoType;
  795. this.isGUMStream = true;
  796. if(isGUMStream === false)
  797. this.isGUMStream = isGUMStream;
  798. var self = this;
  799. if(type == "audio")
  800. {
  801. this.getTracks = function () {
  802. return self.stream.getAudioTracks();
  803. };
  804. }
  805. else
  806. {
  807. this.getTracks = function () {
  808. return self.stream.getVideoTracks();
  809. };
  810. }
  811. this.stream.onended = function()
  812. {
  813. self.streamEnded();
  814. };
  815. }
  816. LocalStream.prototype.streamEnded = function () {
  817. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  818. }
  819. LocalStream.prototype.getOriginalStream = function()
  820. {
  821. return this.stream;
  822. }
  823. LocalStream.prototype.isAudioStream = function () {
  824. return this.type === "audio";
  825. };
  826. LocalStream.prototype.setMute = function(mute)
  827. {
  828. if((window.location.protocol != "https:" && this.isGUMStream) ||
  829. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  830. {
  831. var tracks = this.getTracks();
  832. for (var idx = 0; idx < tracks.length; idx++) {
  833. tracks[idx].enabled = mute;
  834. }
  835. this.eventEmitter.emit(
  836. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  837. !mute);
  838. }
  839. else
  840. {
  841. if(mute === false) {
  842. APP.xmpp.removeStream(this.stream);
  843. this.stream.stop();
  844. this.eventEmitter.emit(
  845. (this.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  846. true);
  847. }
  848. else
  849. {
  850. var self = this;
  851. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  852. (this.isAudioStream() ? ["audio"] : ["video"]),
  853. function (stream) {
  854. if(self.isAudioStream())
  855. {
  856. APP.RTC.changeLocalAudio(stream,
  857. function () {
  858. self.eventEmitter.emit(
  859. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  860. true);
  861. });
  862. }
  863. else
  864. {
  865. APP.RTC.changeLocalVideo(stream, false,
  866. function () {
  867. self.eventEmitter.emit(
  868. (self.type == "audio"? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE),
  869. true);
  870. });
  871. }
  872. });
  873. }
  874. }
  875. };
  876. LocalStream.prototype.isMuted = function () {
  877. var tracks = [];
  878. if(this.type == "audio")
  879. {
  880. tracks = this.stream.getAudioTracks();
  881. }
  882. else
  883. {
  884. if(this.stream.ended)
  885. return true;
  886. tracks = this.stream.getVideoTracks();
  887. }
  888. for (var idx = 0; idx < tracks.length; idx++) {
  889. if(tracks[idx].enabled)
  890. return false;
  891. }
  892. return true;
  893. }
  894. LocalStream.prototype.getId = function () {
  895. return this.stream.getTracks()[0].id;
  896. }
  897. module.exports = LocalStream;
  898. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes.js":103}],8:[function(require,module,exports){
  899. ////These lines should be uncommented when require works in app.js
  900. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  901. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  902. /**
  903. * Creates a MediaStream object for the given data, session id and ssrc.
  904. * It is a wrapper class for the MediaStream.
  905. *
  906. * @param data the data object from which we obtain the stream,
  907. * the peerjid, etc.
  908. * @param sid the session id
  909. * @param ssrc the ssrc corresponding to this MediaStream
  910. *
  911. * @constructor
  912. */
  913. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  914. // XXX(gp) to minimize headaches in the future, we should build our
  915. // abstractions around tracks and not streams. ORTC is track based API.
  916. // Mozilla expects m-lines to represent media tracks.
  917. //
  918. // Practically, what I'm saying is that we should have a MediaTrack class
  919. // and not a MediaStream class.
  920. //
  921. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  922. // a track might have an associated RTX and FEC sources.
  923. this.sid = sid;
  924. this.stream = data.stream;
  925. this.peerjid = data.peerjid;
  926. this.ssrc = ssrc;
  927. this.type = (this.stream.getVideoTracks().length > 0)?
  928. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  929. this.videoType = null;
  930. this.muted = false;
  931. this.eventEmitter = eventEmitter;
  932. }
  933. MediaStream.prototype.getOriginalStream = function()
  934. {
  935. return this.stream;
  936. };
  937. MediaStream.prototype.setMute = function (value)
  938. {
  939. this.stream.muted = value;
  940. this.muted = value;
  941. };
  942. MediaStream.prototype.setVideoType = function (value) {
  943. if(this.videoType === value)
  944. return;
  945. this.videoType = value;
  946. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  947. this.peerjid);
  948. };
  949. module.exports = MediaStream;
  950. },{"../../service/RTC/MediaStreamTypes":100,"../../service/RTC/StreamEventTypes":103}],9:[function(require,module,exports){
  951. var EventEmitter = require("events");
  952. var RTCBrowserType = require("./RTCBrowserType");
  953. var RTCUtils = require("./RTCUtils.js");
  954. var LocalStream = require("./LocalStream.js");
  955. var DataChannels = require("./DataChannels");
  956. var MediaStream = require("./MediaStream.js");
  957. var DesktopSharingEventTypes
  958. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  959. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  960. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  961. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  962. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  963. var UIEvents = require("../../service/UI/UIEvents");
  964. var eventEmitter = new EventEmitter();
  965. function getMediaStreamUsage()
  966. {
  967. var result = {
  968. audio: true,
  969. video: true
  970. };
  971. /** There are some issues with the desktop sharing
  972. * when this property is enabled.
  973. * WARNING: We must change the implementation to start video/audio if we
  974. * receive from the focus that the peer is not muted.
  975. var isSecureConnection = window.location.protocol == "https:";
  976. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  977. {
  978. result = {
  979. audio: false,
  980. video: false
  981. };
  982. }
  983. **/
  984. return result;
  985. }
  986. var RTC = {
  987. rtcUtils: null,
  988. devices: {
  989. audio: true,
  990. video: true
  991. },
  992. localStreams: [],
  993. remoteStreams: {},
  994. localAudio: null,
  995. localVideo: null,
  996. addStreamListener: function (listener, eventType) {
  997. eventEmitter.on(eventType, listener);
  998. },
  999. addListener: function (type, listener) {
  1000. eventEmitter.on(type, listener);
  1001. },
  1002. removeStreamListener: function (listener, eventType) {
  1003. if(!(eventType instanceof StreamEventTypes))
  1004. throw "Illegal argument";
  1005. eventEmitter.removeListener(eventType, listener);
  1006. },
  1007. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  1008. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  1009. //in firefox we have only one stream object
  1010. if(this.localStreams.length == 0 ||
  1011. this.localStreams[0].getOriginalStream() != stream)
  1012. this.localStreams.push(localStream);
  1013. if(isMuted === true)
  1014. localStream.setMute(false);
  1015. if(type == "audio")
  1016. {
  1017. this.localAudio = localStream;
  1018. }
  1019. else
  1020. {
  1021. this.localVideo = localStream;
  1022. }
  1023. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  1024. if(change)
  1025. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  1026. eventEmitter.emit(eventType, localStream, isMuted);
  1027. return localStream;
  1028. },
  1029. removeLocalStream: function (stream) {
  1030. for(var i = 0; i < this.localStreams.length; i++)
  1031. {
  1032. if(this.localStreams[i].getOriginalStream() === stream) {
  1033. delete this.localStreams[i];
  1034. return;
  1035. }
  1036. }
  1037. },
  1038. createRemoteStream: function (data, sid, thessrc) {
  1039. var remoteStream = new MediaStream(data, sid, thessrc,
  1040. RTCBrowserType.getBrowserType(), eventEmitter);
  1041. var jid = data.peerjid || APP.xmpp.myJid();
  1042. if(!this.remoteStreams[jid]) {
  1043. this.remoteStreams[jid] = {};
  1044. }
  1045. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1046. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1047. return remoteStream;
  1048. },
  1049. getPCConstraints: function () {
  1050. return this.rtcUtils.pc_constraints;
  1051. },
  1052. getUserMediaWithConstraints:function(um, success_callback,
  1053. failure_callback, resolution,
  1054. bandwidth, fps, desktopStream)
  1055. {
  1056. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1057. failure_callback, resolution, bandwidth, fps, desktopStream);
  1058. },
  1059. attachMediaStream: function (element, stream) {
  1060. this.rtcUtils.attachMediaStream(element, stream);
  1061. },
  1062. getStreamID: function (stream) {
  1063. return this.rtcUtils.getStreamID(stream);
  1064. },
  1065. getVideoSrc: function (element) {
  1066. return this.rtcUtils.getVideoSrc(element);
  1067. },
  1068. setVideoSrc: function (element, src) {
  1069. this.rtcUtils.setVideoSrc(element, src);
  1070. },
  1071. getVideoElementName: function () {
  1072. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1073. },
  1074. dispose: function() {
  1075. if (this.rtcUtils) {
  1076. this.rtcUtils = null;
  1077. }
  1078. },
  1079. stop: function () {
  1080. this.dispose();
  1081. },
  1082. start: function () {
  1083. var self = this;
  1084. APP.desktopsharing.addListener(
  1085. function (stream, isUsingScreenStream, callback) {
  1086. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1087. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1088. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1089. for(var i = 0; i < changedStreams.length; i++) {
  1090. var type = changedStreams[i].type;
  1091. if (type != "audio") {
  1092. var peerStreams = self.remoteStreams[jid];
  1093. if(!peerStreams)
  1094. continue;
  1095. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1096. if(!videoStream)
  1097. continue;
  1098. videoStream.setVideoType(changedStreams[i].type);
  1099. }
  1100. }
  1101. });
  1102. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1103. DataChannels.init(event.peerconnection, eventEmitter);
  1104. });
  1105. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1106. DataChannels.handleSelectedEndpointEvent);
  1107. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1108. DataChannels.handlePinnedEndpointEvent);
  1109. // In case of IE we continue from 'onReady' callback
  1110. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1111. // once it is initialized.
  1112. var onReady = function () {
  1113. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1114. self.rtcUtils.obtainAudioAndVideoPermissions(
  1115. null, null, getMediaStreamUsage());
  1116. };
  1117. this.rtcUtils = new RTCUtils(this, onReady);
  1118. // Call onReady() if Temasys plugin is not used
  1119. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1120. onReady();
  1121. }
  1122. },
  1123. muteRemoteVideoStream: function (jid, value) {
  1124. var stream;
  1125. if(this.remoteStreams[jid] &&
  1126. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  1127. {
  1128. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1129. }
  1130. if(!stream)
  1131. return true;
  1132. if (value != stream.muted) {
  1133. stream.setMute(value);
  1134. return true;
  1135. }
  1136. return false;
  1137. },
  1138. switchVideoStreams: function (new_stream) {
  1139. this.localVideo.stream = new_stream;
  1140. this.localStreams = [];
  1141. //in firefox we have only one stream object
  1142. if (this.localAudio.getOriginalStream() != new_stream)
  1143. this.localStreams.push(this.localAudio);
  1144. this.localStreams.push(this.localVideo);
  1145. },
  1146. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1147. var oldStream = this.localVideo.getOriginalStream();
  1148. var type = (isUsingScreenStream? "screen" : "video");
  1149. var localCallback = callback;
  1150. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  1151. {
  1152. localCallback = function() {
  1153. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  1154. callback();
  1155. };
  1156. }
  1157. // FIXME: Workaround for FF/IE/Safari
  1158. if (stream && stream.videoStream) {
  1159. stream = stream.videoStream;
  1160. }
  1161. var videoStream = this.rtcUtils.createStream(stream, true);
  1162. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1163. // Stop the stream to trigger onended event for old stream
  1164. oldStream.stop();
  1165. this.switchVideoStreams(videoStream, oldStream);
  1166. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1167. },
  1168. changeLocalAudio: function (stream, callback) {
  1169. var oldStream = this.localAudio.getOriginalStream();
  1170. var newStream = this.rtcUtils.createStream(stream);
  1171. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1172. // Stop the stream to trigger onended event for old stream
  1173. oldStream.stop();
  1174. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1175. },
  1176. isVideoMuted: function (jid) {
  1177. if (jid === APP.xmpp.myJid()) {
  1178. var localVideo = APP.RTC.localVideo;
  1179. return (!localVideo || localVideo.isMuted());
  1180. }
  1181. else
  1182. {
  1183. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1184. return null;
  1185. }
  1186. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1187. }
  1188. },
  1189. /**
  1190. * Checks if video identified by given src is desktop stream.
  1191. * @param videoSrc eg.
  1192. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  1193. * @returns {boolean}
  1194. */
  1195. isVideoSrcDesktop: function (jid) {
  1196. if(!jid)
  1197. return false;
  1198. var isDesktop = false;
  1199. var stream = null;
  1200. if (APP.xmpp.myJid() === jid) {
  1201. // local video
  1202. stream = this.localVideo;
  1203. } else {
  1204. var peerStreams = this.remoteStreams[jid];
  1205. if(!peerStreams)
  1206. return false;
  1207. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  1208. }
  1209. if(stream)
  1210. isDesktop = (stream.videoType === "screen");
  1211. return isDesktop;
  1212. },
  1213. setVideoMute: function(mute, callback, options) {
  1214. if(!this.localVideo)
  1215. return;
  1216. if (mute == APP.RTC.localVideo.isMuted())
  1217. {
  1218. APP.xmpp.sendVideoInfoPresence(mute);
  1219. if(callback)
  1220. callback(mute);
  1221. }
  1222. else
  1223. {
  1224. APP.RTC.localVideo.setMute(!mute);
  1225. APP.xmpp.setVideoMute(
  1226. mute,
  1227. callback,
  1228. options);
  1229. }
  1230. },
  1231. setDeviceAvailability: function (devices) {
  1232. if(!devices)
  1233. return;
  1234. if(devices.audio === true || devices.audio === false)
  1235. this.devices.audio = devices.audio;
  1236. if(devices.video === true || devices.video === false)
  1237. this.devices.video = devices.video;
  1238. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1239. }
  1240. };
  1241. module.exports = RTC;
  1242. },{"../../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){
  1243. var currentBrowser;
  1244. var browserVersion;
  1245. var RTCBrowserType = {
  1246. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1247. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1248. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1249. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1250. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1251. getBrowserType: function () {
  1252. return currentBrowser;
  1253. },
  1254. isChrome: function () {
  1255. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1256. },
  1257. isOpera: function () {
  1258. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1259. },
  1260. isFirefox: function () {
  1261. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1262. },
  1263. isIExplorer: function () {
  1264. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1265. },
  1266. isSafari: function () {
  1267. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1268. },
  1269. isTemasysPluginUsed: function () {
  1270. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1271. },
  1272. getFirefoxVersion: function () {
  1273. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1274. },
  1275. getChromeVersion: function () {
  1276. return RTCBrowserType.isChrome() ? browserVersion : null;
  1277. }
  1278. // Add version getters for other browsers when needed
  1279. };
  1280. // detectOpera() must be called before detectChrome() !!!
  1281. // otherwise Opera wil be detected as Chrome
  1282. function detectChrome() {
  1283. if (navigator.webkitGetUserMedia) {
  1284. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1285. var userAgent = navigator.userAgent.toLowerCase();
  1286. // We can assume that user agent is chrome, because it's
  1287. // enforced when 'ext' streaming method is set
  1288. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1289. console.log("This appears to be Chrome, ver: " + ver);
  1290. return ver;
  1291. }
  1292. return null;
  1293. }
  1294. function detectOpera() {
  1295. var userAgent = navigator.userAgent;
  1296. if (userAgent.match(/Opera|OPR/)) {
  1297. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1298. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1299. console.info("This appears to be Opera, ver: " + version);
  1300. return version;
  1301. }
  1302. return null;
  1303. }
  1304. function detectFirefox() {
  1305. if (navigator.mozGetUserMedia) {
  1306. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1307. var version = parseInt(
  1308. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1309. console.log('This appears to be Firefox, ver: ' + version);
  1310. return version;
  1311. }
  1312. return null;
  1313. }
  1314. function detectSafari() {
  1315. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1316. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1317. console.info("This appears to be Safari");
  1318. // FIXME detect Safari version when needed
  1319. return 1;
  1320. }
  1321. return null;
  1322. }
  1323. function detectIE() {
  1324. var version;
  1325. var ua = window.navigator.userAgent;
  1326. var msie = ua.indexOf('MSIE ');
  1327. if (msie > 0) {
  1328. // IE 10 or older => return version number
  1329. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1330. }
  1331. var trident = ua.indexOf('Trident/');
  1332. if (!version && trident > 0) {
  1333. // IE 11 => return version number
  1334. var rv = ua.indexOf('rv:');
  1335. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1336. }
  1337. var edge = ua.indexOf('Edge/');
  1338. if (!version && edge > 0) {
  1339. // IE 12 => return version number
  1340. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1341. }
  1342. if (version) {
  1343. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1344. console.info("This appears to be IExplorer, ver: " + version);
  1345. }
  1346. return version;
  1347. }
  1348. function detectBrowser() {
  1349. var version;
  1350. var detectors = [
  1351. detectOpera,
  1352. detectChrome,
  1353. detectFirefox,
  1354. detectIE,
  1355. detectSafari
  1356. ];
  1357. // Try all browser detectors
  1358. for (var i = 0; i < detectors.length; i++) {
  1359. version = detectors[i]();
  1360. if (version)
  1361. return version;
  1362. }
  1363. console.error("Failed to detect browser type");
  1364. return undefined;
  1365. }
  1366. browserVersion = detectBrowser();
  1367. module.exports = RTCBrowserType;
  1368. },{}],11:[function(require,module,exports){
  1369. var RTCBrowserType = require("./RTCBrowserType");
  1370. var Resolutions = require("../../service/RTC/Resolutions");
  1371. var AdapterJS = require("./adapter.screenshare");
  1372. var SDPUtil = require("../xmpp/SDPUtil");
  1373. var currentResolution = null;
  1374. function getPreviousResolution(resolution) {
  1375. if(!Resolutions[resolution])
  1376. return null;
  1377. var order = Resolutions[resolution].order;
  1378. var res = null;
  1379. var resName = null;
  1380. for(var i in Resolutions)
  1381. {
  1382. var tmp = Resolutions[i];
  1383. if(res == null || (res.order < tmp.order && tmp.order < order))
  1384. {
  1385. resName = i;
  1386. res = tmp;
  1387. }
  1388. }
  1389. return resName;
  1390. }
  1391. function setResolutionConstraints(constraints, resolution, isAndroid)
  1392. {
  1393. if (resolution && !constraints.video || isAndroid) {
  1394. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1395. }
  1396. if(Resolutions[resolution])
  1397. {
  1398. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1399. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1400. }
  1401. else
  1402. {
  1403. if (isAndroid) {
  1404. constraints.video.mandatory.minWidth = 320;
  1405. constraints.video.mandatory.minHeight = 240;
  1406. constraints.video.mandatory.maxFrameRate = 15;
  1407. }
  1408. }
  1409. if (constraints.video.mandatory.minWidth)
  1410. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  1411. if (constraints.video.mandatory.minHeight)
  1412. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  1413. }
  1414. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1415. {
  1416. var constraints = {audio: false, video: false};
  1417. if (um.indexOf('video') >= 0) {
  1418. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  1419. }
  1420. if (um.indexOf('audio') >= 0) {
  1421. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  1422. }
  1423. if (um.indexOf('screen') >= 0) {
  1424. if (RTCBrowserType.isChrome()) {
  1425. constraints.video = {
  1426. mandatory: {
  1427. chromeMediaSource: "screen",
  1428. googLeakyBucket: true,
  1429. maxWidth: window.screen.width,
  1430. maxHeight: window.screen.height,
  1431. maxFrameRate: 3
  1432. },
  1433. optional: []
  1434. };
  1435. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1436. constraints.video = {
  1437. optional: [
  1438. {
  1439. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1440. }
  1441. ]
  1442. };
  1443. } else {
  1444. console.error(
  1445. "'screen' WebRTC media source is supported only in Chrome" +
  1446. " and with Temasys plugin");
  1447. }
  1448. }
  1449. if (um.indexOf('desktop') >= 0) {
  1450. constraints.video = {
  1451. mandatory: {
  1452. chromeMediaSource: "desktop",
  1453. chromeMediaSourceId: desktopStream,
  1454. googLeakyBucket: true,
  1455. maxWidth: window.screen.width,
  1456. maxHeight: window.screen.height,
  1457. maxFrameRate: 3
  1458. },
  1459. optional: []
  1460. };
  1461. }
  1462. if (constraints.audio) {
  1463. // if it is good enough for hangouts...
  1464. constraints.audio.optional.push(
  1465. {googEchoCancellation: true},
  1466. {googAutoGainControl: true},
  1467. {googNoiseSupression: true},
  1468. {googHighpassFilter: true},
  1469. {googNoisesuppression2: true},
  1470. {googEchoCancellation2: true},
  1471. {googAutoGainControl2: true}
  1472. );
  1473. }
  1474. if (constraints.video) {
  1475. constraints.video.optional.push(
  1476. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1477. );
  1478. if (um.indexOf('video') >= 0) {
  1479. constraints.video.optional.push(
  1480. {googLeakyBucket: true}
  1481. );
  1482. }
  1483. }
  1484. if (um.indexOf('video') >= 0) {
  1485. setResolutionConstraints(constraints, resolution, isAndroid);
  1486. }
  1487. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1488. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1489. constraints.video.optional.push({bandwidth: bandwidth});
  1490. }
  1491. if (fps) { // for some cameras it might be necessary to request 30fps
  1492. // so they choose 30fps mjpg over 10fps yuy2
  1493. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1494. constraints.video.mandatory.minFrameRate = fps;
  1495. }
  1496. return constraints;
  1497. }
  1498. function RTCUtils(RTCService, onTemasysPluginReady)
  1499. {
  1500. var self = this;
  1501. this.service = RTCService;
  1502. if (RTCBrowserType.isFirefox()) {
  1503. var FFversion = RTCBrowserType.getFirefoxVersion();
  1504. if (FFversion >= 40 && config.useBundle && config.useRtcpMux) {
  1505. this.peerconnection = mozRTCPeerConnection;
  1506. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1507. this.pc_constraints = {};
  1508. this.attachMediaStream = function (element, stream) {
  1509. // srcObject is being standardized and FF will eventually
  1510. // support that unprefixed. FF also supports the
  1511. // "element.src = URL.createObjectURL(...)" combo, but that
  1512. // will be deprecated in favour of srcObject.
  1513. //
  1514. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1515. // https://github.com/webrtc/samples/issues/302
  1516. if(!element[0])
  1517. return;
  1518. element[0].mozSrcObject = stream;
  1519. element[0].play();
  1520. };
  1521. this.getStreamID = function (stream) {
  1522. var tracks = stream.getVideoTracks();
  1523. if(!tracks || tracks.length == 0)
  1524. {
  1525. tracks = stream.getAudioTracks();
  1526. }
  1527. return SDPUtil.filter_special_chars(tracks[0].id);
  1528. };
  1529. this.getVideoSrc = function (element) {
  1530. if(!element)
  1531. return null;
  1532. return element.mozSrcObject;
  1533. };
  1534. this.setVideoSrc = function (element, src) {
  1535. if(element)
  1536. element.mozSrcObject = src;
  1537. };
  1538. RTCSessionDescription = mozRTCSessionDescription;
  1539. RTCIceCandidate = mozRTCIceCandidate;
  1540. } else {
  1541. console.error(
  1542. "Firefox requirements not met, ver: " + FFversion +
  1543. ", bundle: " + config.useBundle +
  1544. ", rtcp-mux: " + config.useRtcpMux);
  1545. window.location.href = 'unsupported_browser.html';
  1546. return;
  1547. }
  1548. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1549. this.peerconnection = webkitRTCPeerConnection;
  1550. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1551. this.attachMediaStream = function (element, stream) {
  1552. element.attr('src', webkitURL.createObjectURL(stream));
  1553. };
  1554. this.getStreamID = function (stream) {
  1555. // streams from FF endpoints have the characters '{' and '}'
  1556. // that make jQuery choke.
  1557. return SDPUtil.filter_special_chars(stream.id);
  1558. };
  1559. this.getVideoSrc = function (element) {
  1560. if(!element)
  1561. return null;
  1562. return element.getAttribute("src");
  1563. };
  1564. this.setVideoSrc = function (element, src) {
  1565. if(element)
  1566. element.setAttribute("src", src);
  1567. };
  1568. // DTLS should now be enabled by default but..
  1569. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1570. if (navigator.userAgent.indexOf('Android') != -1) {
  1571. this.pc_constraints = {}; // disable DTLS on Android
  1572. }
  1573. if (!webkitMediaStream.prototype.getVideoTracks) {
  1574. webkitMediaStream.prototype.getVideoTracks = function () {
  1575. return this.videoTracks;
  1576. };
  1577. }
  1578. if (!webkitMediaStream.prototype.getAudioTracks) {
  1579. webkitMediaStream.prototype.getAudioTracks = function () {
  1580. return this.audioTracks;
  1581. };
  1582. }
  1583. }
  1584. // Detect IE/Safari
  1585. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1586. AdapterJS.WebRTCPlugin.setLogLevel(
  1587. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1588. AdapterJS.webRTCReady(function (isPlugin) {
  1589. self.peerconnection = RTCPeerConnection;
  1590. self.getUserMedia = getUserMedia;
  1591. self.attachMediaStream = function (element, stream) {
  1592. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1593. return;
  1594. }
  1595. attachMediaStream(element[0], stream);
  1596. };
  1597. self.getStreamID = function (stream) {
  1598. var id = SDPUtil.filter_special_chars(stream.label);
  1599. return id;
  1600. };
  1601. self.getVideoSrc = function (element) {
  1602. if (!element) {
  1603. console.warn("Attempt to get video SRC of null element");
  1604. return null;
  1605. }
  1606. var src = null;
  1607. var children = element.children;
  1608. for (var i = 0; i !== children.length; ++i) {
  1609. if (children[i].name === 'streamId') {
  1610. return children[i].value;
  1611. }
  1612. }
  1613. //console.info(element.id + " SRC: " + src);
  1614. return null;
  1615. };
  1616. self.setVideoSrc = function (element, src) {
  1617. //console.info("Set video src: ", element, src);
  1618. if (!src) {
  1619. console.warn("Not attaching video stream, 'src' is null");
  1620. return;
  1621. }
  1622. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1623. var stream = AdapterJS.WebRTCPlugin.plugin
  1624. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1625. attachMediaStream(element, stream);
  1626. };
  1627. onTemasysPluginReady(isPlugin);
  1628. });
  1629. } else {
  1630. try {
  1631. console.log('Browser does not appear to be WebRTC-capable');
  1632. } catch (e) { }
  1633. window.location.href = 'unsupported_browser.html';
  1634. }
  1635. }
  1636. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1637. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1638. desktopStream)
  1639. {
  1640. currentResolution = resolution;
  1641. // Check if we are running on Android device
  1642. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1643. var constraints = getConstraints(
  1644. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1645. console.info("Get media constraints", constraints);
  1646. var self = this;
  1647. try {
  1648. this.getUserMedia(constraints,
  1649. function (stream) {
  1650. console.log('onUserMediaSuccess');
  1651. self.setAvailableDevices(um, true);
  1652. success_callback(stream);
  1653. },
  1654. function (error) {
  1655. self.setAvailableDevices(um, false);
  1656. console.warn('Failed to get access to local media. Error ',
  1657. error, constraints);
  1658. if (failure_callback) {
  1659. failure_callback(error);
  1660. }
  1661. });
  1662. } catch (e) {
  1663. console.error('GUM failed: ', e);
  1664. if(failure_callback) {
  1665. failure_callback(e);
  1666. }
  1667. }
  1668. };
  1669. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1670. var devices = {};
  1671. if(um.indexOf("video") != -1)
  1672. {
  1673. devices.video = available;
  1674. }
  1675. if(um.indexOf("audio") != -1)
  1676. {
  1677. devices.audio = available;
  1678. }
  1679. this.service.setDeviceAvailability(devices);
  1680. }
  1681. /**
  1682. * We ask for audio and video combined stream in order to get permissions and
  1683. * not to ask twice.
  1684. */
  1685. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1686. function(devices, callback, usageOptions)
  1687. {
  1688. var self = this;
  1689. // Get AV
  1690. var successCallback = function (stream) {
  1691. if(callback)
  1692. callback(stream, usageOptions);
  1693. else
  1694. self.successCallback(stream, usageOptions);
  1695. };
  1696. if(!devices)
  1697. devices = ['audio', 'video'];
  1698. var newDevices = [];
  1699. if(usageOptions)
  1700. for(var i = 0; i < devices.length; i++)
  1701. {
  1702. var device = devices[i];
  1703. if(usageOptions[device] === true)
  1704. newDevices.push(device);
  1705. }
  1706. else
  1707. newDevices = devices;
  1708. if(newDevices.length === 0)
  1709. {
  1710. successCallback();
  1711. return;
  1712. }
  1713. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1714. // With FF/IE we can't split the stream into audio and video because FF
  1715. // doesn't support media stream constructors. So, we need to get the
  1716. // audio stream separately from the video stream using two distinct GUM
  1717. // calls. Not very user friendly :-( but we don't have many other
  1718. // options neither.
  1719. //
  1720. // Note that we pack those 2 streams in a single object and pass it to
  1721. // the successCallback method.
  1722. var obtainVideo = function (audioStream) {
  1723. self.getUserMediaWithConstraints(
  1724. ['video'],
  1725. function (videoStream) {
  1726. return successCallback({
  1727. audioStream: audioStream,
  1728. videoStream: videoStream
  1729. });
  1730. },
  1731. function (error) {
  1732. console.error(
  1733. 'failed to obtain video stream - stop', error);
  1734. self.errorCallback(error);
  1735. },
  1736. config.resolution || '360');
  1737. };
  1738. var obtainAudio = function () {
  1739. self.getUserMediaWithConstraints(
  1740. ['audio'],
  1741. function (audioStream) {
  1742. if (newDevices.indexOf('video') !== -1)
  1743. obtainVideo(audioStream);
  1744. },
  1745. function (error) {
  1746. console.error(
  1747. 'failed to obtain audio stream - stop', error);
  1748. self.errorCallback(error);
  1749. }
  1750. );
  1751. };
  1752. if (newDevices.indexOf('audio') !== -1) {
  1753. obtainAudio();
  1754. } else {
  1755. obtainVideo(null);
  1756. }
  1757. } else {
  1758. this.getUserMediaWithConstraints(
  1759. newDevices,
  1760. function (stream) {
  1761. successCallback(stream);
  1762. },
  1763. function (error) {
  1764. self.errorCallback(error);
  1765. },
  1766. config.resolution || '360');
  1767. }
  1768. };
  1769. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1770. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1771. // it's an object with two properties: audioStream, videoStream.
  1772. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1773. console.log('got', stream, stream.getAudioTracks().length,
  1774. stream.getVideoTracks().length);
  1775. this.handleLocalStream(stream, usageOptions);
  1776. };
  1777. RTCUtils.prototype.errorCallback = function (error) {
  1778. var self = this;
  1779. console.error('failed to obtain audio/video stream - trying audio only', error);
  1780. var resolution = getPreviousResolution(currentResolution);
  1781. if(typeof error == "object" && error.constraintName && error.name
  1782. && (error.name == "ConstraintNotSatisfiedError" ||
  1783. error.name == "OverconstrainedError") &&
  1784. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1785. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1786. && resolution != null)
  1787. {
  1788. self.getUserMediaWithConstraints(['audio', 'video'],
  1789. function (stream) {
  1790. return self.successCallback(stream);
  1791. }, function (error) {
  1792. return self.errorCallback(error);
  1793. }, resolution);
  1794. }
  1795. else
  1796. {
  1797. self.getUserMediaWithConstraints(
  1798. ['audio'],
  1799. function (stream) {
  1800. return self.successCallback(stream);
  1801. },
  1802. function (error) {
  1803. console.error('failed to obtain audio/video stream - stop',
  1804. error);
  1805. return self.successCallback(null);
  1806. }
  1807. );
  1808. }
  1809. }
  1810. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1811. {
  1812. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1813. // an object with two properties: audioStream, videoStream.
  1814. var audioStream, videoStream;
  1815. if(window.webkitMediaStream)
  1816. {
  1817. audioStream = new webkitMediaStream();
  1818. videoStream = new webkitMediaStream();
  1819. if(stream) {
  1820. var audioTracks = stream.getAudioTracks();
  1821. for (var i = 0; i < audioTracks.length; i++) {
  1822. audioStream.addTrack(audioTracks[i]);
  1823. }
  1824. var videoTracks = stream.getVideoTracks();
  1825. for (i = 0; i < videoTracks.length; i++) {
  1826. videoStream.addTrack(videoTracks[i]);
  1827. }
  1828. }
  1829. }
  1830. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1831. { // Firefox and Temasys plugin
  1832. if (stream && stream.audioStream)
  1833. audioStream = stream.audioStream;
  1834. else
  1835. audioStream = new DummyMediaStream("dummyAudio");
  1836. if (stream && stream.videoStream)
  1837. videoStream = stream.videoStream;
  1838. else
  1839. videoStream = new DummyMediaStream("dummyVideo");
  1840. }
  1841. var audioMuted = (usageOptions && usageOptions.audio === false),
  1842. videoMuted = (usageOptions && usageOptions.video === false);
  1843. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1844. videoGUM = (!usageOptions || usageOptions.video !== false);
  1845. this.service.createLocalStream(audioStream, "audio", null, null,
  1846. audioMuted, audioGUM);
  1847. this.service.createLocalStream(videoStream, "video", null, null,
  1848. videoMuted, videoGUM);
  1849. };
  1850. function DummyMediaStream(id) {
  1851. this.id = id;
  1852. this.label = id;
  1853. this.stop = function() { };
  1854. this.getAudioTracks = function() { return []; }
  1855. this.getVideoTracks = function() { return []; }
  1856. }
  1857. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1858. var newStream = null;
  1859. if (window.webkitMediaStream) {
  1860. newStream = new webkitMediaStream();
  1861. if (newStream) {
  1862. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1863. for (i = 0; i < tracks.length; i++) {
  1864. newStream.addTrack(tracks[i]);
  1865. }
  1866. }
  1867. }
  1868. else {
  1869. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1870. if (stream) {
  1871. newStream = stream;
  1872. } else {
  1873. newStream = new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1874. }
  1875. }
  1876. return newStream;
  1877. };
  1878. module.exports = RTCUtils;
  1879. },{"../../service/RTC/Resolutions":102,"../xmpp/SDPUtil":58,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){
  1880. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1881. // Adapter's interface.
  1882. var AdapterJS = AdapterJS || {};
  1883. // Browserify compatibility
  1884. if(typeof exports !== 'undefined') {
  1885. module.exports = AdapterJS;
  1886. }
  1887. AdapterJS.options = AdapterJS.options || {};
  1888. // uncomment to get virtual webcams
  1889. // AdapterJS.options.getAllCams = true;
  1890. // uncomment to prevent the install prompt when the plugin in not yet installed
  1891. // AdapterJS.options.hidePluginInstallPrompt = true;
  1892. // AdapterJS version
  1893. AdapterJS.VERSION = '0.11.0';
  1894. // This function will be called when the WebRTC API is ready to be used
  1895. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1896. // the plugin
  1897. // You may Override this function to synchronise the start of your application
  1898. // with the WebRTC API being ready.
  1899. // If you decide not to override use this synchronisation, it may result in
  1900. // an extensive CPU usage on the plugin start (once per tab loaded)
  1901. // Params:
  1902. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1903. //
  1904. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1905. // The WebRTC API is ready.
  1906. // Override me and do whatever you want here
  1907. };
  1908. // Sets a callback function to be called when the WebRTC interface is ready.
  1909. // The first argument is the function to callback.\
  1910. // Throws an error if the first argument is not a function
  1911. AdapterJS.webRTCReady = function (callback) {
  1912. if (typeof callback !== 'function') {
  1913. throw new Error('Callback provided is not a function');
  1914. }
  1915. if (true === AdapterJS.onwebrtcreadyDone) {
  1916. // All WebRTC interfaces are ready, just call the callback
  1917. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1918. } else {
  1919. // will be triggered automatically when your browser/plugin is ready.
  1920. AdapterJS.onwebrtcready = callback;
  1921. }
  1922. };
  1923. // Plugin namespace
  1924. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1925. // The object to store plugin information
  1926. AdapterJS.WebRTCPlugin.pluginInfo = {
  1927. prefix : 'Tem',
  1928. plugName : 'TemWebRTCPlugin',
  1929. pluginId : 'plugin0',
  1930. type : 'application/x-temwebrtcplugin',
  1931. onload : '__TemWebRTCReady0',
  1932. portalLink : 'http://skylink.io/plugin/',
  1933. downloadLink : null, //set below
  1934. companyName: 'Temasys'
  1935. };
  1936. if(!!navigator.platform.match(/^Mac/i)) {
  1937. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1938. }
  1939. else if(!!navigator.platform.match(/^Win/i)) {
  1940. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1941. }
  1942. // Unique identifier of each opened page
  1943. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1944. // Use this whenever you want to call the plugin.
  1945. AdapterJS.WebRTCPlugin.plugin = null;
  1946. // Set log level for the plugin once it is ready.
  1947. // The different values are
  1948. // This is an asynchronous function that will run when the plugin is ready
  1949. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1950. // Defines webrtc's JS interface according to the plugin's implementation.
  1951. // Define plugin Browsers as WebRTC Interface.
  1952. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1953. // This function detects whether or not a plugin is installed.
  1954. // Checks if Not IE (firefox, for example), else if it's IE,
  1955. // we're running IE and do something. If not it is not supported.
  1956. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1957. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1958. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1959. // Inject the HTML DOM object element into the page.
  1960. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1961. // States of readiness that the plugin goes through when
  1962. // being injected and stated
  1963. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1964. NONE : 0, // no plugin use
  1965. INITIALIZING : 1, // Detected need for plugin
  1966. INJECTING : 2, // Injecting plugin
  1967. INJECTED: 3, // Plugin element injected but not usable yet
  1968. READY: 4 // Plugin ready to be used
  1969. };
  1970. // Current state of the plugin. You cannot use the plugin before this is
  1971. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1972. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1973. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1974. // Used to make sure AdapterJS.onwebrtcready is only called once
  1975. AdapterJS.onwebrtcreadyDone = false;
  1976. // Log levels for the plugin.
  1977. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1978. /*
  1979. Log outputs are prefixed in some cases.
  1980. INFO: Information reported by the plugin.
  1981. ERROR: Errors originating from within the plugin.
  1982. WEBRTC: Error originating from within the libWebRTC library
  1983. */
  1984. // From the least verbose to the most verbose
  1985. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1986. NONE : 'NONE',
  1987. ERROR : 'ERROR',
  1988. WARNING : 'WARNING',
  1989. INFO: 'INFO',
  1990. VERBOSE: 'VERBOSE',
  1991. SENSITIVE: 'SENSITIVE'
  1992. };
  1993. // Does a waiting check before proceeding to load the plugin.
  1994. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1995. // This methid will use an interval to wait for the plugin to be ready.
  1996. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1997. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1998. // This function will be called when plugin is ready. It sends necessary
  1999. // details to the plugin.
  2000. // The function will wait for the document to be ready and the set the
  2001. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  2002. // indicating that it can start being requested.
  2003. // This function is not in the IE/Safari condition brackets so that
  2004. // TemPluginLoaded function might be called on Chrome/Firefox.
  2005. // This function is the only private function that is not encapsulated to
  2006. // allow the plugin method to be called.
  2007. __TemWebRTCReady0 = function () {
  2008. if (document.readyState === 'complete') {
  2009. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2010. AdapterJS.maybeThroughWebRTCReady();
  2011. } else {
  2012. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  2013. if (document.readyState === 'complete') {
  2014. // TODO: update comments, we wait for the document to be ready
  2015. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  2016. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  2017. AdapterJS.maybeThroughWebRTCReady();
  2018. }
  2019. }, 100);
  2020. }
  2021. };
  2022. AdapterJS.maybeThroughWebRTCReady = function() {
  2023. if (!AdapterJS.onwebrtcreadyDone) {
  2024. AdapterJS.onwebrtcreadyDone = true;
  2025. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  2026. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  2027. }
  2028. }
  2029. };
  2030. // Text namespace
  2031. AdapterJS.TEXT = {
  2032. PLUGIN: {
  2033. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  2034. 'to work on this browser.',
  2035. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  2036. BUTTON: 'Install Now'
  2037. },
  2038. REFRESH: {
  2039. REQUIRE_REFRESH: 'Please refresh page',
  2040. BUTTON: 'Refresh Page'
  2041. }
  2042. };
  2043. // The result of ice connection states.
  2044. // - starting: Ice connection is starting.
  2045. // - checking: Ice connection is checking.
  2046. // - connected Ice connection is connected.
  2047. // - completed Ice connection is connected.
  2048. // - done Ice connection has been completed.
  2049. // - disconnected Ice connection has been disconnected.
  2050. // - failed Ice connection has failed.
  2051. // - closed Ice connection is closed.
  2052. AdapterJS._iceConnectionStates = {
  2053. starting : 'starting',
  2054. checking : 'checking',
  2055. connected : 'connected',
  2056. completed : 'connected',
  2057. done : 'completed',
  2058. disconnected : 'disconnected',
  2059. failed : 'failed',
  2060. closed : 'closed'
  2061. };
  2062. //The IceConnection states that has been fired for each peer.
  2063. AdapterJS._iceConnectionFiredStates = [];
  2064. // Check if WebRTC Interface is defined.
  2065. AdapterJS.isDefined = null;
  2066. // This function helps to retrieve the webrtc detected browser information.
  2067. // This sets:
  2068. // - webrtcDetectedBrowser: The browser agent name.
  2069. // - webrtcDetectedVersion: The browser version.
  2070. // - webrtcDetectedType: The types of webRTC support.
  2071. // - 'moz': Mozilla implementation of webRTC.
  2072. // - 'webkit': WebKit implementation of webRTC.
  2073. // - 'plugin': Using the plugin implementation.
  2074. AdapterJS.parseWebrtcDetectedBrowser = function () {
  2075. var hasMatch, checkMatch = navigator.userAgent.match(
  2076. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  2077. if (/trident/i.test(checkMatch[1])) {
  2078. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  2079. webrtcDetectedBrowser = 'IE';
  2080. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  2081. } else if (checkMatch[1] === 'Chrome') {
  2082. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2083. if (hasMatch !== null) {
  2084. webrtcDetectedBrowser = 'opera';
  2085. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2086. }
  2087. }
  2088. if (navigator.userAgent.indexOf('Safari')) {
  2089. if (typeof InstallTrigger !== 'undefined') {
  2090. webrtcDetectedBrowser = 'firefox';
  2091. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2092. webrtcDetectedBrowser = 'IE';
  2093. } else if (
  2094. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2095. webrtcDetectedBrowser = 'safari';
  2096. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2097. webrtcDetectedBrowser = 'opera';
  2098. } else if (!!window.chrome) {
  2099. webrtcDetectedBrowser = 'chrome';
  2100. }
  2101. }
  2102. if (!webrtcDetectedBrowser) {
  2103. webrtcDetectedVersion = checkMatch[1];
  2104. }
  2105. if (!webrtcDetectedVersion) {
  2106. try {
  2107. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2108. [navigator.appName, navigator.appVersion, '-?'];
  2109. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2110. checkMatch.splice(1, 1, hasMatch[1]);
  2111. }
  2112. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2113. } catch (error) { }
  2114. }
  2115. };
  2116. // To fix configuration as some browsers does not support
  2117. // the 'urls' attribute.
  2118. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2119. if (pcConfig === null) {
  2120. return;
  2121. }
  2122. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2123. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2124. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2125. delete pcConfig.iceServers[i].urls;
  2126. }
  2127. }
  2128. };
  2129. AdapterJS.addEvent = function(elem, evnt, func) {
  2130. if (elem.addEventListener) { // W3C DOM
  2131. elem.addEventListener(evnt, func, false);
  2132. } else if (elem.attachEvent) {// OLD IE DOM
  2133. elem.attachEvent('on'+evnt, func);
  2134. } else { // No much to do
  2135. elem[evnt] = func;
  2136. }
  2137. };
  2138. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2139. // only inject once the page is ready
  2140. if (document.readyState !== 'complete') {
  2141. return;
  2142. }
  2143. var w = window;
  2144. var i = document.createElement('iframe');
  2145. i.style.position = 'fixed';
  2146. i.style.top = '-41px';
  2147. i.style.left = 0;
  2148. i.style.right = 0;
  2149. i.style.width = '100%';
  2150. i.style.height = '40px';
  2151. i.style.backgroundColor = '#ffffe1';
  2152. i.style.border = 'none';
  2153. i.style.borderBottom = '1px solid #888888';
  2154. i.style.zIndex = '9999999';
  2155. if(typeof i.style.webkitTransition === 'string') {
  2156. i.style.webkitTransition = 'all .5s ease-out';
  2157. } else if(typeof i.style.transition === 'string') {
  2158. i.style.transition = 'all .5s ease-out';
  2159. }
  2160. document.body.appendChild(i);
  2161. c = (i.contentWindow) ? i.contentWindow :
  2162. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2163. c.document.open();
  2164. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2165. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2166. 'middle; cursor: default;">' + text + '</span>');
  2167. if(buttonText && buttonLink) {
  2168. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2169. c.document.close();
  2170. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2171. if (!!displayRefreshBar) {
  2172. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2173. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2174. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2175. }
  2176. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2177. e.preventDefault();
  2178. try {
  2179. event.cancelBubble = true;
  2180. } catch(error) { }
  2181. });
  2182. }
  2183. else {
  2184. c.document.close();
  2185. }
  2186. AdapterJS.addEvent(c.document, 'click', function() {
  2187. w.document.body.removeChild(i);
  2188. });
  2189. setTimeout(function() {
  2190. if(typeof i.style.webkitTransform === 'string') {
  2191. i.style.webkitTransform = 'translateY(40px)';
  2192. } else if(typeof i.style.transform === 'string') {
  2193. i.style.transform = 'translateY(40px)';
  2194. } else {
  2195. i.style.top = '0px';
  2196. }
  2197. }, 300);
  2198. };
  2199. // -----------------------------------------------------------
  2200. // Detected webrtc implementation. Types are:
  2201. // - 'moz': Mozilla implementation of webRTC.
  2202. // - 'webkit': WebKit implementation of webRTC.
  2203. // - 'plugin': Using the plugin implementation.
  2204. webrtcDetectedType = null;
  2205. // Detected webrtc datachannel support. Types are:
  2206. // - 'SCTP': SCTP datachannel support.
  2207. // - 'RTP': RTP datachannel support.
  2208. webrtcDetectedDCSupport = null;
  2209. // Set the settings for creating DataChannels, MediaStream for
  2210. // Cross-browser compability.
  2211. // - This is only for SCTP based support browsers.
  2212. // the 'urls' attribute.
  2213. checkMediaDataChannelSettings =
  2214. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2215. if (typeof callback !== 'function') {
  2216. return;
  2217. }
  2218. var beOfferer = true;
  2219. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2220. // Nightly version does not require MozDontOfferDataChannel for interop
  2221. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2222. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2223. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2224. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2225. // Resends an updated version of constraints for MozDataChannel to work
  2226. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2227. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2228. try {
  2229. delete constraints.mandatory.MozDontOfferDataChannel;
  2230. } catch (error) {
  2231. console.error('Failed deleting MozDontOfferDataChannel');
  2232. console.error(error);
  2233. }
  2234. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2235. constraints.mandatory.MozDontOfferDataChannel = true;
  2236. }
  2237. if (!isLocalFirefox) {
  2238. // temporary measure to remove Moz* constraints in non Firefox browsers
  2239. for (var prop in constraints.mandatory) {
  2240. if (constraints.mandatory.hasOwnProperty(prop)) {
  2241. if (prop.indexOf('Moz') !== -1) {
  2242. delete constraints.mandatory[prop];
  2243. }
  2244. }
  2245. }
  2246. }
  2247. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2248. // interopability of the media stream
  2249. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2250. beOfferer = false;
  2251. }
  2252. callback(beOfferer, constraints);
  2253. };
  2254. // Handles the differences for all browsers ice connection state output.
  2255. // - Tested outcomes are:
  2256. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2257. // - Chrome (answerer) : 'checking' > 'connected'
  2258. // - Firefox (offerer) : 'checking' > 'connected'
  2259. // - Firefox (answerer): 'checking' > 'connected'
  2260. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2261. if (typeof callback !== 'function') {
  2262. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2263. return;
  2264. }
  2265. peerId = (peerId) ? peerId : 'peer';
  2266. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2267. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2268. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2269. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2270. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2271. }
  2272. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2273. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2274. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2275. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2276. setTimeout(function () {
  2277. AdapterJS._iceConnectionFiredStates[peerId]
  2278. .push(AdapterJS._iceConnectionStates.done);
  2279. callback(AdapterJS._iceConnectionStates.done);
  2280. }, 1000);
  2281. }
  2282. callback(iceConnectionState);
  2283. }
  2284. return;
  2285. };
  2286. // Firefox:
  2287. // - Creates iceServer from the url for Firefox.
  2288. // - Create iceServer with stun url.
  2289. // - Create iceServer with turn url.
  2290. // - Ignore the transport parameter from TURN url for FF version <=27.
  2291. // - Return null for createIceServer if transport=tcp.
  2292. // - FF 27 and above supports transport parameters in TURN url,
  2293. // - So passing in the full url to create iceServer.
  2294. // Chrome:
  2295. // - Creates iceServer from the url for Chrome M33 and earlier.
  2296. // - Create iceServer with stun url.
  2297. // - Chrome M28 & above uses below TURN format.
  2298. // Plugin:
  2299. // - Creates Ice Server for Plugin Browsers
  2300. // - If Stun - Create iceServer with stun url.
  2301. // - Else - Create iceServer with turn url
  2302. // - This is a WebRTC Function
  2303. createIceServer = null;
  2304. // Firefox:
  2305. // - Creates IceServers for Firefox
  2306. // - Use .url for FireFox.
  2307. // - Multiple Urls support
  2308. // Chrome:
  2309. // - Creates iceServers from the urls for Chrome M34 and above.
  2310. // - .urls is supported since Chrome M34.
  2311. // - Multiple Urls support
  2312. // Plugin:
  2313. // - Creates Ice Servers for Plugin Browsers
  2314. // - Multiple Urls support
  2315. // - This is a WebRTC Function
  2316. createIceServers = null;
  2317. //------------------------------------------------------------
  2318. //The RTCPeerConnection object.
  2319. RTCPeerConnection = null;
  2320. // Creates RTCSessionDescription object for Plugin Browsers
  2321. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2322. RTCSessionDescription : null;
  2323. // Creates RTCIceCandidate object for Plugin Browsers
  2324. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2325. RTCIceCandidate : null;
  2326. // Get UserMedia (only difference is the prefix).
  2327. // Code from Adam Barth.
  2328. getUserMedia = null;
  2329. // Attach a media stream to an element.
  2330. attachMediaStream = null;
  2331. // Re-attach a media stream to an element.
  2332. reattachMediaStream = null;
  2333. // Detected browser agent name. Types are:
  2334. // - 'firefox': Firefox browser.
  2335. // - 'chrome': Chrome browser.
  2336. // - 'opera': Opera browser.
  2337. // - 'safari': Safari browser.
  2338. // - 'IE' - Internet Explorer browser.
  2339. webrtcDetectedBrowser = null;
  2340. // Detected browser version.
  2341. webrtcDetectedVersion = null;
  2342. // Check for browser types and react accordingly
  2343. if (navigator.mozGetUserMedia) {
  2344. webrtcDetectedBrowser = 'firefox';
  2345. webrtcDetectedVersion = parseInt(navigator
  2346. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2347. webrtcDetectedType = 'moz';
  2348. webrtcDetectedDCSupport = 'SCTP';
  2349. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2350. AdapterJS.maybeFixConfiguration(pcConfig);
  2351. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2352. };
  2353. // The RTCSessionDescription object.
  2354. RTCSessionDescription = mozRTCSessionDescription;
  2355. window.RTCSessionDescription = RTCSessionDescription;
  2356. // The RTCIceCandidate object.
  2357. RTCIceCandidate = mozRTCIceCandidate;
  2358. window.RTCIceCandidate = RTCIceCandidate;
  2359. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2360. navigator.getUserMedia = window.getUserMedia;
  2361. // Shim for MediaStreamTrack.getSources.
  2362. MediaStreamTrack.getSources = function(successCb) {
  2363. setTimeout(function() {
  2364. var infos = [
  2365. { kind: 'audio', id: 'default', label:'', facing:'' },
  2366. { kind: 'video', id: 'default', label:'', facing:'' }
  2367. ];
  2368. successCb(infos);
  2369. }, 0);
  2370. };
  2371. createIceServer = function (url, username, password) {
  2372. var iceServer = null;
  2373. var url_parts = url.split(':');
  2374. if (url_parts[0].indexOf('stun') === 0) {
  2375. iceServer = { url : url };
  2376. } else if (url_parts[0].indexOf('turn') === 0) {
  2377. if (webrtcDetectedVersion < 27) {
  2378. var turn_url_parts = url.split('?');
  2379. if (turn_url_parts.length === 1 ||
  2380. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2381. iceServer = {
  2382. url : turn_url_parts[0],
  2383. credential : password,
  2384. username : username
  2385. };
  2386. }
  2387. } else {
  2388. iceServer = {
  2389. url : url,
  2390. credential : password,
  2391. username : username
  2392. };
  2393. }
  2394. }
  2395. return iceServer;
  2396. };
  2397. createIceServers = function (urls, username, password) {
  2398. var iceServers = [];
  2399. for (i = 0; i < urls.length; i++) {
  2400. var iceServer = createIceServer(urls[i], username, password);
  2401. if (iceServer !== null) {
  2402. iceServers.push(iceServer);
  2403. }
  2404. }
  2405. return iceServers;
  2406. };
  2407. attachMediaStream = function (element, stream) {
  2408. element.mozSrcObject = stream;
  2409. if (stream !== null)
  2410. element.play();
  2411. return element;
  2412. };
  2413. reattachMediaStream = function (to, from) {
  2414. to.mozSrcObject = from.mozSrcObject;
  2415. to.play();
  2416. return to;
  2417. };
  2418. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2419. if (!callback) {
  2420. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2421. ': 1 argument required, but only 0 present.');
  2422. }
  2423. return callback([]);
  2424. };
  2425. // Fake get{Video,Audio}Tracks
  2426. if (!MediaStream.prototype.getVideoTracks) {
  2427. MediaStream.prototype.getVideoTracks = function () {
  2428. return [];
  2429. };
  2430. }
  2431. if (!MediaStream.prototype.getAudioTracks) {
  2432. MediaStream.prototype.getAudioTracks = function () {
  2433. return [];
  2434. };
  2435. }
  2436. AdapterJS.maybeThroughWebRTCReady();
  2437. } else if (navigator.webkitGetUserMedia) {
  2438. webrtcDetectedBrowser = 'chrome';
  2439. webrtcDetectedType = 'webkit';
  2440. webrtcDetectedVersion = parseInt(navigator
  2441. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2442. // check if browser is opera 20+
  2443. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2444. if (checkIfOpera !== null) {
  2445. webrtcDetectedBrowser = 'opera';
  2446. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2447. }
  2448. // check browser datachannel support
  2449. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2450. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2451. webrtcDetectedDCSupport = 'SCTP';
  2452. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2453. webrtcDetectedVersion > 24) {
  2454. webrtcDetectedDCSupport = 'RTP';
  2455. } else {
  2456. webrtcDetectedDCSupport = '';
  2457. }
  2458. createIceServer = function (url, username, password) {
  2459. var iceServer = null;
  2460. var url_parts = url.split(':');
  2461. if (url_parts[0].indexOf('stun') === 0) {
  2462. iceServer = { 'url' : url };
  2463. } else if (url_parts[0].indexOf('turn') === 0) {
  2464. iceServer = {
  2465. 'url' : url,
  2466. 'credential' : password,
  2467. 'username' : username
  2468. };
  2469. }
  2470. return iceServer;
  2471. };
  2472. createIceServers = function (urls, username, password) {
  2473. var iceServers = [];
  2474. if (webrtcDetectedVersion >= 34) {
  2475. iceServers = {
  2476. 'urls' : urls,
  2477. 'credential' : password,
  2478. 'username' : username
  2479. };
  2480. } else {
  2481. for (i = 0; i < urls.length; i++) {
  2482. var iceServer = createIceServer(urls[i], username, password);
  2483. if (iceServer !== null) {
  2484. iceServers.push(iceServer);
  2485. }
  2486. }
  2487. }
  2488. return iceServers;
  2489. };
  2490. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2491. if (webrtcDetectedVersion < 34) {
  2492. AdapterJS.maybeFixConfiguration(pcConfig);
  2493. }
  2494. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2495. };
  2496. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2497. navigator.getUserMedia = window.getUserMedia;
  2498. attachMediaStream = function (element, stream) {
  2499. if (typeof element.srcObject !== 'undefined') {
  2500. element.srcObject = stream;
  2501. } else if (typeof element.mozSrcObject !== 'undefined') {
  2502. element.mozSrcObject = stream;
  2503. } else if (typeof element.src !== 'undefined') {
  2504. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2505. } else {
  2506. console.log('Error attaching stream to element.');
  2507. }
  2508. return element;
  2509. };
  2510. reattachMediaStream = function (to, from) {
  2511. to.src = from.src;
  2512. return to;
  2513. };
  2514. AdapterJS.maybeThroughWebRTCReady();
  2515. } else { // TRY TO USE PLUGIN
  2516. // IE 9 is not offering an implementation of console.log until you open a console
  2517. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2518. /* jshint -W020 */
  2519. console = {} || console;
  2520. // Implemented based on console specs from MDN
  2521. // You may override these functions
  2522. console.log = function (arg) {};
  2523. console.info = function (arg) {};
  2524. console.error = function (arg) {};
  2525. console.dir = function (arg) {};
  2526. console.exception = function (arg) {};
  2527. console.trace = function (arg) {};
  2528. console.warn = function (arg) {};
  2529. console.count = function (arg) {};
  2530. console.debug = function (arg) {};
  2531. console.count = function (arg) {};
  2532. console.time = function (arg) {};
  2533. console.timeEnd = function (arg) {};
  2534. console.group = function (arg) {};
  2535. console.groupCollapsed = function (arg) {};
  2536. console.groupEnd = function (arg) {};
  2537. /* jshint +W020 */
  2538. }
  2539. webrtcDetectedType = 'plugin';
  2540. webrtcDetectedDCSupport = 'plugin';
  2541. AdapterJS.parseWebrtcDetectedBrowser();
  2542. isIE = webrtcDetectedBrowser === 'IE';
  2543. /* jshint -W035 */
  2544. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2545. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2546. /* empty because it needs to prevent the function from running. */
  2547. }
  2548. };
  2549. /* jshint +W035 */
  2550. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2551. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2552. // Call immediately if possible
  2553. // Once the plugin is set, the code will always take this path
  2554. callback();
  2555. } else {
  2556. // otherwise start a 100ms interval
  2557. var checkPluginReadyState = setInterval(function () {
  2558. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2559. clearInterval(checkPluginReadyState);
  2560. callback();
  2561. }
  2562. }, 100);
  2563. }
  2564. };
  2565. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2566. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2567. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2568. });
  2569. };
  2570. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2571. // only inject once the page is ready
  2572. if (document.readyState !== 'complete') {
  2573. return;
  2574. }
  2575. // Prevent multiple injections
  2576. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2577. return;
  2578. }
  2579. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2580. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2581. var frag = document.createDocumentFragment();
  2582. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2583. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2584. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2585. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2586. '<param name="pluginId" value="' +
  2587. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2588. '<param name="windowless" value="false" /> ' +
  2589. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2590. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2591. '" />' +
  2592. // uncomment to be able to use virtual cams
  2593. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2594. '</object>';
  2595. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2596. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2597. }
  2598. document.body.appendChild(frag);
  2599. // Need to re-fetch the plugin
  2600. AdapterJS.WebRTCPlugin.plugin =
  2601. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2602. } else {
  2603. // Load Plugin
  2604. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2605. AdapterJS.WebRTCPlugin.plugin.id =
  2606. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2607. // IE will only start the plugin if it's ACTUALLY visible
  2608. if (isIE) {
  2609. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2610. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2611. } else { // The size of the plugin on Safari should be 0x0px
  2612. // so that the autorisation prompt is at the top
  2613. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2614. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2615. }
  2616. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2617. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2618. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2619. '<param name="pluginId" value="' +
  2620. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2621. '<param name="windowless" value="false" /> ' +
  2622. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2623. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2624. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2625. }
  2626. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2627. };
  2628. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2629. function (comName, plugName, installedCb, notInstalledCb) {
  2630. if (!isIE) {
  2631. var pluginArray = navigator.plugins;
  2632. for (var i = 0; i < pluginArray.length; i++) {
  2633. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2634. installedCb();
  2635. return;
  2636. }
  2637. }
  2638. notInstalledCb();
  2639. } else {
  2640. try {
  2641. var axo = new ActiveXObject(comName + '.' + plugName);
  2642. } catch (e) {
  2643. notInstalledCb();
  2644. return;
  2645. }
  2646. installedCb();
  2647. }
  2648. };
  2649. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2650. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2651. AdapterJS.isDefined = function (variable) {
  2652. return variable !== null && variable !== undefined;
  2653. };
  2654. createIceServer = function (url, username, password) {
  2655. var iceServer = null;
  2656. var url_parts = url.split(':');
  2657. if (url_parts[0].indexOf('stun') === 0) {
  2658. iceServer = {
  2659. 'url' : url,
  2660. 'hasCredentials' : false
  2661. };
  2662. } else if (url_parts[0].indexOf('turn') === 0) {
  2663. iceServer = {
  2664. 'url' : url,
  2665. 'hasCredentials' : true,
  2666. 'credential' : password,
  2667. 'username' : username
  2668. };
  2669. }
  2670. return iceServer;
  2671. };
  2672. createIceServers = function (urls, username, password) {
  2673. var iceServers = [];
  2674. for (var i = 0; i < urls.length; ++i) {
  2675. iceServers.push(createIceServer(urls[i], username, password));
  2676. }
  2677. return iceServers;
  2678. };
  2679. RTCSessionDescription = function (info) {
  2680. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2681. return AdapterJS.WebRTCPlugin.plugin.
  2682. ConstructSessionDescription(info.type, info.sdp);
  2683. };
  2684. RTCPeerConnection = function (servers, constraints) {
  2685. var iceServers = null;
  2686. if (servers) {
  2687. iceServers = servers.iceServers;
  2688. for (var i = 0; i < iceServers.length; i++) {
  2689. if (iceServers[i].urls && !iceServers[i].url) {
  2690. iceServers[i].url = iceServers[i].urls;
  2691. }
  2692. iceServers[i].hasCredentials = AdapterJS.
  2693. isDefined(iceServers[i].username) &&
  2694. AdapterJS.isDefined(iceServers[i].credential);
  2695. }
  2696. }
  2697. var mandatory = (constraints && constraints.mandatory) ?
  2698. constraints.mandatory : null;
  2699. var optional = (constraints && constraints.optional) ?
  2700. constraints.optional : null;
  2701. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2702. return AdapterJS.WebRTCPlugin.plugin.
  2703. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2704. iceServers, mandatory, optional);
  2705. };
  2706. MediaStreamTrack = {};
  2707. MediaStreamTrack.getSources = function (callback) {
  2708. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2709. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2710. });
  2711. };
  2712. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2713. constraints.audio = constraints.audio || false;
  2714. constraints.video = constraints.video || false;
  2715. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2716. AdapterJS.WebRTCPlugin.plugin.
  2717. getUserMedia(constraints, successCallback, failureCallback);
  2718. });
  2719. };
  2720. window.navigator.getUserMedia = window.getUserMedia;
  2721. attachMediaStream = function (element, stream) {
  2722. if (!element || !element.parentNode) {
  2723. return;
  2724. }
  2725. var streamId
  2726. if (stream === null) {
  2727. streamId = '';
  2728. }
  2729. else {
  2730. stream.enableSoundTracks(true);
  2731. streamId = stream.id;
  2732. }
  2733. if (element.nodeName.toLowerCase() !== 'audio') {
  2734. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2735. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2736. var frag = document.createDocumentFragment();
  2737. var temp = document.createElement('div');
  2738. var classHTML = '';
  2739. if (element.className) {
  2740. classHTML = 'class="' + element.className + '" ';
  2741. } else if (element.attributes && element.attributes['class']) {
  2742. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2743. }
  2744. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2745. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2746. '<param name="pluginId" value="' + elementId + '" /> ' +
  2747. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2748. '<param name="windowless" value="true" /> ' +
  2749. '<param name="streamId" value="' + streamId + '" /> ' +
  2750. '</object>';
  2751. while (temp.firstChild) {
  2752. frag.appendChild(temp.firstChild);
  2753. }
  2754. var height = '';
  2755. var width = '';
  2756. if (element.getBoundingClientRect) {
  2757. var rectObject = element.getBoundingClientRect();
  2758. width = rectObject.width + 'px';
  2759. height = rectObject.height + 'px';
  2760. }
  2761. else if (element.width) {
  2762. width = element.width;
  2763. height = element.height;
  2764. } else {
  2765. // TODO: What scenario could bring us here?
  2766. }
  2767. element.parentNode.insertBefore(frag, element);
  2768. frag = document.getElementById(elementId);
  2769. frag.width = width;
  2770. frag.height = height;
  2771. element.parentNode.removeChild(element);
  2772. } else {
  2773. var children = element.children;
  2774. for (var i = 0; i !== children.length; ++i) {
  2775. if (children[i].name === 'streamId') {
  2776. children[i].value = streamId;
  2777. break;
  2778. }
  2779. }
  2780. element.setStreamId(streamId);
  2781. }
  2782. var newElement = document.getElementById(elementId);
  2783. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2784. if (isIE) { // on IE the event needs to be plugged manually
  2785. newElement.attachEvent('onplaying', newElement.onplaying);
  2786. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2787. newElement._TemOnClick = function (id) {
  2788. var arg = {
  2789. srcElement : document.getElementById(id)
  2790. };
  2791. newElement.onclick(arg);
  2792. };
  2793. }
  2794. return newElement;
  2795. } else {
  2796. return element;
  2797. }
  2798. };
  2799. reattachMediaStream = function (to, from) {
  2800. var stream = null;
  2801. var children = from.children;
  2802. for (var i = 0; i !== children.length; ++i) {
  2803. if (children[i].name === 'streamId') {
  2804. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2805. stream = AdapterJS.WebRTCPlugin.plugin
  2806. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2807. break;
  2808. }
  2809. }
  2810. if (stream !== null) {
  2811. return attachMediaStream(to, stream);
  2812. } else {
  2813. console.log('Could not find the stream associated with this element');
  2814. }
  2815. };
  2816. RTCIceCandidate = function (candidate) {
  2817. if (!candidate.sdpMid) {
  2818. candidate.sdpMid = '';
  2819. }
  2820. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2821. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2822. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2823. );
  2824. };
  2825. // inject plugin
  2826. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2827. AdapterJS.WebRTCPlugin.injectPlugin();
  2828. };
  2829. // This function will be called if the plugin is needed (browser different
  2830. // from Chrome or Firefox), but the plugin is not installed.
  2831. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2832. function() {
  2833. AdapterJS.addEvent(document,
  2834. 'readystatechange',
  2835. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2836. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2837. };
  2838. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2839. if (AdapterJS.options.hidePluginInstallPrompt) {
  2840. return;
  2841. }
  2842. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2843. if(downloadLink) { // if download link
  2844. var popupString;
  2845. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2846. popupString = 'This website requires you to install the ' +
  2847. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2848. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2849. ' WebRTC Plugin</a>' +
  2850. ' to work on this browser.';
  2851. } else { // no portal link, just print a generic explanation
  2852. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2853. }
  2854. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2855. } else { // no download link, just print a generic explanation
  2856. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2857. }
  2858. };
  2859. // Try to detect the plugin and act accordingly
  2860. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2861. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2862. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2863. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2864. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2865. }
  2866. (function () {
  2867. 'use strict';
  2868. var baseGetUserMedia = null;
  2869. AdapterJS.TEXT.EXTENSION = {
  2870. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2871. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2872. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2873. BUTTON_FF: 'Install Now',
  2874. BUTTON_CHROME: 'Go to Chrome Web Store'
  2875. };
  2876. var clone = function(obj) {
  2877. if (null == obj || "object" != typeof obj) return obj;
  2878. var copy = obj.constructor();
  2879. for (var attr in obj) {
  2880. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2881. }
  2882. return copy;
  2883. };
  2884. if (window.navigator.mozGetUserMedia) {
  2885. baseGetUserMedia = window.navigator.getUserMedia;
  2886. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2887. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2888. // intercepting screensharing requests
  2889. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2890. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2891. }
  2892. var updatedConstraints = clone(constraints);
  2893. //constraints.video.mediaSource = constraints.video.mediaSource;
  2894. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2895. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2896. // strange but this works anyway
  2897. var checkIfReady = setInterval(function () {
  2898. if (document.readyState === 'complete') {
  2899. clearInterval(checkIfReady);
  2900. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2901. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2902. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2903. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2904. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2905. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2906. } else {
  2907. failureCb(error);
  2908. }
  2909. });
  2910. }
  2911. }, 1);
  2912. } else { // regular GetUserMediaRequest
  2913. baseGetUserMedia(constraints, successCb, failureCb);
  2914. }
  2915. };
  2916. getUserMedia = navigator.getUserMedia;
  2917. } else if (window.navigator.webkitGetUserMedia) {
  2918. baseGetUserMedia = window.navigator.getUserMedia;
  2919. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2920. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2921. if (window.webrtcDetectedBrowser !== 'chrome') {
  2922. throw new Error('Current browser does not support screensharing');
  2923. }
  2924. // would be fine since no methods
  2925. var updatedConstraints = clone(constraints);
  2926. var chromeCallback = function(error, sourceId) {
  2927. if(!error) {
  2928. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2929. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2930. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2931. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2932. if (sourceId) {
  2933. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2934. }
  2935. delete updatedConstraints.video.mediaSource;
  2936. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2937. } else {
  2938. if (error === 'permission-denied') {
  2939. throw new Error('Permission denied for screen retrieval');
  2940. } else {
  2941. throw new Error('Failed retrieving selected screen');
  2942. }
  2943. }
  2944. };
  2945. var onIFrameCallback = function (event) {
  2946. if (!event.data) {
  2947. return;
  2948. }
  2949. if (event.data.chromeMediaSourceId) {
  2950. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2951. chromeCallback('permission-denied');
  2952. } else {
  2953. chromeCallback(null, event.data.chromeMediaSourceId);
  2954. }
  2955. }
  2956. if (event.data.chromeExtensionStatus) {
  2957. if (event.data.chromeExtensionStatus === 'not-installed') {
  2958. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2959. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2960. event.data.data, true, true);
  2961. } else {
  2962. chromeCallback(event.data.chromeExtensionStatus, null);
  2963. }
  2964. }
  2965. // this event listener is no more needed
  2966. window.removeEventListener('message', onIFrameCallback);
  2967. };
  2968. window.addEventListener('message', onIFrameCallback);
  2969. postFrameMessage({
  2970. captureSourceId: true
  2971. });
  2972. } else {
  2973. baseGetUserMedia(constraints, successCb, failureCb);
  2974. }
  2975. };
  2976. getUserMedia = navigator.getUserMedia;
  2977. } else {
  2978. baseGetUserMedia = window.navigator.getUserMedia;
  2979. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2980. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2981. // would be fine since no methods
  2982. var updatedConstraints = clone(constraints);
  2983. // wait for plugin to be ready
  2984. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2985. // check if screensharing feature is available
  2986. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2987. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2988. // set the constraints
  2989. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2990. updatedConstraints.video.optional.push({
  2991. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2992. });
  2993. delete updatedConstraints.video.mediaSource;
  2994. } else {
  2995. throw new Error('Your WebRTC plugin does not support screensharing');
  2996. }
  2997. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2998. });
  2999. } else {
  3000. baseGetUserMedia(constraints, successCb, failureCb);
  3001. }
  3002. };
  3003. getUserMedia = window.navigator.getUserMedia;
  3004. }
  3005. if (window.webrtcDetectedBrowser === 'chrome') {
  3006. var iframe = document.createElement('iframe');
  3007. iframe.onload = function() {
  3008. iframe.isLoaded = true;
  3009. };
  3010. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  3011. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  3012. iframe.style.display = 'none';
  3013. (document.body || document.documentElement).appendChild(iframe);
  3014. var postFrameMessage = function (object) {
  3015. object = object || {};
  3016. if (!iframe.isLoaded) {
  3017. setTimeout(function () {
  3018. iframe.contentWindow.postMessage(object, '*');
  3019. }, 100);
  3020. return;
  3021. }
  3022. iframe.contentWindow.postMessage(object, '*');
  3023. };
  3024. }
  3025. })();
  3026. },{}],13:[function(require,module,exports){
  3027. var UI = {};
  3028. var VideoLayout = require("./videolayout/VideoLayout.js");
  3029. var AudioLevels = require("./audio_levels/AudioLevels.js");
  3030. var Prezi = require("./prezi/Prezi.js");
  3031. var Etherpad = require("./etherpad/Etherpad.js");
  3032. var Chat = require("./side_pannels/chat/Chat.js");
  3033. var Toolbar = require("./toolbars/Toolbar");
  3034. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  3035. var BottomToolbar = require("./toolbars/BottomToolbar");
  3036. var ContactList = require("./side_pannels/contactlist/ContactList");
  3037. var Avatar = require("./avatar/Avatar");
  3038. var EventEmitter = require("events");
  3039. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  3040. var Settings = require("./../settings/Settings");
  3041. var PanelToggler = require("./side_pannels/SidePanelToggler");
  3042. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  3043. UI.messageHandler = require("./util/MessageHandler");
  3044. var messageHandler = UI.messageHandler;
  3045. var Authentication = require("./authentication/Authentication");
  3046. var UIUtil = require("./util/UIUtil");
  3047. var NicknameHandler = require("./util/NicknameHandler");
  3048. var CQEvents = require("../../service/connectionquality/CQEvents");
  3049. var DesktopSharingEventTypes
  3050. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3051. var RTCEvents = require("../../service/RTC/RTCEvents");
  3052. var RTCBrowserType = require("../RTC/RTCBrowserType");
  3053. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  3054. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  3055. var MemberEvents = require("../../service/members/Events");
  3056. var eventEmitter = new EventEmitter();
  3057. var roomName = null;
  3058. function promptDisplayName() {
  3059. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  3060. message += APP.translation.translateString(
  3061. "dialog.displayNameRequired");
  3062. message += '</h2>' +
  3063. '<input name="displayName" type="text" data-i18n=' +
  3064. '"[placeholder]defaultNickname" placeholder="' +
  3065. APP.translation.translateString(
  3066. "defaultNickname", {name: "Jane Pink"}) +
  3067. '" autofocus>';
  3068. var buttonTxt
  3069. = APP.translation.generateTranslationHTML("dialog.Ok");
  3070. var buttons = [];
  3071. buttons.push({title: buttonTxt, value: "ok"});
  3072. messageHandler.openDialog(null, message,
  3073. true,
  3074. buttons,
  3075. function (e, v, m, f) {
  3076. if (v == "ok") {
  3077. var displayName = f.displayName;
  3078. if (displayName) {
  3079. VideoLayout.inputDisplayNameHandler(displayName);
  3080. return true;
  3081. }
  3082. }
  3083. e.preventDefault();
  3084. },
  3085. function () {
  3086. var form = $.prompt.getPrompt();
  3087. var input = form.find("input[name='displayName']");
  3088. var button = form.find("button");
  3089. button.attr("disabled", "disabled");
  3090. input.keyup(function () {
  3091. if(!input.val())
  3092. button.attr("disabled", "disabled");
  3093. else
  3094. button.removeAttr("disabled");
  3095. });
  3096. }
  3097. );
  3098. }
  3099. function notifyForInitialMute()
  3100. {
  3101. messageHandler.notify(null, "notify.mutedTitle", "connected",
  3102. "notify.muted", null, {timeOut: 120000});
  3103. }
  3104. function setupPrezi()
  3105. {
  3106. $("#reloadPresentationLink").click(function()
  3107. {
  3108. Prezi.reloadPresentation();
  3109. });
  3110. }
  3111. function setupChat()
  3112. {
  3113. Chat.init();
  3114. $("#toggle_smileys").click(function() {
  3115. Chat.toggleSmileys();
  3116. });
  3117. }
  3118. function setupToolbars() {
  3119. Toolbar.init(UI);
  3120. Toolbar.setupButtonsFromConfig();
  3121. BottomToolbar.init();
  3122. }
  3123. function streamHandler(stream, isMuted) {
  3124. switch (stream.type)
  3125. {
  3126. case "audio":
  3127. VideoLayout.changeLocalAudio(stream, isMuted);
  3128. break;
  3129. case "video":
  3130. VideoLayout.changeLocalVideo(stream, isMuted);
  3131. break;
  3132. case "stream":
  3133. VideoLayout.changeLocalStream(stream, isMuted);
  3134. break;
  3135. }
  3136. }
  3137. function onXmppConnectionFailed(stropheErrorMsg) {
  3138. var title = APP.translation.generateTranslationHTML(
  3139. "dialog.error");
  3140. var message;
  3141. if (stropheErrorMsg) {
  3142. message = APP.translation.generateTranslationHTML(
  3143. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  3144. } else {
  3145. message = APP.translation.generateTranslationHTML(
  3146. "dialog.connectError");
  3147. }
  3148. messageHandler.openDialog(
  3149. title, message, true, {}, function (e, v, m, f) { return false; });
  3150. }
  3151. function onDisposeConference(unload) {
  3152. Toolbar.showAuthenticateButton(false);
  3153. }
  3154. function onDisplayNameChanged(jid, displayName) {
  3155. ContactList.onDisplayNameChange(jid, displayName);
  3156. SettingsMenu.onDisplayNameChange(jid, displayName);
  3157. VideoLayout.onDisplayNameChanged(jid, displayName);
  3158. }
  3159. function registerListeners() {
  3160. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  3161. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  3162. APP.RTC.addStreamListener(function (stream) {
  3163. VideoLayout.onRemoteStreamAdded(stream);
  3164. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  3165. APP.RTC.addStreamListener(function (jid) {
  3166. VideoLayout.onVideoTypeChanged(jid);
  3167. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  3168. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  3169. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  3170. VideoLayout.onDominantSpeakerChanged(resourceJid);
  3171. });
  3172. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  3173. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  3174. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  3175. endpointsEnteringLastN, stream);
  3176. });
  3177. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  3178. function (devices) {
  3179. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  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.STREAMS_CHANGED, function (jid, changedStreams) {
  3258. for(stream in changedStreams)
  3259. {
  3260. // might need to update the direction if participant just went from sendrecv to recvonly
  3261. if (stream.type === 'video' || stream.type === 'screen') {
  3262. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>' + APP.RTC.getVideoElementName());
  3263. switch (stream.direction) {
  3264. case 'sendrecv':
  3265. el.show();
  3266. break;
  3267. case 'recvonly':
  3268. el.hide();
  3269. break;
  3270. }
  3271. }
  3272. }
  3273. });
  3274. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  3275. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  3276. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  3277. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  3278. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  3279. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  3280. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  3281. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  3282. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  3283. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  3284. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  3285. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  3286. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  3287. onAuthenticationRequired);
  3288. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  3289. function (resource, devices) {
  3290. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  3291. });
  3292. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  3293. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  3294. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  3295. onDtmfSupportChanged);
  3296. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  3297. SettingsMenu.setStartMuted(audio, video);
  3298. });
  3299. }
  3300. /**
  3301. * Mutes/unmutes the local video.
  3302. *
  3303. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3304. * @param options an object which specifies optional arguments such as the
  3305. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3306. * specifies whether the method was initiated in response to a user command (in
  3307. * contrast to an automatic decision taken by the application logic)
  3308. */
  3309. function setVideoMute(mute, options) {
  3310. APP.RTC.setVideoMute(mute,
  3311. UI.setVideoMuteButtonsState,
  3312. options);
  3313. }
  3314. function onResize()
  3315. {
  3316. Chat.resizeChat();
  3317. VideoLayout.resizeLargeVideoContainer();
  3318. }
  3319. function bindEvents()
  3320. {
  3321. /**
  3322. * Resizes and repositions videos in full screen mode.
  3323. */
  3324. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3325. onResize);
  3326. $(window).resize(onResize);
  3327. }
  3328. UI.start = function (init) {
  3329. document.title = interfaceConfig.APP_NAME;
  3330. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3331. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3332. {
  3333. $("#videoconference_page").hide();
  3334. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3335. setupWelcomePage();
  3336. return;
  3337. }
  3338. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  3339. var leftWatermarkDiv
  3340. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  3341. leftWatermarkDiv.css({display: 'block'});
  3342. leftWatermarkDiv.parent().get(0).href
  3343. = interfaceConfig.JITSI_WATERMARK_LINK;
  3344. }
  3345. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  3346. var rightWatermarkDiv
  3347. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  3348. rightWatermarkDiv.css({display: 'block'});
  3349. rightWatermarkDiv.parent().get(0).href
  3350. = interfaceConfig.BRAND_WATERMARK_LINK;
  3351. rightWatermarkDiv.get(0).style.backgroundImage
  3352. = "url(images/rightwatermark.png)";
  3353. }
  3354. if (interfaceConfig.SHOW_POWERED_BY) {
  3355. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  3356. }
  3357. $("#welcome_page").hide();
  3358. $("#videospace").mousemove(function () {
  3359. return ToolbarToggler.showToolbar();
  3360. });
  3361. // Set the defaults for prompt dialogs.
  3362. jQuery.prompt.setDefaults({persistent: false});
  3363. VideoLayout.init(eventEmitter);
  3364. AudioLevels.init();
  3365. NicknameHandler.init(eventEmitter);
  3366. registerListeners();
  3367. bindEvents();
  3368. setupPrezi();
  3369. setupToolbars();
  3370. setupChat();
  3371. document.title = interfaceConfig.APP_NAME;
  3372. $("#downloadlog").click(function (event) {
  3373. dump(event.target);
  3374. });
  3375. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3376. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  3377. {
  3378. $("#videoconference_page").hide();
  3379. var setupWelcomePage = require("./welcome_page/WelcomePage");
  3380. setupWelcomePage();
  3381. return;
  3382. }
  3383. $("#welcome_page").hide();
  3384. // Display notice message at the top of the toolbar
  3385. if (config.noticeMessage) {
  3386. $('#noticeText').text(config.noticeMessage);
  3387. $('#notice').css({display: 'block'});
  3388. }
  3389. if (!RTCBrowserType.isIExplorer()) {
  3390. document.getElementById('largeVideo').volume = 0;
  3391. }
  3392. if(config.requireDisplayName) {
  3393. var currentSettings = Settings.getSettings();
  3394. if (!currentSettings.displayName) {
  3395. promptDisplayName();
  3396. }
  3397. }
  3398. init();
  3399. toastr.options = {
  3400. "closeButton": true,
  3401. "debug": false,
  3402. "positionClass": "notification-bottom-right",
  3403. "onclick": null,
  3404. "showDuration": "300",
  3405. "hideDuration": "1000",
  3406. "timeOut": "2000",
  3407. "extendedTimeOut": "1000",
  3408. "showEasing": "swing",
  3409. "hideEasing": "linear",
  3410. "showMethod": "fadeIn",
  3411. "hideMethod": "fadeOut",
  3412. "reposition": function() {
  3413. if(PanelToggler.isVisible()) {
  3414. $("#toast-container").addClass("notification-bottom-right-center");
  3415. } else {
  3416. $("#toast-container").removeClass("notification-bottom-right-center");
  3417. }
  3418. },
  3419. "newestOnTop": false
  3420. };
  3421. SettingsMenu.init();
  3422. };
  3423. function chatAddError(errorMessage, originalText)
  3424. {
  3425. return Chat.chatAddError(errorMessage, originalText);
  3426. };
  3427. function chatSetSubject(text)
  3428. {
  3429. return Chat.chatSetSubject(text);
  3430. };
  3431. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3432. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3433. }
  3434. function onMucJoined(jid, info) {
  3435. Toolbar.updateRoomUrl(window.location.href);
  3436. var meHTML = APP.translation.generateTranslationHTML("me");
  3437. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3438. var settings = Settings.getSettings();
  3439. // Add myself to the contact list.
  3440. ContactList.addContact(jid, settings.email || settings.uid);
  3441. // Once we've joined the muc show the toolbar
  3442. ToolbarToggler.showToolbar();
  3443. var displayName = !config.displayJids
  3444. ? info.displayName : Strophe.getResourceFromJid(jid);
  3445. if (displayName)
  3446. onDisplayNameChanged('localVideoContainer', displayName);
  3447. VideoLayout.mucJoined();
  3448. }
  3449. function initEtherpad(name) {
  3450. Etherpad.init(name);
  3451. }
  3452. function onMucMemberLeft(jid) {
  3453. console.log('left.muc', jid);
  3454. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3455. '>.displayname').html();
  3456. messageHandler.notify(displayName,'notify.somebody',
  3457. 'disconnected',
  3458. 'notify.disconnected');
  3459. if(!config.startAudioMuted ||
  3460. config.startAudioMuted > APP.members.size())
  3461. UIUtil.playSoundNotification('userLeft');
  3462. // Need to call this with a slight delay, otherwise the element couldn't be
  3463. // found for some reason.
  3464. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  3465. window.setTimeout(function () {
  3466. var container = document.getElementById(
  3467. 'participant_' + Strophe.getResourceFromJid(jid));
  3468. if (container) {
  3469. ContactList.removeContact(jid);
  3470. VideoLayout.removeConnectionIndicator(jid);
  3471. // hide here, wait for video to close before removing
  3472. $(container).hide();
  3473. VideoLayout.resizeThumbnails();
  3474. }
  3475. }, 10);
  3476. VideoLayout.participantLeft(jid);
  3477. };
  3478. function onLocalRoleChanged(jid, info, pres, isModerator)
  3479. {
  3480. console.info("My role changed, new role: " + info.role);
  3481. onModeratorStatusChanged(isModerator);
  3482. VideoLayout.showModeratorIndicator();
  3483. SettingsMenu.onRoleChanged();
  3484. if (isModerator) {
  3485. Authentication.closeAuthenticationWindow();
  3486. messageHandler.notify(null, "notify.me",
  3487. 'connected', "notify.moderator");
  3488. }
  3489. }
  3490. function onModeratorStatusChanged(isModerator) {
  3491. Toolbar.showSipCallButton(isModerator);
  3492. Toolbar.showRecordingButton(
  3493. isModerator); //&&
  3494. // FIXME:
  3495. // Recording visible if
  3496. // there are at least 2(+ 1 focus) participants
  3497. //Object.keys(connection.emuc.members).length >= 3);
  3498. }
  3499. function onPasswordRequired(callback) {
  3500. // password is required
  3501. Toolbar.lockLockButton();
  3502. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3503. message += APP.translation.translateString(
  3504. "dialog.passwordRequired");
  3505. message += '</h2>' +
  3506. '<input name="lockKey" type="text" data-i18n=' +
  3507. '"[placeholder]dialog.password" placeholder="' +
  3508. APP.translation.translateString("dialog.password") +
  3509. '" autofocus>';
  3510. messageHandler.openTwoButtonDialog(null, null, null, message,
  3511. true,
  3512. "dialog.Ok",
  3513. function (e, v, m, f) {},
  3514. null,
  3515. function (e, v, m, f) {
  3516. if (v) {
  3517. var lockKey = f.lockKey;
  3518. if (lockKey) {
  3519. Toolbar.setSharedKey(lockKey);
  3520. callback(lockKey);
  3521. }
  3522. }
  3523. },
  3524. ':input:first'
  3525. );
  3526. }
  3527. /**
  3528. * The dialpad button is shown iff there is at least one member that supports
  3529. * DTMF (e.g. jigasi).
  3530. */
  3531. function onDtmfSupportChanged(dtmfSupport) {
  3532. //TODO: enable when the UI is ready
  3533. //Toolbar.showDialPadButton(dtmfSupport);
  3534. }
  3535. function onMucMemberJoined(jid, id, displayName) {
  3536. messageHandler.notify(displayName,'notify.somebody',
  3537. 'connected',
  3538. 'notify.connected');
  3539. if(!config.startAudioMuted ||
  3540. config.startAudioMuted > APP.members.size())
  3541. UIUtil.playSoundNotification('userJoined');
  3542. // Add Peer's container
  3543. VideoLayout.ensurePeerContainerExists(jid,id);
  3544. }
  3545. function onMucPresenceStatus(jid, info) {
  3546. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3547. }
  3548. function onMucRoleChanged(role, displayName) {
  3549. VideoLayout.showModeratorIndicator();
  3550. if (role === 'moderator') {
  3551. var messageKey, messageOptions = {};
  3552. if (!displayName) {
  3553. messageKey = "notify.grantedToUnknown";
  3554. }
  3555. else
  3556. {
  3557. messageKey = "notify.grantedTo";
  3558. messageOptions = {to: displayName};
  3559. }
  3560. messageHandler.notify(
  3561. displayName,'notify.somebody',
  3562. 'connected', messageKey,
  3563. messageOptions);
  3564. }
  3565. }
  3566. function onAuthenticationRequired(intervalCallback) {
  3567. Authentication.openAuthenticationDialog(
  3568. roomName, intervalCallback, function () {
  3569. Toolbar.authenticateClicked();
  3570. });
  3571. };
  3572. function onLastNChanged(oldValue, newValue) {
  3573. if (config.muteLocalVideoIfNotInLastN) {
  3574. setVideoMute(!newValue, { 'byUser': false });
  3575. }
  3576. }
  3577. UI.toggleSmileys = function () {
  3578. Chat.toggleSmileys();
  3579. };
  3580. UI.getSettings = function () {
  3581. return Settings.getSettings();
  3582. };
  3583. UI.toggleFilmStrip = function () {
  3584. return BottomToolbar.toggleFilmStrip();
  3585. };
  3586. UI.toggleChat = function () {
  3587. return BottomToolbar.toggleChat();
  3588. };
  3589. UI.toggleContactList = function () {
  3590. return BottomToolbar.toggleContactList();
  3591. };
  3592. UI.inputDisplayNameHandler = function (value) {
  3593. VideoLayout.inputDisplayNameHandler(value);
  3594. };
  3595. UI.getLargeVideoJid = function()
  3596. {
  3597. return VideoLayout.getLargeVideoJid();
  3598. };
  3599. UI.generateRoomName = function() {
  3600. if(roomName)
  3601. return roomName;
  3602. var roomnode = null;
  3603. var path = window.location.pathname;
  3604. // determinde the room node from the url
  3605. // TODO: just the roomnode or the whole bare jid?
  3606. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3607. // custom function might be responsible for doing the pushstate
  3608. roomnode = config.getroomnode(path);
  3609. } else {
  3610. /* fall back to default strategy
  3611. * this is making assumptions about how the URL->room mapping happens.
  3612. * It currently assumes deployment at root, with a rewrite like the
  3613. * following one (for nginx):
  3614. location ~ ^/([a-zA-Z0-9]+)$ {
  3615. rewrite ^/(.*)$ / break;
  3616. }
  3617. */
  3618. if (path.length > 1) {
  3619. roomnode = path.substr(1).toLowerCase();
  3620. } else {
  3621. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3622. roomnode = word.toLowerCase();
  3623. window.history.pushState('VideoChat',
  3624. 'Room: ' + word, window.location.pathname + word);
  3625. }
  3626. }
  3627. roomName = roomnode + '@' + config.hosts.muc;
  3628. return roomName;
  3629. };
  3630. UI.connectionIndicatorShowMore = function(jid)
  3631. {
  3632. return VideoLayout.showMore(jid);
  3633. };
  3634. UI.showLoginPopup = function(callback)
  3635. {
  3636. console.log('password is required');
  3637. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3638. message += APP.translation.translateString(
  3639. "dialog.passwordRequired");
  3640. message += '</h2>' +
  3641. '<input name="username" type="text" ' +
  3642. 'placeholder="user@domain.net" autofocus>' +
  3643. '<input name="password" ' +
  3644. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3645. ' placeholder="user password">';
  3646. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3647. true,
  3648. "dialog.Ok",
  3649. function (e, v, m, f) {
  3650. if (v) {
  3651. if (f.username !== null && f.password != null) {
  3652. callback(f.username, f.password);
  3653. }
  3654. }
  3655. },
  3656. null, null, ':input:first'
  3657. );
  3658. }
  3659. UI.checkForNicknameAndJoin = function () {
  3660. Authentication.closeAuthenticationDialog();
  3661. Authentication.stopInterval();
  3662. var nick = null;
  3663. if (config.useNicks) {
  3664. nick = window.prompt('Your nickname (optional)');
  3665. }
  3666. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3667. };
  3668. function dump(elem, filename) {
  3669. elem = elem.parentNode;
  3670. elem.download = filename || 'meetlog.json';
  3671. elem.href = 'data:application/json;charset=utf-8,\n';
  3672. var data = APP.xmpp.populateData();
  3673. var metadata = {};
  3674. metadata.time = new Date();
  3675. metadata.url = window.location.href;
  3676. metadata.ua = navigator.userAgent;
  3677. var log = APP.xmpp.getLogger();
  3678. if (log) {
  3679. metadata.xmpp = log;
  3680. }
  3681. data.metadata = metadata;
  3682. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3683. return false;
  3684. }
  3685. UI.getRoomName = function () {
  3686. return roomName;
  3687. };
  3688. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3689. if(muteAudio || muteVideo) notifyForInitialMute();
  3690. if(muteAudio) UI.setAudioMuted(true);
  3691. if(muteVideo) UI.setVideoMute(true);
  3692. }
  3693. /**
  3694. * Mutes/unmutes the local video.
  3695. */
  3696. UI.toggleVideo = function () {
  3697. setVideoMute(!APP.RTC.localVideo.isMuted());
  3698. };
  3699. /**
  3700. * Mutes / unmutes audio for the local participant.
  3701. */
  3702. UI.toggleAudio = function() {
  3703. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3704. };
  3705. /**
  3706. * Sets muted audio state for the local participant.
  3707. */
  3708. UI.setAudioMuted = function (mute, earlyMute) {
  3709. var audioMute = null;
  3710. if(earlyMute)
  3711. audioMute = function (mute, cb) {
  3712. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3713. };
  3714. else
  3715. audioMute = function (mute, cb) {
  3716. return APP.xmpp.setAudioMute(mute, cb);
  3717. }
  3718. if(!audioMute(mute, function () {
  3719. VideoLayout.showLocalAudioIndicator(mute);
  3720. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3721. }))
  3722. {
  3723. // We still click the button.
  3724. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3725. return;
  3726. }
  3727. }
  3728. UI.addListener = function (type, listener) {
  3729. eventEmitter.on(type, listener);
  3730. }
  3731. UI.clickOnVideo = function (videoNumber) {
  3732. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3733. if (remoteVideos.length > videoNumber) {
  3734. remoteVideos[videoNumber].click();
  3735. }
  3736. }
  3737. //Used by torture
  3738. UI.showToolbar = function () {
  3739. return ToolbarToggler.showToolbar();
  3740. }
  3741. //Used by torture
  3742. UI.dockToolbar = function (isDock) {
  3743. return ToolbarToggler.dockToolbar(isDock);
  3744. }
  3745. UI.setVideoMuteButtonsState = function (mute) {
  3746. var video = $('#video');
  3747. var communicativeClass = "icon-camera";
  3748. var muteClass = "icon-camera icon-camera-disabled";
  3749. if (mute) {
  3750. video.removeClass(communicativeClass);
  3751. video.addClass(muteClass);
  3752. } else {
  3753. video.removeClass(muteClass);
  3754. video.addClass(communicativeClass);
  3755. }
  3756. }
  3757. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3758. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3759. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3760. if(resourceJid === APP.xmpp.myResource())
  3761. SettingsMenu.changeAvatar(thumbUrl);
  3762. }
  3763. UI.setVideoMute = setVideoMute;
  3764. module.exports = UI;
  3765. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes":103,"../../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){
  3766. var CanvasUtil = require("./CanvasUtils");
  3767. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3768. function initActiveSpeakerAudioLevels() {
  3769. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3770. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3771. // Draw a circle.
  3772. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3773. // Add a shadow around the circle
  3774. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3775. ASDrawContext.shadowOffsetX = 0;
  3776. ASDrawContext.shadowOffsetY = 0;
  3777. }
  3778. /**
  3779. * The audio Levels plugin.
  3780. */
  3781. var AudioLevels = (function(my) {
  3782. var audioLevelCanvasCache = {};
  3783. my.LOCAL_LEVEL = 'local';
  3784. my.init = function () {
  3785. initActiveSpeakerAudioLevels();
  3786. }
  3787. /**
  3788. * Updates the audio level canvas for the given peerJid. If the canvas
  3789. * didn't exist we create it.
  3790. */
  3791. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3792. var resourceJid = null;
  3793. var videoSpanId = null;
  3794. if (!peerJid)
  3795. videoSpanId = 'localVideoContainer';
  3796. else {
  3797. resourceJid = Strophe.getResourceFromJid(peerJid);
  3798. videoSpanId = 'participant_' + resourceJid;
  3799. }
  3800. var videoSpan = document.getElementById(videoSpanId);
  3801. if (!videoSpan) {
  3802. if (resourceJid)
  3803. console.error("No video element for jid", resourceJid);
  3804. else
  3805. console.error("No video element for local video.");
  3806. return;
  3807. }
  3808. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3809. var videoSpaceWidth = $('#remoteVideos').width();
  3810. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3811. var thumbnailWidth = thumbnailSize[0];
  3812. var thumbnailHeight = thumbnailSize[1];
  3813. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3814. audioLevelCanvas = document.createElement('canvas');
  3815. audioLevelCanvas.className = "audiolevel";
  3816. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3817. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3818. resizeAudioLevelCanvas( audioLevelCanvas,
  3819. thumbnailWidth,
  3820. thumbnailHeight);
  3821. videoSpan.appendChild(audioLevelCanvas);
  3822. } else {
  3823. audioLevelCanvas = audioLevelCanvas.get(0);
  3824. resizeAudioLevelCanvas( audioLevelCanvas,
  3825. thumbnailWidth,
  3826. thumbnailHeight);
  3827. }
  3828. };
  3829. /**
  3830. * Updates the audio level UI for the given resourceJid.
  3831. *
  3832. * @param resourceJid the resource jid indicating the video element for
  3833. * which we draw the audio level
  3834. * @param audioLevel the newAudio level to render
  3835. */
  3836. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3837. drawAudioLevelCanvas(resourceJid, audioLevel);
  3838. var videoSpanId = getVideoSpanId(resourceJid);
  3839. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3840. if (!audioLevelCanvas)
  3841. return;
  3842. var drawContext = audioLevelCanvas.getContext('2d');
  3843. var canvasCache = audioLevelCanvasCache[resourceJid];
  3844. drawContext.clearRect (0, 0,
  3845. audioLevelCanvas.width, audioLevelCanvas.height);
  3846. drawContext.drawImage(canvasCache, 0, 0);
  3847. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3848. if(!APP.xmpp.myJid()) {
  3849. return;
  3850. }
  3851. resourceJid = APP.xmpp.myResource();
  3852. }
  3853. if(resourceJid === largeVideoResourceJid) {
  3854. window.requestAnimationFrame(function () {
  3855. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3856. });
  3857. }
  3858. };
  3859. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3860. if($("#activeSpeaker").css("visibility") == "hidden")
  3861. return;
  3862. ASDrawContext.clearRect(0, 0, 300, 300);
  3863. if(audioLevel == 0)
  3864. return;
  3865. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3866. // Fill the shape.
  3867. ASDrawContext.fill();
  3868. };
  3869. /**
  3870. * Resizes the given audio level canvas to match the given thumbnail size.
  3871. */
  3872. function resizeAudioLevelCanvas(audioLevelCanvas,
  3873. thumbnailWidth,
  3874. thumbnailHeight) {
  3875. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3876. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3877. }
  3878. /**
  3879. * Draws the audio level canvas into the cached canvas object.
  3880. *
  3881. * @param resourceJid the resource jid indicating the video element for
  3882. * which we draw the audio level
  3883. * @param audioLevel the newAudio level to render
  3884. */
  3885. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3886. if (!audioLevelCanvasCache[resourceJid]) {
  3887. var videoSpanId = getVideoSpanId(resourceJid);
  3888. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3889. /*
  3890. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3891. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3892. * error. Since audio levels are frequently updated, the errors have
  3893. * been observed to pile into the console, strain the CPU.
  3894. */
  3895. if (audioLevelCanvasOrig)
  3896. {
  3897. audioLevelCanvasCache[resourceJid]
  3898. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3899. }
  3900. }
  3901. var canvas = audioLevelCanvasCache[resourceJid];
  3902. if (!canvas)
  3903. return;
  3904. var drawContext = canvas.getContext('2d');
  3905. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3906. var shadowLevel = getShadowLevel(audioLevel);
  3907. if (shadowLevel > 0)
  3908. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3909. CanvasUtil.drawRoundRectGlow( drawContext,
  3910. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  3911. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3912. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3913. interfaceConfig.CANVAS_RADIUS,
  3914. interfaceConfig.SHADOW_COLOR,
  3915. shadowLevel);
  3916. }
  3917. /**
  3918. * Returns the shadow/glow level for the given audio level.
  3919. *
  3920. * @param audioLevel the audio level from which we determine the shadow
  3921. * level
  3922. */
  3923. function getShadowLevel (audioLevel) {
  3924. var shadowLevel = 0;
  3925. if (audioLevel <= 0.3) {
  3926. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3927. }
  3928. else if (audioLevel <= 0.6) {
  3929. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3930. }
  3931. else {
  3932. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3933. }
  3934. return shadowLevel;
  3935. }
  3936. /**
  3937. * Returns the video span id corresponding to the given resourceJid or local
  3938. * user.
  3939. */
  3940. function getVideoSpanId(resourceJid) {
  3941. var videoSpanId = null;
  3942. if (resourceJid === AudioLevels.LOCAL_LEVEL
  3943. || (APP.xmpp.myResource() && resourceJid
  3944. === APP.xmpp.myResource()))
  3945. videoSpanId = 'localVideoContainer';
  3946. else
  3947. videoSpanId = 'participant_' + resourceJid;
  3948. return videoSpanId;
  3949. }
  3950. /**
  3951. * Indicates that the remote video has been resized.
  3952. */
  3953. $(document).bind('remotevideo.resized', function (event, width, height) {
  3954. var resized = false;
  3955. $('#remoteVideos>span>canvas').each(function() {
  3956. var canvas = $(this).get(0);
  3957. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3958. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3959. resized = true;
  3960. }
  3961. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3962. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3963. resized = true;
  3964. }
  3965. });
  3966. if (resized)
  3967. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3968. audioLevelCanvasCache[resourceJid].width
  3969. = width + interfaceConfig.CANVAS_EXTRA;
  3970. audioLevelCanvasCache[resourceJid].height
  3971. = height + interfaceConfig.CANVAS_EXTRA;
  3972. });
  3973. });
  3974. return my;
  3975. })(AudioLevels || {});
  3976. module.exports = AudioLevels;
  3977. },{"./CanvasUtils":15}],15:[function(require,module,exports){
  3978. /**
  3979. * Utility class for drawing canvas shapes.
  3980. */
  3981. var CanvasUtil = (function(my) {
  3982. /**
  3983. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3984. * of the glow.
  3985. *
  3986. * @param drawContext the context of the canvas to draw to
  3987. * @param x the x coordinate of the round rectangle
  3988. * @param y the y coordinate of the round rectangle
  3989. * @param w the width of the round rectangle
  3990. * @param h the height of the round rectangle
  3991. * @param glowColor the color of the glow
  3992. * @param glowWidth the width of the glow
  3993. */
  3994. my.drawRoundRectGlow
  3995. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3996. // Save the previous state of the context.
  3997. drawContext.save();
  3998. if (w < 2 * r) r = w / 2;
  3999. if (h < 2 * r) r = h / 2;
  4000. // Draw a round rectangle.
  4001. drawContext.beginPath();
  4002. drawContext.moveTo(x+r, y);
  4003. drawContext.arcTo(x+w, y, x+w, y+h, r);
  4004. drawContext.arcTo(x+w, y+h, x, y+h, r);
  4005. drawContext.arcTo(x, y+h, x, y, r);
  4006. drawContext.arcTo(x, y, x+w, y, r);
  4007. drawContext.closePath();
  4008. // Add a shadow around the rectangle
  4009. drawContext.shadowColor = glowColor;
  4010. drawContext.shadowBlur = glowWidth;
  4011. drawContext.shadowOffsetX = 0;
  4012. drawContext.shadowOffsetY = 0;
  4013. // Fill the shape.
  4014. drawContext.fill();
  4015. drawContext.save();
  4016. drawContext.restore();
  4017. // 1) Uncomment this line to use Composite Operation, which is doing the
  4018. // same as the clip function below and is also antialiasing the round
  4019. // border, but is said to be less fast performance wise.
  4020. // drawContext.globalCompositeOperation='destination-out';
  4021. drawContext.beginPath();
  4022. drawContext.moveTo(x+r, y);
  4023. drawContext.arcTo(x+w, y, x+w, y+h, r);
  4024. drawContext.arcTo(x+w, y+h, x, y+h, r);
  4025. drawContext.arcTo(x, y+h, x, y, r);
  4026. drawContext.arcTo(x, y, x+w, y, r);
  4027. drawContext.closePath();
  4028. // 2) Uncomment this line to use Composite Operation, which is doing the
  4029. // same as the clip function below and is also antialiasing the round
  4030. // border, but is said to be less fast performance wise.
  4031. // drawContext.fill();
  4032. // Comment these two lines if choosing to do the same with composite
  4033. // operation above 1 and 2.
  4034. drawContext.clip();
  4035. drawContext.clearRect(0, 0, 277, 200);
  4036. // Restore the previous context state.
  4037. drawContext.restore();
  4038. };
  4039. /**
  4040. * Clones the given canvas.
  4041. *
  4042. * @return the new cloned canvas.
  4043. */
  4044. my.cloneCanvas = function (oldCanvas) {
  4045. /*
  4046. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  4047. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  4048. * levels are frequently updated, the errors have been observed to pile
  4049. * into the console, strain the CPU.
  4050. */
  4051. if (!oldCanvas)
  4052. return oldCanvas;
  4053. //create a new canvas
  4054. var newCanvas = document.createElement('canvas');
  4055. var context = newCanvas.getContext('2d');
  4056. //set dimensions
  4057. newCanvas.width = oldCanvas.width;
  4058. newCanvas.height = oldCanvas.height;
  4059. //apply the old canvas to the new one
  4060. context.drawImage(oldCanvas, 0, 0);
  4061. //return the new canvas
  4062. return newCanvas;
  4063. };
  4064. return my;
  4065. })(CanvasUtil || {});
  4066. module.exports = CanvasUtil;
  4067. },{}],16:[function(require,module,exports){
  4068. /* global $, APP*/
  4069. var LoginDialog = require('./LoginDialog');
  4070. var Moderator = require('../../xmpp/moderator');
  4071. /* Initial "authentication required" dialog */
  4072. var authDialog = null;
  4073. /* Loop retry ID that wits for other user to create the room */
  4074. var authRetryId = null;
  4075. var authenticationWindow = null;
  4076. var Authentication = {
  4077. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  4078. // This is the loop that will wait for the room to be created by
  4079. // someone else. 'auth_required.moderator' will bring us back here.
  4080. authRetryId = window.setTimeout(intervalCallback, 5000);
  4081. // Show prompt only if it's not open
  4082. if (authDialog !== null) {
  4083. return;
  4084. }
  4085. // extract room name from 'room@muc.server.net'
  4086. var room = roomName.substr(0, roomName.indexOf('@'));
  4087. var title
  4088. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  4089. var msg
  4090. = APP.translation.generateTranslationHTML(
  4091. "dialog.WaitForHostMsg", {room: room});
  4092. var buttonTxt
  4093. = APP.translation.generateTranslationHTML("dialog.IamHost");
  4094. var buttons = [];
  4095. buttons.push({title: buttonTxt, value: "authNow"});
  4096. authDialog = APP.UI.messageHandler.openDialog(
  4097. title,
  4098. msg,
  4099. true,
  4100. buttons,
  4101. function (onSubmitEvent, submitValue) {
  4102. // Do not close the dialog yet
  4103. onSubmitEvent.preventDefault();
  4104. // Open login popup
  4105. if (submitValue === 'authNow') {
  4106. callback();
  4107. }
  4108. }
  4109. );
  4110. },
  4111. closeAuthenticationWindow: function () {
  4112. if (authenticationWindow) {
  4113. authenticationWindow.close();
  4114. authenticationWindow = null;
  4115. }
  4116. },
  4117. xmppAuthenticate: function () {
  4118. var loginDialog = LoginDialog.show(
  4119. function (connection, state) {
  4120. if (!state) {
  4121. // User cancelled
  4122. loginDialog.close();
  4123. return;
  4124. } else if (state == APP.xmpp.Status.CONNECTED) {
  4125. loginDialog.close();
  4126. Authentication.stopInterval();
  4127. Authentication.closeAuthenticationDialog();
  4128. // Close the connection as anonymous one will be used
  4129. // to create the conference. Session-id will authorize
  4130. // the request.
  4131. connection.disconnect();
  4132. var roomName = APP.UI.generateRoomName();
  4133. Moderator.allocateConferenceFocus(roomName, function () {
  4134. // If it's not "on the fly" authentication now join
  4135. // the conference room
  4136. if (!APP.xmpp.getMUCJoined()) {
  4137. APP.UI.checkForNicknameAndJoin();
  4138. }
  4139. });
  4140. }
  4141. }, true);
  4142. },
  4143. focusAuthenticationWindow: function () {
  4144. // If auth window exists just bring it to the front
  4145. if (authenticationWindow) {
  4146. authenticationWindow.focus();
  4147. return;
  4148. }
  4149. },
  4150. closeAuthenticationDialog: function () {
  4151. // Close authentication dialog if opened
  4152. if (authDialog) {
  4153. authDialog.close();
  4154. authDialog = null;
  4155. }
  4156. },
  4157. createAuthenticationWindow: function (callback, url) {
  4158. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  4159. url, 910, 660,
  4160. // On closed
  4161. function () {
  4162. // Close authentication dialog if opened
  4163. Authentication.closeAuthenticationDialog();
  4164. callback();
  4165. authenticationWindow = null;
  4166. });
  4167. return authenticationWindow;
  4168. },
  4169. stopInterval: function () {
  4170. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  4171. if (authRetryId) {
  4172. window.clearTimeout(authRetryId);
  4173. authRetryId = null;
  4174. }
  4175. }
  4176. };
  4177. module.exports = Authentication;
  4178. },{"../../xmpp/moderator":60,"./LoginDialog":17}],17:[function(require,module,exports){
  4179. /* global $, APP, config*/
  4180. var XMPP = require('../../xmpp/xmpp');
  4181. var Moderator = require('../../xmpp/moderator');
  4182. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  4183. // anonymous domain is not enabled
  4184. /**
  4185. * Creates new <tt>Dialog</tt> instance.
  4186. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  4187. * when we either fail to connect or succeed(check Strophe.Status).
  4188. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  4189. * in order to create session-id after the connection is established.
  4190. * @constructor
  4191. */
  4192. function Dialog(callback, obtainSession) {
  4193. var self = this;
  4194. var stop = false;
  4195. var connection = APP.xmpp.createConnection();
  4196. var message = '<h2 data-i18n="dialog.passwordRequired">';
  4197. message += APP.translation.translateString("dialog.passwordRequired");
  4198. message += '</h2>' +
  4199. '<input name="username" type="text" ' +
  4200. 'placeholder="user@domain.net" autofocus>' +
  4201. '<input name="password" ' +
  4202. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  4203. ' placeholder="user password">';
  4204. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  4205. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  4206. var states = {
  4207. login: {
  4208. html: message,
  4209. buttons: [
  4210. { title: okButton, value: true},
  4211. { title: cancelButton, value: false}
  4212. ],
  4213. focus: ':input:first',
  4214. submit: function (e, v, m, f) {
  4215. e.preventDefault();
  4216. if (v) {
  4217. var jid = f.username;
  4218. var password = f.password;
  4219. if (jid && password) {
  4220. stop = false;
  4221. connection.reset();
  4222. connDialog.goToState('connecting');
  4223. connection.connect(jid, password, stateHandler);
  4224. }
  4225. } else {
  4226. // User cancelled
  4227. stop = true;
  4228. callback();
  4229. }
  4230. }
  4231. },
  4232. connecting: {
  4233. title: APP.translation.translateString('dialog.connecting'),
  4234. html: '<div id="connectionStatus"></div>',
  4235. buttons: [],
  4236. defaultButton: 0
  4237. },
  4238. finished: {
  4239. title: APP.translation.translateString('dialog.error'),
  4240. html: '<div id="errorMessage"></div>',
  4241. buttons: [
  4242. {
  4243. title: APP.translation.translateString('dialog.retry'),
  4244. value: 'retry'
  4245. },
  4246. {
  4247. title: APP.translation.translateString('dialog.Cancel'),
  4248. value: 'cancel'
  4249. },
  4250. ],
  4251. defaultButton: 0,
  4252. submit: function (e, v, m, f) {
  4253. e.preventDefault();
  4254. if (v === 'retry')
  4255. connDialog.goToState('login');
  4256. else
  4257. callback();
  4258. }
  4259. }
  4260. };
  4261. var connDialog
  4262. = APP.UI.messageHandler.openDialogWithStates(states,
  4263. { persistent: true, closeText: '' }, null);
  4264. var stateHandler = function (status, message) {
  4265. if (stop) {
  4266. return;
  4267. }
  4268. var translateKey = "connection." + XMPP.getStatusString(status);
  4269. var statusStr = APP.translation.translateString(translateKey);
  4270. // Display current state
  4271. var connectionStatus =
  4272. connDialog.getState('connecting').find('#connectionStatus');
  4273. connectionStatus.text(statusStr);
  4274. switch (status) {
  4275. case XMPP.Status.CONNECTED:
  4276. stop = true;
  4277. if (!obtainSession) {
  4278. callback(connection, status);
  4279. return;
  4280. }
  4281. // Obtaining session-id status
  4282. connectionStatus.text(
  4283. APP.translation.translateString(
  4284. 'connection.FETCH_SESSION_ID'));
  4285. // Authenticate with Jicofo and obtain session-id
  4286. var roomName = APP.UI.generateRoomName();
  4287. // Jicofo will return new session-id when connected
  4288. // from authenticated domain
  4289. connection.sendIQ(
  4290. Moderator.createConferenceIq(roomName),
  4291. function (result) {
  4292. connectionStatus.text(
  4293. APP.translation.translateString(
  4294. 'connection.GOT_SESSION_ID'));
  4295. stop = true;
  4296. // Parse session-id
  4297. Moderator.parseSessionId(result);
  4298. callback(connection, status);
  4299. },
  4300. function (error) {
  4301. console.error("Auth on the fly failed", error);
  4302. stop = true;
  4303. var errorMsg =
  4304. APP.translation.translateString(
  4305. 'connection.GET_SESSION_ID_ERROR') +
  4306. $(error).find('>error').attr('code');
  4307. self.displayError(errorMsg);
  4308. connection.disconnect();
  4309. });
  4310. break;
  4311. case XMPP.Status.AUTHFAIL:
  4312. case XMPP.Status.CONNFAIL:
  4313. case XMPP.Status.DISCONNECTED:
  4314. stop = true;
  4315. callback(connection, status);
  4316. var errorMessage = statusStr;
  4317. if (message)
  4318. {
  4319. errorMessage += ': ' + message;
  4320. }
  4321. self.displayError(errorMessage);
  4322. break;
  4323. default:
  4324. break;
  4325. }
  4326. };
  4327. /**
  4328. * Displays error message in 'finished' state which allows either to cancel
  4329. * or retry.
  4330. * @param message the final message to be displayed.
  4331. */
  4332. this.displayError = function (message) {
  4333. var finishedState = connDialog.getState('finished');
  4334. var errorMessageElem = finishedState.find('#errorMessage');
  4335. errorMessageElem.text(message);
  4336. connDialog.goToState('finished');
  4337. };
  4338. /**
  4339. * Closes LoginDialog.
  4340. */
  4341. this.close = function () {
  4342. stop = true;
  4343. connDialog.close();
  4344. };
  4345. }
  4346. var LoginDialog = {
  4347. /**
  4348. * Displays login prompt used to establish new XMPP connection. Given
  4349. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4350. * called when we connect successfully(status === CONNECTED) or when we fail
  4351. * to do so. On connection failure program can call Dialog.close() method in
  4352. * order to cancel or do nothing to let the user retry.
  4353. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4354. * called when we either fail to connect or succeed(check
  4355. * Strophe.Status).
  4356. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4357. * Jicofo in order to create session-id after the connection is
  4358. * established.
  4359. * @returns {Dialog}
  4360. */
  4361. show: function (callback, obtainSession) {
  4362. return new Dialog(callback, obtainSession);
  4363. }
  4364. };
  4365. module.exports = LoginDialog;
  4366. },{"../../xmpp/moderator":60,"../../xmpp/xmpp":68}],18:[function(require,module,exports){
  4367. var Settings = require("../../settings/Settings");
  4368. var users = {};
  4369. var Avatar = {
  4370. /**
  4371. * Sets the user's avatar in the settings menu(if local user), contact list
  4372. * and thumbnail
  4373. * @param jid jid of the user
  4374. * @param id email or userID to be used as a hash
  4375. */
  4376. setUserAvatar: function (jid, id) {
  4377. if (id) {
  4378. if (users[jid] === id) {
  4379. return;
  4380. }
  4381. users[jid] = id;
  4382. }
  4383. var thumbUrl = this.getGravatarUrl(users[jid] || jid, 100);
  4384. var contactListUrl = this.getGravatarUrl(users[jid] || jid);
  4385. var resourceJid = Strophe.getResourceFromJid(jid);
  4386. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4387. },
  4388. getGravatarUrl: function (id, size) {
  4389. if(id === APP.xmpp.myJid() || !id) {
  4390. id = Settings.getSettings().uid;
  4391. }
  4392. return 'https://www.gravatar.com/avatar/' +
  4393. MD5.hexdigest(id.trim().toLowerCase()) +
  4394. "?d=wavatar&size=" + (size || "30");
  4395. }
  4396. };
  4397. module.exports = Avatar;
  4398. },{"../../settings/Settings":49}],19:[function(require,module,exports){
  4399. /* global $, config,
  4400. setLargeVideoVisible, Util */
  4401. var VideoLayout = require("../videolayout/VideoLayout");
  4402. var Prezi = require("../prezi/Prezi");
  4403. var UIUtil = require("../util/UIUtil");
  4404. var etherpadName = null;
  4405. var etherpadIFrame = null;
  4406. var domain = null;
  4407. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4408. /**
  4409. * Resizes the etherpad.
  4410. */
  4411. function resize() {
  4412. if ($('#etherpad>iframe').length) {
  4413. var remoteVideos = $('#remoteVideos');
  4414. var availableHeight
  4415. = window.innerHeight - remoteVideos.outerHeight();
  4416. var availableWidth = UIUtil.getAvailableVideoWidth();
  4417. $('#etherpad>iframe').width(availableWidth);
  4418. $('#etherpad>iframe').height(availableHeight);
  4419. }
  4420. }
  4421. /**
  4422. * Creates the Etherpad button and adds it to the toolbar.
  4423. */
  4424. function enableEtherpadButton() {
  4425. if (!$('#etherpadButton').is(":visible"))
  4426. $('#etherpadButton').css({display: 'inline-block'});
  4427. }
  4428. /**
  4429. * Creates the IFrame for the etherpad.
  4430. */
  4431. function createIFrame() {
  4432. etherpadIFrame = document.createElement('iframe');
  4433. etherpadIFrame.src = domain + etherpadName + options;
  4434. etherpadIFrame.frameBorder = 0;
  4435. etherpadIFrame.scrolling = "no";
  4436. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  4437. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  4438. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  4439. document.getElementById('etherpad').appendChild(etherpadIFrame);
  4440. etherpadIFrame.onload = function() {
  4441. document.domain = document.domain;
  4442. bubbleIframeMouseMove(etherpadIFrame);
  4443. setTimeout(function() {
  4444. // the iframes inside of the etherpad are
  4445. // not yet loaded when the etherpad iframe is loaded
  4446. var outer = etherpadIFrame.
  4447. contentDocument.getElementsByName("ace_outer")[0];
  4448. bubbleIframeMouseMove(outer);
  4449. var inner = outer.
  4450. contentDocument.getElementsByName("ace_inner")[0];
  4451. bubbleIframeMouseMove(inner);
  4452. }, 2000);
  4453. };
  4454. }
  4455. function bubbleIframeMouseMove(iframe){
  4456. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4457. iframe.contentWindow.onmousemove = function(e){
  4458. if(existingOnMouseMove) existingOnMouseMove(e);
  4459. var evt = document.createEvent("MouseEvents");
  4460. var boundingClientRect = iframe.getBoundingClientRect();
  4461. evt.initMouseEvent(
  4462. "mousemove",
  4463. true, // bubbles
  4464. false, // not cancelable
  4465. window,
  4466. e.detail,
  4467. e.screenX,
  4468. e.screenY,
  4469. e.clientX + boundingClientRect.left,
  4470. e.clientY + boundingClientRect.top,
  4471. e.ctrlKey,
  4472. e.altKey,
  4473. e.shiftKey,
  4474. e.metaKey,
  4475. e.button,
  4476. null // no related element
  4477. );
  4478. iframe.dispatchEvent(evt);
  4479. };
  4480. }
  4481. /**
  4482. * On video selected event.
  4483. */
  4484. $(document).bind('video.selected', function (event, isPresentation) {
  4485. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  4486. Etherpad.toggleEtherpad(isPresentation);
  4487. });
  4488. var Etherpad = {
  4489. /**
  4490. * Initializes the etherpad.
  4491. */
  4492. init: function (name) {
  4493. if (config.etherpad_base && !etherpadName && name) {
  4494. domain = config.etherpad_base;
  4495. etherpadName = name;
  4496. enableEtherpadButton();
  4497. /**
  4498. * Resizes the etherpad, when the window is resized.
  4499. */
  4500. $(window).resize(function () {
  4501. resize();
  4502. });
  4503. }
  4504. },
  4505. /**
  4506. * Opens/hides the Etherpad.
  4507. */
  4508. toggleEtherpad: function (isPresentation) {
  4509. if (!etherpadIFrame)
  4510. createIFrame();
  4511. var largeVideo = null;
  4512. if (Prezi.isPresentationVisible())
  4513. largeVideo = $('#presentation>iframe');
  4514. else
  4515. largeVideo = $('#largeVideo');
  4516. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  4517. $('#activeSpeaker').css('visibility', 'hidden');
  4518. largeVideo.fadeOut(300, function () {
  4519. if (Prezi.isPresentationVisible()) {
  4520. largeVideo.css({opacity: '0'});
  4521. } else {
  4522. VideoLayout.setLargeVideoVisible(false);
  4523. }
  4524. });
  4525. $('#etherpad>iframe').fadeIn(300, function () {
  4526. document.body.style.background = '#eeeeee';
  4527. $('#etherpad>iframe').css({visibility: 'visible'});
  4528. $('#etherpad').css({zIndex: 2});
  4529. });
  4530. }
  4531. else if ($('#etherpad>iframe')) {
  4532. $('#etherpad>iframe').fadeOut(300, function () {
  4533. $('#etherpad>iframe').css({visibility: 'hidden'});
  4534. $('#etherpad').css({zIndex: 0});
  4535. document.body.style.background = 'black';
  4536. });
  4537. if (!isPresentation) {
  4538. $('#largeVideo').fadeIn(300, function () {
  4539. VideoLayout.setLargeVideoVisible(true);
  4540. });
  4541. }
  4542. }
  4543. resize();
  4544. },
  4545. isVisible: function() {
  4546. var etherpadIframe = $('#etherpad>iframe');
  4547. return etherpadIframe && etherpadIframe.is(':visible');
  4548. }
  4549. };
  4550. module.exports = Etherpad;
  4551. },{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){
  4552. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4553. var UIUtil = require("../util/UIUtil");
  4554. var VideoLayout = require("../videolayout/VideoLayout");
  4555. var messageHandler = require("../util/MessageHandler");
  4556. var PreziPlayer = require("./PreziPlayer");
  4557. var preziPlayer = null;
  4558. var Prezi = {
  4559. /**
  4560. * Reloads the current presentation.
  4561. */
  4562. reloadPresentation: function() {
  4563. var iframe = document.getElementById(preziPlayer.options.preziId);
  4564. iframe.src = iframe.src;
  4565. },
  4566. /**
  4567. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4568. * otherwise.
  4569. */
  4570. isPresentationVisible: function () {
  4571. return ($('#presentation>iframe') != null
  4572. && $('#presentation>iframe').css('opacity') == 1);
  4573. },
  4574. /**
  4575. * Opens the Prezi dialog, from which the user could choose a presentation
  4576. * to load.
  4577. */
  4578. openPreziDialog: function() {
  4579. var myprezi = APP.xmpp.getPrezi();
  4580. if (myprezi) {
  4581. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4582. null,
  4583. "dialog.removePreziMsg",
  4584. null,
  4585. false,
  4586. "dialog.Remove",
  4587. function(e,v,m,f) {
  4588. if(v) {
  4589. APP.xmpp.removePreziFromPresence();
  4590. }
  4591. }
  4592. );
  4593. }
  4594. else if (preziPlayer != null) {
  4595. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4596. null, "dialog.sharePreziMsg",
  4597. null,
  4598. false,
  4599. "dialog.Ok",
  4600. function(e,v,m,f) {
  4601. $.prompt.close();
  4602. }
  4603. );
  4604. }
  4605. else {
  4606. var html = APP.translation.generateTranslationHTML(
  4607. "dialog.sharePreziTitle");
  4608. var cancelButton = APP.translation.generateTranslationHTML(
  4609. "dialog.Cancel");
  4610. var shareButton = APP.translation.generateTranslationHTML(
  4611. "dialog.Share");
  4612. var backButton = APP.translation.generateTranslationHTML(
  4613. "dialog.Back");
  4614. var buttons = [];
  4615. var buttons1 = [];
  4616. // Cancel button to both states
  4617. buttons.push({title: cancelButton, value: false});
  4618. buttons1.push({title: cancelButton, value: false});
  4619. // Share button
  4620. buttons.push({title: shareButton, value: true});
  4621. // Back button
  4622. buttons1.push({title: backButton, value: true});
  4623. var linkError = APP.translation.generateTranslationHTML(
  4624. "dialog.preziLinkError");
  4625. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4626. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4627. var openPreziState = {
  4628. state0: {
  4629. html: '<h2>' + html + '</h2>' +
  4630. '<input name="preziUrl" type="text" ' +
  4631. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4632. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4633. '\' placeholder="' + defaultUrl + '" autofocus>',
  4634. persistent: false,
  4635. buttons: buttons,
  4636. focus: ':input:first',
  4637. defaultButton: 0,
  4638. submit: function (e, v, m, f) {
  4639. e.preventDefault();
  4640. if(v)
  4641. {
  4642. var preziUrl = f.preziUrl;
  4643. if (preziUrl)
  4644. {
  4645. var urlValue
  4646. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4647. if (urlValue.indexOf('http://prezi.com/') != 0
  4648. && urlValue.indexOf('https://prezi.com/') != 0)
  4649. {
  4650. $.prompt.goToState('state1');
  4651. return false;
  4652. }
  4653. else {
  4654. var presIdTmp = urlValue.substring(
  4655. urlValue.indexOf("prezi.com/") + 10);
  4656. if (!isAlphanumeric(presIdTmp)
  4657. || presIdTmp.indexOf('/') < 2) {
  4658. $.prompt.goToState('state1');
  4659. return false;
  4660. }
  4661. else {
  4662. APP.xmpp.addToPresence("prezi", urlValue);
  4663. $.prompt.close();
  4664. }
  4665. }
  4666. }
  4667. }
  4668. else
  4669. $.prompt.close();
  4670. }
  4671. },
  4672. state1: {
  4673. html: '<h2>' + html + '</h2>' +
  4674. linkError,
  4675. persistent: false,
  4676. buttons: buttons1,
  4677. focus: ':input:first',
  4678. defaultButton: 1,
  4679. submit: function (e, v, m, f) {
  4680. e.preventDefault();
  4681. if (v === 0)
  4682. $.prompt.close();
  4683. else
  4684. $.prompt.goToState('state0');
  4685. }
  4686. }
  4687. };
  4688. messageHandler.openDialogWithStates(openPreziState);
  4689. }
  4690. }
  4691. };
  4692. /**
  4693. * A new presentation has been added.
  4694. *
  4695. * @param event the event indicating the add of a presentation
  4696. * @param jid the jid from which the presentation was added
  4697. * @param presUrl url of the presentation
  4698. * @param currentSlide the current slide to which we should move
  4699. */
  4700. function presentationAdded(event, jid, presUrl, currentSlide) {
  4701. console.log("presentation added", presUrl);
  4702. var presId = getPresentationId(presUrl);
  4703. var elementId = 'participant_'
  4704. + Strophe.getResourceFromJid(jid)
  4705. + '_' + presId;
  4706. VideoLayout.addPreziContainer(elementId);
  4707. VideoLayout.resizeThumbnails();
  4708. var controlsEnabled = false;
  4709. if (jid === APP.xmpp.myJid())
  4710. controlsEnabled = true;
  4711. setPresentationVisible(true);
  4712. $('#largeVideoContainer').hover(
  4713. function (event) {
  4714. if (Prezi.isPresentationVisible()) {
  4715. var reloadButtonRight = window.innerWidth
  4716. - $('#presentation>iframe').offset().left
  4717. - $('#presentation>iframe').width();
  4718. $('#reloadPresentation').css({ right: reloadButtonRight,
  4719. display:'inline-block'});
  4720. }
  4721. },
  4722. function (event) {
  4723. if (!Prezi.isPresentationVisible())
  4724. $('#reloadPresentation').css({display:'none'});
  4725. else {
  4726. var e = event.toElement || event.relatedTarget;
  4727. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4728. $('#reloadPresentation').css({display:'none'});
  4729. }
  4730. });
  4731. preziPlayer = new PreziPlayer(
  4732. 'presentation',
  4733. {preziId: presId,
  4734. width: getPresentationWidth(),
  4735. height: getPresentationHeihgt(),
  4736. controls: controlsEnabled,
  4737. debug: true
  4738. });
  4739. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4740. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4741. console.log("prezi status", event.value);
  4742. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4743. if (jid != APP.xmpp.myJid())
  4744. preziPlayer.flyToStep(currentSlide);
  4745. }
  4746. });
  4747. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4748. console.log("event value", event.value);
  4749. APP.xmpp.addToPresence("preziSlide", event.value);
  4750. });
  4751. $("#" + elementId).css( 'background-image',
  4752. 'url(../images/avatarprezi.png)');
  4753. $("#" + elementId).click(
  4754. function () {
  4755. setPresentationVisible(true);
  4756. }
  4757. );
  4758. };
  4759. /**
  4760. * A presentation has been removed.
  4761. *
  4762. * @param event the event indicating the remove of a presentation
  4763. * @param jid the jid for which the presentation was removed
  4764. * @param the url of the presentation
  4765. */
  4766. function presentationRemoved(event, jid, presUrl) {
  4767. console.log('presentation removed', presUrl);
  4768. var presId = getPresentationId(presUrl);
  4769. setPresentationVisible(false);
  4770. $('#participant_'
  4771. + Strophe.getResourceFromJid(jid)
  4772. + '_' + presId).remove();
  4773. $('#presentation>iframe').remove();
  4774. if (preziPlayer != null) {
  4775. preziPlayer.destroy();
  4776. preziPlayer = null;
  4777. }
  4778. };
  4779. /**
  4780. * Indicates if the given string is an alphanumeric string.
  4781. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4782. * purpose of checking URIs.
  4783. */
  4784. function isAlphanumeric(unsafeText) {
  4785. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4786. return regex.test(unsafeText);
  4787. }
  4788. /**
  4789. * Returns the presentation id from the given url.
  4790. */
  4791. function getPresentationId (presUrl) {
  4792. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4793. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4794. }
  4795. /**
  4796. * Returns the presentation width.
  4797. */
  4798. function getPresentationWidth() {
  4799. var availableWidth = UIUtil.getAvailableVideoWidth();
  4800. var availableHeight = getPresentationHeihgt();
  4801. var aspectRatio = 16.0 / 9.0;
  4802. if (availableHeight < availableWidth / aspectRatio) {
  4803. availableWidth = Math.floor(availableHeight * aspectRatio);
  4804. }
  4805. return availableWidth;
  4806. }
  4807. /**
  4808. * Returns the presentation height.
  4809. */
  4810. function getPresentationHeihgt() {
  4811. var remoteVideos = $('#remoteVideos');
  4812. return window.innerHeight - remoteVideos.outerHeight();
  4813. }
  4814. /**
  4815. * Resizes the presentation iframe.
  4816. */
  4817. function resize() {
  4818. if ($('#presentation>iframe')) {
  4819. $('#presentation>iframe').width(getPresentationWidth());
  4820. $('#presentation>iframe').height(getPresentationHeihgt());
  4821. }
  4822. }
  4823. /**
  4824. * Shows/hides a presentation.
  4825. */
  4826. function setPresentationVisible(visible) {
  4827. var prezi = $('#presentation>iframe');
  4828. if (visible) {
  4829. // Trigger the video.selected event to indicate a change in the
  4830. // large video.
  4831. $(document).trigger("video.selected", [true]);
  4832. $('#largeVideo').fadeOut(300);
  4833. prezi.fadeIn(300, function() {
  4834. prezi.css({opacity:'1'});
  4835. ToolbarToggler.dockToolbar(true);
  4836. VideoLayout.setLargeVideoVisible(false);
  4837. });
  4838. $('#activeSpeaker').css('visibility', 'hidden');
  4839. }
  4840. else {
  4841. if (prezi.css('opacity') == '1') {
  4842. prezi.fadeOut(300, function () {
  4843. prezi.css({opacity:'0'});
  4844. $('#reloadPresentation').css({display:'none'});
  4845. $('#largeVideo').fadeIn(300, function() {
  4846. VideoLayout.setLargeVideoVisible(true);
  4847. ToolbarToggler.dockToolbar(false);
  4848. });
  4849. });
  4850. }
  4851. }
  4852. }
  4853. /**
  4854. * Presentation has been removed.
  4855. */
  4856. $(document).bind('presentationremoved.muc', presentationRemoved);
  4857. /**
  4858. * Presentation has been added.
  4859. */
  4860. $(document).bind('presentationadded.muc', presentationAdded);
  4861. /*
  4862. * Indicates presentation slide change.
  4863. */
  4864. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4865. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4866. preziPlayer.flyToStep(current);
  4867. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4868. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4869. preziPlayer.flyToStep(current, i);
  4870. }
  4871. }
  4872. });
  4873. /**
  4874. * On video selected event.
  4875. */
  4876. $(document).bind('video.selected', function (event, isPresentation) {
  4877. if (!isPresentation && $('#presentation>iframe')) {
  4878. setPresentationVisible(false);
  4879. }
  4880. });
  4881. $(window).resize(function () {
  4882. resize();
  4883. });
  4884. module.exports = Prezi;
  4885. },{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){
  4886. (function() {
  4887. "use strict";
  4888. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4889. window.PreziPlayer = (function() {
  4890. PreziPlayer.API_VERSION = 1;
  4891. PreziPlayer.CURRENT_STEP = 'currentStep';
  4892. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4893. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4894. PreziPlayer.STATUS_LOADING = 'loading';
  4895. PreziPlayer.STATUS_READY = 'ready';
  4896. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4897. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4898. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4899. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4900. PreziPlayer.EVENT_STATUS = "statusChange";
  4901. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4902. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4903. PreziPlayer.domain = "https://prezi.com";
  4904. PreziPlayer.path = "/player/";
  4905. PreziPlayer.players = {};
  4906. PreziPlayer.binded_methods = ['changesHandler'];
  4907. PreziPlayer.createMultiplePlayers = function(optionArray){
  4908. for(var i=0; i<optionArray.length; i++) {
  4909. var optionSet = optionArray[i];
  4910. new PreziPlayer(optionSet.id, optionSet);
  4911. };
  4912. };
  4913. PreziPlayer.messageReceived = function(event){
  4914. var message, item, player;
  4915. try {
  4916. message = JSON.parse(event.data);
  4917. if (message.id && (player = PreziPlayer.players[message.id])) {
  4918. if (player.options.debug === true) {
  4919. if (console && console.log)
  4920. console.log('received', message);
  4921. }
  4922. if (message.type === "changes") {
  4923. player.changesHandler(message);
  4924. }
  4925. for (var i = 0; i < player.callbacks.length; i++) {
  4926. item = player.callbacks[i];
  4927. if (item && message.type === item.event) {
  4928. item.callback(message);
  4929. }
  4930. }
  4931. }
  4932. } catch (e) { }
  4933. };
  4934. function PreziPlayer(id, options) {
  4935. var params, paramString = "", _this = this;
  4936. if (PreziPlayer.players[id]){
  4937. PreziPlayer.players[id].destroy();
  4938. }
  4939. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4940. var method_name = PreziPlayer.binded_methods[i];
  4941. _this[method_name] = __bind(_this[method_name], _this);
  4942. };
  4943. options = options || {};
  4944. this.options = options;
  4945. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4946. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4947. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4948. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4949. this.callbacks = [];
  4950. this.id = id;
  4951. this.embedTo = document.getElementById(id);
  4952. if (!this.embedTo) {
  4953. throw "The element id is not available.";
  4954. }
  4955. this.iframe = document.createElement('iframe');
  4956. params = [
  4957. { name: 'oid', value: options.preziId },
  4958. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4959. { name: 'controls', value: options.controls ? 1 : 0 }
  4960. ];
  4961. for(var i=0; i<params.length; i++) {
  4962. var param = params[i];
  4963. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4964. };
  4965. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4966. this.iframe.frameBorder = 0;
  4967. this.iframe.scrolling = "no";
  4968. this.iframe.width = options.width || 640;
  4969. this.iframe.height = options.height || 480;
  4970. this.embedTo.innerHTML = '';
  4971. // JITSI: IN CASE SOMETHING GOES WRONG.
  4972. try {
  4973. this.embedTo.appendChild(this.iframe);
  4974. }
  4975. catch (err) {
  4976. console.log("CATCH ERROR");
  4977. }
  4978. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4979. // crashes for us.
  4980. this.initPollInterval = setInterval(function(){
  4981. _this.sendMessage({'action': 'init'});
  4982. }, 500);
  4983. PreziPlayer.players[id] = this;
  4984. }
  4985. PreziPlayer.prototype.changesHandler = function(message) {
  4986. var key, value, j, item;
  4987. if (this.initPollInterval) {
  4988. clearInterval(this.initPollInterval);
  4989. this.initPollInterval = false;
  4990. }
  4991. for (key in message.data) {
  4992. if (message.data.hasOwnProperty(key)){
  4993. value = message.data[key];
  4994. this.values[key] = value;
  4995. for (j=0; j<this.callbacks.length; j++) {
  4996. item = this.callbacks[j];
  4997. if (item && item.event === key + "Change"){
  4998. item.callback({type: item.event, value: value});
  4999. }
  5000. }
  5001. }
  5002. }
  5003. };
  5004. PreziPlayer.prototype.destroy = function() {
  5005. if (this.initPollInterval) {
  5006. clearInterval(this.initPollInterval);
  5007. this.initPollInterval = false;
  5008. }
  5009. this.embedTo.innerHTML = '';
  5010. };
  5011. PreziPlayer.prototype.sendMessage = function(message) {
  5012. if (this.options.debug === true) {
  5013. if (console && console.log) console.log('sent', message);
  5014. }
  5015. message.version = PreziPlayer.API_VERSION;
  5016. message.id = this.id;
  5017. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  5018. };
  5019. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  5020. PreziPlayer.prototype.flyToNextStep = function() {
  5021. return this.sendMessage({
  5022. 'action': 'present',
  5023. 'data': ['moveToNextStep']
  5024. });
  5025. };
  5026. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  5027. PreziPlayer.prototype.flyToPreviousStep = function() {
  5028. return this.sendMessage({
  5029. 'action': 'present',
  5030. 'data': ['moveToPrevStep']
  5031. });
  5032. };
  5033. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  5034. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  5035. var obj = this;
  5036. // check animation_step
  5037. if (animation_step > 0 &&
  5038. obj.values.animationCountOnSteps &&
  5039. obj.values.animationCountOnSteps[step] <= animation_step) {
  5040. animation_step = obj.values.animationCountOnSteps[step];
  5041. }
  5042. // jump to animation steps by calling flyToNextStep()
  5043. function doAnimationSteps() {
  5044. if (obj.values.isMoving == true) {
  5045. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  5046. return;
  5047. }
  5048. while (animation_step-- > 0) {
  5049. obj.flyToNextStep(); // do the animation steps
  5050. }
  5051. }
  5052. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  5053. // jump to the step
  5054. return this.sendMessage({
  5055. 'action': 'present',
  5056. 'data': ['moveToStep', step]
  5057. });
  5058. };
  5059. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  5060. PreziPlayer.prototype.flyToObject = function(objectId) {
  5061. return this.sendMessage({
  5062. 'action': 'present',
  5063. 'data': ['moveToObject', objectId]
  5064. });
  5065. };
  5066. PreziPlayer.prototype.play = function(defaultDelay) {
  5067. return this.sendMessage({
  5068. 'action': 'present',
  5069. 'data': ['startAutoPlay', defaultDelay]
  5070. });
  5071. };
  5072. PreziPlayer.prototype.stop = function() {
  5073. return this.sendMessage({
  5074. 'action': 'present',
  5075. 'data': ['stopAutoPlay']
  5076. });
  5077. };
  5078. PreziPlayer.prototype.pause = function(defaultDelay) {
  5079. return this.sendMessage({
  5080. 'action': 'present',
  5081. 'data': ['pauseAutoPlay', defaultDelay]
  5082. });
  5083. };
  5084. PreziPlayer.prototype.getCurrentStep = function() {
  5085. return this.values.currentStep;
  5086. };
  5087. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  5088. return this.values.currentAnimationStep;
  5089. };
  5090. PreziPlayer.prototype.getCurrentObject = function() {
  5091. return this.values.currentObject;
  5092. };
  5093. PreziPlayer.prototype.getStatus = function() {
  5094. return this.values.status;
  5095. };
  5096. PreziPlayer.prototype.isPlaying = function() {
  5097. return this.values.isAutoPlaying;
  5098. };
  5099. PreziPlayer.prototype.getStepCount = function() {
  5100. return this.values.stepCount;
  5101. };
  5102. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  5103. return this.values.animationCountOnSteps;
  5104. };
  5105. PreziPlayer.prototype.getTitle = function() {
  5106. return this.values.title;
  5107. };
  5108. PreziPlayer.prototype.setDimensions = function(dims) {
  5109. for (var parameter in dims) {
  5110. this.iframe[parameter] = dims[parameter];
  5111. }
  5112. }
  5113. PreziPlayer.prototype.getDimensions = function() {
  5114. return {
  5115. width: parseInt(this.iframe.width, 10),
  5116. height: parseInt(this.iframe.height, 10)
  5117. }
  5118. }
  5119. PreziPlayer.prototype.on = function(event, callback) {
  5120. this.callbacks.push({
  5121. event: event,
  5122. callback: callback
  5123. });
  5124. };
  5125. PreziPlayer.prototype.off = function(event, callback) {
  5126. var j, item;
  5127. if (event === undefined) {
  5128. this.callbacks = [];
  5129. }
  5130. j = this.callbacks.length;
  5131. while (j--) {
  5132. item = this.callbacks[j];
  5133. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  5134. this.callbacks.splice(j, 1);
  5135. }
  5136. }
  5137. };
  5138. if (window.addEventListener) {
  5139. window.addEventListener('message', PreziPlayer.messageReceived, false);
  5140. } else {
  5141. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  5142. }
  5143. return PreziPlayer;
  5144. })();
  5145. })();
  5146. module.exports = PreziPlayer;
  5147. },{}],22:[function(require,module,exports){
  5148. var Chat = require("./chat/Chat");
  5149. var ContactList = require("./contactlist/ContactList");
  5150. var Settings = require("./../../settings/Settings");
  5151. var SettingsMenu = require("./settings/SettingsMenu");
  5152. var VideoLayout = require("../videolayout/VideoLayout");
  5153. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  5154. var UIUtil = require("../util/UIUtil");
  5155. var LargeVideo = require("../videolayout/LargeVideo");
  5156. /**
  5157. * Toggler for the chat, contact list, settings menu, etc..
  5158. */
  5159. var PanelToggler = (function(my) {
  5160. var currentlyOpen = null;
  5161. var buttons = {
  5162. '#chatspace': '#chatBottomButton',
  5163. '#contactlist': '#contactListButton',
  5164. '#settingsmenu': '#settingsButton'
  5165. };
  5166. /**
  5167. * Toggles the windows in the side panel
  5168. * @param object the window that should be shown
  5169. * @param selector the selector for the element containing the panel
  5170. * @param onOpenComplete function to be called when the panel is opened
  5171. * @param onOpen function to be called if the window is going to be opened
  5172. * @param onClose function to be called if the window is going to be closed
  5173. */
  5174. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  5175. UIUtil.buttonClick(buttons[selector], "active");
  5176. if (object.isVisible()) {
  5177. $("#toast-container").animate({
  5178. right: '5px'
  5179. },
  5180. {
  5181. queue: false,
  5182. duration: 500
  5183. });
  5184. $(selector).hide("slide", {
  5185. direction: "right",
  5186. queue: false,
  5187. duration: 500
  5188. });
  5189. if(typeof onClose === "function") {
  5190. onClose();
  5191. }
  5192. currentlyOpen = null;
  5193. }
  5194. else {
  5195. // Undock the toolbar when the chat is shown and if we're in a
  5196. // video mode.
  5197. if (LargeVideo.isLargeVideoVisible()) {
  5198. ToolbarToggler.dockToolbar(false);
  5199. }
  5200. if(currentlyOpen) {
  5201. var current = $(currentlyOpen);
  5202. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  5203. current.css('z-index', 4);
  5204. setTimeout(function () {
  5205. current.css('display', 'none');
  5206. current.css('z-index', 5);
  5207. }, 500);
  5208. }
  5209. $("#toast-container").animate({
  5210. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  5211. },
  5212. {
  5213. queue: false,
  5214. duration: 500
  5215. });
  5216. $(selector).show("slide", {
  5217. direction: "right",
  5218. queue: false,
  5219. duration: 500,
  5220. complete: onOpenComplete
  5221. });
  5222. if(typeof onOpen === "function") {
  5223. onOpen();
  5224. }
  5225. currentlyOpen = selector;
  5226. }
  5227. };
  5228. /**
  5229. * Opens / closes the chat area.
  5230. */
  5231. my.toggleChat = function() {
  5232. var chatCompleteFunction = Chat.isVisible() ?
  5233. function() {} : function () {
  5234. Chat.scrollChatToBottom();
  5235. $('#chatspace').trigger('shown');
  5236. };
  5237. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  5238. toggle(Chat,
  5239. '#chatspace',
  5240. function () {
  5241. // Request the focus in the nickname field or the chat input field.
  5242. if ($('#nickname').css('visibility') === 'visible') {
  5243. $('#nickinput').focus();
  5244. } else {
  5245. $('#usermsg').focus();
  5246. }
  5247. },
  5248. null,
  5249. Chat.resizeChat,
  5250. null);
  5251. };
  5252. /**
  5253. * Opens / closes the contact list area.
  5254. */
  5255. my.toggleContactList = function () {
  5256. var completeFunction = ContactList.isVisible() ?
  5257. function() {} : function () { $('#contactlist').trigger('shown');};
  5258. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5259. toggle(ContactList,
  5260. '#contactlist',
  5261. null,
  5262. function() {
  5263. ContactList.setVisualNotification(false);
  5264. },
  5265. null);
  5266. };
  5267. /**
  5268. * Opens / closes the settings menu
  5269. */
  5270. my.toggleSettingsMenu = function() {
  5271. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5272. toggle(SettingsMenu,
  5273. '#settingsmenu',
  5274. null,
  5275. function() {
  5276. var settings = Settings.getSettings();
  5277. $('#setDisplayName').get(0).value = settings.displayName;
  5278. $('#setEmail').get(0).value = settings.email;
  5279. },
  5280. null);
  5281. };
  5282. /**
  5283. * Returns the size of the side panel.
  5284. */
  5285. my.getPanelSize = function () {
  5286. var availableHeight = window.innerHeight;
  5287. var availableWidth = window.innerWidth;
  5288. var panelWidth = 200;
  5289. if (availableWidth * 0.2 < 200) {
  5290. panelWidth = availableWidth * 0.2;
  5291. }
  5292. return [panelWidth, availableHeight];
  5293. };
  5294. my.isVisible = function() {
  5295. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5296. };
  5297. return my;
  5298. }(PanelToggler || {}));
  5299. module.exports = PanelToggler;
  5300. },{"../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){
  5301. /* global $, Util, nickname:true */
  5302. var Replacement = require("./Replacement");
  5303. var CommandsProcessor = require("./Commands");
  5304. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5305. var smileys = require("./smileys.json").smileys;
  5306. var NicknameHandler = require("../../util/NicknameHandler");
  5307. var UIUtil = require("../../util/UIUtil");
  5308. var UIEvents = require("../../../../service/UI/UIEvents");
  5309. var notificationInterval = false;
  5310. var unreadMessages = 0;
  5311. /**
  5312. * Shows/hides a visual notification, indicating that a message has arrived.
  5313. */
  5314. function setVisualNotification(show) {
  5315. var unreadMsgElement = document.getElementById('unreadMessages');
  5316. var unreadMsgBottomElement
  5317. = document.getElementById('bottomUnreadMessages');
  5318. var glower = $('#chatButton');
  5319. var bottomGlower = $('#chatBottomButton');
  5320. if (unreadMessages) {
  5321. unreadMsgElement.innerHTML = unreadMessages.toString();
  5322. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5323. ToolbarToggler.dockToolbar(true);
  5324. var chatButtonElement
  5325. = document.getElementById('chatButton').parentNode;
  5326. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5327. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5328. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5329. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5330. unreadMsgElement.setAttribute(
  5331. 'style',
  5332. 'top:' + topIndent +
  5333. '; left:' + leftIndent + ';');
  5334. var chatBottomButtonElement
  5335. = document.getElementById('chatBottomButton').parentNode;
  5336. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5337. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5338. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5339. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5340. unreadMsgBottomElement.setAttribute(
  5341. 'style',
  5342. 'top:' + bottomTopIndent +
  5343. '; left:' + bottomLeftIndent + ';');
  5344. if (!glower.hasClass('icon-chat-simple')) {
  5345. glower.removeClass('icon-chat');
  5346. glower.addClass('icon-chat-simple');
  5347. }
  5348. }
  5349. else {
  5350. unreadMsgElement.innerHTML = '';
  5351. unreadMsgBottomElement.innerHTML = '';
  5352. glower.removeClass('icon-chat-simple');
  5353. glower.addClass('icon-chat');
  5354. }
  5355. if (show && !notificationInterval) {
  5356. notificationInterval = window.setInterval(function () {
  5357. glower.toggleClass('active');
  5358. bottomGlower.toggleClass('active glowing');
  5359. }, 800);
  5360. }
  5361. else if (!show && notificationInterval) {
  5362. window.clearInterval(notificationInterval);
  5363. notificationInterval = false;
  5364. glower.removeClass('active');
  5365. bottomGlower.removeClass('glowing');
  5366. bottomGlower.addClass('active');
  5367. }
  5368. }
  5369. /**
  5370. * Returns the current time in the format it is shown to the user
  5371. * @returns {string}
  5372. */
  5373. function getCurrentTime(stamp) {
  5374. var now = (stamp? new Date(stamp): new Date());
  5375. var hour = now.getHours();
  5376. var minute = now.getMinutes();
  5377. var second = now.getSeconds();
  5378. if(hour.toString().length === 1) {
  5379. hour = '0'+hour;
  5380. }
  5381. if(minute.toString().length === 1) {
  5382. minute = '0'+minute;
  5383. }
  5384. if(second.toString().length === 1) {
  5385. second = '0'+second;
  5386. }
  5387. return hour+':'+minute+':'+second;
  5388. }
  5389. function toggleSmileys()
  5390. {
  5391. var smileys = $('#smileysContainer');
  5392. if(!smileys.is(':visible')) {
  5393. smileys.show("slide", { direction: "down", duration: 300});
  5394. } else {
  5395. smileys.hide("slide", { direction: "down", duration: 300});
  5396. }
  5397. $('#usermsg').focus();
  5398. }
  5399. function addClickFunction(smiley, number) {
  5400. smiley.onclick = function addSmileyToMessage() {
  5401. var usermsg = $('#usermsg');
  5402. var message = usermsg.val();
  5403. message += smileys['smiley' + number];
  5404. usermsg.val(message);
  5405. usermsg.get(0).setSelectionRange(message.length, message.length);
  5406. toggleSmileys();
  5407. usermsg.focus();
  5408. };
  5409. }
  5410. /**
  5411. * Adds the smileys container to the chat
  5412. */
  5413. function addSmileys() {
  5414. var smileysContainer = document.createElement('div');
  5415. smileysContainer.id = 'smileysContainer';
  5416. for(var i = 1; i <= 21; i++) {
  5417. var smileyContainer = document.createElement('div');
  5418. smileyContainer.id = 'smiley' + i;
  5419. smileyContainer.className = 'smileyContainer';
  5420. var smiley = document.createElement('img');
  5421. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5422. smiley.className = 'smiley';
  5423. addClickFunction(smiley, i);
  5424. smileyContainer.appendChild(smiley);
  5425. smileysContainer.appendChild(smileyContainer);
  5426. }
  5427. $("#chatspace").append(smileysContainer);
  5428. }
  5429. /**
  5430. * Resizes the chat conversation.
  5431. */
  5432. function resizeChatConversation() {
  5433. var msgareaHeight = $('#usermsg').outerHeight();
  5434. var chatspace = $('#chatspace');
  5435. var width = chatspace.width();
  5436. var chat = $('#chatconversation');
  5437. var smileys = $('#smileysarea');
  5438. smileys.height(msgareaHeight);
  5439. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5440. $('#smileysContainer').css('bottom', msgareaHeight);
  5441. chat.width(width - 10);
  5442. chat.height(window.innerHeight - 15 - msgareaHeight);
  5443. }
  5444. /**
  5445. * Chat related user interface.
  5446. */
  5447. var Chat = (function (my) {
  5448. /**
  5449. * Initializes chat related interface.
  5450. */
  5451. my.init = function () {
  5452. if(NicknameHandler.getNickname())
  5453. Chat.setChatConversationMode(true);
  5454. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5455. function (nickname) {
  5456. Chat.setChatConversationMode(true);
  5457. });
  5458. $('#nickinput').keydown(function (event) {
  5459. if (event.keyCode === 13) {
  5460. event.preventDefault();
  5461. var val = UIUtil.escapeHtml(this.value);
  5462. this.value = '';
  5463. if (!NicknameHandler.getNickname()) {
  5464. NicknameHandler.setNickname(val);
  5465. return;
  5466. }
  5467. }
  5468. });
  5469. $('#usermsg').keydown(function (event) {
  5470. if (event.keyCode === 13) {
  5471. event.preventDefault();
  5472. var value = this.value;
  5473. $('#usermsg').val('').trigger('autosize.resize');
  5474. this.focus();
  5475. var command = new CommandsProcessor(value);
  5476. if(command.isCommand())
  5477. {
  5478. command.processCommand();
  5479. }
  5480. else
  5481. {
  5482. var message = UIUtil.escapeHtml(value);
  5483. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5484. }
  5485. }
  5486. });
  5487. var onTextAreaResize = function () {
  5488. resizeChatConversation();
  5489. Chat.scrollChatToBottom();
  5490. };
  5491. $('#usermsg').autosize({callback: onTextAreaResize});
  5492. $("#chatspace").bind("shown",
  5493. function () {
  5494. unreadMessages = 0;
  5495. setVisualNotification(false);
  5496. });
  5497. addSmileys();
  5498. };
  5499. /**
  5500. * Appends the given message to the chat conversation.
  5501. */
  5502. my.updateChatConversation = function (from, displayName, message, myjid, stamp) {
  5503. var divClassName = '';
  5504. if (APP.xmpp.myJid() === from) {
  5505. divClassName = "localuser";
  5506. }
  5507. else {
  5508. divClassName = "remoteuser";
  5509. if (!Chat.isVisible()) {
  5510. unreadMessages++;
  5511. UIUtil.playSoundNotification('chatNotification');
  5512. setVisualNotification(true);
  5513. }
  5514. }
  5515. // replace links and smileys
  5516. // Strophe already escapes special symbols on sending,
  5517. // so we escape here only tags to avoid double &amp;
  5518. var escMessage = message.replace(/</g, '&lt;').
  5519. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5520. var escDisplayName = UIUtil.escapeHtml(displayName);
  5521. message = Replacement.processReplacements(escMessage);
  5522. var messageContainer =
  5523. '<div class="chatmessage">'+
  5524. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5525. '<div class="username ' + divClassName +'">' + escDisplayName +
  5526. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5527. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5528. '</div>';
  5529. $('#chatconversation').append(messageContainer);
  5530. $('#chatconversation').animate(
  5531. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5532. };
  5533. /**
  5534. * Appends error message to the conversation
  5535. * @param errorMessage the received error message.
  5536. * @param originalText the original message.
  5537. */
  5538. my.chatAddError = function(errorMessage, originalText)
  5539. {
  5540. errorMessage = UIUtil.escapeHtml(errorMessage);
  5541. originalText = UIUtil.escapeHtml(originalText);
  5542. $('#chatconversation').append(
  5543. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5544. (originalText? (' \"'+ originalText + '\"') : "") +
  5545. ' was not sent.' +
  5546. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5547. $('#chatconversation').animate(
  5548. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5549. };
  5550. /**
  5551. * Sets the subject to the UI
  5552. * @param subject the subject
  5553. */
  5554. my.chatSetSubject = function(subject)
  5555. {
  5556. if(subject)
  5557. subject = subject.trim();
  5558. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5559. if(subject === "")
  5560. {
  5561. $("#subject").css({display: "none"});
  5562. }
  5563. else
  5564. {
  5565. $("#subject").css({display: "block"});
  5566. }
  5567. };
  5568. /**
  5569. * Sets the chat conversation mode.
  5570. */
  5571. my.setChatConversationMode = function (isConversationMode) {
  5572. if (isConversationMode) {
  5573. $('#nickname').css({visibility: 'hidden'});
  5574. $('#chatconversation').css({visibility: 'visible'});
  5575. $('#usermsg').css({visibility: 'visible'});
  5576. $('#smileysarea').css({visibility: 'visible'});
  5577. $('#usermsg').focus();
  5578. }
  5579. };
  5580. /**
  5581. * Resizes the chat area.
  5582. */
  5583. my.resizeChat = function () {
  5584. var chatSize = require("../SidePanelToggler").getPanelSize();
  5585. $('#chatspace').width(chatSize[0]);
  5586. $('#chatspace').height(chatSize[1]);
  5587. resizeChatConversation();
  5588. };
  5589. /**
  5590. * Indicates if the chat is currently visible.
  5591. */
  5592. my.isVisible = function () {
  5593. return $('#chatspace').is(":visible");
  5594. };
  5595. /**
  5596. * Shows and hides the window with the smileys
  5597. */
  5598. my.toggleSmileys = toggleSmileys;
  5599. /**
  5600. * Scrolls chat to the bottom.
  5601. */
  5602. my.scrollChatToBottom = function() {
  5603. setTimeout(function () {
  5604. $('#chatconversation').scrollTop(
  5605. $('#chatconversation')[0].scrollHeight);
  5606. }, 5);
  5607. };
  5608. return my;
  5609. }(Chat || {}));
  5610. module.exports = Chat;
  5611. },{"../../../../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){
  5612. var UIUtil = require("../../util/UIUtil");
  5613. /**
  5614. * List with supported commands. The keys are the names of the commands and
  5615. * the value is the function that processes the message.
  5616. * @type {{String: function}}
  5617. */
  5618. var commands = {
  5619. "topic" : processTopic
  5620. };
  5621. /**
  5622. * Extracts the command from the message.
  5623. * @param message the received message
  5624. * @returns {string} the command
  5625. */
  5626. function getCommand(message)
  5627. {
  5628. if(message)
  5629. {
  5630. for(var command in commands)
  5631. {
  5632. if(message.indexOf("/" + command) == 0)
  5633. return command;
  5634. }
  5635. }
  5636. return "";
  5637. };
  5638. /**
  5639. * Processes the data for topic command.
  5640. * @param commandArguments the arguments of the topic command.
  5641. */
  5642. function processTopic(commandArguments)
  5643. {
  5644. var topic = UIUtil.escapeHtml(commandArguments);
  5645. APP.xmpp.setSubject(topic);
  5646. }
  5647. /**
  5648. * Constructs new CommandProccessor instance from a message that
  5649. * handles commands received via chat messages.
  5650. * @param message the message
  5651. * @constructor
  5652. */
  5653. function CommandsProcessor(message)
  5654. {
  5655. var command = getCommand(message);
  5656. /**
  5657. * Returns the name of the command.
  5658. * @returns {String} the command
  5659. */
  5660. this.getCommand = function()
  5661. {
  5662. return command;
  5663. };
  5664. var messageArgument = message.substr(command.length + 2);
  5665. /**
  5666. * Returns the arguments of the command.
  5667. * @returns {string}
  5668. */
  5669. this.getArgument = function()
  5670. {
  5671. return messageArgument;
  5672. };
  5673. }
  5674. /**
  5675. * Checks whether this instance is valid command or not.
  5676. * @returns {boolean}
  5677. */
  5678. CommandsProcessor.prototype.isCommand = function()
  5679. {
  5680. if(this.getCommand())
  5681. return true;
  5682. return false;
  5683. };
  5684. /**
  5685. * Processes the command.
  5686. */
  5687. CommandsProcessor.prototype.processCommand = function()
  5688. {
  5689. if(!this.isCommand())
  5690. return;
  5691. commands[this.getCommand()](this.getArgument());
  5692. };
  5693. module.exports = CommandsProcessor;
  5694. },{"../../util/UIUtil":35}],25:[function(require,module,exports){
  5695. var Smileys = require("./smileys.json");
  5696. /**
  5697. * Processes links and smileys in "body"
  5698. */
  5699. function processReplacements(body)
  5700. {
  5701. //make links clickable
  5702. body = linkify(body);
  5703. //add smileys
  5704. body = smilify(body);
  5705. return body;
  5706. }
  5707. /**
  5708. * Finds and replaces all links in the links in "body"
  5709. * with their <a href=""></a>
  5710. */
  5711. function linkify(inputText)
  5712. {
  5713. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5714. //URLs starting with http://, https://, or ftp://
  5715. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5716. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5717. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5718. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5719. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5720. //Change email addresses to mailto:: links.
  5721. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5722. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5723. return replacedText;
  5724. }
  5725. /**
  5726. * Replaces common smiley strings with images
  5727. */
  5728. function smilify(body)
  5729. {
  5730. if(!body) {
  5731. return body;
  5732. }
  5733. var regexs = Smileys["regexs"];
  5734. for(var smiley in regexs) {
  5735. if(regexs.hasOwnProperty(smiley)) {
  5736. body = body.replace(regexs[smiley],
  5737. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5738. }
  5739. }
  5740. return body;
  5741. }
  5742. module.exports = {
  5743. processReplacements: processReplacements,
  5744. linkify: linkify
  5745. };
  5746. },{"./smileys.json":26}],26:[function(require,module,exports){
  5747. module.exports={
  5748. "smileys": {
  5749. "smiley1": ":)",
  5750. "smiley2": ":(",
  5751. "smiley3": ":D",
  5752. "smiley4": "(y)",
  5753. "smiley5": " :P",
  5754. "smiley6": "(wave)",
  5755. "smiley7": "(blush)",
  5756. "smiley8": "(chuckle)",
  5757. "smiley9": "(shocked)",
  5758. "smiley10": ":*",
  5759. "smiley11": "(n)",
  5760. "smiley12": "(search)",
  5761. "smiley13": " <3",
  5762. "smiley14": "(oops)",
  5763. "smiley15": "(angry)",
  5764. "smiley16": "(angel)",
  5765. "smiley17": "(sick)",
  5766. "smiley18": ";(",
  5767. "smiley19": "(bomb)",
  5768. "smiley20": "(clap)",
  5769. "smiley21": " ;)"
  5770. },
  5771. "regexs": {
  5772. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5773. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5774. "smiley1": /(:-\)|:\))/gi,
  5775. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5776. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5777. "smiley6": /(\(wave\))/gi,
  5778. "smiley7": /(\(blush\))/gi,
  5779. "smiley8": /(\(chuckle\))/gi,
  5780. "smiley9": /(:-0|\(shocked\))/gi,
  5781. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5782. "smiley11": /(\(n\))/gi,
  5783. "smiley12": /(\(search\))/g,
  5784. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5785. "smiley14": /(\(oops\))/gi,
  5786. "smiley15": /(\(angry\))/gi,
  5787. "smiley16": /(\(angel\))/gi,
  5788. "smiley17": /(\(sick\))/gi,
  5789. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5790. "smiley19": /(\(bomb\))/gi,
  5791. "smiley20": /(\(clap\))/gi,
  5792. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5793. }
  5794. }
  5795. },{}],27:[function(require,module,exports){
  5796. var numberOfContacts = 0;
  5797. var notificationInterval;
  5798. /**
  5799. * Updates the number of participants in the contact list button and sets
  5800. * the glow
  5801. * @param delta indicates whether a new user has joined (1) or someone has
  5802. * left(-1)
  5803. */
  5804. function updateNumberOfParticipants(delta) {
  5805. numberOfContacts += delta;
  5806. if (numberOfContacts === 1) {
  5807. // when the user is alone we don't show the number of participants
  5808. $("#numberOfParticipants").text('');
  5809. ContactList.setVisualNotification(false);
  5810. } else if (numberOfContacts > 1) {
  5811. ContactList.setVisualNotification(!ContactList.isVisible());
  5812. $("#numberOfParticipants").text(numberOfContacts);
  5813. } else {
  5814. console.error("Invalid number of participants: " + numberOfContacts);
  5815. }
  5816. }
  5817. /**
  5818. * Creates the avatar element.
  5819. *
  5820. * @return the newly created avatar element
  5821. */
  5822. function createAvatar(id) {
  5823. var avatar = document.createElement('img');
  5824. avatar.className = "icon-avatar avatar";
  5825. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  5826. return avatar;
  5827. }
  5828. /**
  5829. * Creates the display name paragraph.
  5830. *
  5831. * @param displayName the display name to set
  5832. */
  5833. function createDisplayNameParagraph(key, displayName) {
  5834. var p = document.createElement('p');
  5835. if(displayName)
  5836. p.innerText = displayName;
  5837. else if(key)
  5838. {
  5839. p.setAttribute("data-i18n",key);
  5840. p.innerText = APP.translation.translateString(key);
  5841. }
  5842. return p;
  5843. }
  5844. function stopGlowing(glower) {
  5845. window.clearInterval(notificationInterval);
  5846. notificationInterval = false;
  5847. glower.removeClass('glowing');
  5848. if (!ContactList.isVisible()) {
  5849. glower.removeClass('active');
  5850. }
  5851. }
  5852. /**
  5853. * Contact list.
  5854. */
  5855. var ContactList = {
  5856. /**
  5857. * Indicates if the chat is currently visible.
  5858. *
  5859. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5860. * otherwise
  5861. */
  5862. isVisible: function () {
  5863. return $('#contactlist').is(":visible");
  5864. },
  5865. /**
  5866. * Adds a contact for the given peerJid if such doesn't yet exist.
  5867. *
  5868. * @param peerJid the peerJid corresponding to the contact
  5869. * @param id the user's email or userId used to get the user's avatar
  5870. */
  5871. ensureAddContact: function (peerJid, id) {
  5872. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5873. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5874. if (!contact || contact.length <= 0)
  5875. ContactList.addContact(peerJid, id);
  5876. },
  5877. /**
  5878. * Adds a contact for the given peer jid.
  5879. *
  5880. * @param peerJid the jid of the contact to add
  5881. * @param id the email or userId of the user
  5882. */
  5883. addContact: function (peerJid, id) {
  5884. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5885. var contactlist = $('#contacts');
  5886. var newContact = document.createElement('li');
  5887. newContact.id = resourceJid;
  5888. newContact.className = "clickable";
  5889. newContact.onclick = function (event) {
  5890. if (event.currentTarget.className === "clickable") {
  5891. $(ContactList).trigger('contactclicked', [peerJid]);
  5892. }
  5893. };
  5894. newContact.appendChild(createAvatar(id));
  5895. newContact.appendChild(createDisplayNameParagraph("participant"));
  5896. if (resourceJid === APP.xmpp.myResource()) {
  5897. contactlist.prepend(newContact);
  5898. }
  5899. else {
  5900. contactlist.append(newContact);
  5901. }
  5902. updateNumberOfParticipants(1);
  5903. },
  5904. /**
  5905. * Removes a contact for the given peer jid.
  5906. *
  5907. * @param peerJid the peerJid corresponding to the contact to remove
  5908. */
  5909. removeContact: function (peerJid) {
  5910. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5911. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5912. if (contact && contact.length > 0) {
  5913. var contactlist = $('#contactlist>ul');
  5914. contactlist.get(0).removeChild(contact.get(0));
  5915. updateNumberOfParticipants(-1);
  5916. }
  5917. },
  5918. setVisualNotification: function (show, stopGlowingIn) {
  5919. var glower = $('#contactListButton');
  5920. if (show && !notificationInterval) {
  5921. notificationInterval = window.setInterval(function () {
  5922. glower.toggleClass('active glowing');
  5923. }, 800);
  5924. }
  5925. else if (!show && notificationInterval) {
  5926. stopGlowing(glower);
  5927. }
  5928. if (stopGlowingIn) {
  5929. setTimeout(function () {
  5930. stopGlowing(glower);
  5931. }, stopGlowingIn);
  5932. }
  5933. },
  5934. setClickable: function (resourceJid, isClickable) {
  5935. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5936. if (isClickable) {
  5937. contact.addClass('clickable');
  5938. } else {
  5939. contact.removeClass('clickable');
  5940. }
  5941. },
  5942. onDisplayNameChange: function (peerJid, displayName) {
  5943. if (peerJid === 'localVideoContainer')
  5944. peerJid = APP.xmpp.myJid();
  5945. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5946. var contactName = $('#contacts #' + resourceJid + '>p');
  5947. if (contactName && displayName && displayName.length > 0)
  5948. contactName.html(displayName);
  5949. },
  5950. userAvatarChanged: function (resourceJid, contactListUrl) {
  5951. // set the avatar in the contact list
  5952. var contact = $('#' + resourceJid + '>img');
  5953. if (contact && contact.length > 0) {
  5954. contact.get(0).src = contactListUrl;
  5955. }
  5956. }
  5957. };
  5958. module.exports = ContactList;
  5959. },{}],28:[function(require,module,exports){
  5960. var Avatar = require("../../avatar/Avatar");
  5961. var Settings = require("./../../../settings/Settings");
  5962. var UIUtil = require("../../util/UIUtil");
  5963. var languages = require("../../../../service/translation/languages");
  5964. function generateLanguagesSelectBox()
  5965. {
  5966. var currentLang = APP.translation.getCurrentLanguage();
  5967. var html = "<select id=\"languages_selectbox\">";
  5968. var langArray = languages.getLanguages();
  5969. for(var i = 0; i < langArray.length; i++)
  5970. {
  5971. var lang = langArray[i];
  5972. html += "<option ";
  5973. if(lang === currentLang)
  5974. html += "selected ";
  5975. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5976. html += "</option>";
  5977. }
  5978. return html + "</select>";
  5979. }
  5980. var SettingsMenu = {
  5981. init: function () {
  5982. $("#startMutedOptions").before(generateLanguagesSelectBox());
  5983. APP.translation.translateElement($("#languages_selectbox"));
  5984. $('#settingsmenu>input').keyup(function(event){
  5985. if(event.keyCode === 13) {//enter
  5986. SettingsMenu.update();
  5987. }
  5988. });
  5989. if(APP.xmpp.isModerator())
  5990. {
  5991. $("#startMutedOptions").css("display", "block");
  5992. }
  5993. else
  5994. {
  5995. $("#startMutedOptions").css("display", "none");
  5996. }
  5997. $("#updateSettings").click(function () {
  5998. SettingsMenu.update();
  5999. });
  6000. },
  6001. onRoleChanged: function () {
  6002. if(APP.xmpp.isModerator())
  6003. {
  6004. $("#startMutedOptions").css("display", "block");
  6005. }
  6006. else
  6007. {
  6008. $("#startMutedOptions").css("display", "none");
  6009. }
  6010. },
  6011. setStartMuted: function (audio, video) {
  6012. $("#startAudioMuted").attr("checked", audio);
  6013. $("#startVideoMuted").attr("checked", video);
  6014. },
  6015. update: function() {
  6016. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  6017. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  6018. if(newDisplayName) {
  6019. var displayName = Settings.setDisplayName(newDisplayName);
  6020. APP.xmpp.addToPresence("displayName", displayName, true);
  6021. }
  6022. var language = $("#languages_selectbox").val();
  6023. APP.translation.setLanguage(language);
  6024. Settings.setLanguage(language);
  6025. APP.xmpp.addToPresence("email", newEmail);
  6026. var email = Settings.setEmail(newEmail);
  6027. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  6028. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  6029. APP.xmpp.addToPresence("startMuted",
  6030. [startAudioMuted, startVideoMuted]);
  6031. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  6032. },
  6033. isVisible: function() {
  6034. return $('#settingsmenu').is(':visible');
  6035. },
  6036. setDisplayName: function(newDisplayName) {
  6037. var displayName = Settings.setDisplayName(newDisplayName);
  6038. $('#setDisplayName').get(0).value = displayName;
  6039. },
  6040. onDisplayNameChange: function(peerJid, newDisplayName) {
  6041. if(peerJid === 'localVideoContainer' ||
  6042. peerJid === APP.xmpp.myJid()) {
  6043. this.setDisplayName(newDisplayName);
  6044. }
  6045. },
  6046. changeAvatar: function (thumbUrl) {
  6047. $('#avatar').get(0).src = thumbUrl;
  6048. }
  6049. };
  6050. module.exports = SettingsMenu;
  6051. },{"../../../../service/translation/languages":109,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":49}],29:[function(require,module,exports){
  6052. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6053. var buttonHandlers = {
  6054. "bottom_toolbar_contact_list": function () {
  6055. BottomToolbar.toggleContactList();
  6056. },
  6057. "bottom_toolbar_film_strip": function () {
  6058. BottomToolbar.toggleFilmStrip();
  6059. },
  6060. "bottom_toolbar_chat": function () {
  6061. BottomToolbar.toggleChat();
  6062. }
  6063. };
  6064. var BottomToolbar = (function (my) {
  6065. my.init = function () {
  6066. for(var k in buttonHandlers)
  6067. $("#" + k).click(buttonHandlers[k]);
  6068. };
  6069. my.toggleChat = function() {
  6070. PanelToggler.toggleChat();
  6071. };
  6072. my.toggleContactList = function() {
  6073. PanelToggler.toggleContactList();
  6074. };
  6075. my.toggleFilmStrip = function() {
  6076. var filmstrip = $("#remoteVideos");
  6077. filmstrip.toggleClass("hidden");
  6078. };
  6079. $(document).bind("remotevideo.resized", function (event, width, height) {
  6080. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  6081. $('#bottomToolbar').css({bottom: bottom + 'px'});
  6082. });
  6083. return my;
  6084. }(BottomToolbar || {}));
  6085. module.exports = BottomToolbar;
  6086. },{"../side_pannels/SidePanelToggler":22}],30:[function(require,module,exports){
  6087. /* global APP,$, buttonClick, config, lockRoom,
  6088. setSharedKey, Util */
  6089. var messageHandler = require("../util/MessageHandler");
  6090. var BottomToolbar = require("./BottomToolbar");
  6091. var Prezi = require("../prezi/Prezi");
  6092. var Etherpad = require("../etherpad/Etherpad");
  6093. var PanelToggler = require("../side_pannels/SidePanelToggler");
  6094. var Authentication = require("../authentication/Authentication");
  6095. var UIUtil = require("../util/UIUtil");
  6096. var AuthenticationEvents
  6097. = require("../../../service/authentication/AuthenticationEvents");
  6098. var roomUrl = null;
  6099. var sharedKey = '';
  6100. var UI = null;
  6101. var buttonHandlers =
  6102. {
  6103. "toolbar_button_mute": function () {
  6104. return APP.UI.toggleAudio();
  6105. },
  6106. "toolbar_button_camera": function () {
  6107. return APP.UI.toggleVideo();
  6108. },
  6109. /*"toolbar_button_authentication": function () {
  6110. return Toolbar.authenticateClicked();
  6111. },*/
  6112. "toolbar_button_record": function () {
  6113. return toggleRecording();
  6114. },
  6115. "toolbar_button_security": function () {
  6116. return Toolbar.openLockDialog();
  6117. },
  6118. "toolbar_button_link": function () {
  6119. return Toolbar.openLinkDialog();
  6120. },
  6121. "toolbar_button_chat": function () {
  6122. return BottomToolbar.toggleChat();
  6123. },
  6124. "toolbar_button_prezi": function () {
  6125. return Prezi.openPreziDialog();
  6126. },
  6127. "toolbar_button_etherpad": function () {
  6128. return Etherpad.toggleEtherpad(0);
  6129. },
  6130. "toolbar_button_desktopsharing": function () {
  6131. return APP.desktopsharing.toggleScreenSharing();
  6132. },
  6133. "toolbar_button_fullScreen": function()
  6134. {
  6135. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  6136. return Toolbar.toggleFullScreen();
  6137. },
  6138. "toolbar_button_sip": function () {
  6139. return callSipButtonClicked();
  6140. },
  6141. "toolbar_button_dialpad": function () {
  6142. return dialpadButtonClicked();
  6143. },
  6144. "toolbar_button_settings": function () {
  6145. PanelToggler.toggleSettingsMenu();
  6146. },
  6147. "toolbar_button_hangup": function () {
  6148. return hangup();
  6149. },
  6150. "toolbar_button_login": function () {
  6151. Toolbar.authenticateClicked();
  6152. },
  6153. "toolbar_button_logout": function () {
  6154. // Ask for confirmation
  6155. messageHandler.openTwoButtonDialog(
  6156. "dialog.logoutTitle",
  6157. null,
  6158. "dialog.logoutQuestion",
  6159. null,
  6160. false,
  6161. "dialog.Yes",
  6162. function (evt, yes) {
  6163. if (yes) {
  6164. APP.xmpp.logout(function (url) {
  6165. if (url) {
  6166. window.location.href = url;
  6167. } else {
  6168. hangup();
  6169. }
  6170. });
  6171. }
  6172. });
  6173. }
  6174. };
  6175. function hangup() {
  6176. APP.xmpp.disposeConference();
  6177. if(config.enableWelcomePage)
  6178. {
  6179. setTimeout(function()
  6180. {
  6181. window.localStorage.welcomePageDisabled = false;
  6182. window.location.pathname = "/";
  6183. }, 10000);
  6184. }
  6185. var title = APP.translation.generateTranslationHTML(
  6186. "dialog.sessTerminated");
  6187. var msg = APP.translation.generateTranslationHTML(
  6188. "dialog.hungUp");
  6189. var button = APP.translation.generateTranslationHTML(
  6190. "dialog.joinAgain");
  6191. var buttons = [];
  6192. buttons.push({title: button, value: true});
  6193. UI.messageHandler.openDialog(
  6194. title,
  6195. msg,
  6196. true,
  6197. buttons,
  6198. function(event, value, message, formVals)
  6199. {
  6200. window.location.reload();
  6201. return false;
  6202. }
  6203. );
  6204. }
  6205. /**
  6206. * Starts or stops the recording for the conference.
  6207. */
  6208. function toggleRecording() {
  6209. APP.xmpp.toggleRecording(function (callback) {
  6210. var msg = APP.translation.generateTranslationHTML(
  6211. "dialog.recordingToken");
  6212. var token = APP.translation.translateString("dialog.token");
  6213. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  6214. '<h2>' + msg + '</h2>' +
  6215. '<input name="recordingToken" type="text" ' +
  6216. ' data-i18n="[placeholder]dialog.token" ' +
  6217. 'placeholder="' + token + '" autofocus>',
  6218. false,
  6219. "dialog.Save",
  6220. function (e, v, m, f) {
  6221. if (v) {
  6222. var token = f.recordingToken;
  6223. if (token) {
  6224. callback(UIUtil.escapeHtml(token));
  6225. }
  6226. }
  6227. },
  6228. null,
  6229. function () { },
  6230. ':input:first'
  6231. );
  6232. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  6233. }
  6234. /**
  6235. * Locks / unlocks the room.
  6236. */
  6237. function lockRoom(lock) {
  6238. var currentSharedKey = '';
  6239. if (lock)
  6240. currentSharedKey = sharedKey;
  6241. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6242. // password is required
  6243. if (sharedKey)
  6244. {
  6245. console.log('set room password');
  6246. Toolbar.lockLockButton();
  6247. }
  6248. else
  6249. {
  6250. console.log('removed room password');
  6251. Toolbar.unlockLockButton();
  6252. }
  6253. }, function (err) {
  6254. console.warn('setting password failed', err);
  6255. messageHandler.showError("dialog.lockTitle",
  6256. "dialog.lockMessage");
  6257. Toolbar.setSharedKey('');
  6258. }, function () {
  6259. console.warn('room passwords not supported');
  6260. messageHandler.showError("dialog.warning",
  6261. "dialog.passwordNotSupported");
  6262. Toolbar.setSharedKey('');
  6263. });
  6264. };
  6265. /**
  6266. * Invite participants to conference.
  6267. */
  6268. function inviteParticipants() {
  6269. if (roomUrl === null)
  6270. return;
  6271. var sharedKeyText = "";
  6272. if (sharedKey && sharedKey.length > 0) {
  6273. sharedKeyText =
  6274. APP.translation.translateString("email.sharedKey",
  6275. {sharedKey: sharedKey});
  6276. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6277. }
  6278. var supportedBrowsers = "Chromium, Google Chrome " +
  6279. APP.translation.translateString("email.and") + " Opera";
  6280. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6281. var subject = APP.translation.translateString("email.subject",
  6282. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6283. var body = APP.translation.translateString("email.body",
  6284. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6285. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6286. body = body.replace(/\n/g, "%0D%0A");
  6287. if (window.localStorage.displayname) {
  6288. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6289. }
  6290. if (interfaceConfig.INVITATION_POWERED_BY) {
  6291. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6292. }
  6293. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6294. }
  6295. function dialpadButtonClicked()
  6296. {
  6297. //TODO show the dialpad window
  6298. }
  6299. function callSipButtonClicked()
  6300. {
  6301. var defaultNumber
  6302. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6303. var sipMsg = APP.translation.generateTranslationHTML(
  6304. "dialog.sipMsg");
  6305. messageHandler.openTwoButtonDialog(null, null, null,
  6306. '<h2>' + sipMsg + '</h2>' +
  6307. '<input name="sipNumber" type="text"' +
  6308. ' value="' + defaultNumber + '" autofocus>',
  6309. false,
  6310. "dialog.Dial",
  6311. function (e, v, m, f) {
  6312. if (v) {
  6313. var numberInput = f.sipNumber;
  6314. if (numberInput) {
  6315. APP.xmpp.dial(
  6316. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6317. }
  6318. }
  6319. },
  6320. null, null, ':input:first'
  6321. );
  6322. }
  6323. var Toolbar = (function (my) {
  6324. my.init = function (ui) {
  6325. for(var k in buttonHandlers)
  6326. $("#" + k).click(buttonHandlers[k]);
  6327. UI = ui;
  6328. // Update login info
  6329. APP.xmpp.addListener(
  6330. AuthenticationEvents.IDENTITY_UPDATED,
  6331. function (authenticationEnabled, userIdentity) {
  6332. var loggedIn = false;
  6333. if (userIdentity) {
  6334. loggedIn = true;
  6335. }
  6336. Toolbar.showAuthenticateButton(authenticationEnabled);
  6337. if (authenticationEnabled) {
  6338. Toolbar.setAuthenticatedIdentity(userIdentity);
  6339. Toolbar.showLoginButton(!loggedIn);
  6340. Toolbar.showLogoutButton(loggedIn);
  6341. }
  6342. }
  6343. );
  6344. },
  6345. /**
  6346. * Sets shared key
  6347. * @param sKey the shared key
  6348. */
  6349. my.setSharedKey = function (sKey) {
  6350. sharedKey = sKey;
  6351. };
  6352. my.authenticateClicked = function () {
  6353. Authentication.focusAuthenticationWindow();
  6354. if (!APP.xmpp.isExternalAuthEnabled()) {
  6355. Authentication.xmppAuthenticate();
  6356. return;
  6357. }
  6358. // Get authentication URL
  6359. if (!APP.xmpp.getMUCJoined()) {
  6360. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6361. // If conference has not been started yet - redirect to login page
  6362. window.location.href = url;
  6363. });
  6364. } else {
  6365. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6366. // Otherwise - open popup with authentication URL
  6367. var authenticationWindow = Authentication.createAuthenticationWindow(
  6368. function () {
  6369. // On popup closed - retry room allocation
  6370. APP.xmpp.allocateConferenceFocus(
  6371. APP.UI.getRoomName(),
  6372. function () { console.info("AUTH DONE"); }
  6373. );
  6374. }, url);
  6375. if (!authenticationWindow) {
  6376. messageHandler.openMessageDialog(
  6377. null, "dialog.popupError");
  6378. }
  6379. });
  6380. }
  6381. };
  6382. /**
  6383. * Updates the room invite url.
  6384. */
  6385. my.updateRoomUrl = function (newRoomUrl) {
  6386. roomUrl = newRoomUrl;
  6387. // If the invite dialog has been already opened we update the information.
  6388. var inviteLink = document.getElementById('inviteLinkRef');
  6389. if (inviteLink) {
  6390. inviteLink.value = roomUrl;
  6391. inviteLink.select();
  6392. $('#inviteLinkRef').parent()
  6393. .find('button[value=true]').prop('disabled', false);
  6394. }
  6395. };
  6396. /**
  6397. * Disables and enables some of the buttons.
  6398. */
  6399. my.setupButtonsFromConfig = function () {
  6400. if (config.disablePrezi)
  6401. {
  6402. $("#prezi_button").css({display: "none"});
  6403. }
  6404. };
  6405. /**
  6406. * Opens the lock room dialog.
  6407. */
  6408. my.openLockDialog = function () {
  6409. // Only the focus is able to set a shared key.
  6410. if (!APP.xmpp.isModerator()) {
  6411. if (sharedKey) {
  6412. messageHandler.openMessageDialog(null,
  6413. "dialog.passwordError");
  6414. } else {
  6415. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6416. }
  6417. } else {
  6418. if (sharedKey) {
  6419. messageHandler.openTwoButtonDialog(null, null,
  6420. "dialog.passwordCheck",
  6421. null,
  6422. false,
  6423. "dialog.Remove",
  6424. function (e, v) {
  6425. if (v) {
  6426. Toolbar.setSharedKey('');
  6427. lockRoom(false);
  6428. }
  6429. });
  6430. } else {
  6431. var msg = APP.translation.generateTranslationHTML(
  6432. "dialog.passwordMsg");
  6433. var yourPassword = APP.translation.translateString(
  6434. "dialog.yourPassword");
  6435. messageHandler.openTwoButtonDialog(null, null, null,
  6436. '<h2>' + msg + '</h2>' +
  6437. '<input name="lockKey" type="text"' +
  6438. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6439. 'placeholder="' + yourPassword + '" autofocus>',
  6440. false,
  6441. "dialog.Save",
  6442. function (e, v, m, f) {
  6443. if (v) {
  6444. var lockKey = f.lockKey;
  6445. if (lockKey) {
  6446. Toolbar.setSharedKey(
  6447. UIUtil.escapeHtml(lockKey));
  6448. lockRoom(true);
  6449. }
  6450. }
  6451. },
  6452. null, null, 'input:first'
  6453. );
  6454. }
  6455. }
  6456. };
  6457. /**
  6458. * Opens the invite link dialog.
  6459. */
  6460. my.openLinkDialog = function () {
  6461. var inviteAttreibutes;
  6462. if (roomUrl === null) {
  6463. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6464. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6465. } else {
  6466. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6467. }
  6468. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6469. null, null,
  6470. '<input id="inviteLinkRef" type="text" ' +
  6471. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6472. false,
  6473. "dialog.Invite",
  6474. function (e, v) {
  6475. if (v) {
  6476. if (roomUrl) {
  6477. inviteParticipants();
  6478. }
  6479. }
  6480. },
  6481. function (event) {
  6482. if (roomUrl) {
  6483. document.getElementById('inviteLinkRef').select();
  6484. } else {
  6485. if (event && event.target)
  6486. $(event.target)
  6487. .find('button[value=true]').prop('disabled', true);
  6488. }
  6489. }
  6490. );
  6491. };
  6492. /**
  6493. * Opens the settings dialog.
  6494. * FIXME: not used ?
  6495. */
  6496. my.openSettingsDialog = function () {
  6497. var settings1 = APP.translation.generateTranslationHTML(
  6498. "dialog.settings1");
  6499. var settings2 = APP.translation.generateTranslationHTML(
  6500. "dialog.settings2");
  6501. var settings3 = APP.translation.generateTranslationHTML(
  6502. "dialog.settings3");
  6503. var yourPassword = APP.translation.translateString(
  6504. "dialog.yourPassword");
  6505. messageHandler.openTwoButtonDialog(null,
  6506. '<h2>' + settings1 + '</h2>' +
  6507. '<input type="checkbox" id="initMuted">' +
  6508. settings2 + '<br/>' +
  6509. '<input type="checkbox" id="requireNicknames">' +
  6510. settings3 +
  6511. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6512. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6513. null,
  6514. null,
  6515. false,
  6516. "dialog.Save",
  6517. function () {
  6518. document.getElementById('lockKey').focus();
  6519. },
  6520. function (e, v) {
  6521. if (v) {
  6522. if ($('#initMuted').is(":checked")) {
  6523. // it is checked
  6524. }
  6525. if ($('#requireNicknames').is(":checked")) {
  6526. // it is checked
  6527. }
  6528. /*
  6529. var lockKey = document.getElementById('lockKey');
  6530. if (lockKey.value) {
  6531. setSharedKey(lockKey.value);
  6532. lockRoom(true);
  6533. }
  6534. */
  6535. }
  6536. }
  6537. );
  6538. };
  6539. /**
  6540. * Toggles the application in and out of full screen mode
  6541. * (a.k.a. presentation mode in Chrome).
  6542. */
  6543. my.toggleFullScreen = function () {
  6544. var fsElement = document.documentElement;
  6545. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6546. //Enter Full Screen
  6547. if (fsElement.mozRequestFullScreen) {
  6548. fsElement.mozRequestFullScreen();
  6549. }
  6550. else {
  6551. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6552. }
  6553. } else {
  6554. //Exit Full Screen
  6555. if (document.mozCancelFullScreen) {
  6556. document.mozCancelFullScreen();
  6557. } else {
  6558. document.webkitCancelFullScreen();
  6559. }
  6560. }
  6561. };
  6562. /**
  6563. * Unlocks the lock button state.
  6564. */
  6565. my.unlockLockButton = function () {
  6566. if ($("#lockIcon").hasClass("icon-security-locked"))
  6567. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6568. };
  6569. /**
  6570. * Updates the lock button state to locked.
  6571. */
  6572. my.lockLockButton = function () {
  6573. if ($("#lockIcon").hasClass("icon-security"))
  6574. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6575. };
  6576. /**
  6577. * Shows or hides authentication button
  6578. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6579. */
  6580. my.showAuthenticateButton = function (show) {
  6581. if (show) {
  6582. $('#authentication').css({display: "inline"});
  6583. }
  6584. else {
  6585. $('#authentication').css({display: "none"});
  6586. }
  6587. };
  6588. // Shows or hides the 'recording' button.
  6589. my.showRecordingButton = function (show) {
  6590. if (!config.enableRecording) {
  6591. return;
  6592. }
  6593. if (show) {
  6594. $('#recording').css({display: "inline"});
  6595. }
  6596. else {
  6597. $('#recording').css({display: "none"});
  6598. }
  6599. };
  6600. // Sets the state of the recording button
  6601. my.setRecordingButtonState = function (isRecording) {
  6602. var selector = $('#recordButton');
  6603. if (isRecording) {
  6604. selector.removeClass("icon-recEnable");
  6605. selector.addClass("icon-recEnable active");
  6606. } else {
  6607. selector.removeClass("icon-recEnable active");
  6608. selector.addClass("icon-recEnable");
  6609. }
  6610. };
  6611. // Shows or hides SIP calls button
  6612. my.showSipCallButton = function (show) {
  6613. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6614. $('#sipCallButton').css({display: "inline-block"});
  6615. } else {
  6616. $('#sipCallButton').css({display: "none"});
  6617. }
  6618. };
  6619. // Shows or hides the dialpad button
  6620. my.showDialPadButton = function (show) {
  6621. if (show) {
  6622. $('#dialPadButton').css({display: "inline-block"});
  6623. } else {
  6624. $('#dialPadButton').css({display: "none"});
  6625. }
  6626. };
  6627. /**
  6628. * Displays user authenticated identity name(login).
  6629. * @param authIdentity identity name to be displayed.
  6630. */
  6631. my.setAuthenticatedIdentity = function (authIdentity) {
  6632. if (authIdentity) {
  6633. var selector = $('#toolbar_auth_identity');
  6634. selector.css({display: "list-item"});
  6635. selector.text(authIdentity);
  6636. } else {
  6637. $('#toolbar_auth_identity').css({display: "none"});
  6638. }
  6639. };
  6640. /**
  6641. * Shows/hides login button.
  6642. * @param show <tt>true</tt> to show
  6643. */
  6644. my.showLoginButton = function (show) {
  6645. if (show) {
  6646. $('#toolbar_button_login').css({display: "list-item"});
  6647. } else {
  6648. $('#toolbar_button_login').css({display: "none"});
  6649. }
  6650. };
  6651. /**
  6652. * Shows/hides logout button.
  6653. * @param show <tt>true</tt> to show
  6654. */
  6655. my.showLogoutButton = function (show) {
  6656. if (show) {
  6657. $('#toolbar_button_logout').css({display: "list-item"});
  6658. } else {
  6659. $('#toolbar_button_logout').css({display: "none"});
  6660. }
  6661. };
  6662. /**
  6663. * Sets the state of the button. The button has blue glow if desktop
  6664. * streaming is active.
  6665. * @param active the state of the desktop streaming.
  6666. */
  6667. my.changeDesktopSharingButtonState = function (active) {
  6668. var button = $("#desktopsharing > a");
  6669. if (active)
  6670. {
  6671. button.addClass("glow");
  6672. }
  6673. else
  6674. {
  6675. button.removeClass("glow");
  6676. }
  6677. };
  6678. return my;
  6679. }(Toolbar || {}));
  6680. module.exports = Toolbar;
  6681. },{"../../../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){
  6682. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  6683. var toolbarTimeoutObject,
  6684. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6685. function showDesktopSharingButton() {
  6686. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6687. $('#desktopsharing').css({display: "inline"});
  6688. } else {
  6689. $('#desktopsharing').css({display: "none"});
  6690. }
  6691. }
  6692. /**
  6693. * Hides the toolbar.
  6694. */
  6695. function hideToolbar() {
  6696. if(config.alwaysVisibleToolbar)
  6697. return;
  6698. var header = $("#header"),
  6699. bottomToolbar = $("#bottomToolbar");
  6700. var isToolbarHover = false;
  6701. header.find('*').each(function () {
  6702. var id = $(this).attr('id');
  6703. if ($("#" + id + ":hover").length > 0) {
  6704. isToolbarHover = true;
  6705. }
  6706. });
  6707. if ($("#bottomToolbar:hover").length > 0) {
  6708. isToolbarHover = true;
  6709. }
  6710. clearTimeout(toolbarTimeoutObject);
  6711. toolbarTimeoutObject = null;
  6712. if (!isToolbarHover) {
  6713. header.hide("slide", { direction: "up", duration: 300});
  6714. $('#subject').animate({top: "-=40"}, 300);
  6715. if ($("#remoteVideos").hasClass("hidden")) {
  6716. bottomToolbar.hide(
  6717. "slide", {direction: "right", duration: 300});
  6718. }
  6719. }
  6720. else {
  6721. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6722. }
  6723. }
  6724. var ToolbarToggler = {
  6725. /**
  6726. * Shows the main toolbar.
  6727. */
  6728. showToolbar: function () {
  6729. var header = $("#header"),
  6730. bottomToolbar = $("#bottomToolbar");
  6731. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6732. header.show("slide", { direction: "up", duration: 300});
  6733. $('#subject').animate({top: "+=40"}, 300);
  6734. if (!bottomToolbar.is(":visible")) {
  6735. bottomToolbar.show(
  6736. "slide", {direction: "right", duration: 300});
  6737. }
  6738. if (toolbarTimeoutObject) {
  6739. clearTimeout(toolbarTimeoutObject);
  6740. toolbarTimeoutObject = null;
  6741. }
  6742. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6743. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6744. }
  6745. if (APP.xmpp.isModerator())
  6746. {
  6747. // TODO: Enable settings functionality.
  6748. // Need to uncomment the settings button in index.html.
  6749. // $('#settingsButton').css({visibility:"visible"});
  6750. }
  6751. // Show/hide desktop sharing button
  6752. showDesktopSharingButton();
  6753. },
  6754. /**
  6755. * Docks/undocks the toolbar.
  6756. *
  6757. * @param isDock indicates what operation to perform
  6758. */
  6759. dockToolbar: function (isDock) {
  6760. if (isDock) {
  6761. // First make sure the toolbar is shown.
  6762. if (!$('#header').is(':visible')) {
  6763. this.showToolbar();
  6764. }
  6765. // Then clear the time out, to dock the toolbar.
  6766. if (toolbarTimeoutObject) {
  6767. clearTimeout(toolbarTimeoutObject);
  6768. toolbarTimeoutObject = null;
  6769. }
  6770. }
  6771. else {
  6772. if (!$('#header').is(':visible')) {
  6773. this.showToolbar();
  6774. }
  6775. else {
  6776. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6777. }
  6778. }
  6779. },
  6780. showDesktopSharingButton: showDesktopSharingButton
  6781. };
  6782. module.exports = ToolbarToggler;
  6783. },{}],32:[function(require,module,exports){
  6784. var JitsiPopover = (function () {
  6785. /**
  6786. * Constructs new JitsiPopover and attaches it to the element
  6787. * @param element jquery selector
  6788. * @param options the options for the popover.
  6789. * @constructor
  6790. */
  6791. function JitsiPopover(element, options)
  6792. {
  6793. this.options = {
  6794. skin: "white",
  6795. content: ""
  6796. };
  6797. if(options)
  6798. {
  6799. if(options.skin)
  6800. this.options.skin = options.skin;
  6801. if(options.content)
  6802. this.options.content = options.content;
  6803. }
  6804. this.elementIsHovered = false;
  6805. this.popoverIsHovered = false;
  6806. this.popoverShown = false;
  6807. element.data("jitsi_popover", this);
  6808. this.element = element;
  6809. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6810. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6811. '<div class="jitsiPopupmenuPadding"></div></div>';
  6812. var self = this;
  6813. this.element.on("mouseenter", function () {
  6814. self.elementIsHovered = true;
  6815. self.show();
  6816. }).on("mouseleave", function () {
  6817. self.elementIsHovered = false;
  6818. setTimeout(function () {
  6819. self.hide();
  6820. }, 10);
  6821. });
  6822. }
  6823. /**
  6824. * Shows the popover
  6825. */
  6826. JitsiPopover.prototype.show = function () {
  6827. this.createPopover();
  6828. this.popoverShown = true;
  6829. };
  6830. /**
  6831. * Hides the popover
  6832. */
  6833. JitsiPopover.prototype.hide = function () {
  6834. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  6835. {
  6836. this.forceHide();
  6837. }
  6838. };
  6839. /**
  6840. * Hides the popover
  6841. */
  6842. JitsiPopover.prototype.forceHide = function () {
  6843. $(".jitsipopover").remove();
  6844. this.popoverShown = false;
  6845. };
  6846. /**
  6847. * Creates the popover html
  6848. */
  6849. JitsiPopover.prototype.createPopover = function () {
  6850. $("body").append(this.template);
  6851. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6852. var self = this;
  6853. $(".jitsipopover").on("mouseenter", function () {
  6854. self.popoverIsHovered = true;
  6855. }).on("mouseleave", function () {
  6856. self.popoverIsHovered = false;
  6857. self.hide();
  6858. });
  6859. this.refreshPosition();
  6860. };
  6861. /**
  6862. * Refreshes the position of the popover
  6863. */
  6864. JitsiPopover.prototype.refreshPosition = function () {
  6865. $(".jitsipopover").position({
  6866. my: "bottom",
  6867. at: "top",
  6868. collision: "fit",
  6869. of: this.element,
  6870. using: function (position, elements) {
  6871. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  6872. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  6873. $(".jitsipopover > .arrow").css({left: calcLeft});
  6874. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  6875. }
  6876. });
  6877. };
  6878. /**
  6879. * Updates the content of popover.
  6880. * @param content new content
  6881. */
  6882. JitsiPopover.prototype.updateContent = function (content) {
  6883. this.options.content = content;
  6884. if(!this.popoverShown)
  6885. return;
  6886. $(".jitsipopover").remove();
  6887. this.createPopover();
  6888. };
  6889. return JitsiPopover;
  6890. })();
  6891. module.exports = JitsiPopover;
  6892. },{}],33:[function(require,module,exports){
  6893. /* global $, APP, jQuery, toastr */
  6894. var messageHandler = (function(my) {
  6895. /**
  6896. * Shows a message to the user.
  6897. *
  6898. * @param titleString the title of the message
  6899. * @param messageString the text of the message
  6900. */
  6901. my.openMessageDialog = function(titleKey, messageKey) {
  6902. var title = null;
  6903. if(titleKey)
  6904. {
  6905. title = APP.translation.generateTranslationHTML(titleKey);
  6906. }
  6907. var message = APP.translation.generateTranslationHTML(messageKey);
  6908. $.prompt(message,
  6909. {
  6910. title: title,
  6911. persistent: false
  6912. }
  6913. );
  6914. };
  6915. /**
  6916. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6917. *
  6918. * @param titleString the title of the message
  6919. * @param msgString the text of the message
  6920. * @param persistent boolean value which determines whether the message is persistent or not
  6921. * @param leftButton the fist button's text
  6922. * @param submitFunction function to be called on submit
  6923. * @param loadedFunction function to be called after the prompt is fully loaded
  6924. * @param closeFunction function to be called after the prompt is closed
  6925. * @param focus optional focus selector or button index to be focused after
  6926. * the dialog is opened
  6927. * @param defaultButton index of default button which will be activated when
  6928. * the user press 'enter'. Indexed from 0.
  6929. */
  6930. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6931. persistent, leftButtonKey, submitFunction, loadedFunction,
  6932. closeFunction, focus, defaultButton)
  6933. {
  6934. var buttons = [];
  6935. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6936. buttons.push({ title: leftButton, value: true});
  6937. var cancelButton
  6938. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6939. buttons.push({title: cancelButton, value: false});
  6940. var message = msgString, title = titleString;
  6941. if (titleKey)
  6942. {
  6943. title = APP.translation.generateTranslationHTML(titleKey);
  6944. }
  6945. if (msgKey) {
  6946. message = APP.translation.generateTranslationHTML(msgKey);
  6947. }
  6948. $.prompt(message, {
  6949. title: title,
  6950. persistent: false,
  6951. buttons: buttons,
  6952. defaultButton: defaultButton,
  6953. focus: focus,
  6954. loaded: loadedFunction,
  6955. submit: submitFunction,
  6956. close: closeFunction
  6957. });
  6958. };
  6959. /**
  6960. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6961. *
  6962. * @param titleString the title of the message
  6963. * @param msgString the text of the message
  6964. * @param persistent boolean value which determines whether the message is persistent or not
  6965. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  6966. * that will be passed to submitFunction
  6967. * @param submitFunction function to be called on submit
  6968. * @param loadedFunction function to be called after the prompt is fully loaded
  6969. */
  6970. my.openDialog = function (titleString, msgString, persistent, buttons,
  6971. submitFunction, loadedFunction) {
  6972. var args = {
  6973. title: titleString,
  6974. persistent: persistent,
  6975. buttons: buttons,
  6976. defaultButton: 1,
  6977. loaded: loadedFunction,
  6978. submit: submitFunction
  6979. };
  6980. if (persistent) {
  6981. args.closeText = '';
  6982. }
  6983. return new Impromptu(msgString, args);
  6984. };
  6985. /**
  6986. * Closes currently opened dialog.
  6987. */
  6988. my.closeDialog = function () {
  6989. $.prompt.close();
  6990. };
  6991. /**
  6992. * Shows a dialog with different states to the user.
  6993. *
  6994. * @param statesObject object containing all the states of the dialog
  6995. */
  6996. my.openDialogWithStates = function (statesObject, options) {
  6997. return new Impromptu(statesObject, options);
  6998. };
  6999. /**
  7000. * Opens new popup window for given <tt>url</tt> centered over current
  7001. * window.
  7002. *
  7003. * @param url the URL to be displayed in the popup window
  7004. * @param w the width of the popup window
  7005. * @param h the height of the popup window
  7006. * @param onPopupClosed optional callback function called when popup window
  7007. * has been closed.
  7008. *
  7009. * @returns popup window object if opened successfully or undefined
  7010. * in case we failed to open it(popup blocked)
  7011. */
  7012. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  7013. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  7014. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  7015. var popup = window.open(
  7016. url, '_blank',
  7017. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  7018. if (popup && onPopupClosed) {
  7019. var pollTimer = window.setInterval(function () {
  7020. if (popup.closed !== false) {
  7021. window.clearInterval(pollTimer);
  7022. onPopupClosed();
  7023. }
  7024. }, 200);
  7025. }
  7026. return popup;
  7027. };
  7028. /**
  7029. * Shows a dialog prompting the user to send an error report.
  7030. *
  7031. * @param titleString the title of the message
  7032. * @param msgString the text of the message
  7033. * @param error the error that is being reported
  7034. */
  7035. my.openReportDialog = function(titleKey, msgKey, error) {
  7036. my.openMessageDialog(titleKey, msgKey);
  7037. console.log(error);
  7038. //FIXME send the error to the server
  7039. };
  7040. /**
  7041. * Shows an error dialog to the user.
  7042. * @param title the title of the message
  7043. * @param message the text of the messafe
  7044. */
  7045. my.showError = function(titleKey, msgKey) {
  7046. if(!titleKey) {
  7047. titleKey = "dialog.oops";
  7048. }
  7049. if(!msgKey)
  7050. {
  7051. msgKey = "dialog.defaultError";
  7052. }
  7053. messageHandler.openMessageDialog(titleKey, msgKey);
  7054. };
  7055. my.notify = function(displayName, displayNameKey,
  7056. cls, messageKey, messageArguments, options) {
  7057. var displayNameSpan = '<span class="nickname" ';
  7058. if(displayName)
  7059. {
  7060. displayNameSpan += ">" + displayName;
  7061. }
  7062. else
  7063. {
  7064. displayNameSpan += "data-i18n='" + displayNameKey +
  7065. "'>" + APP.translation.translateString(displayNameKey);
  7066. }
  7067. displayNameSpan += "</span>";
  7068. toastr.info(
  7069. displayNameSpan + '<br>' +
  7070. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  7071. (messageArguments?
  7072. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  7073. : "") + ">" +
  7074. APP.translation.translateString(messageKey,
  7075. messageArguments) +
  7076. '</span>', null, options);
  7077. };
  7078. return my;
  7079. }(messageHandler || {}));
  7080. module.exports = messageHandler;
  7081. },{}],34:[function(require,module,exports){
  7082. var UIEvents = require("../../../service/UI/UIEvents");
  7083. var nickname = null;
  7084. var eventEmitter = null;
  7085. var NickanameHandler = {
  7086. init: function (emitter) {
  7087. eventEmitter = emitter;
  7088. var storedDisplayName = window.localStorage.displayname;
  7089. if (storedDisplayName) {
  7090. nickname = storedDisplayName;
  7091. }
  7092. },
  7093. setNickname: function (newNickname) {
  7094. if (!newNickname || nickname === newNickname)
  7095. return;
  7096. nickname = newNickname;
  7097. window.localStorage.displayname = nickname;
  7098. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  7099. },
  7100. getNickname: function () {
  7101. return nickname;
  7102. },
  7103. addListener: function (type, listener) {
  7104. eventEmitter.on(type, listener);
  7105. }
  7106. };
  7107. module.exports = NickanameHandler;
  7108. },{"../../../service/UI/UIEvents":104}],35:[function(require,module,exports){
  7109. /**
  7110. * Created by hristo on 12/22/14.
  7111. */
  7112. module.exports = {
  7113. /**
  7114. * Returns the available video width.
  7115. */
  7116. getAvailableVideoWidth: function (isVisible) {
  7117. var PanelToggler = require("../side_pannels/SidePanelToggler");
  7118. if(typeof isVisible === "undefined" || isVisible === null)
  7119. isVisible = PanelToggler.isVisible();
  7120. var rightPanelWidth
  7121. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  7122. return window.innerWidth - rightPanelWidth;
  7123. },
  7124. /**
  7125. * Changes the style class of the element given by id.
  7126. */
  7127. buttonClick: function(id, classname) {
  7128. $(id).toggleClass(classname); // add the class to the clicked element
  7129. },
  7130. /**
  7131. * Returns the text width for the given element.
  7132. *
  7133. * @param el the element
  7134. */
  7135. getTextWidth: function (el) {
  7136. return (el.clientWidth + 1);
  7137. },
  7138. /**
  7139. * Returns the text height for the given element.
  7140. *
  7141. * @param el the element
  7142. */
  7143. getTextHeight: function (el) {
  7144. return (el.clientHeight + 1);
  7145. },
  7146. /**
  7147. * Plays the sound given by id.
  7148. *
  7149. * @param id the identifier of the audio element.
  7150. */
  7151. playSoundNotification: function (id) {
  7152. document.getElementById(id).play();
  7153. },
  7154. /**
  7155. * Escapes the given text.
  7156. */
  7157. escapeHtml: function (unsafeText) {
  7158. return $('<div/>').text(unsafeText).html();
  7159. },
  7160. imageToGrayScale: function (canvas) {
  7161. var context = canvas.getContext('2d');
  7162. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  7163. var pixels = imgData.data;
  7164. for (var i = 0, n = pixels.length; i < n; i += 4) {
  7165. var grayscale
  7166. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  7167. pixels[i ] = grayscale; // red
  7168. pixels[i+1] = grayscale; // green
  7169. pixels[i+2] = grayscale; // blue
  7170. // pixels[i+3] is alpha
  7171. }
  7172. // redraw the image in black & white
  7173. context.putImageData(imgData, 0, 0);
  7174. },
  7175. setTooltip: function (element, key, position) {
  7176. element.setAttribute("data-i18n", "[data-content]" + key);
  7177. element.setAttribute("data-toggle", "popover");
  7178. element.setAttribute("data-placement", position);
  7179. element.setAttribute("data-html", true);
  7180. element.setAttribute("data-container", "body");
  7181. }
  7182. };
  7183. },{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){
  7184. var JitsiPopover = require("../util/JitsiPopover");
  7185. /**
  7186. * Constructs new connection indicator.
  7187. * @param videoContainer the video container associated with the indicator.
  7188. * @constructor
  7189. */
  7190. function ConnectionIndicator(videoContainer, jid)
  7191. {
  7192. this.videoContainer = videoContainer;
  7193. this.bandwidth = null;
  7194. this.packetLoss = null;
  7195. this.bitrate = null;
  7196. this.showMoreValue = false;
  7197. this.resolution = null;
  7198. this.transport = [];
  7199. this.popover = null;
  7200. this.jid = jid;
  7201. this.create();
  7202. }
  7203. /**
  7204. * Values for the connection quality
  7205. * @type {{98: string,
  7206. * 81: string,
  7207. * 64: string,
  7208. * 47: string,
  7209. * 30: string,
  7210. * 0: string}}
  7211. */
  7212. ConnectionIndicator.connectionQualityValues = {
  7213. 98: "18px", //full
  7214. 81: "15px",//4 bars
  7215. 64: "11px",//3 bars
  7216. 47: "7px",//2 bars
  7217. 30: "3px",//1 bar
  7218. 0: "0px"//empty
  7219. };
  7220. ConnectionIndicator.getIP = function(value)
  7221. {
  7222. return value.substring(0, value.lastIndexOf(":"));
  7223. };
  7224. ConnectionIndicator.getPort = function(value)
  7225. {
  7226. return value.substring(value.lastIndexOf(":") + 1, value.length);
  7227. };
  7228. ConnectionIndicator.getStringFromArray = function (array) {
  7229. var res = "";
  7230. for(var i = 0; i < array.length; i++)
  7231. {
  7232. res += (i === 0? "" : ", ") + array[i];
  7233. }
  7234. return res;
  7235. };
  7236. /**
  7237. * Generates the html content.
  7238. * @returns {string} the html content.
  7239. */
  7240. ConnectionIndicator.prototype.generateText = function () {
  7241. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7242. var translate = APP.translation.translateString;
  7243. if(this.bitrate === null)
  7244. {
  7245. downloadBitrate = "N/A";
  7246. uploadBitrate = "N/A";
  7247. }
  7248. else
  7249. {
  7250. downloadBitrate =
  7251. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7252. uploadBitrate =
  7253. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7254. }
  7255. if(this.packetLoss === null)
  7256. {
  7257. packetLoss = "N/A";
  7258. }
  7259. else
  7260. {
  7261. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7262. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  7263. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7264. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  7265. }
  7266. var resolutionValue = null;
  7267. if(this.resolution && this.jid != null)
  7268. {
  7269. var keys = Object.keys(this.resolution);
  7270. for(var ssrc in this.resolution)
  7271. {
  7272. resolutionValue = this.resolution[ssrc];
  7273. }
  7274. }
  7275. if(this.jid === null)
  7276. {
  7277. resolution = "";
  7278. if(this.resolution === null || !Object.keys(this.resolution) ||
  7279. Object.keys(this.resolution).length === 0)
  7280. {
  7281. resolution = "N/A";
  7282. }
  7283. else
  7284. for(i in this.resolution)
  7285. {
  7286. resolutionValue = this.resolution[i];
  7287. if(resolutionValue)
  7288. {
  7289. if(resolutionValue.height &&
  7290. resolutionValue.width)
  7291. {
  7292. resolution += (resolution === ""? "" : ", ") +
  7293. resolutionValue.width + "x" +
  7294. resolutionValue.height;
  7295. }
  7296. }
  7297. }
  7298. }
  7299. else if(!resolutionValue ||
  7300. !resolutionValue.height ||
  7301. !resolutionValue.width)
  7302. {
  7303. resolution = "N/A";
  7304. }
  7305. else
  7306. {
  7307. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7308. }
  7309. var result = "<table style='width:100%'>" +
  7310. "<tr>" +
  7311. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7312. translate("connectionindicator.bitrate") + "</span></td>" +
  7313. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7314. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7315. uploadBitrate + "</td>" +
  7316. "</tr><tr>" +
  7317. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7318. translate("connectionindicator.packetloss") + "</span></td>" +
  7319. "<td>" + packetLoss + "</td>" +
  7320. "</tr><tr>" +
  7321. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7322. translate("connectionindicator.resolution") + "</span></td>" +
  7323. "<td>" + resolution + "</td></tr></table>";
  7324. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7325. result += "<div class=\"jitsipopover_showmore\" " +
  7326. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7327. this.jid + "')\" data-i18n='connectionindicator." +
  7328. (this.showMoreValue ? "less" : "more") + "'>" +
  7329. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7330. "</div><br />";
  7331. }
  7332. if(this.showMoreValue)
  7333. {
  7334. var downloadBandwidth, uploadBandwidth, transport;
  7335. if(this.bandwidth === null)
  7336. {
  7337. downloadBandwidth = "N/A";
  7338. uploadBandwidth = "N/A";
  7339. }
  7340. else
  7341. {
  7342. downloadBandwidth = this.bandwidth.download?
  7343. this.bandwidth.download + " Kbps" :
  7344. "N/A";
  7345. uploadBandwidth = this.bandwidth.upload?
  7346. this.bandwidth.upload + " Kbps" :
  7347. "N/A";
  7348. }
  7349. if(!this.transport || this.transport.length === 0)
  7350. {
  7351. transport = "<tr>" +
  7352. "<td><span class='jitsipopover_blue' " +
  7353. "data-i18n='connectionindicator.address'>" +
  7354. translate("connectionindicator.address") + "</span></td>" +
  7355. "<td> N/A</td></tr>";
  7356. }
  7357. else
  7358. {
  7359. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7360. for(i = 0; i < this.transport.length; i++)
  7361. {
  7362. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7363. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7364. var localIP =
  7365. ConnectionIndicator.getIP(this.transport[i].localip);
  7366. var localPort =
  7367. ConnectionIndicator.getPort(this.transport[i].localip);
  7368. if(data.remoteIP.indexOf(ip) == -1)
  7369. {
  7370. data.remoteIP.push(ip);
  7371. }
  7372. if(data.remotePort.indexOf(port) == -1)
  7373. {
  7374. data.remotePort.push(port);
  7375. }
  7376. if(data.localIP.indexOf(localIP) == -1)
  7377. {
  7378. data.localIP.push(localIP);
  7379. }
  7380. if(data.localPort.indexOf(localPort) == -1)
  7381. {
  7382. data.localPort.push(localPort);
  7383. }
  7384. }
  7385. var local_address_key = "connectionindicator.localaddress";
  7386. var remote_address_key = "connectionindicator.remoteaddress";
  7387. var localTransport =
  7388. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7389. local_address_key +"' data-i18n-options='" +
  7390. JSON.stringify({count: data.localIP.length}) + "'>" +
  7391. translate(local_address_key, {count: data.localIP.length}) +
  7392. "</span></td><td> " +
  7393. ConnectionIndicator.getStringFromArray(data.localIP) +
  7394. "</td></tr>";
  7395. transport =
  7396. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7397. remote_address_key + "' data-i18n-options='" +
  7398. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7399. translate(remote_address_key,
  7400. {count: data.remoteIP.length}) +
  7401. "</span></td><td> " +
  7402. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7403. "</td></tr>";
  7404. var key_remote = "connectionindicator.remoteport",
  7405. key_local = "connectionindicator.localport";
  7406. transport += "<tr>" +
  7407. "<td>" +
  7408. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7409. "' data-i18n-options='" +
  7410. JSON.stringify({count: this.transport.length}) + "'>" +
  7411. translate(key_remote, {count: this.transport.length}) +
  7412. "</span></td><td>";
  7413. localTransport += "<tr>" +
  7414. "<td>" +
  7415. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7416. "' data-i18n-options='" +
  7417. JSON.stringify({count: this.transport.length}) + "'>" +
  7418. translate(key_local, {count: this.transport.length}) +
  7419. "</span></td><td>";
  7420. transport +=
  7421. ConnectionIndicator.getStringFromArray(data.remotePort);
  7422. localTransport +=
  7423. ConnectionIndicator.getStringFromArray(data.localPort);
  7424. transport += "</td></tr>";
  7425. transport += localTransport + "</td></tr>";
  7426. transport +="<tr>" +
  7427. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7428. translate("connectionindicator.transport") + "</span></td>" +
  7429. "<td>" + this.transport[0].type + "</td></tr>";
  7430. }
  7431. result += "<table style='width:100%'>" +
  7432. "<tr>" +
  7433. "<td>" +
  7434. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7435. translate("connectionindicator.bandwidth") + "</span>" +
  7436. "</td><td>" +
  7437. "<span class='jitsipopover_green'>&darr;</span>" +
  7438. downloadBandwidth +
  7439. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7440. uploadBandwidth + "</td></tr>";
  7441. result += transport + "</table>";
  7442. }
  7443. return result;
  7444. };
  7445. /**
  7446. * Shows or hide the additional information.
  7447. */
  7448. ConnectionIndicator.prototype.showMore = function () {
  7449. this.showMoreValue = !this.showMoreValue;
  7450. this.updatePopoverData();
  7451. };
  7452. function createIcon(classes)
  7453. {
  7454. var icon = document.createElement("span");
  7455. for(var i in classes)
  7456. {
  7457. icon.classList.add(classes[i]);
  7458. }
  7459. icon.appendChild(
  7460. document.createElement("i")).classList.add("icon-connection");
  7461. return icon;
  7462. }
  7463. /**
  7464. * Creates the indicator
  7465. */
  7466. ConnectionIndicator.prototype.create = function () {
  7467. this.connectionIndicatorContainer = document.createElement("div");
  7468. this.connectionIndicatorContainer.className = "connectionindicator";
  7469. this.connectionIndicatorContainer.style.display = "none";
  7470. this.videoContainer.container.appendChild(this.connectionIndicatorContainer);
  7471. this.popover = new JitsiPopover(
  7472. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7473. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7474. APP.translation.translateString("connectionindicator.na") + "</div>",
  7475. skin: "black"});
  7476. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7477. createIcon(["connection", "connection_empty"]));
  7478. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7479. createIcon(["connection", "connection_full"]));
  7480. };
  7481. /**
  7482. * Removes the indicator
  7483. */
  7484. ConnectionIndicator.prototype.remove = function()
  7485. {
  7486. if (this.connectionIndicatorContainer.parentNode) {
  7487. this.connectionIndicatorContainer.parentNode.removeChild(
  7488. this.connectionIndicatorContainer);
  7489. }
  7490. this.popover.forceHide();
  7491. };
  7492. /**
  7493. * Updates the data of the indicator
  7494. * @param percent the percent of connection quality
  7495. * @param object the statistics data.
  7496. */
  7497. ConnectionIndicator.prototype.updateConnectionQuality =
  7498. function (percent, object) {
  7499. if(percent === null)
  7500. {
  7501. this.connectionIndicatorContainer.style.display = "none";
  7502. this.popover.forceHide();
  7503. return;
  7504. }
  7505. else
  7506. {
  7507. if(this.connectionIndicatorContainer.style.display == "none") {
  7508. this.connectionIndicatorContainer.style.display = "block";
  7509. this.videoContainer.updateIconPositions();
  7510. }
  7511. }
  7512. this.bandwidth = object.bandwidth;
  7513. this.bitrate = object.bitrate;
  7514. this.packetLoss = object.packetLoss;
  7515. this.transport = object.transport;
  7516. if(object.resolution)
  7517. {
  7518. this.resolution = object.resolution;
  7519. }
  7520. for(var quality in ConnectionIndicator.connectionQualityValues)
  7521. {
  7522. if(percent >= quality)
  7523. {
  7524. this.fullIcon.style.width =
  7525. ConnectionIndicator.connectionQualityValues[quality];
  7526. }
  7527. }
  7528. this.updatePopoverData();
  7529. };
  7530. /**
  7531. * Updates the resolution
  7532. * @param resolution the new resolution
  7533. */
  7534. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7535. this.resolution = resolution;
  7536. this.updatePopoverData();
  7537. };
  7538. /**
  7539. * Updates the content of the popover
  7540. */
  7541. ConnectionIndicator.prototype.updatePopoverData = function () {
  7542. this.popover.updateContent(
  7543. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7544. APP.translation.translateElement($(".connection_info"));
  7545. };
  7546. /**
  7547. * Hides the popover
  7548. */
  7549. ConnectionIndicator.prototype.hide = function () {
  7550. this.popover.forceHide();
  7551. };
  7552. /**
  7553. * Hides the indicator
  7554. */
  7555. ConnectionIndicator.prototype.hideIndicator = function () {
  7556. this.connectionIndicatorContainer.style.display = "none";
  7557. if(this.popover)
  7558. this.popover.forceHide();
  7559. };
  7560. module.exports = ConnectionIndicator;
  7561. },{"../util/JitsiPopover":32}],37:[function(require,module,exports){
  7562. var Avatar = require("../avatar/Avatar");
  7563. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7564. var UIUtil = require("../util/UIUtil");
  7565. var UIEvents = require("../../../service/UI/UIEvents");
  7566. var xmpp = require("../../xmpp/xmpp");
  7567. // FIXME: With Temasys we have to re-select everytime
  7568. //var video = $('#largeVideo');
  7569. var currentVideoWidth = null;
  7570. var currentVideoHeight = null;
  7571. // By default we use camera
  7572. var getVideoSize = getCameraVideoSize;
  7573. var getVideoPosition = getCameraVideoPosition;
  7574. var currentSmallVideo = null;
  7575. var oldSmallVideo = null;
  7576. /**
  7577. * Sets the size and position of the given video element.
  7578. *
  7579. * @param video the video element to position
  7580. * @param width the desired video width
  7581. * @param height the desired video height
  7582. * @param horizontalIndent the left and right indent
  7583. * @param verticalIndent the top and bottom indent
  7584. */
  7585. function positionVideo(video,
  7586. width,
  7587. height,
  7588. horizontalIndent,
  7589. verticalIndent,
  7590. animate) {
  7591. if(animate)
  7592. {
  7593. video.animate({
  7594. width: width,
  7595. height: height,
  7596. top: verticalIndent,
  7597. bottom: verticalIndent,
  7598. left: horizontalIndent,
  7599. right: horizontalIndent
  7600. },
  7601. {
  7602. queue: false,
  7603. duration: 500
  7604. });
  7605. }
  7606. else
  7607. {
  7608. video.width(width);
  7609. video.height(height);
  7610. video.css({ top: verticalIndent + 'px',
  7611. bottom: verticalIndent + 'px',
  7612. left: horizontalIndent + 'px',
  7613. right: horizontalIndent + 'px'});
  7614. }
  7615. }
  7616. /**
  7617. * Returns an array of the video dimensions, so that it keeps it's aspect
  7618. * ratio and fits available area with it's larger dimension. This method
  7619. * ensures that whole video will be visible and can leave empty areas.
  7620. *
  7621. * @return an array with 2 elements, the video width and the video height
  7622. */
  7623. function getDesktopVideoSize(videoWidth,
  7624. videoHeight,
  7625. videoSpaceWidth,
  7626. videoSpaceHeight) {
  7627. if (!videoWidth)
  7628. videoWidth = currentVideoWidth;
  7629. if (!videoHeight)
  7630. videoHeight = currentVideoHeight;
  7631. var aspectRatio = videoWidth / videoHeight;
  7632. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7633. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7634. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7635. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7636. {
  7637. availableHeight = videoSpaceHeight;
  7638. availableWidth = availableHeight * aspectRatio;
  7639. }
  7640. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7641. {
  7642. availableWidth = videoSpaceWidth;
  7643. availableHeight = availableWidth / aspectRatio;
  7644. }
  7645. return [availableWidth, availableHeight];
  7646. }
  7647. /**
  7648. * Returns an array of the video horizontal and vertical indents,
  7649. * so that if fits its parent.
  7650. *
  7651. * @return an array with 2 elements, the horizontal indent and the vertical
  7652. * indent
  7653. */
  7654. function getCameraVideoPosition(videoWidth,
  7655. videoHeight,
  7656. videoSpaceWidth,
  7657. videoSpaceHeight) {
  7658. // Parent height isn't completely calculated when we position the video in
  7659. // full screen mode and this is why we use the screen height in this case.
  7660. // Need to think it further at some point and implement it properly.
  7661. var isFullScreen = document.fullScreen ||
  7662. document.mozFullScreen ||
  7663. document.webkitIsFullScreen;
  7664. if (isFullScreen)
  7665. videoSpaceHeight = window.innerHeight;
  7666. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7667. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7668. return [horizontalIndent, verticalIndent];
  7669. }
  7670. /**
  7671. * Returns an array of the video horizontal and vertical indents.
  7672. * Centers horizontally and top aligns vertically.
  7673. *
  7674. * @return an array with 2 elements, the horizontal indent and the vertical
  7675. * indent
  7676. */
  7677. function getDesktopVideoPosition(videoWidth,
  7678. videoHeight,
  7679. videoSpaceWidth,
  7680. videoSpaceHeight) {
  7681. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7682. var verticalIndent = 0;// Top aligned
  7683. return [horizontalIndent, verticalIndent];
  7684. }
  7685. /**
  7686. * Returns an array of the video dimensions, so that it covers the screen.
  7687. * It leaves no empty areas, but some parts of the video might not be visible.
  7688. *
  7689. * @return an array with 2 elements, the video width and the video height
  7690. */
  7691. function getCameraVideoSize(videoWidth,
  7692. videoHeight,
  7693. videoSpaceWidth,
  7694. videoSpaceHeight) {
  7695. if (!videoWidth)
  7696. videoWidth = currentVideoWidth;
  7697. if (!videoHeight)
  7698. videoHeight = currentVideoHeight;
  7699. var aspectRatio = videoWidth / videoHeight;
  7700. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7701. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7702. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7703. availableHeight = videoSpaceHeight;
  7704. availableWidth = availableHeight * aspectRatio;
  7705. }
  7706. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7707. availableWidth = videoSpaceWidth;
  7708. availableHeight = availableWidth / aspectRatio;
  7709. }
  7710. return [availableWidth, availableHeight];
  7711. }
  7712. /**
  7713. * Updates the src of the active speaker avatar
  7714. * @param jid of the current active speaker
  7715. */
  7716. function updateActiveSpeakerAvatarSrc() {
  7717. var avatar = $("#activeSpeakerAvatar")[0];
  7718. var jid = currentSmallVideo.peerJid;
  7719. var url = Avatar.getGravatarUrl(jid);
  7720. if(avatar.src === url)
  7721. return;
  7722. var isMuted = null;
  7723. if(!LargeVideo.VideoLayout.isInLastN(currentSmallVideo.resourceJid)) {
  7724. isMuted = true;
  7725. }
  7726. else
  7727. {
  7728. isMuted = APP.RTC.isVideoMuted(jid);
  7729. }
  7730. if (jid && isMuted !== null) {
  7731. avatar.src = url;
  7732. $("#largeVideo").css("visibility", isMuted ? "hidden" : "visible");
  7733. currentSmallVideo.showAvatar(isMuted);
  7734. }
  7735. }
  7736. function changeVideo(isVisible) {
  7737. updateActiveSpeakerAvatarSrc();
  7738. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7739. var videoTransform = document.getElementById('largeVideo')
  7740. .style.webkitTransform;
  7741. var flipX = currentSmallVideo.flipX;
  7742. if (flipX && videoTransform !== 'scaleX(-1)') {
  7743. document.getElementById('largeVideo').style.webkitTransform
  7744. = "scaleX(-1)";
  7745. }
  7746. else if (!flipX && videoTransform === 'scaleX(-1)') {
  7747. document.getElementById('largeVideo').style.webkitTransform
  7748. = "none";
  7749. }
  7750. var isDesktop = APP.RTC.isVideoSrcDesktop(currentSmallVideo.peerJid);
  7751. // Change the way we'll be measuring and positioning large video
  7752. getVideoSize = isDesktop
  7753. ? getDesktopVideoSize
  7754. : getCameraVideoSize;
  7755. getVideoPosition = isDesktop
  7756. ? getDesktopVideoPosition
  7757. : getCameraVideoPosition;
  7758. // Only if the large video is currently visible.
  7759. // Disable previous dominant speaker video.
  7760. if (oldSmallVideo) {
  7761. oldSmallVideo.enableDominantSpeaker(false);
  7762. }
  7763. // Enable new dominant speaker in the remote videos section.
  7764. if (currentSmallVideo) {
  7765. currentSmallVideo.enableDominantSpeaker(true);
  7766. }
  7767. if (isVisible) {
  7768. $('#largeVideo').fadeIn(300);
  7769. }
  7770. if(oldSmallVideo)
  7771. oldSmallVideo.showAvatar();
  7772. }
  7773. var LargeVideo = {
  7774. init: function (VideoLayout, emitter) {
  7775. this.VideoLayout = VideoLayout;
  7776. this.eventEmitter = emitter;
  7777. var self = this;
  7778. // Listen for large video size updates
  7779. var largeVideo = $('#largeVideo')[0];
  7780. var onplaying = function (arg1, arg2, arg3) {
  7781. // re-select
  7782. if (RTCBrowserType.isTemasysPluginUsed())
  7783. largeVideo = $('#largeVideo')[0];
  7784. currentVideoWidth = largeVideo.videoWidth;
  7785. currentVideoHeight = largeVideo.videoHeight;
  7786. self.position(currentVideoWidth, currentVideoHeight);
  7787. };
  7788. largeVideo.onplaying = onplaying;
  7789. },
  7790. /**
  7791. * Indicates if the large video is currently visible.
  7792. *
  7793. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7794. */
  7795. isLargeVideoVisible: function() {
  7796. return $('#largeVideo').is(':visible');
  7797. },
  7798. /**
  7799. * Updates the large video with the given new video source.
  7800. */
  7801. updateLargeVideo: function(resourceJid, forceUpdate) {
  7802. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7803. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7804. if ((currentSmallVideo && currentSmallVideo.resourceJid !== resourceJid)
  7805. || forceUpdate) {
  7806. $('#activeSpeaker').css('visibility', 'hidden');
  7807. if(currentSmallVideo) {
  7808. oldSmallVideo = currentSmallVideo;
  7809. } else {
  7810. oldSmallVideo = null;
  7811. }
  7812. currentSmallVideo = newSmallVideo;
  7813. var oldJid = null;
  7814. if(oldSmallVideo)
  7815. oldJid = oldSmallVideo.peerJid;
  7816. if (oldJid !== resourceJid) {
  7817. // we want the notification to trigger even if userJid is undefined,
  7818. // or null.
  7819. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  7820. resourceJid);
  7821. }
  7822. $('#largeVideo').fadeOut(300,
  7823. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7824. } else {
  7825. if(currentSmallVideo) {
  7826. currentSmallVideo.showAvatar();
  7827. }
  7828. }
  7829. },
  7830. /**
  7831. * Shows/hides the large video.
  7832. */
  7833. setLargeVideoVisible: function(isVisible) {
  7834. if (isVisible) {
  7835. $('#largeVideo').css({visibility: 'visible'});
  7836. $('.watermark').css({visibility: 'visible'});
  7837. if(currentSmallVideo)
  7838. currentSmallVideo.enableDominantSpeaker(true);
  7839. }
  7840. else {
  7841. $('#largeVideo').css({visibility: 'hidden'});
  7842. $('#activeSpeaker').css('visibility', 'hidden');
  7843. $('.watermark').css({visibility: 'hidden'});
  7844. if(currentSmallVideo)
  7845. currentSmallVideo.enableDominantSpeaker(false);
  7846. }
  7847. },
  7848. onVideoTypeChanged: function (jid) {
  7849. if(jid && currentSmallVideo && jid === currentSmallVideo.peerJid)
  7850. {
  7851. var isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7852. getVideoSize = isDesktop
  7853. ? getDesktopVideoSize
  7854. : getCameraVideoSize;
  7855. getVideoPosition = isDesktop
  7856. ? getDesktopVideoPosition
  7857. : getCameraVideoPosition;
  7858. this.position(null, null);
  7859. }
  7860. },
  7861. /**
  7862. * Positions the large video.
  7863. *
  7864. * @param videoWidth the stream video width
  7865. * @param videoHeight the stream video height
  7866. */
  7867. position: function (videoWidth, videoHeight,
  7868. videoSpaceWidth, videoSpaceHeight, animate) {
  7869. if(!videoSpaceWidth)
  7870. videoSpaceWidth = $('#videospace').width();
  7871. if(!videoSpaceHeight)
  7872. videoSpaceHeight = window.innerHeight;
  7873. var videoSize = getVideoSize(videoWidth,
  7874. videoHeight,
  7875. videoSpaceWidth,
  7876. videoSpaceHeight);
  7877. var largeVideoWidth = videoSize[0];
  7878. var largeVideoHeight = videoSize[1];
  7879. var videoPosition = getVideoPosition(largeVideoWidth,
  7880. largeVideoHeight,
  7881. videoSpaceWidth,
  7882. videoSpaceHeight);
  7883. var horizontalIndent = videoPosition[0];
  7884. var verticalIndent = videoPosition[1];
  7885. positionVideo($('#largeVideo'),
  7886. largeVideoWidth,
  7887. largeVideoHeight,
  7888. horizontalIndent, verticalIndent, animate);
  7889. },
  7890. isLargeVideoOnTop: function () {
  7891. var Etherpad = require("../etherpad/Etherpad");
  7892. var Prezi = require("../prezi/Prezi");
  7893. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  7894. },
  7895. resize: function (animate, isVisible, completeFunction) {
  7896. var availableHeight = window.innerHeight;
  7897. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7898. if (availableWidth < 0 || availableHeight < 0) return;
  7899. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7900. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7901. $('#activeSpeaker').css('top', top);
  7902. if(animate)
  7903. {
  7904. $('#videospace').animate({
  7905. right: window.innerWidth - availableWidth,
  7906. width: availableWidth,
  7907. height: availableHeight
  7908. },
  7909. {
  7910. queue: false,
  7911. duration: 500,
  7912. complete: completeFunction
  7913. });
  7914. $('#largeVideoContainer').animate({
  7915. width: availableWidth,
  7916. height: availableHeight
  7917. },
  7918. {
  7919. queue: false,
  7920. duration: 500
  7921. });
  7922. }
  7923. else
  7924. {
  7925. $('#videospace').width(availableWidth);
  7926. $('#videospace').height(availableHeight);
  7927. $('#largeVideoContainer').width(availableWidth);
  7928. $('#largeVideoContainer').height(availableHeight);
  7929. }
  7930. return [availableWidth, availableHeight];
  7931. },
  7932. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7933. var size = this.resize(true, isVisible, completeFunction);
  7934. this.position(null, null, size[0], size[1], true);
  7935. },
  7936. getResourceJid: function () {
  7937. if(!currentSmallVideo)
  7938. return null;
  7939. return currentSmallVideo.resourceJid;
  7940. },
  7941. updateAvatar: function (resourceJid) {
  7942. if (resourceJid === this.getResourceJid()) {
  7943. updateActiveSpeakerAvatarSrc();
  7944. }
  7945. },
  7946. showAvatar: function (resourceJid, show) {
  7947. if(this.getResourceJid() === resourceJid
  7948. && LargeVideo.isLargeVideoOnTop())
  7949. {
  7950. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7951. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7952. return true;
  7953. }
  7954. return false;
  7955. }
  7956. }
  7957. module.exports = LargeVideo;
  7958. },{"../../../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){
  7959. var SmallVideo = require("./SmallVideo");
  7960. var ConnectionIndicator = require("./ConnectionIndicator");
  7961. var NicknameHandler = require("../util/NicknameHandler");
  7962. var UIUtil = require("../util/UIUtil");
  7963. var LargeVideo = require("./LargeVideo");
  7964. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7965. function LocalVideo(VideoLayout)
  7966. {
  7967. this.videoSpanId = "localVideoContainer";
  7968. this.container = $("#localVideoContainer").get(0);
  7969. this.VideoLayout = VideoLayout;
  7970. this.flipX = true;
  7971. this.peerJid = null;
  7972. this.resourceJid = null;
  7973. }
  7974. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  7975. LocalVideo.prototype.constructor = LocalVideo;
  7976. /**
  7977. * Creates the edit display name button.
  7978. *
  7979. * @returns the edit button
  7980. */
  7981. function createEditDisplayNameButton() {
  7982. var editButton = document.createElement('a');
  7983. editButton.className = 'displayname';
  7984. UIUtil.setTooltip(editButton,
  7985. "videothumbnail.editnickname",
  7986. "top");
  7987. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  7988. return editButton;
  7989. }
  7990. /**
  7991. * Sets the display name for the given video span id.
  7992. */
  7993. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  7994. if (!this.container) {
  7995. console.warn(
  7996. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  7997. return;
  7998. }
  7999. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8000. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  8001. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8002. // If we already have a display name for this video.
  8003. if (nameSpan.length > 0) {
  8004. if (nameSpan.text() !== displayName) {
  8005. if (displayName && displayName.length > 0)
  8006. {
  8007. var meHTML = APP.translation.generateTranslationHTML("me");
  8008. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  8009. }
  8010. else
  8011. $('#localDisplayName').html(defaultLocalDisplayName);
  8012. }
  8013. } else {
  8014. var editButton = createEditDisplayNameButton();
  8015. nameSpan = document.createElement('span');
  8016. nameSpan.className = 'displayname';
  8017. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8018. if (displayName && displayName.length > 0) {
  8019. var meHTML = APP.translation.generateTranslationHTML("me");
  8020. nameSpan.innerHTML = displayName + meHTML;
  8021. }
  8022. else {
  8023. nameSpan.innerHTML = defaultLocalDisplayName;
  8024. }
  8025. nameSpan.id = 'localDisplayName';
  8026. this.container.appendChild(editButton);
  8027. //translates popover of edit button
  8028. APP.translation.translateElement($("a.displayname"));
  8029. var editableText = document.createElement('input');
  8030. editableText.className = 'displayname';
  8031. editableText.type = 'text';
  8032. editableText.id = 'editDisplayName';
  8033. if (displayName && displayName.length) {
  8034. editableText.value = displayName;
  8035. }
  8036. var defaultNickname = APP.translation.translateString(
  8037. "defaultNickname", {name: "Jane Pink"});
  8038. editableText.setAttribute('style', 'display:none;');
  8039. editableText.setAttribute('data-18n',
  8040. '[placeholder]defaultNickname');
  8041. editableText.setAttribute("data-i18n-options",
  8042. JSON.stringify({name: "Jane Pink"}));
  8043. editableText.setAttribute("placeholder", defaultNickname);
  8044. this.container.appendChild(editableText);
  8045. var self = this;
  8046. $('#localVideoContainer .displayname')
  8047. .bind("click", function (e) {
  8048. e.preventDefault();
  8049. e.stopPropagation();
  8050. $('#localDisplayName').hide();
  8051. $('#editDisplayName').show();
  8052. $('#editDisplayName').focus();
  8053. $('#editDisplayName').select();
  8054. $('#editDisplayName').one("focusout", function (e) {
  8055. self.VideoLayout.inputDisplayNameHandler(this.value);
  8056. });
  8057. $('#editDisplayName').on('keydown', function (e) {
  8058. if (e.keyCode === 13) {
  8059. e.preventDefault();
  8060. self.VideoLayout.inputDisplayNameHandler(this.value);
  8061. }
  8062. });
  8063. });
  8064. }
  8065. }
  8066. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  8067. NicknameHandler.setNickname(name);
  8068. if (!$('#localDisplayName').is(":visible")) {
  8069. if (NicknameHandler.getNickname())
  8070. {
  8071. var meHTML = APP.translation.generateTranslationHTML("me");
  8072. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  8073. }
  8074. else
  8075. {
  8076. var defaultHTML = APP.translation.generateTranslationHTML(
  8077. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8078. $('#localDisplayName')
  8079. .html(defaultHTML);
  8080. }
  8081. $('#localDisplayName').show();
  8082. }
  8083. $('#editDisplayName').hide();
  8084. }
  8085. LocalVideo.prototype.createConnectionIndicator = function()
  8086. {
  8087. if(this.connectionIndicator)
  8088. return;
  8089. this.connectionIndicator
  8090. = new ConnectionIndicator(this, null);
  8091. }
  8092. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  8093. var self = this;
  8094. function localVideoClick(event) {
  8095. // FIXME: with Temasys plugin event arg is not an event, but
  8096. // the clicked object itself, so we have to skip this call
  8097. if (event.stopPropagation) {
  8098. event.stopPropagation();
  8099. }
  8100. self.VideoLayout.handleVideoThumbClicked(
  8101. false,
  8102. APP.xmpp.myResource());
  8103. }
  8104. $('#localVideoContainer').off('click');
  8105. $('#localVideoContainer').on('click', localVideoClick);
  8106. // Add hover handler
  8107. $('#localVideoContainer').hover(
  8108. function() {
  8109. self.showDisplayName(true);
  8110. },
  8111. function() {
  8112. if (!LargeVideo.isLargeVideoVisible()
  8113. || APP.xmpp.myResource() !== LargeVideo.getResourceJid())
  8114. self.showDisplayName(false);
  8115. }
  8116. );
  8117. if(isMuted)
  8118. {
  8119. APP.UI.setVideoMute(true);
  8120. return;
  8121. }
  8122. this.flipX = (stream.videoType == "screen")? false : true;
  8123. var localVideo = document.createElement('video');
  8124. localVideo.id = 'localVideo_' +
  8125. APP.RTC.getStreamID(stream.getOriginalStream());
  8126. if (!RTCBrowserType.isIExplorer()) {
  8127. localVideo.autoplay = true;
  8128. localVideo.volume = 0; // is it required if audio is separated ?
  8129. }
  8130. localVideo.oncontextmenu = function () { return false; };
  8131. var localVideoContainer = document.getElementById('localVideoWrapper');
  8132. localVideoContainer.appendChild(localVideo);
  8133. var localVideoSelector = $('#' + localVideo.id);
  8134. // Add click handler to both video and video wrapper elements in case
  8135. // there's no video.
  8136. // onclick has to be used with Temasys plugin
  8137. localVideo.onclick = localVideoClick;
  8138. if (this.flipX) {
  8139. localVideoSelector.addClass("flipVideoX");
  8140. }
  8141. // Attach WebRTC stream
  8142. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  8143. // Add stream ended handler
  8144. stream.getOriginalStream().onended = function () {
  8145. // We have to re-select after attach when Temasys plugin is used,
  8146. // because <video> element is replaced with <object>
  8147. localVideo = $('#' + localVideo.id)[0];
  8148. localVideoContainer.removeChild(localVideo);
  8149. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  8150. };
  8151. }
  8152. LocalVideo.prototype.joined = function (jid) {
  8153. this.peerJid = jid;
  8154. this.resourceJid = Strophe.getResourceFromJid(jid);
  8155. }
  8156. module.exports = LocalVideo;
  8157. },{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){
  8158. var ConnectionIndicator = require("./ConnectionIndicator");
  8159. var SmallVideo = require("./SmallVideo");
  8160. var AudioLevels = require("../audio_levels/AudioLevels");
  8161. var LargeVideo = require("./LargeVideo");
  8162. var Avatar = require("../avatar/Avatar");
  8163. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8164. function RemoteVideo(peerJid, VideoLayout)
  8165. {
  8166. this.peerJid = peerJid;
  8167. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8168. this.videoSpanId = 'participant_' + this.resourceJid;
  8169. this.VideoLayout = VideoLayout;
  8170. this.addRemoteVideoContainer();
  8171. this.connectionIndicator = new ConnectionIndicator(
  8172. this, this.peerJid);
  8173. this.setDisplayName();
  8174. var nickfield = document.createElement('span');
  8175. nickfield.className = "nick";
  8176. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8177. this.container.appendChild(nickfield);
  8178. this.flipX = false;
  8179. }
  8180. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8181. RemoteVideo.prototype.constructor = RemoteVideo;
  8182. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8183. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8184. if (APP.xmpp.isModerator())
  8185. this.addRemoteVideoMenu();
  8186. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8187. return this.container;
  8188. };
  8189. /**
  8190. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8191. * given <tt>parentElement</tt>.
  8192. *
  8193. * @param jid the jid indicating the video for which we're adding a menu.
  8194. * @param parentElement the parent element where this menu will be added
  8195. */
  8196. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8197. var spanElement = document.createElement('span');
  8198. spanElement.className = 'remotevideomenu';
  8199. this.container.appendChild(spanElement);
  8200. var menuElement = document.createElement('i');
  8201. menuElement.className = 'fa fa-angle-down';
  8202. menuElement.title = 'Remote user controls';
  8203. spanElement.appendChild(menuElement);
  8204. var popupmenuElement = document.createElement('ul');
  8205. popupmenuElement.className = 'popupmenu';
  8206. popupmenuElement.id
  8207. = 'remote_popupmenu_' + this.resourceJid;
  8208. spanElement.appendChild(popupmenuElement);
  8209. var muteMenuItem = document.createElement('li');
  8210. var muteLinkItem = document.createElement('a');
  8211. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  8212. if (!this.isMuted) {
  8213. muteLinkItem.innerHTML = mutedIndicator +
  8214. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8215. muteLinkItem.className = 'mutelink';
  8216. }
  8217. else {
  8218. muteLinkItem.innerHTML = mutedIndicator +
  8219. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  8220. muteLinkItem.className = 'mutelink disabled';
  8221. }
  8222. var self = this;
  8223. muteLinkItem.onclick = function(){
  8224. if ($(this).attr('disabled') != undefined) {
  8225. event.preventDefault();
  8226. }
  8227. var isMute = self.isMuted == true;
  8228. APP.xmpp.setMute(self.peerJid, !isMute);
  8229. popupmenuElement.setAttribute('style', 'display:none;');
  8230. if (isMute) {
  8231. this.innerHTML = mutedIndicator +
  8232. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  8233. this.className = 'mutelink disabled';
  8234. }
  8235. else {
  8236. this.innerHTML = mutedIndicator +
  8237. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  8238. this.className = 'mutelink';
  8239. }
  8240. };
  8241. muteMenuItem.appendChild(muteLinkItem);
  8242. popupmenuElement.appendChild(muteMenuItem);
  8243. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8244. var ejectMenuItem = document.createElement('li');
  8245. var ejectLinkItem = document.createElement('a');
  8246. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8247. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8248. ejectLinkItem.onclick = function(){
  8249. APP.xmpp.eject(self.peerJid);
  8250. popupmenuElement.setAttribute('style', 'display:none;');
  8251. };
  8252. ejectMenuItem.appendChild(ejectLinkItem);
  8253. popupmenuElement.appendChild(ejectMenuItem);
  8254. var paddingSpan = document.createElement('span');
  8255. paddingSpan.className = 'popupmenuPadding';
  8256. popupmenuElement.appendChild(paddingSpan);
  8257. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  8258. }
  8259. /**
  8260. * Removes the remote stream element corresponding to the given stream and
  8261. * parent container.
  8262. *
  8263. * @param stream the stream
  8264. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8265. * @param container
  8266. */
  8267. RemoteVideo.prototype.removeRemoteStreamElement = function (stream, isVideo, id) {
  8268. if (!this.container)
  8269. return false;
  8270. var select = null;
  8271. if (isVideo) {
  8272. select = $('#' + id);
  8273. }
  8274. else
  8275. select = $('#' + this.videoSpanId + '>audio');
  8276. // Mark video as removed to cancel waiting loop(if video is removed
  8277. // before has started)
  8278. select.removed = true;
  8279. select.remove();
  8280. var audioCount = $('#' + this.videoSpanId + '>audio').length;
  8281. var videoCount = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName()).length;
  8282. if (!audioCount && !videoCount) {
  8283. console.log("Remove whole user", this.videoSpanId);
  8284. if(this.connectionIndicator)
  8285. this.connectionIndicator.remove();
  8286. // Remove whole container
  8287. if (this.container.parentNode)
  8288. this.container.parentNode.removeChild(this.container);
  8289. this.VideoLayout.resizeThumbnails();
  8290. }
  8291. if (isVideo)
  8292. this.VideoLayout.updateRemovedVideo(this.resourceJid);
  8293. };
  8294. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8295. if (!this.container)
  8296. return;
  8297. var self = this;
  8298. var isVideo = stream.getVideoTracks().length > 0;
  8299. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8300. var newElementId = streamElement.id;
  8301. this.container.appendChild(streamElement);
  8302. var sel = $('#' + newElementId);
  8303. sel.hide();
  8304. // If the container is currently visible we attach the stream.
  8305. if (!isVideo
  8306. || (this.container.offsetParent !== null && isVideo)) {
  8307. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8308. // when video playback starts
  8309. if (isVideo && stream.id !== 'mixedmslabel') {
  8310. var onPlayingHandler = function () {
  8311. // FIXME: why do i have to do this for FF?
  8312. if (RTCBrowserType.isFirefox()) {
  8313. APP.RTC.attachMediaStream(sel, stream);
  8314. }
  8315. if (RTCBrowserType.isTemasysPluginUsed()) {
  8316. sel = $('#' + newElementId);
  8317. }
  8318. self.VideoLayout.videoactive(sel, self.resourceJid);
  8319. sel[0].onplaying = null;
  8320. if (RTCBrowserType.isTemasysPluginUsed()) {
  8321. // 'currentTime' is used to check if the video has started
  8322. // and the value is not set by the plugin, so we do it
  8323. sel[0].currentTime = 1;
  8324. }
  8325. };
  8326. sel[0].onplaying = onPlayingHandler;
  8327. }
  8328. APP.RTC.attachMediaStream(sel, stream);
  8329. }
  8330. var self = this;
  8331. stream.onended = function () {
  8332. console.log('stream ended', this);
  8333. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8334. };
  8335. // Name of video element name is different for IE/Safari
  8336. var videoElem = APP.RTC.getVideoElementName();
  8337. // Add click handler.
  8338. var onClickHandler = function (event) {
  8339. /*
  8340. * FIXME It turns out that videoThumb may not exist (if there is
  8341. * no actual video).
  8342. */
  8343. var videoThumb = $('#' + self.videoSpanId + '>' + videoElem).get(0);
  8344. if (videoThumb) {
  8345. self.VideoLayout.handleVideoThumbClicked(
  8346. false,
  8347. self.resourceJid);
  8348. }
  8349. // On IE we need to populate this handler on video <object>
  8350. // and it does not give event instance as an argument,
  8351. // so we check here for methods.
  8352. if (event.stopPropagation && event.preventDefault) {
  8353. event.stopPropagation();
  8354. event.preventDefault();
  8355. }
  8356. return false;
  8357. };
  8358. this.container.onclick = onClickHandler;
  8359. // reselect
  8360. if (RTCBrowserType.isTemasysPluginUsed())
  8361. sel = $('#' + newElementId);
  8362. sel[0].onclick = onClickHandler;
  8363. //FIXME
  8364. // Add hover handler
  8365. $(this.container).hover(
  8366. function() {
  8367. self.showDisplayName(true);
  8368. },
  8369. function() {
  8370. var videoSrc = null;
  8371. var videoSelector = $('#' + self.videoSpanId + '>' + videoElem);
  8372. if (videoSelector && videoSelector.length > 0) {
  8373. videoSrc = APP.RTC.getVideoSrc(videoSelector.get(0));
  8374. }
  8375. // If the video has been "pinned" by the user we want to
  8376. // keep the display name on place.
  8377. if (!LargeVideo.isLargeVideoVisible()
  8378. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  8379. self.showDisplayName(false);
  8380. }
  8381. );
  8382. },
  8383. /**
  8384. * Show/hide peer container for the given resourceJid.
  8385. */
  8386. RemoteVideo.prototype.showPeerContainer = function (state) {
  8387. if (!this.container)
  8388. return;
  8389. var isHide = state === 'hide';
  8390. var resizeThumbnails = false;
  8391. if (!isHide) {
  8392. if (!$(this.container).is(':visible')) {
  8393. resizeThumbnails = true;
  8394. $(this.container).show();
  8395. }
  8396. this.showAvatar(state !== 'show');
  8397. }
  8398. else if ($(this.container).is(':visible') && isHide)
  8399. {
  8400. resizeThumbnails = true;
  8401. $(this.container).hide();
  8402. if(this.connectionIndicator)
  8403. this.connectionIndicator.hide();
  8404. }
  8405. if (resizeThumbnails) {
  8406. this.VideoLayout.resizeThumbnails();
  8407. }
  8408. // We want to be able to pin a participant from the contact list, even
  8409. // if he's not in the lastN set!
  8410. // ContactList.setClickable(resourceJid, !isHide);
  8411. };
  8412. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8413. if(this.connectionIndicator)
  8414. this.connectionIndicator.remove();
  8415. }
  8416. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8417. if(this.connectionIndicator)
  8418. this.connectionIndicator.hide();
  8419. }
  8420. /**
  8421. * Updates the remote video menu.
  8422. *
  8423. * @param jid the jid indicating the video for which we're adding a menu.
  8424. * @param isMuted indicates the current mute state
  8425. */
  8426. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8427. var muteMenuItem
  8428. = $('#remote_popupmenu_'
  8429. + this.resourceJid
  8430. + '>li>a.mutelink');
  8431. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8432. if (muteMenuItem.length) {
  8433. var muteLink = muteMenuItem.get(0);
  8434. if (isMuted === 'true') {
  8435. muteLink.innerHTML = mutedIndicator + ' Muted';
  8436. muteLink.className = 'mutelink disabled';
  8437. }
  8438. else {
  8439. muteLink.innerHTML = mutedIndicator + ' Mute';
  8440. muteLink.className = 'mutelink';
  8441. }
  8442. }
  8443. }
  8444. /**
  8445. * Sets the display name for the given video span id.
  8446. */
  8447. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8448. if (!this.container) {
  8449. console.warn(
  8450. "Unable to set displayName - " + this.videoSpanId + " does not exist");
  8451. return;
  8452. }
  8453. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8454. // If we already have a display name for this video.
  8455. if (nameSpan.length > 0) {
  8456. if (displayName && displayName.length > 0)
  8457. {
  8458. $('#' + this.videoSpanId + '_name').html(displayName);
  8459. }
  8460. else if (key && key.length > 0)
  8461. {
  8462. var nameHtml = APP.translation.generateTranslationHTML(key);
  8463. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8464. }
  8465. else
  8466. $('#' + this.videoSpanId + '_name').text(
  8467. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8468. } else {
  8469. nameSpan = document.createElement('span');
  8470. nameSpan.className = 'displayname';
  8471. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8472. if (displayName && displayName.length > 0) {
  8473. nameSpan.innerText = displayName;
  8474. }
  8475. else
  8476. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8477. nameSpan.id = this.videoSpanId + '_name';
  8478. }
  8479. }
  8480. /**
  8481. * Removes remote video menu element from video element identified by
  8482. * given <tt>videoElementId</tt>.
  8483. *
  8484. * @param videoElementId the id of local or remote video element.
  8485. */
  8486. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8487. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8488. if (menuSpan.length) {
  8489. menuSpan.remove();
  8490. }
  8491. }
  8492. RemoteVideo.createContainer = function (spanId) {
  8493. var container = document.createElement('span');
  8494. container.id = spanId;
  8495. container.className = 'videocontainer';
  8496. var remotes = document.getElementById('remoteVideos');
  8497. return remotes.appendChild(container);
  8498. };
  8499. module.exports = RemoteVideo;
  8500. },{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){
  8501. var UIUtil = require("../util/UIUtil");
  8502. var LargeVideo = require("./LargeVideo");
  8503. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8504. function SmallVideo(){
  8505. this.isMuted = false;
  8506. this.hasAvatar = false;
  8507. }
  8508. function setVisibility(selector, show) {
  8509. if (selector && selector.length > 0) {
  8510. selector.css("visibility", show ? "visible" : "hidden");
  8511. }
  8512. }
  8513. SmallVideo.prototype.showDisplayName = function(isShow) {
  8514. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8515. if (isShow) {
  8516. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8517. nameSpan.setAttribute("style", "display:inline-block;");
  8518. }
  8519. else {
  8520. if (nameSpan)
  8521. nameSpan.setAttribute("style", "display:none;");
  8522. }
  8523. };
  8524. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8525. if(!this.container)
  8526. return;
  8527. $("#" + this.videoSpanId + " > .noMic").remove();
  8528. $("#" + this.videoSpanId + " > .noVideo").remove();
  8529. if(!devices.audio)
  8530. {
  8531. this.container.appendChild(
  8532. document.createElement("div")).setAttribute("class","noMic");
  8533. }
  8534. if(!devices.video)
  8535. {
  8536. this.container.appendChild(
  8537. document.createElement("div")).setAttribute("class","noVideo");
  8538. }
  8539. if(!devices.audio && !devices.video)
  8540. {
  8541. $("#" + this.videoSpanId + " > .noMic").css("background-position", "75%");
  8542. $("#" + this.videoSpanId + " > .noVideo").css("background-position", "25%");
  8543. $("#" + this.videoSpanId + " > .noVideo").css("background-color", "transparent");
  8544. }
  8545. }
  8546. /**
  8547. * Shows the presence status message for the given video.
  8548. */
  8549. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8550. if (!this.container) {
  8551. // No container
  8552. return;
  8553. }
  8554. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8555. if (!statusSpan.length) {
  8556. //Add status span
  8557. statusSpan = document.createElement('span');
  8558. statusSpan.className = 'status';
  8559. statusSpan.id = this.videoSpanId + '_status';
  8560. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8561. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8562. }
  8563. // Display status
  8564. if (statusMsg && statusMsg.length) {
  8565. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8566. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8567. }
  8568. else {
  8569. // Hide
  8570. statusSpan.get(0).setAttribute("style", "display:none;");
  8571. }
  8572. };
  8573. /**
  8574. * Creates an audio or video stream element.
  8575. */
  8576. SmallVideo.createStreamElement = function (sid, stream) {
  8577. var isVideo = stream.getVideoTracks().length > 0;
  8578. var element = isVideo
  8579. ? document.createElement('video')
  8580. : document.createElement('audio');
  8581. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  8582. + sid + '_' + APP.RTC.getStreamID(stream);
  8583. element.id = id;
  8584. if (!RTCBrowserType.isIExplorer()) {
  8585. element.autoplay = true;
  8586. }
  8587. element.oncontextmenu = function () { return false; };
  8588. return element;
  8589. };
  8590. /**
  8591. * Updates the data for the indicator
  8592. * @param id the id of the indicator
  8593. * @param percent the percent for connection quality
  8594. * @param object the data
  8595. */
  8596. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8597. if(this.connectionIndicator)
  8598. this.connectionIndicator.updateConnectionQuality(percent, object);
  8599. }
  8600. SmallVideo.prototype.hideIndicator = function () {
  8601. if(this.connectionIndicator)
  8602. this.connectionIndicator.hideIndicator();
  8603. }
  8604. /**
  8605. * Shows audio muted indicator over small videos.
  8606. * @param {string} isMuted
  8607. */
  8608. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8609. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8610. if (!isMuted) {
  8611. if (audioMutedSpan.length > 0) {
  8612. audioMutedSpan.popover('hide');
  8613. audioMutedSpan.remove();
  8614. }
  8615. }
  8616. else {
  8617. if(audioMutedSpan.length == 0 ) {
  8618. audioMutedSpan = document.createElement('span');
  8619. audioMutedSpan.className = 'audioMuted';
  8620. UIUtil.setTooltip(audioMutedSpan,
  8621. "videothumbnail.mute",
  8622. "top");
  8623. this.container.appendChild(audioMutedSpan);
  8624. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8625. var mutedIndicator = document.createElement('i');
  8626. mutedIndicator.className = 'icon-mic-disabled';
  8627. audioMutedSpan.appendChild(mutedIndicator);
  8628. }
  8629. this.updateIconPositions();
  8630. }
  8631. this.isMuted = isMuted;
  8632. };
  8633. /**
  8634. * Shows video muted indicator over small videos.
  8635. */
  8636. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8637. this.showAvatar(isMuted);
  8638. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8639. if (isMuted === false) {
  8640. if (videoMutedSpan.length > 0) {
  8641. videoMutedSpan.remove();
  8642. }
  8643. }
  8644. else {
  8645. if(videoMutedSpan.length == 0) {
  8646. videoMutedSpan = document.createElement('span');
  8647. videoMutedSpan.className = 'videoMuted';
  8648. this.container.appendChild(videoMutedSpan);
  8649. var mutedIndicator = document.createElement('i');
  8650. mutedIndicator.className = 'icon-camera-disabled';
  8651. UIUtil.setTooltip(mutedIndicator,
  8652. "videothumbnail.videomute",
  8653. "top");
  8654. videoMutedSpan.appendChild(mutedIndicator);
  8655. //translate texts for muted indicator
  8656. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8657. }
  8658. this.updateIconPositions();
  8659. }
  8660. };
  8661. SmallVideo.prototype.enableDominantSpeaker = function (isEnable)
  8662. {
  8663. var displayName = this.resourceJid;
  8664. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8665. if (nameSpan.length > 0)
  8666. displayName = nameSpan.html();
  8667. console.log("UI enable dominant speaker",
  8668. displayName,
  8669. this.resourceJid,
  8670. isEnable);
  8671. if (!this.container) {
  8672. return;
  8673. }
  8674. var video = $('#' + this.videoSpanId + '>' + APP.RTC.getVideoElementName());
  8675. if (video && video.length > 0) {
  8676. if (isEnable) {
  8677. this.showDisplayName(LargeVideo.isLargeVideoOnTop());
  8678. if (!this.container.classList.contains("dominantspeaker"))
  8679. this.container.classList.add("dominantspeaker");
  8680. }
  8681. else {
  8682. this.showDisplayName(false);
  8683. if (this.container.classList.contains("dominantspeaker"))
  8684. this.container.classList.remove("dominantspeaker");
  8685. }
  8686. }
  8687. this.showAvatar();
  8688. };
  8689. SmallVideo.prototype.updateIconPositions = function () {
  8690. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8691. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8692. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8693. if(connectionIndicator.length > 0
  8694. && connectionIndicator[0].style.display != "none") {
  8695. audioMutedSpan.css({right: "23px"});
  8696. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8697. }
  8698. else
  8699. {
  8700. audioMutedSpan.css({right: "0px"});
  8701. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8702. }
  8703. }
  8704. /**
  8705. * Creates the element indicating the moderator(owner) of the conference.
  8706. *
  8707. * @param parentElement the parent element where the owner indicator will
  8708. * be added
  8709. */
  8710. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8711. // Show moderator indicator
  8712. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8713. if (!indicatorSpan || indicatorSpan.length === 0) {
  8714. indicatorSpan = document.createElement('span');
  8715. indicatorSpan.className = 'focusindicator';
  8716. this.container.appendChild(indicatorSpan);
  8717. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8718. }
  8719. if (indicatorSpan.children().length !== 0)
  8720. return;
  8721. var moderatorIndicator = document.createElement('i');
  8722. moderatorIndicator.className = 'fa fa-star';
  8723. indicatorSpan[0].appendChild(moderatorIndicator);
  8724. UIUtil.setTooltip(indicatorSpan[0],
  8725. "videothumbnail.moderator",
  8726. "top");
  8727. //translates text in focus indicators
  8728. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8729. }
  8730. SmallVideo.prototype.getSrc = function () {
  8731. var videoElement = APP.RTC.getVideoElementName();
  8732. return APP.RTC.getVideoSrc(
  8733. $('#' + this.videoSpanId).find(videoElement).get(0));
  8734. },
  8735. SmallVideo.prototype.focus = function(isFocused)
  8736. {
  8737. if(!isFocused) {
  8738. this.container.classList.remove("videoContainerFocused");
  8739. }
  8740. else
  8741. {
  8742. this.container.classList.add("videoContainerFocused");
  8743. }
  8744. }
  8745. SmallVideo.prototype.hasVideo = function () {
  8746. return $("#" + this.videoSpanId).find(
  8747. APP.RTC.getVideoElementName()).length !== 0;
  8748. }
  8749. /**
  8750. * Hides or shows the user's avatar
  8751. * @param show whether we should show the avatar or not
  8752. * video because there is no dominant speaker and no focused speaker
  8753. */
  8754. SmallVideo.prototype.showAvatar = function (show) {
  8755. if(!this.hasAvatar)
  8756. return;
  8757. var videoElem = APP.RTC.getVideoElementName();
  8758. var video = $('#' + this.videoSpanId).find(videoElem);
  8759. var avatar = $('#avatar_' + this.resourceJid);
  8760. if (show === undefined || show === null) {
  8761. if(!this.VideoLayout.isInLastN(this.resourceJid)) {
  8762. show = true;
  8763. }
  8764. else
  8765. {
  8766. show = APP.RTC.isVideoMuted(this.peerJid);
  8767. }
  8768. }
  8769. if (LargeVideo.showAvatar(this.resourceJid, show))
  8770. {
  8771. setVisibility(avatar, false);
  8772. setVisibility(video, false);
  8773. } else {
  8774. if (video && video.length > 0) {
  8775. setVisibility(video, !show);
  8776. }
  8777. setVisibility(avatar, show);
  8778. }
  8779. }
  8780. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8781. var thumbnail = $('#' + this.videoSpanId);
  8782. var avatar = $('#avatar_' + this.resourceJid);
  8783. this.hasAvatar = true;
  8784. // set the avatar in the thumbnail
  8785. if (avatar && avatar.length > 0) {
  8786. avatar[0].src = thumbUrl;
  8787. } else {
  8788. if (thumbnail && thumbnail.length > 0) {
  8789. avatar = document.createElement('img');
  8790. avatar.id = 'avatar_' + this.resourceJid;
  8791. avatar.className = 'userAvatar';
  8792. avatar.src = thumbUrl;
  8793. thumbnail.append(avatar);
  8794. }
  8795. }
  8796. }
  8797. module.exports = SmallVideo;
  8798. },{"../../RTC/RTCBrowserType":10,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){
  8799. var AudioLevels = require("../audio_levels/AudioLevels");
  8800. var Avatar = require("../avatar/Avatar");
  8801. var ContactList = require("../side_pannels/contactlist/ContactList");
  8802. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8803. var UIEvents = require("../../../service/UI/UIEvents");
  8804. var RTC = require("../../RTC/RTC");
  8805. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8806. var RemoteVideo = require("./RemoteVideo");
  8807. var LargeVideo = require("./LargeVideo");
  8808. var LocalVideo = require("./LocalVideo");
  8809. var remoteVideos = {};
  8810. var localVideoThumbnail = null;
  8811. var currentDominantSpeaker = null;
  8812. var lastNCount = config.channelLastN;
  8813. var localLastNCount = config.channelLastN;
  8814. var localLastNSet = [];
  8815. var lastNEndpointsCache = [];
  8816. var lastNPickupJid = null;
  8817. var eventEmitter = null;
  8818. /**
  8819. * Currently focused video jid
  8820. * @type {String}
  8821. */
  8822. var focusedVideoResourceJid = null;
  8823. var VideoLayout = (function (my) {
  8824. my.init = function (emitter) {
  8825. eventEmitter = emitter;
  8826. localVideoThumbnail = new LocalVideo(VideoLayout);
  8827. VideoLayout.resizeLargeVideoContainer();
  8828. LargeVideo.init(VideoLayout, emitter);
  8829. };
  8830. my.isInLastN = function(resource) {
  8831. return lastNCount < 0 // lastN is disabled, return true
  8832. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  8833. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  8834. };
  8835. my.changeLocalStream = function (stream, isMuted) {
  8836. VideoLayout.changeLocalVideo(stream, isMuted);
  8837. };
  8838. my.changeLocalAudio = function(stream, isMuted) {
  8839. if (isMuted)
  8840. APP.UI.setAudioMuted(true, true);
  8841. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8842. var localAudio = document.getElementById('localAudio');
  8843. // Writing volume not allowed in IE
  8844. if (!RTCBrowserType.isIExplorer()) {
  8845. localAudio.autoplay = true;
  8846. localAudio.volume = 0;
  8847. }
  8848. };
  8849. my.changeLocalVideo = function(stream, isMuted) {
  8850. // Set default display name.
  8851. localVideoThumbnail.setDisplayName();
  8852. localVideoThumbnail.createConnectionIndicator();
  8853. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8854. localVideoThumbnail.changeVideo(stream, isMuted);
  8855. LargeVideo.updateLargeVideo(
  8856. APP.xmpp.myResource(),
  8857. /* force update only before conference starts */
  8858. !APP.xmpp.isConferenceInProgress());
  8859. };
  8860. my.mucJoined = function () {
  8861. var myResourceJid = APP.xmpp.myResource();
  8862. localVideoThumbnail.joined(APP.xmpp.myJid());
  8863. if (!LargeVideo.getResourceJid())
  8864. LargeVideo.updateLargeVideo(myResourceJid, true);
  8865. };
  8866. /**
  8867. * Adds or removes icons for not available camera and microphone.
  8868. * @param resourceJid the jid of user
  8869. * @param devices available devices
  8870. */
  8871. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  8872. if(!devices)
  8873. return;
  8874. if(!resourceJid)
  8875. {
  8876. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  8877. }
  8878. else
  8879. {
  8880. if(remoteVideos[resourceJid])
  8881. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  8882. }
  8883. }
  8884. /**
  8885. * Checks if removed video is currently displayed and tries to display
  8886. * another one instead.
  8887. * @param removedVideoSrc src stream identifier of the video.
  8888. */
  8889. my.updateRemovedVideo = function(resourceJid) {
  8890. var videoElem = RTC.getVideoElementName();
  8891. if (resourceJid === LargeVideo.getResourceJid()) {
  8892. // this is currently displayed as large
  8893. // pick the last visible video in the row
  8894. // if nobody else is left, this picks the local video
  8895. var pick
  8896. = $('#remoteVideos>' +
  8897. 'span[id!="mixedstream"]:visible:last>' + videoElem).get(0);
  8898. if (!pick) {
  8899. console.info("Last visible video no longer exists");
  8900. pick = $('#remoteVideos>' +
  8901. 'span[id!="mixedstream"]>' + videoElem).get(0);
  8902. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  8903. // Try local video
  8904. console.info("Fallback to local video...");
  8905. pick = $('#remoteVideos>span>span>' + videoElem).get(0);
  8906. }
  8907. }
  8908. // mute if localvideo
  8909. if (pick) {
  8910. var container = pick.parentNode;
  8911. } else {
  8912. console.warn("Failed to elect large video");
  8913. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  8914. }
  8915. var jid = null;
  8916. if(container)
  8917. {
  8918. if(container.id == "localVideoWrapper")
  8919. {
  8920. jid = APP.xmpp.myResource();
  8921. }
  8922. else
  8923. {
  8924. jid = VideoLayout.getPeerContainerResourceJid(container);
  8925. }
  8926. }
  8927. else
  8928. return;
  8929. LargeVideo.updateLargeVideo(jid);
  8930. }
  8931. };
  8932. my.onRemoteStreamAdded = function (stream) {
  8933. if (stream.peerjid) {
  8934. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  8935. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  8936. remoteVideos[resourceJid].addRemoteStreamElement(
  8937. stream.sid,
  8938. stream.getOriginalStream(),
  8939. stream.ssrc);
  8940. }
  8941. };
  8942. my.getLargeVideoJid = function () {
  8943. return LargeVideo.getResourceJid();
  8944. };
  8945. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  8946. resourceJid) {
  8947. if(focusedVideoResourceJid) {
  8948. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  8949. if(oldSmallVideo)
  8950. oldSmallVideo.focus(false);
  8951. }
  8952. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  8953. // Unlock current focused.
  8954. if (focusedVideoResourceJid === resourceJid)
  8955. {
  8956. focusedVideoResourceJid = null;
  8957. // Enable the currently set dominant speaker.
  8958. if (currentDominantSpeaker) {
  8959. if(smallVideo && smallVideo.hasVideo())
  8960. {
  8961. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  8962. }
  8963. }
  8964. if (!noPinnedEndpointChangedEvent) {
  8965. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  8966. }
  8967. return;
  8968. }
  8969. // Lock new video
  8970. focusedVideoResourceJid = resourceJid;
  8971. // Update focused/pinned interface.
  8972. if (resourceJid)
  8973. {
  8974. if(smallVideo)
  8975. smallVideo.focus(true);
  8976. if (!noPinnedEndpointChangedEvent) {
  8977. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  8978. }
  8979. }
  8980. if (LargeVideo.getResourceJid() === resourceJid &&
  8981. LargeVideo.isLargeVideoOnTop()) {
  8982. return;
  8983. }
  8984. // Triggers a "video.selected" event. The "false" parameter indicates
  8985. // this isn't a prezi.
  8986. $(document).trigger("video.selected", [false]);
  8987. LargeVideo.updateLargeVideo(resourceJid);
  8988. // Writing volume not allowed in IE
  8989. if (!RTCBrowserType.isIExplorer()) {
  8990. $('audio').each(function (idx, el) {
  8991. el.volume = 0;
  8992. el.volume = 1;
  8993. });
  8994. }
  8995. };
  8996. /**
  8997. * Checks if container for participant identified by given peerJid exists
  8998. * in the document and creates it eventually.
  8999. *
  9000. * @param peerJid peer Jid to check.
  9001. * @param userId user email or id for setting the avatar
  9002. *
  9003. * @return Returns <tt>true</tt> if the peer container exists,
  9004. * <tt>false</tt> - otherwise
  9005. */
  9006. my.ensurePeerContainerExists = function(peerJid, userId) {
  9007. ContactList.ensureAddContact(peerJid, userId);
  9008. var resourceJid = Strophe.getResourceFromJid(peerJid);
  9009. if(!remoteVideos[resourceJid])
  9010. {
  9011. remoteVideos[resourceJid] = new RemoteVideo(peerJid, VideoLayout);
  9012. Avatar.setUserAvatar(peerJid, userId);
  9013. // In case this is not currently in the last n we don't show it.
  9014. if (localLastNCount
  9015. && localLastNCount > 0
  9016. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  9017. remoteVideos[resourceJid].showPeerContainer('hide');
  9018. }
  9019. else
  9020. VideoLayout.resizeThumbnails();
  9021. }
  9022. };
  9023. my.inputDisplayNameHandler = function (name) {
  9024. localVideoThumbnail.inputDisplayNameHandler(name);
  9025. };
  9026. my.videoactive = function (videoelem, resourceJid) {
  9027. videoelem.show();
  9028. VideoLayout.resizeThumbnails();
  9029. // Update the large video to the last added video only if there's no
  9030. // current dominant, focused speaker or prezi playing or update it to
  9031. // the current dominant speaker.
  9032. if ((!focusedVideoResourceJid &&
  9033. !currentDominantSpeaker &&
  9034. !require("../prezi/Prezi").isPresentationVisible()) ||
  9035. (resourceJid &&
  9036. currentDominantSpeaker === resourceJid)) {
  9037. LargeVideo.updateLargeVideo(resourceJid, true);
  9038. }
  9039. }
  9040. /**
  9041. * Shows the presence status message for the given video.
  9042. */
  9043. my.setPresenceStatus = function (resourceJid, statusMsg) {
  9044. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  9045. };
  9046. /**
  9047. * Shows a visual indicator for the moderator of the conference.
  9048. */
  9049. my.showModeratorIndicator = function () {
  9050. var isModerator = APP.xmpp.isModerator();
  9051. if (isModerator) {
  9052. localVideoThumbnail.createModeratorIndicatorElement();
  9053. }
  9054. var members = APP.xmpp.getMembers();
  9055. Object.keys(members).forEach(function (jid) {
  9056. if (Strophe.getResourceFromJid(jid) === 'focus') {
  9057. // Skip server side focus
  9058. return;
  9059. }
  9060. var resourceJid = Strophe.getResourceFromJid(jid);
  9061. var member = members[jid];
  9062. if (member.role === 'moderator') {
  9063. remoteVideos[resourceJid].removeRemoteVideoMenu();
  9064. remoteVideos[resourceJid].createModeratorIndicatorElement();
  9065. } else if (isModerator) {
  9066. // We are moderator, but user is not - add menu
  9067. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  9068. remoteVideos[resourceJid].addRemoteVideoMenu();
  9069. }
  9070. }
  9071. });
  9072. };
  9073. /*
  9074. * Shows or hides the audio muted indicator over the local thumbnail video.
  9075. * @param {boolean} isMuted
  9076. */
  9077. my.showLocalAudioIndicator = function(isMuted) {
  9078. localVideoThumbnail.showAudioIndicator(isMuted);
  9079. };
  9080. /**
  9081. * Resizes the large video container.
  9082. */
  9083. my.resizeLargeVideoContainer = function () {
  9084. LargeVideo.resize();
  9085. VideoLayout.resizeThumbnails();
  9086. LargeVideo.position();
  9087. };
  9088. /**
  9089. * Resizes thumbnails.
  9090. */
  9091. my.resizeThumbnails = function(animate) {
  9092. var videoSpaceWidth = $('#remoteVideos').width();
  9093. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  9094. var width = thumbnailSize[0];
  9095. var height = thumbnailSize[1];
  9096. $('.userAvatar').css('left', (width - height) / 2);
  9097. if(animate)
  9098. {
  9099. $('#remoteVideos').animate({
  9100. height: height
  9101. },
  9102. {
  9103. queue: false,
  9104. duration: 500
  9105. });
  9106. $('#remoteVideos>span').animate({
  9107. height: height,
  9108. width: width
  9109. },
  9110. {
  9111. queue: false,
  9112. duration: 500,
  9113. complete: function () {
  9114. $(document).trigger(
  9115. "remotevideo.resized",
  9116. [width,
  9117. height]);
  9118. }
  9119. });
  9120. }
  9121. else
  9122. {
  9123. // size videos so that while keeping AR and max height, we have a
  9124. // nice fit
  9125. $('#remoteVideos').height(height);
  9126. $('#remoteVideos>span').width(width);
  9127. $('#remoteVideos>span').height(height);
  9128. $(document).trigger("remotevideo.resized", [width, height]);
  9129. }
  9130. };
  9131. /**
  9132. * Calculates the thumbnail size.
  9133. *
  9134. * @param videoSpaceWidth the width of the video space
  9135. */
  9136. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9137. // Calculate the available height, which is the inner window height minus
  9138. // 39px for the header minus 2px for the delimiter lines on the top and
  9139. // bottom of the large video, minus the 36px space inside the remoteVideos
  9140. // container used for highlighting shadow.
  9141. var availableHeight = 100;
  9142. var numvids = $('#remoteVideos>span:visible').length;
  9143. if (localLastNCount && localLastNCount > 0) {
  9144. numvids = Math.min(localLastNCount + 1, numvids);
  9145. }
  9146. // Remove the 3px borders arround videos and border around the remote
  9147. // videos area and the 4 pixels between the local video and the others
  9148. //TODO: Find out where the 4 pixels come from and remove them
  9149. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9150. var availableWidth = availableWinWidth / numvids;
  9151. var aspectRatio = 16.0 / 9.0;
  9152. var maxHeight = Math.min(160, availableHeight);
  9153. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  9154. if (availableHeight < availableWidth / aspectRatio) {
  9155. availableWidth = Math.floor(availableHeight * aspectRatio);
  9156. }
  9157. return [availableWidth, availableHeight];
  9158. };
  9159. /**
  9160. * Returns the corresponding resource jid to the given peer container
  9161. * DOM element.
  9162. *
  9163. * @return the corresponding resource jid to the given peer container
  9164. * DOM element
  9165. */
  9166. my.getPeerContainerResourceJid = function (containerElement) {
  9167. var i = containerElement.id.indexOf('participant_');
  9168. if (i >= 0)
  9169. return containerElement.id.substring(i + 12);
  9170. };
  9171. /**
  9172. * On contact list item clicked.
  9173. */
  9174. $(ContactList).bind('contactclicked', function(event, jid) {
  9175. if (!jid) {
  9176. return;
  9177. }
  9178. var resource = Strophe.getResourceFromJid(jid);
  9179. var videoContainer = $("#participant_" + resource);
  9180. if (videoContainer.length > 0) {
  9181. var videoThumb
  9182. = $(RTC.getVideoElementName(), videoContainer).get(0);
  9183. // It is not always the case that a videoThumb exists (if there is
  9184. // no actual video).
  9185. if (videoThumb) {
  9186. if (videoThumb.src && videoThumb.src != '') {
  9187. // We have a video src, great! Let's update the large video
  9188. // now.
  9189. VideoLayout.handleVideoThumbClicked(
  9190. false,
  9191. Strophe.getResourceFromJid(jid));
  9192. } else {
  9193. // If we don't have a video src for jid, there's absolutely
  9194. // no point in calling handleVideoThumbClicked; Quite
  9195. // simply, it won't work because it needs an src to attach
  9196. // to the large video.
  9197. //
  9198. // Instead, we trigger the pinned endpoint changed event to
  9199. // let the bridge adjust its lastN set for myjid and store
  9200. // the pinned user in the lastNPickupJid variable to be
  9201. // picked up later by the lastN changed event handler.
  9202. lastNPickupJid = jid;
  9203. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9204. Strophe.getResourceFromJid(jid));
  9205. }
  9206. } else if (jid == APP.xmpp.myJid()) {
  9207. $("#localVideoContainer").click();
  9208. }
  9209. }
  9210. });
  9211. /**
  9212. * On audio muted event.
  9213. */
  9214. my.onAudioMute = function (jid, isMuted) {
  9215. var resourceJid = Strophe.getResourceFromJid(jid);
  9216. if (resourceJid === APP.xmpp.myResource()) {
  9217. localVideoThumbnail.showAudioIndicator(isMuted);
  9218. } else {
  9219. VideoLayout.ensurePeerContainerExists(jid);
  9220. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9221. if (APP.xmpp.isModerator()) {
  9222. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9223. }
  9224. }
  9225. };
  9226. /**
  9227. * On video muted event.
  9228. */
  9229. my.onVideoMute = function (jid, value) {
  9230. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, value))
  9231. return;
  9232. if (jid === APP.xmpp.myJid()) {
  9233. localVideoThumbnail.showVideoIndicator(value);
  9234. } else {
  9235. VideoLayout.ensurePeerContainerExists(jid);
  9236. remoteVideos[Strophe.getResourceFromJid(jid)].showVideoIndicator(value);
  9237. }
  9238. };
  9239. /**
  9240. * Display name changed.
  9241. */
  9242. my.onDisplayNameChanged =
  9243. function (jid, displayName, status) {
  9244. if (jid === 'localVideoContainer'
  9245. || jid === APP.xmpp.myJid()) {
  9246. localVideoThumbnail.setDisplayName(displayName);
  9247. } else {
  9248. VideoLayout.ensurePeerContainerExists(jid);
  9249. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9250. displayName,
  9251. status);
  9252. }
  9253. };
  9254. /**
  9255. * On dominant speaker changed event.
  9256. */
  9257. my.onDominantSpeakerChanged = function (resourceJid) {
  9258. // We ignore local user events.
  9259. if (resourceJid === APP.xmpp.myResource())
  9260. return;
  9261. var members = APP.xmpp.getMembers();
  9262. // Update the current dominant speaker.
  9263. if (resourceJid !== currentDominantSpeaker) {
  9264. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9265. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9266. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9267. !members[currentJID].displayName)) {
  9268. remoteVideos[resourceJid].setDisplayName(null);
  9269. }
  9270. if(resourceJid && (!members || !members[newJID] ||
  9271. !members[newJID].displayName)) {
  9272. remoteVideos[resourceJid].setDisplayName(null,
  9273. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9274. }
  9275. currentDominantSpeaker = resourceJid;
  9276. } else {
  9277. return;
  9278. }
  9279. // Obtain container for new dominant speaker.
  9280. var container = document.getElementById(
  9281. 'participant_' + resourceJid);
  9282. // Local video will not have container found, but that's ok
  9283. // since we don't want to switch to local video.
  9284. if (container && !focusedVideoResourceJid)
  9285. {
  9286. var video
  9287. = container.getElementsByTagName(RTC.getVideoElementName());
  9288. // Update the large video if the video source is already available,
  9289. // otherwise wait for the "videoactive.jingle" event.
  9290. if (video.length && video[0].currentTime > 0) {
  9291. LargeVideo.updateLargeVideo(resourceJid);
  9292. }
  9293. }
  9294. };
  9295. /**
  9296. * On last N change event.
  9297. *
  9298. * @param lastNEndpoints the list of last N endpoints
  9299. * @param endpointsEnteringLastN the list currently entering last N
  9300. * endpoints
  9301. */
  9302. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  9303. endpointsEnteringLastN,
  9304. stream) {
  9305. if (lastNCount !== lastNEndpoints.length)
  9306. lastNCount = lastNEndpoints.length;
  9307. lastNEndpointsCache = lastNEndpoints;
  9308. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9309. //
  9310. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9311. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9312. // so E sees them. C is only in E's local LastN set.
  9313. //
  9314. // If F starts talking and LastN = 3, then E should see thumbnails for
  9315. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9316. // enters E's local LastN ejecting C.
  9317. // Increase the local LastN set size, if necessary.
  9318. if (lastNCount > localLastNCount) {
  9319. localLastNCount = lastNCount;
  9320. }
  9321. // Update the local LastN set preserving the order in which the
  9322. // endpoints appeared in the LastN/local LastN set.
  9323. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9324. for (var i = 0; i < localLastNSet.length; i++) {
  9325. if (nextLocalLastNSet.length >= localLastNCount) {
  9326. break;
  9327. }
  9328. var resourceJid = localLastNSet[i];
  9329. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9330. nextLocalLastNSet.push(resourceJid);
  9331. }
  9332. }
  9333. localLastNSet = nextLocalLastNSet;
  9334. var updateLargeVideo = false;
  9335. // Handle LastN/local LastN changes.
  9336. $('#remoteVideos>span').each(function( index, element ) {
  9337. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9338. var isReceived = true;
  9339. if (resourceJid
  9340. && lastNEndpoints.indexOf(resourceJid) < 0
  9341. && localLastNSet.indexOf(resourceJid) < 0) {
  9342. console.log("Remove from last N", resourceJid);
  9343. remoteVideos[resourceJid].showPeerContainer('hide');
  9344. isReceived = false;
  9345. } else if (resourceJid
  9346. && $('#participant_' + resourceJid).is(':visible')
  9347. && lastNEndpoints.indexOf(resourceJid) < 0
  9348. && localLastNSet.indexOf(resourceJid) >= 0) {
  9349. remoteVideos[resourceJid].showPeerContainer('avatar');
  9350. isReceived = false;
  9351. }
  9352. if (!isReceived) {
  9353. // resourceJid has dropped out of the server side lastN set, so
  9354. // it is no longer being received. If resourceJid was being
  9355. // displayed in the large video we have to switch to another
  9356. // user.
  9357. if (!updateLargeVideo && resourceJid === LargeVideo.getResourceJid()) {
  9358. updateLargeVideo = true;
  9359. }
  9360. }
  9361. });
  9362. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9363. endpointsEnteringLastN = lastNEndpoints;
  9364. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9365. endpointsEnteringLastN.forEach(function (resourceJid) {
  9366. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9367. remoteVideos[resourceJid].showPeerContainer('show');
  9368. if (!isVisible) {
  9369. console.log("Add to last N", resourceJid);
  9370. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9371. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9372. var sel = $('#participant_' + resourceJid +
  9373. '>' + RTC.getVideoElementName());
  9374. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9375. if (lastNPickupJid == mediaStream.peerjid) {
  9376. // Clean up the lastN pickup jid.
  9377. lastNPickupJid = null;
  9378. // Don't fire the events again, they've already
  9379. // been fired in the contact list click handler.
  9380. VideoLayout.handleVideoThumbClicked(
  9381. false,
  9382. Strophe.getResourceFromJid(mediaStream.peerjid));
  9383. updateLargeVideo = false;
  9384. }
  9385. remoteVideos[resourceJid].waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream);
  9386. }
  9387. });
  9388. }
  9389. // The endpoint that was being shown in the large video has dropped out
  9390. // of the lastN set and there was no lastN pickup jid. We need to update
  9391. // the large video now.
  9392. if (updateLargeVideo) {
  9393. var resource, container, src;
  9394. var myResource
  9395. = APP.xmpp.myResource();
  9396. // Find out which endpoint to show in the large video.
  9397. for (var i = 0; i < lastNEndpoints.length; i++) {
  9398. resource = lastNEndpoints[i];
  9399. if (!resource || resource === myResource)
  9400. continue;
  9401. // videoSrcToSsrc needs to be update for this call to succeed.
  9402. LargeVideo.updateLargeVideo(resource);
  9403. break;
  9404. }
  9405. }
  9406. };
  9407. /**
  9408. * Updates local stats
  9409. * @param percent
  9410. * @param object
  9411. */
  9412. my.updateLocalConnectionStats = function (percent, object) {
  9413. var resolution = null;
  9414. if(object.resolution !== null)
  9415. {
  9416. resolution = object.resolution;
  9417. object.resolution = resolution[APP.xmpp.myJid()];
  9418. delete resolution[APP.xmpp.myJid()];
  9419. }
  9420. localVideoThumbnail.updateStatsIndicator(percent, object);
  9421. for(var jid in resolution)
  9422. {
  9423. if(resolution[jid] === null)
  9424. continue;
  9425. var resourceJid = Strophe.getResourceFromJid(jid);
  9426. if(remoteVideos[resourceJid] && remoteVideos[resourceJid].connectionIndicator)
  9427. {
  9428. remoteVideos[resourceJid].connectionIndicator.updateResolution(resolution[jid]);
  9429. }
  9430. }
  9431. };
  9432. /**
  9433. * Updates remote stats.
  9434. * @param jid the jid associated with the stats
  9435. * @param percent the connection quality percent
  9436. * @param object the stats data
  9437. */
  9438. my.updateConnectionStats = function (jid, percent, object) {
  9439. var resourceJid = Strophe.getResourceFromJid(jid);
  9440. if(remoteVideos[resourceJid])
  9441. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9442. };
  9443. /**
  9444. * Removes the connection
  9445. * @param jid
  9446. */
  9447. my.removeConnectionIndicator = function (jid) {
  9448. remoteVideos[Strophe.getResourceFromJid(jid)].removeConnectionIndicator();
  9449. };
  9450. /**
  9451. * Hides the connection indicator
  9452. * @param jid
  9453. */
  9454. my.hideConnectionIndicator = function (jid) {
  9455. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9456. };
  9457. /**
  9458. * Hides all the indicators
  9459. */
  9460. my.onStatsStop = function () {
  9461. for(var video in remoteVideos)
  9462. {
  9463. remoteVideos[video].hideIndicator();
  9464. }
  9465. localVideoThumbnail.hideIndicator();
  9466. };
  9467. my.participantLeft = function (jid) {
  9468. // Unlock large video
  9469. var resourceJid = Strophe.getResourceFromJid(jid);
  9470. if (focusedVideoResourceJid === resourceJid)
  9471. {
  9472. console.info("Focused video owner has left the conference");
  9473. focusedVideoResourceJid = null;
  9474. }
  9475. };
  9476. my.onVideoTypeChanged = function (jid) {
  9477. LargeVideo.onVideoTypeChanged(jid);
  9478. };
  9479. my.showMore = function (jid) {
  9480. if(APP.xmpp.myJid = jid)
  9481. {
  9482. localVideoThumbnail.connectionIndicator.showMore();
  9483. }
  9484. else
  9485. {
  9486. remoteVideos[Strophe.getResourceFromJid(jid)].connectionIndicator.showMore();
  9487. }
  9488. };
  9489. my.addPreziContainer = function (id) {
  9490. return RemoteVideo.createContainer(id);
  9491. };
  9492. my.setLargeVideoVisible = function (isVisible) {
  9493. LargeVideo.setLargeVideoVisible(isVisible);
  9494. if(!isVisible && focusedVideoResourceJid)
  9495. {
  9496. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9497. if(smallVideo)
  9498. smallVideo.focus(false);
  9499. smallVideo.showAvatar();
  9500. focusedVideoResourceJid = null;
  9501. }
  9502. };
  9503. /**
  9504. * Resizes the video area
  9505. * @param completeFunction a function to be called when the video space is resized
  9506. */
  9507. my.resizeVideoArea = function(isVisible, completeFunction) {
  9508. LargeVideo.resizeVideoAreaAnimated(isVisible, completeFunction);
  9509. VideoLayout.resizeThumbnails(true);
  9510. };
  9511. my.getSmallVideo = function (resourceJid) {
  9512. if(resourceJid == APP.xmpp.myResource())
  9513. {
  9514. return localVideoThumbnail;
  9515. }
  9516. else
  9517. {
  9518. if(!remoteVideos[resourceJid])
  9519. return null;
  9520. return remoteVideos[resourceJid];
  9521. }
  9522. };
  9523. my.userAvatarChanged = function(resourceJid, thumbUrl)
  9524. {
  9525. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9526. if(smallVideo)
  9527. smallVideo.avatarChanged(thumbUrl);
  9528. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9529. };
  9530. return my;
  9531. }(VideoLayout || {}));
  9532. module.exports = VideoLayout;
  9533. },{"../../../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){
  9534. //var nouns = [
  9535. //];
  9536. var pluralNouns = [
  9537. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9538. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9539. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9540. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9541. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9542. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9543. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9544. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9545. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9546. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9547. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9548. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9549. ];
  9550. //var places = [
  9551. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9552. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9553. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9554. // "Bridge"
  9555. //];
  9556. var verbs = [
  9557. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9558. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9559. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9560. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9561. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9562. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9563. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9564. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9565. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9566. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9567. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9568. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9569. ];
  9570. var adverbs = [
  9571. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9572. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9573. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9574. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9575. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9576. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9577. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9578. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9579. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9580. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9581. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9582. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9583. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9584. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9585. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9586. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9587. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9588. ];
  9589. var adjectives = [
  9590. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9591. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9592. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9593. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9594. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9595. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9596. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9597. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9598. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9599. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9600. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9601. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9602. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9603. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9604. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9605. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9606. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9607. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9608. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9609. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9610. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9611. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9612. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9613. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9614. "Zealous"
  9615. ];
  9616. //var pronouns = [
  9617. //];
  9618. //var conjunctions = [
  9619. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9620. //];
  9621. /*
  9622. * Maps a string (category name) to the array of words from that category.
  9623. */
  9624. var CATEGORIES =
  9625. {
  9626. //"_NOUN_": nouns,
  9627. "_PLURALNOUN_": pluralNouns,
  9628. //"_PLACE_": places,
  9629. "_VERB_": verbs,
  9630. "_ADVERB_": adverbs,
  9631. "_ADJECTIVE_": adjectives
  9632. //"_PRONOUN_": pronouns,
  9633. //"_CONJUNCTION_": conjunctions,
  9634. };
  9635. var PATTERNS = [
  9636. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9637. // BeautifulFungiOrSpaghetti
  9638. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9639. // AmazinglyScaryToy
  9640. //"_ADVERB__ADJECTIVE__NOUN_",
  9641. // NeitherTrashNorRifle
  9642. //"Neither_NOUN_Nor_NOUN_",
  9643. //"Either_NOUN_Or_NOUN_",
  9644. // EitherCopulateOrInvestigate
  9645. //"Either_VERB_Or_VERB_",
  9646. //"Neither_VERB_Nor_VERB_",
  9647. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9648. //"The_ADVERB__ADJECTIVE__NOUN_",
  9649. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9650. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9651. // WolvesComputeBadly
  9652. //"_PLURALNOUN__VERB__ADVERB_",
  9653. // UniteFacilitateAndMerge
  9654. //"_VERB__VERB_And_VERB_",
  9655. //NastyWitchesAtThePub
  9656. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9657. ];
  9658. /*
  9659. * Returns a random element from the array 'arr'
  9660. */
  9661. function randomElement(arr)
  9662. {
  9663. return arr[Math.floor(Math.random() * arr.length)];
  9664. }
  9665. /*
  9666. * Returns true if the string 's' contains one of the
  9667. * template strings.
  9668. */
  9669. function hasTemplate(s)
  9670. {
  9671. for (var template in CATEGORIES){
  9672. if (s.indexOf(template) >= 0){
  9673. return true;
  9674. }
  9675. }
  9676. }
  9677. /**
  9678. * Generates new room name.
  9679. */
  9680. var RoomNameGenerator = {
  9681. generateRoomWithoutSeparator: function()
  9682. {
  9683. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  9684. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  9685. var name = randomElement(PATTERNS);
  9686. var word;
  9687. while (hasTemplate(name)){
  9688. for (var template in CATEGORIES){
  9689. word = randomElement(CATEGORIES[template]);
  9690. name = name.replace(template, word);
  9691. }
  9692. }
  9693. return name;
  9694. }
  9695. }
  9696. module.exports = RoomNameGenerator;
  9697. },{}],43:[function(require,module,exports){
  9698. var animateTimeout, updateTimeout;
  9699. var RoomNameGenerator = require("./RoomnameGenerator");
  9700. function enter_room()
  9701. {
  9702. var val = $("#enter_room_field").val();
  9703. if(!val) {
  9704. val = $("#enter_room_field").attr("room_name");
  9705. }
  9706. if (val) {
  9707. window.location.pathname = "/" + val;
  9708. }
  9709. }
  9710. function animate(word) {
  9711. var currentVal = $("#enter_room_field").attr("placeholder");
  9712. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9713. animateTimeout = setTimeout(function() {
  9714. animate(word.substring(1, word.length))
  9715. }, 70);
  9716. }
  9717. function update_roomname()
  9718. {
  9719. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9720. $("#enter_room_field").attr("room_name", word);
  9721. $("#enter_room_field").attr("placeholder", "");
  9722. clearTimeout(animateTimeout);
  9723. animate(word);
  9724. updateTimeout = setTimeout(update_roomname, 10000);
  9725. }
  9726. function setupWelcomePage()
  9727. {
  9728. $("#videoconference_page").hide();
  9729. $("#domain_name").text(
  9730. window.location.protocol + "//" + window.location.host + "/");
  9731. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9732. var leftWatermarkDiv
  9733. = $("#welcome_page_header div[class='watermark leftwatermark']");
  9734. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  9735. {
  9736. leftWatermarkDiv.css({display: 'block'});
  9737. leftWatermarkDiv.parent().get(0).href
  9738. = interfaceConfig.JITSI_WATERMARK_LINK;
  9739. }
  9740. }
  9741. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9742. var rightWatermarkDiv
  9743. = $("#welcome_page_header div[class='watermark rightwatermark']");
  9744. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9745. rightWatermarkDiv.css({display: 'block'});
  9746. rightWatermarkDiv.parent().get(0).href
  9747. = interfaceConfig.BRAND_WATERMARK_LINK;
  9748. rightWatermarkDiv.get(0).style.backgroundImage
  9749. = "url(images/rightwatermark.png)";
  9750. }
  9751. }
  9752. if (interfaceConfig.SHOW_POWERED_BY) {
  9753. $("#welcome_page_header>a[class='poweredby']")
  9754. .css({display: 'block'});
  9755. }
  9756. $("#enter_room_button").click(function()
  9757. {
  9758. enter_room();
  9759. });
  9760. $("#enter_room_field").keydown(function (event) {
  9761. if (event.keyCode === 13 /* enter */) {
  9762. enter_room();
  9763. }
  9764. });
  9765. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  9766. var updateTimeout;
  9767. var animateTimeout;
  9768. $("#reload_roomname").click(function () {
  9769. clearTimeout(updateTimeout);
  9770. clearTimeout(animateTimeout);
  9771. update_roomname();
  9772. });
  9773. $("#reload_roomname").show();
  9774. update_roomname();
  9775. }
  9776. $("#disable_welcome").click(function () {
  9777. window.localStorage.welcomePageDisabled
  9778. = $("#disable_welcome").is(":checked");
  9779. });
  9780. }
  9781. module.exports = setupWelcomePage;
  9782. },{"./RoomnameGenerator":42}],44:[function(require,module,exports){
  9783. var params = {};
  9784. function getConfigParamsFromUrl() {
  9785. if(!location.hash)
  9786. return {};
  9787. var hash = location.hash.substr(1);
  9788. var result = {};
  9789. hash.split("&").forEach(function(part) {
  9790. var item = part.split("=");
  9791. result[item[0]] = JSON.parse(
  9792. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  9793. });
  9794. return result;
  9795. }
  9796. params = getConfigParamsFromUrl();
  9797. var URLProcessor = {
  9798. setConfigParametersFromUrl: function () {
  9799. for(var k in params)
  9800. {
  9801. if(typeof k !== "string" || k.indexOf("config.") === -1)
  9802. continue;
  9803. var v = params[k];
  9804. var confKey = k.substr(7);
  9805. if(config[confKey] && typeof config[confKey] !== typeof v)
  9806. {
  9807. console.warn("The type of " + k +
  9808. " is wrong. That parameter won't be updated in config.js.");
  9809. continue;
  9810. }
  9811. config[confKey] = v;
  9812. }
  9813. }
  9814. };
  9815. module.exports = URLProcessor;
  9816. },{}],45:[function(require,module,exports){
  9817. var EventEmitter = require("events");
  9818. var eventEmitter = new EventEmitter();
  9819. var CQEvents = require("../../service/connectionquality/CQEvents");
  9820. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9821. /**
  9822. * local stats
  9823. * @type {{}}
  9824. */
  9825. var stats = {};
  9826. /**
  9827. * remote stats
  9828. * @type {{}}
  9829. */
  9830. var remoteStats = {};
  9831. /**
  9832. * Interval for sending statistics to other participants
  9833. * @type {null}
  9834. */
  9835. var sendIntervalId = null;
  9836. /**
  9837. * Start statistics sending.
  9838. */
  9839. function startSendingStats() {
  9840. sendStats();
  9841. sendIntervalId = setInterval(sendStats, 10000);
  9842. }
  9843. /**
  9844. * Sends statistics to other participants
  9845. */
  9846. function sendStats() {
  9847. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  9848. }
  9849. /**
  9850. * Converts statistics to format for sending through XMPP
  9851. * @param stats the statistics
  9852. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  9853. */
  9854. function convertToMUCStats(stats) {
  9855. return {
  9856. "bitrate_download": stats.bitrate.download,
  9857. "bitrate_upload": stats.bitrate.upload,
  9858. "packetLoss_total": stats.packetLoss.total,
  9859. "packetLoss_download": stats.packetLoss.download,
  9860. "packetLoss_upload": stats.packetLoss.upload
  9861. };
  9862. }
  9863. /**
  9864. * Converts statitistics to format used by VideoLayout
  9865. * @param stats
  9866. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  9867. */
  9868. function parseMUCStats(stats) {
  9869. return {
  9870. bitrate: {
  9871. download: stats.bitrate_download,
  9872. upload: stats.bitrate_upload
  9873. },
  9874. packetLoss: {
  9875. total: stats.packetLoss_total,
  9876. download: stats.packetLoss_download,
  9877. upload: stats.packetLoss_upload
  9878. }
  9879. };
  9880. }
  9881. var ConnectionQuality = {
  9882. init: function () {
  9883. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  9884. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  9885. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  9886. },
  9887. /**
  9888. * Updates the local statistics
  9889. * @param data new statistics
  9890. */
  9891. updateLocalStats: function (data) {
  9892. stats = data;
  9893. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  9894. if (sendIntervalId == null) {
  9895. startSendingStats();
  9896. }
  9897. },
  9898. /**
  9899. * Updates remote statistics
  9900. * @param jid the jid associated with the statistics
  9901. * @param data the statistics
  9902. */
  9903. updateRemoteStats: function (jid, data) {
  9904. if (data == null || data.packetLoss_total == null) {
  9905. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  9906. return;
  9907. }
  9908. remoteStats[jid] = parseMUCStats(data);
  9909. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  9910. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  9911. },
  9912. /**
  9913. * Stops statistics sending.
  9914. */
  9915. stopSendingStats: function () {
  9916. clearInterval(sendIntervalId);
  9917. sendIntervalId = null;
  9918. //notify UI about stopping statistics gathering
  9919. eventEmitter.emit(CQEvents.STOP);
  9920. },
  9921. /**
  9922. * Returns the local statistics.
  9923. */
  9924. getStats: function () {
  9925. return stats;
  9926. },
  9927. addListener: function (type, listener) {
  9928. eventEmitter.on(type, listener);
  9929. }
  9930. };
  9931. module.exports = ConnectionQuality;
  9932. },{"../../service/connectionquality/CQEvents":106,"../../service/xmpp/XMPPEvents":110,"events":1}],46:[function(require,module,exports){
  9933. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  9934. getUserMediaWithConstraints */
  9935. /**
  9936. * Indicates that desktop stream is currently in use(for toggle purpose).
  9937. * @type {boolean}
  9938. */
  9939. var isUsingScreenStream = false;
  9940. /**
  9941. * Indicates that switch stream operation is in progress and prevent from
  9942. * triggering new events.
  9943. * @type {boolean}
  9944. */
  9945. var switchInProgress = false;
  9946. /**
  9947. * Method used to get screen sharing stream.
  9948. *
  9949. * @type {function (stream_callback, failure_callback}
  9950. */
  9951. var obtainDesktopStream = null;
  9952. /**
  9953. * Indicates whether desktop sharing extension is installed.
  9954. * @type {boolean}
  9955. */
  9956. var extInstalled = false;
  9957. /**
  9958. * Indicates whether update of desktop sharing extension is required.
  9959. * @type {boolean}
  9960. */
  9961. var extUpdateRequired = false;
  9962. var AdapterJS = require("../RTC/adapter.screenshare");
  9963. var EventEmitter = require("events");
  9964. var eventEmitter = new EventEmitter();
  9965. var DesktopSharingEventTypes
  9966. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  9967. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9968. var RTCEvents = require("../../service/RTC/RTCEvents");
  9969. /**
  9970. * Method obtains desktop stream from WebRTC 'screen' source.
  9971. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  9972. */
  9973. function obtainWebRTCScreen(streamCallback, failCallback) {
  9974. APP.RTC.getUserMediaWithConstraints(
  9975. ['screen'],
  9976. streamCallback,
  9977. failCallback
  9978. );
  9979. }
  9980. /**
  9981. * Constructs inline install URL for Chrome desktop streaming extension.
  9982. * The 'chromeExtensionId' must be defined in config.js.
  9983. * @returns {string}
  9984. */
  9985. function getWebStoreInstallUrl()
  9986. {
  9987. return "https://chrome.google.com/webstore/detail/" +
  9988. config.chromeExtensionId;
  9989. }
  9990. /**
  9991. * Checks whether extension update is required.
  9992. * @param minVersion minimal required version
  9993. * @param extVersion current extension version
  9994. * @returns {boolean}
  9995. */
  9996. function isUpdateRequired(minVersion, extVersion)
  9997. {
  9998. try
  9999. {
  10000. var s1 = minVersion.split('.');
  10001. var s2 = extVersion.split('.');
  10002. var len = Math.max(s1.length, s2.length);
  10003. for (var i = 0; i < len; i++)
  10004. {
  10005. var n1 = 0,
  10006. n2 = 0;
  10007. if (i < s1.length)
  10008. n1 = parseInt(s1[i]);
  10009. if (i < s2.length)
  10010. n2 = parseInt(s2[i]);
  10011. if (isNaN(n1) || isNaN(n2))
  10012. {
  10013. return true;
  10014. }
  10015. else if (n1 !== n2)
  10016. {
  10017. return n1 > n2;
  10018. }
  10019. }
  10020. // will happen if boths version has identical numbers in
  10021. // their components (even if one of them is longer, has more components)
  10022. return false;
  10023. }
  10024. catch (e)
  10025. {
  10026. console.error("Failed to parse extension version", e);
  10027. APP.UI.messageHandler.showError("dialog.error",
  10028. "dialog.detectext");
  10029. return true;
  10030. }
  10031. }
  10032. function checkChromeExtInstalled(callback) {
  10033. if (!chrome.runtime) {
  10034. // No API, so no extension for sure
  10035. callback(false, false);
  10036. return;
  10037. }
  10038. chrome.runtime.sendMessage(
  10039. config.chromeExtensionId,
  10040. { getVersion: true },
  10041. function (response) {
  10042. if (!response || !response.version) {
  10043. // Communication failure - assume that no endpoint exists
  10044. console.warn(
  10045. "Extension not installed?: ", chrome.runtime.lastError);
  10046. callback(false, false);
  10047. return;
  10048. }
  10049. // Check installed extension version
  10050. var extVersion = response.version;
  10051. console.log('Extension version is: ' + extVersion);
  10052. var updateRequired
  10053. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10054. callback(!updateRequired, updateRequired);
  10055. }
  10056. );
  10057. }
  10058. function doGetStreamFromExtension(streamCallback, failCallback) {
  10059. // Sends 'getStream' msg to the extension.
  10060. // Extension id must be defined in the config.
  10061. chrome.runtime.sendMessage(
  10062. config.chromeExtensionId,
  10063. { getStream: true, sources: config.desktopSharingSources },
  10064. function (response) {
  10065. if (!response) {
  10066. failCallback(chrome.runtime.lastError);
  10067. return;
  10068. }
  10069. console.log("Response from extension: " + response);
  10070. if (response.streamId) {
  10071. APP.RTC.getUserMediaWithConstraints(
  10072. ['desktop'],
  10073. function (stream) {
  10074. streamCallback(stream);
  10075. },
  10076. failCallback,
  10077. null, null, null,
  10078. response.streamId);
  10079. } else {
  10080. failCallback("Extension failed to get the stream");
  10081. }
  10082. }
  10083. );
  10084. }
  10085. /**
  10086. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10087. * stream for returned stream token.
  10088. */
  10089. function obtainScreenFromExtension(streamCallback, failCallback) {
  10090. if (extInstalled) {
  10091. doGetStreamFromExtension(streamCallback, failCallback);
  10092. } else {
  10093. if (extUpdateRequired) {
  10094. alert(
  10095. 'Jitsi Desktop Streamer requires update. ' +
  10096. 'Changes will take effect after next Chrome restart.');
  10097. }
  10098. chrome.webstore.install(
  10099. getWebStoreInstallUrl(),
  10100. function (arg) {
  10101. console.log("Extension installed successfully", arg);
  10102. extInstalled = true;
  10103. // We need to give a moment for the endpoint to become available
  10104. window.setTimeout(function () {
  10105. doGetStreamFromExtension(streamCallback, failCallback);
  10106. }, 500);
  10107. },
  10108. function (arg) {
  10109. console.log("Failed to install the extension", arg);
  10110. failCallback(arg);
  10111. APP.UI.messageHandler.showError("dialog.error",
  10112. "dialog.failtoinstall");
  10113. }
  10114. );
  10115. }
  10116. }
  10117. /**
  10118. * Call this method to toggle desktop sharing feature.
  10119. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10120. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10121. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10122. * enabled), pass any other string or nothing in order to disable this
  10123. * feature completely.
  10124. */
  10125. function setDesktopSharing(method) {
  10126. obtainDesktopStream = null;
  10127. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10128. // care about 'method' parameter
  10129. if (RTCBrowserType.isTemasysPluginUsed()) {
  10130. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10131. console.info("Screensharing not supported by this plugin version");
  10132. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10133. console.info(
  10134. "Screensharing not available with Temasys plugin on this site");
  10135. } else {
  10136. obtainDesktopStream = obtainWebRTCScreen;
  10137. console.info("Using Temasys plugin for desktop sharing");
  10138. }
  10139. } else if (RTCBrowserType.isChrome()) {
  10140. if (method == "ext") {
  10141. if (RTCBrowserType.getChromeVersion() >= 34) {
  10142. obtainDesktopStream = obtainScreenFromExtension;
  10143. console.info("Using Chrome extension for desktop sharing");
  10144. initChromeExtension();
  10145. } else {
  10146. console.info("Chrome extension not supported until ver 34");
  10147. }
  10148. } else if (method == "webrtc") {
  10149. obtainDesktopStream = obtainWebRTCScreen;
  10150. console.info("Using Chrome WebRTC for desktop sharing");
  10151. }
  10152. }
  10153. if (!obtainDesktopStream) {
  10154. console.info("Desktop sharing disabled");
  10155. }
  10156. }
  10157. /**
  10158. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10159. * config.js to support inline installs. Host site must be selected as main
  10160. * website of published extension.
  10161. */
  10162. function initInlineInstalls()
  10163. {
  10164. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10165. }
  10166. function initChromeExtension() {
  10167. // Initialize Chrome extension inline installs
  10168. initInlineInstalls();
  10169. // Check if extension is installed
  10170. checkChromeExtInstalled(function (installed, updateRequired) {
  10171. extInstalled = installed;
  10172. extUpdateRequired = updateRequired;
  10173. console.info(
  10174. "Chrome extension installed: " + extInstalled +
  10175. " updateRequired: " + extUpdateRequired);
  10176. });
  10177. }
  10178. function getVideoStreamFailed(error) {
  10179. console.error("Failed to obtain the stream to switch to", error);
  10180. switchInProgress = false;
  10181. isUsingScreenStream = false;
  10182. newStreamCreated(null);
  10183. }
  10184. function getDesktopStreamFailed(error) {
  10185. console.error("Failed to obtain the stream to switch to", error);
  10186. switchInProgress = false;
  10187. }
  10188. function streamSwitchDone() {
  10189. switchInProgress = false;
  10190. eventEmitter.emit(
  10191. DesktopSharingEventTypes.SWITCHING_DONE,
  10192. isUsingScreenStream);
  10193. }
  10194. function newStreamCreated(stream)
  10195. {
  10196. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10197. stream, isUsingScreenStream, streamSwitchDone);
  10198. }
  10199. function onEndedHandler(stream) {
  10200. if (!switchInProgress && isUsingScreenStream) {
  10201. APP.desktopsharing.toggleScreenSharing();
  10202. }
  10203. //FIXME: to be verified
  10204. if (stream.removeEventListener) {
  10205. stream.removeEventListener('ended', onEndedHandler);
  10206. } else {
  10207. stream.detachEvent('ended', onEndedHandler);
  10208. }
  10209. }
  10210. // Called when RTC finishes initialization
  10211. function onWebRtcReady() {
  10212. setDesktopSharing(config.desktopSharing);
  10213. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10214. }
  10215. module.exports = {
  10216. isUsingScreenStream: function () {
  10217. return isUsingScreenStream;
  10218. },
  10219. /**
  10220. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10221. * and enabled.
  10222. */
  10223. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10224. init: function () {
  10225. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10226. },
  10227. addListener: function (listener, type)
  10228. {
  10229. eventEmitter.on(type, listener);
  10230. },
  10231. removeListener: function (listener, type) {
  10232. eventEmitter.removeListener(type, listener);
  10233. },
  10234. /*
  10235. * Toggles screen sharing.
  10236. */
  10237. toggleScreenSharing: function () {
  10238. if (switchInProgress || !obtainDesktopStream) {
  10239. console.warn("Switch in progress or no method defined");
  10240. return;
  10241. }
  10242. switchInProgress = true;
  10243. if (!isUsingScreenStream)
  10244. {
  10245. // Switch to desktop stream
  10246. obtainDesktopStream(
  10247. function (stream) {
  10248. // We now use screen stream
  10249. isUsingScreenStream = true;
  10250. // Hook 'ended' event to restore camera
  10251. // when screen stream stops
  10252. //FIXME: to be verified
  10253. if (stream.addEventListener) {
  10254. stream.addEventListener('ended', function () {
  10255. onEndedHandler(stream);
  10256. });
  10257. } else {
  10258. stream.attachEvent('ended', function () {
  10259. onEndedHandler(stream);
  10260. });
  10261. }
  10262. newStreamCreated(stream);
  10263. },
  10264. getDesktopStreamFailed);
  10265. } else {
  10266. // Disable screen stream
  10267. APP.RTC.getUserMediaWithConstraints(
  10268. ['video'],
  10269. function (stream) {
  10270. // We are now using camera stream
  10271. isUsingScreenStream = false;
  10272. newStreamCreated(stream);
  10273. },
  10274. getVideoStreamFailed, config.resolution || '360'
  10275. );
  10276. }
  10277. }
  10278. };
  10279. },{"../../service/RTC/RTCEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":107,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],47:[function(require,module,exports){
  10280. //maps keycode to character, id of popover for given function and function
  10281. var shortcuts = {
  10282. 67: {
  10283. character: "C",
  10284. id: "toggleChatPopover",
  10285. function: APP.UI.toggleChat
  10286. },
  10287. 70: {
  10288. character: "F",
  10289. id: "filmstripPopover",
  10290. function: APP.UI.toggleFilmStrip
  10291. },
  10292. 77: {
  10293. character: "M",
  10294. id: "mutePopover",
  10295. function: APP.UI.toggleAudio
  10296. },
  10297. 84: {
  10298. character: "T",
  10299. function: function() {
  10300. if(!APP.RTC.localAudio.isMuted()) {
  10301. APP.UI.toggleAudio();
  10302. }
  10303. }
  10304. },
  10305. 86: {
  10306. character: "V",
  10307. id: "toggleVideoPopover",
  10308. function: APP.UI.toggleVideo
  10309. }
  10310. };
  10311. var KeyboardShortcut = {
  10312. init: function () {
  10313. window.onkeyup = function(e) {
  10314. var keycode = e.which;
  10315. if(!($(":focus").is("input[type=text]") ||
  10316. $(":focus").is("input[type=password]") ||
  10317. $(":focus").is("textarea"))) {
  10318. if (typeof shortcuts[keycode] === "object") {
  10319. shortcuts[keycode].function();
  10320. }
  10321. else if (keycode >= "0".charCodeAt(0) &&
  10322. keycode <= "9".charCodeAt(0)) {
  10323. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10324. }
  10325. //esc while the smileys are visible hides them
  10326. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10327. APP.UI.toggleSmileys();
  10328. }
  10329. };
  10330. window.onkeydown = function(e) {
  10331. if(!($(":focus").is("input[type=text]") ||
  10332. $(":focus").is("input[type=password]") ||
  10333. $(":focus").is("textarea"))) {
  10334. if(e.which === "T".charCodeAt(0)) {
  10335. if(APP.RTC.localAudio.isMuted()) {
  10336. APP.UI.toggleAudio();
  10337. }
  10338. }
  10339. }
  10340. };
  10341. var self = this;
  10342. $('body').popover({ selector: '[data-toggle=popover]',
  10343. trigger: 'click hover',
  10344. content: function() {
  10345. return this.getAttribute("content") +
  10346. self.getShortcut(this.getAttribute("shortcut"));
  10347. }
  10348. });
  10349. },
  10350. /**
  10351. *
  10352. * @param id indicates the popover associated with the shortcut
  10353. * @returns {string} the keyboard shortcut used for the id given
  10354. */
  10355. getShortcut: function (id) {
  10356. for (var keycode in shortcuts) {
  10357. if (shortcuts.hasOwnProperty(keycode)) {
  10358. if (shortcuts[keycode].id === id) {
  10359. return " (" + shortcuts[keycode].character + ")";
  10360. }
  10361. }
  10362. }
  10363. return "";
  10364. }
  10365. };
  10366. module.exports = KeyboardShortcut;
  10367. },{}],48:[function(require,module,exports){
  10368. /* global APP */
  10369. /**
  10370. * This module is meant to (eventually) contain and manage all information
  10371. * about members/participants of the conference, so that other modules don't
  10372. * have to do it on their own, and so that other modules can access members'
  10373. * information from a single place.
  10374. *
  10375. * Currently this module only manages information about the support of jingle
  10376. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10377. * be added as needed.
  10378. */
  10379. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10380. var Events = require("../../service/members/Events");
  10381. var EventEmitter = require("events");
  10382. var eventEmitter = new EventEmitter();
  10383. /**
  10384. * The actual container.
  10385. */
  10386. var members = {};
  10387. /**
  10388. * There is at least one member that supports DTMF (i.e. is jigasi).
  10389. */
  10390. var atLeastOneDtmf = false;
  10391. function registerListeners() {
  10392. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10393. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10394. }
  10395. /**
  10396. * Handles a new member joining the MUC.
  10397. */
  10398. function onMucMemberJoined(jid, id, displayName) {
  10399. var member = {
  10400. displayName: displayName
  10401. };
  10402. APP.xmpp.getConnection().disco.info(
  10403. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10404. members[jid] = member;
  10405. }
  10406. /**
  10407. * Handles a member leaving the MUC.
  10408. */
  10409. function onMucMemberLeft(jid) {
  10410. delete members[jid];
  10411. updateAtLeastOneDtmf();
  10412. }
  10413. /**
  10414. * Handles the reception of a disco#info packet from a particular JID.
  10415. * @param jid the JID sending the packet.
  10416. * @param iq the packet.
  10417. */
  10418. function onDiscoInfoReceived(jid, iq) {
  10419. if (!members[jid])
  10420. return;
  10421. var supportsDtmf
  10422. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10423. updateDtmf(jid, supportsDtmf);
  10424. }
  10425. /**
  10426. * Updates the 'supportsDtmf' field for a member.
  10427. * @param jid the jid of the member.
  10428. * @param newValue the new value for the 'supportsDtmf' field.
  10429. */
  10430. function updateDtmf(jid, newValue) {
  10431. var oldValue = members[jid].supportsDtmf;
  10432. members[jid].supportsDtmf = newValue;
  10433. if (newValue != oldValue) {
  10434. updateAtLeastOneDtmf();
  10435. }
  10436. }
  10437. /**
  10438. * Checks each member's 'supportsDtmf' field and updates
  10439. * 'atLastOneSupportsDtmf'.
  10440. */
  10441. function updateAtLeastOneDtmf(){
  10442. var newAtLeastOneDtmf = false;
  10443. for (var key in members) {
  10444. if (typeof members[key].supportsDtmf !== 'undefined'
  10445. && members[key].supportsDtmf) {
  10446. newAtLeastOneDtmf= true;
  10447. break;
  10448. }
  10449. }
  10450. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10451. atLeastOneDtmf = newAtLeastOneDtmf;
  10452. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10453. }
  10454. }
  10455. /**
  10456. * Exported interface.
  10457. */
  10458. var Members = {
  10459. start: function(){
  10460. registerListeners();
  10461. },
  10462. addListener: function(type, listener)
  10463. {
  10464. eventEmitter.on(type, listener);
  10465. },
  10466. removeListener: function (type, listener) {
  10467. eventEmitter.removeListener(type, listener);
  10468. },
  10469. size: function () {
  10470. return Object.keys(members).length;
  10471. },
  10472. getMembers: function () {
  10473. return members;
  10474. }
  10475. };
  10476. module.exports = Members;
  10477. },{"../../service/members/Events":108,"../../service/xmpp/XMPPEvents":110,"events":1}],49:[function(require,module,exports){
  10478. var email = '';
  10479. var displayName = '';
  10480. var userId;
  10481. var language = null;
  10482. function supportsLocalStorage() {
  10483. try {
  10484. return 'localStorage' in window && window.localStorage !== null;
  10485. } catch (e) {
  10486. console.log("localstorage is not supported");
  10487. return false;
  10488. }
  10489. }
  10490. function generateUniqueId() {
  10491. function _p8() {
  10492. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10493. }
  10494. return _p8() + _p8() + _p8() + _p8();
  10495. }
  10496. if (supportsLocalStorage()) {
  10497. if (!window.localStorage.jitsiMeetId) {
  10498. window.localStorage.jitsiMeetId = generateUniqueId();
  10499. console.log("generated id", window.localStorage.jitsiMeetId);
  10500. }
  10501. userId = window.localStorage.jitsiMeetId || '';
  10502. email = window.localStorage.email || '';
  10503. displayName = window.localStorage.displayname || '';
  10504. language = window.localStorage.language;
  10505. } else {
  10506. console.log("local storage is not supported");
  10507. userId = generateUniqueId();
  10508. }
  10509. var Settings =
  10510. {
  10511. setDisplayName: function (newDisplayName) {
  10512. displayName = newDisplayName;
  10513. window.localStorage.displayname = displayName;
  10514. return displayName;
  10515. },
  10516. setEmail: function (newEmail)
  10517. {
  10518. email = newEmail;
  10519. window.localStorage.email = newEmail;
  10520. return email;
  10521. },
  10522. getSettings: function () {
  10523. return {
  10524. email: email,
  10525. displayName: displayName,
  10526. uid: userId,
  10527. language: language
  10528. };
  10529. },
  10530. setLanguage: function (lang) {
  10531. language = lang;
  10532. window.localStorage.language = lang;
  10533. }
  10534. };
  10535. module.exports = Settings;
  10536. },{}],50:[function(require,module,exports){
  10537. /**
  10538. * Provides statistics for the local stream.
  10539. */
  10540. /**
  10541. * Size of the webaudio analizer buffer.
  10542. * @type {number}
  10543. */
  10544. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10545. /**
  10546. * Value of the webaudio analizer smoothing time parameter.
  10547. * @type {number}
  10548. */
  10549. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10550. /**
  10551. * Converts time domain data array to audio level.
  10552. * @param array the time domain data array.
  10553. * @returns {number} the audio level
  10554. */
  10555. function timeDomainDataToAudioLevel(samples) {
  10556. var maxVolume = 0;
  10557. var length = samples.length;
  10558. for (var i = 0; i < length; i++) {
  10559. if (maxVolume < samples[i])
  10560. maxVolume = samples[i];
  10561. }
  10562. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10563. };
  10564. /**
  10565. * Animates audio level change
  10566. * @param newLevel the new audio level
  10567. * @param lastLevel the last audio level
  10568. * @returns {Number} the audio level to be set
  10569. */
  10570. function animateLevel(newLevel, lastLevel)
  10571. {
  10572. var value = 0;
  10573. var diff = lastLevel - newLevel;
  10574. if(diff > 0.2)
  10575. {
  10576. value = lastLevel - 0.2;
  10577. }
  10578. else if(diff < -0.4)
  10579. {
  10580. value = lastLevel + 0.4;
  10581. }
  10582. else
  10583. {
  10584. value = newLevel;
  10585. }
  10586. return parseFloat(value.toFixed(3));
  10587. }
  10588. /**
  10589. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10590. *
  10591. * @param stream the local stream
  10592. * @param interval stats refresh interval given in ms.
  10593. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10594. * update.
  10595. * @constructor
  10596. */
  10597. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10598. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10599. this.stream = stream;
  10600. this.intervalId = null;
  10601. this.intervalMilis = interval;
  10602. this.eventEmitter = eventEmitter;
  10603. this.audioLevel = 0;
  10604. this.statisticsService = statisticsService;
  10605. }
  10606. /**
  10607. * Starts the collecting the statistics.
  10608. */
  10609. LocalStatsCollector.prototype.start = function () {
  10610. if (config.disableAudioLevels || !window.AudioContext)
  10611. return;
  10612. var context = new AudioContext();
  10613. var analyser = context.createAnalyser();
  10614. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10615. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10616. var source = context.createMediaStreamSource(this.stream);
  10617. source.connect(analyser);
  10618. var self = this;
  10619. this.intervalId = setInterval(
  10620. function () {
  10621. var array = new Uint8Array(analyser.frequencyBinCount);
  10622. analyser.getByteTimeDomainData(array);
  10623. var audioLevel = timeDomainDataToAudioLevel(array);
  10624. if(audioLevel != self.audioLevel) {
  10625. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10626. self.eventEmitter.emit(
  10627. "statistics.audioLevel",
  10628. self.statisticsService.LOCAL_JID,
  10629. self.audioLevel);
  10630. }
  10631. },
  10632. this.intervalMilis
  10633. );
  10634. };
  10635. /**
  10636. * Stops collecting the statistics.
  10637. */
  10638. LocalStatsCollector.prototype.stop = function () {
  10639. if (this.intervalId) {
  10640. clearInterval(this.intervalId);
  10641. this.intervalId = null;
  10642. }
  10643. };
  10644. module.exports = LocalStatsCollector;
  10645. },{}],51:[function(require,module,exports){
  10646. /* global ssrc2jid */
  10647. /* jshint -W117 */
  10648. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10649. /**
  10650. * Calculates packet lost percent using the number of lost packets and the
  10651. * number of all packet.
  10652. * @param lostPackets the number of lost packets
  10653. * @param totalPackets the number of all packets.
  10654. * @returns {number} packet loss percent
  10655. */
  10656. function calculatePacketLoss(lostPackets, totalPackets) {
  10657. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10658. return 0;
  10659. return Math.round((lostPackets/totalPackets)*100);
  10660. }
  10661. function getStatValue(item, name) {
  10662. var browserType = RTCBrowserType.getBrowserType();
  10663. if (!keyMap[browserType][name])
  10664. throw "The property isn't supported!";
  10665. var key = keyMap[browserType][name];
  10666. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10667. item.stat(key) : item[key];
  10668. }
  10669. /**
  10670. * Peer statistics data holder.
  10671. * @constructor
  10672. */
  10673. function PeerStats()
  10674. {
  10675. this.ssrc2Loss = {};
  10676. this.ssrc2AudioLevel = {};
  10677. this.ssrc2bitrate = {};
  10678. this.ssrc2resolution = {};
  10679. }
  10680. /**
  10681. * The bandwidth
  10682. * @type {{}}
  10683. */
  10684. PeerStats.bandwidth = {};
  10685. /**
  10686. * The bit rate
  10687. * @type {{}}
  10688. */
  10689. PeerStats.bitrate = {};
  10690. /**
  10691. * The packet loss rate
  10692. * @type {{}}
  10693. */
  10694. PeerStats.packetLoss = null;
  10695. /**
  10696. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10697. * represented by this instance.
  10698. * @param ssrc audio or video RTP stream SSRC.
  10699. * @param lossRate new packet loss rate value to be set.
  10700. */
  10701. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10702. {
  10703. this.ssrc2Loss[ssrc] = lossRate;
  10704. };
  10705. /**
  10706. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10707. * represented by this instance.
  10708. * @param ssrc audio or video RTP stream SSRC.
  10709. * @param resolution new resolution value to be set.
  10710. */
  10711. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10712. {
  10713. if(resolution === null && this.ssrc2resolution[ssrc])
  10714. {
  10715. delete this.ssrc2resolution[ssrc];
  10716. }
  10717. else if(resolution !== null)
  10718. this.ssrc2resolution[ssrc] = resolution;
  10719. };
  10720. /**
  10721. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10722. * represented by this instance.
  10723. * @param ssrc audio or video RTP stream SSRC.
  10724. * @param bitrate new bitrate value to be set.
  10725. */
  10726. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10727. {
  10728. if(this.ssrc2bitrate[ssrc])
  10729. {
  10730. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10731. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10732. }
  10733. else {
  10734. this.ssrc2bitrate[ssrc] = bitrate;
  10735. }
  10736. };
  10737. /**
  10738. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10739. * the stream which belongs to the peer represented by this instance.
  10740. * @param ssrc RTP stream SSRC for which current audio level value will be
  10741. * updated.
  10742. * @param audioLevel the new audio level value to be set. Value is truncated to
  10743. * fit the range from 0 to 1.
  10744. */
  10745. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10746. {
  10747. // Range limit 0 - 1
  10748. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10749. };
  10750. function formatAudioLevel(audioLevel) {
  10751. return Math.min(Math.max(audioLevel, 0), 1);
  10752. }
  10753. /**
  10754. * Array with the transport information.
  10755. * @type {Array}
  10756. */
  10757. PeerStats.transport = [];
  10758. /**
  10759. * <tt>StatsCollector</tt> registers for stats updates of given
  10760. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10761. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10762. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10763. * instance as an event source.
  10764. *
  10765. * @param peerconnection webRTC peer connection object.
  10766. * @param interval stats refresh interval given in ms.
  10767. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10768. * called on stats update.
  10769. * @constructor
  10770. */
  10771. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10772. {
  10773. this.peerconnection = peerconnection;
  10774. this.baselineAudioLevelsReport = null;
  10775. this.currentAudioLevelsReport = null;
  10776. this.currentStatsReport = null;
  10777. this.baselineStatsReport = null;
  10778. this.audioLevelsIntervalId = null;
  10779. this.eventEmitter = eventEmitter;
  10780. /**
  10781. * Gather PeerConnection stats once every this many milliseconds.
  10782. */
  10783. this.GATHER_INTERVAL = 15000;
  10784. /**
  10785. * Log stats via the focus once every this many milliseconds.
  10786. */
  10787. this.LOG_INTERVAL = 60000;
  10788. /**
  10789. * Gather stats and store them in this.statsToBeLogged.
  10790. */
  10791. this.gatherStatsIntervalId = null;
  10792. /**
  10793. * Send the stats already saved in this.statsToBeLogged to be logged via
  10794. * the focus.
  10795. */
  10796. this.logStatsIntervalId = null;
  10797. /**
  10798. * Stores the statistics which will be send to the focus to be logged.
  10799. */
  10800. this.statsToBeLogged =
  10801. {
  10802. timestamps: [],
  10803. stats: {}
  10804. };
  10805. // Updates stats interval
  10806. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10807. this.statsIntervalId = null;
  10808. this.statsIntervalMilis = statsInterval;
  10809. // Map of jids to PeerStats
  10810. this.jid2stats = {};
  10811. }
  10812. module.exports = StatsCollector;
  10813. /**
  10814. * Stops stats updates.
  10815. */
  10816. StatsCollector.prototype.stop = function () {
  10817. if (this.audioLevelsIntervalId) {
  10818. clearInterval(this.audioLevelsIntervalId);
  10819. this.audioLevelsIntervalId = null;
  10820. }
  10821. if (this.statsIntervalId)
  10822. {
  10823. clearInterval(this.statsIntervalId);
  10824. this.statsIntervalId = null;
  10825. }
  10826. if(this.logStatsIntervalId)
  10827. {
  10828. clearInterval(this.logStatsIntervalId);
  10829. this.logStatsIntervalId = null;
  10830. }
  10831. if(this.gatherStatsIntervalId)
  10832. {
  10833. clearInterval(this.gatherStatsIntervalId);
  10834. this.gatherStatsIntervalId = null;
  10835. }
  10836. };
  10837. /**
  10838. * Callback passed to <tt>getStats</tt> method.
  10839. * @param error an error that occurred on <tt>getStats</tt> call.
  10840. */
  10841. StatsCollector.prototype.errorCallback = function (error)
  10842. {
  10843. console.error("Get stats error", error);
  10844. this.stop();
  10845. };
  10846. /**
  10847. * Starts stats updates.
  10848. */
  10849. StatsCollector.prototype.start = function ()
  10850. {
  10851. var self = this;
  10852. if(!config.disableAudioLevels) {
  10853. this.audioLevelsIntervalId = setInterval(
  10854. function () {
  10855. // Interval updates
  10856. self.peerconnection.getStats(
  10857. function (report) {
  10858. var results = null;
  10859. if (!report || !report.result ||
  10860. typeof report.result != 'function') {
  10861. results = report;
  10862. }
  10863. else {
  10864. results = report.result();
  10865. }
  10866. //console.error("Got interval report", results);
  10867. self.currentAudioLevelsReport = results;
  10868. self.processAudioLevelReport();
  10869. self.baselineAudioLevelsReport =
  10870. self.currentAudioLevelsReport;
  10871. },
  10872. self.errorCallback
  10873. );
  10874. },
  10875. self.audioLevelsIntervalMilis
  10876. );
  10877. }
  10878. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10879. this.statsIntervalId = setInterval(
  10880. function () {
  10881. // Interval updates
  10882. self.peerconnection.getStats(
  10883. function (report) {
  10884. var results = null;
  10885. if (!report || !report.result ||
  10886. typeof report.result != 'function') {
  10887. //firefox
  10888. results = report;
  10889. }
  10890. else {
  10891. //chrome
  10892. results = report.result();
  10893. }
  10894. //console.error("Got interval report", results);
  10895. self.currentStatsReport = results;
  10896. try {
  10897. self.processStatsReport();
  10898. }
  10899. catch (e) {
  10900. console.error("Unsupported key:" + e, e);
  10901. }
  10902. self.baselineStatsReport = self.currentStatsReport;
  10903. },
  10904. self.errorCallback
  10905. );
  10906. },
  10907. self.statsIntervalMilis
  10908. );
  10909. }
  10910. if (config.logStats && !navigator.mozGetUserMedia) {
  10911. this.gatherStatsIntervalId = setInterval(
  10912. function () {
  10913. self.peerconnection.getStats(
  10914. function (report) {
  10915. self.addStatsToBeLogged(report.result());
  10916. },
  10917. function () {
  10918. }
  10919. );
  10920. },
  10921. this.GATHER_INTERVAL
  10922. );
  10923. this.logStatsIntervalId = setInterval(
  10924. function() { self.logStats(); },
  10925. this.LOG_INTERVAL);
  10926. }
  10927. };
  10928. /**
  10929. * Checks whether a certain record should be included in the logged statistics.
  10930. */
  10931. function acceptStat(reportId, reportType, statName) {
  10932. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10933. return false;
  10934. if (reportType == "ssrc") {
  10935. if (statName == "googTrackId" ||
  10936. statName == "transportId" ||
  10937. statName == "ssrc")
  10938. return false;
  10939. }
  10940. return true;
  10941. }
  10942. /**
  10943. * Checks whether a certain record should be included in the logged statistics.
  10944. */
  10945. function acceptReport(id, type) {
  10946. if (id.substring(0, 15) == "googCertificate" ||
  10947. id.substring(0, 9) == "googTrack" ||
  10948. id.substring(0, 20) == "googLibjingleSession")
  10949. return false;
  10950. if (type == "googComponent")
  10951. return false;
  10952. return true;
  10953. }
  10954. /**
  10955. * Converts the stats to the format used for logging, and saves the data in
  10956. * this.statsToBeLogged.
  10957. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10958. */
  10959. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10960. var self = this;
  10961. var num_records = this.statsToBeLogged.timestamps.length;
  10962. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10963. reports.map(function (report) {
  10964. if (!acceptReport(report.id, report.type))
  10965. return;
  10966. var stat = self.statsToBeLogged.stats[report.id];
  10967. if (!stat) {
  10968. stat = self.statsToBeLogged.stats[report.id] = {};
  10969. }
  10970. stat.type = report.type;
  10971. report.names().map(function (name) {
  10972. if (!acceptStat(report.id, report.type, name))
  10973. return;
  10974. var values = stat[name];
  10975. if (!values) {
  10976. values = stat[name] = [];
  10977. }
  10978. while (values.length < num_records) {
  10979. values.push(null);
  10980. }
  10981. values.push(report.stat(name));
  10982. });
  10983. });
  10984. };
  10985. StatsCollector.prototype.logStats = function () {
  10986. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10987. return;
  10988. // Reset the stats
  10989. this.statsToBeLogged.stats = {};
  10990. this.statsToBeLogged.timestamps = [];
  10991. };
  10992. var keyMap = {};
  10993. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10994. "ssrc": "ssrc",
  10995. "packetsReceived": "packetsReceived",
  10996. "packetsLost": "packetsLost",
  10997. "packetsSent": "packetsSent",
  10998. "bytesReceived": "bytesReceived",
  10999. "bytesSent": "bytesSent"
  11000. };
  11001. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11002. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11003. "sendBandwidth": "googAvailableSendBandwidth",
  11004. "remoteAddress": "googRemoteAddress",
  11005. "transportType": "googTransportType",
  11006. "localAddress": "googLocalAddress",
  11007. "activeConnection": "googActiveConnection",
  11008. "ssrc": "ssrc",
  11009. "packetsReceived": "packetsReceived",
  11010. "packetsSent": "packetsSent",
  11011. "packetsLost": "packetsLost",
  11012. "bytesReceived": "bytesReceived",
  11013. "bytesSent": "bytesSent",
  11014. "googFrameHeightReceived": "googFrameHeightReceived",
  11015. "googFrameWidthReceived": "googFrameWidthReceived",
  11016. "googFrameHeightSent": "googFrameHeightSent",
  11017. "googFrameWidthSent": "googFrameWidthSent",
  11018. "audioInputLevel": "audioInputLevel",
  11019. "audioOutputLevel": "audioOutputLevel"
  11020. };
  11021. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11022. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11023. /**
  11024. * Stats processing logic.
  11025. */
  11026. StatsCollector.prototype.processStatsReport = function () {
  11027. if (!this.baselineStatsReport) {
  11028. return;
  11029. }
  11030. for (var idx in this.currentStatsReport) {
  11031. var now = this.currentStatsReport[idx];
  11032. try {
  11033. if (getStatValue(now, 'receiveBandwidth') ||
  11034. getStatValue(now, 'sendBandwidth')) {
  11035. PeerStats.bandwidth = {
  11036. "download": Math.round(
  11037. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11038. "upload": Math.round(
  11039. (getStatValue(now, 'sendBandwidth')) / 1000)
  11040. };
  11041. }
  11042. }
  11043. catch(e){/*not supported*/}
  11044. if(now.type == 'googCandidatePair')
  11045. {
  11046. var ip, type, localIP, active;
  11047. try {
  11048. ip = getStatValue(now, 'remoteAddress');
  11049. type = getStatValue(now, "transportType");
  11050. localIP = getStatValue(now, "localAddress");
  11051. active = getStatValue(now, "activeConnection");
  11052. }
  11053. catch(e){/*not supported*/}
  11054. if(!ip || !type || !localIP || active != "true")
  11055. continue;
  11056. var addressSaved = false;
  11057. for(var i = 0; i < PeerStats.transport.length; i++)
  11058. {
  11059. if(PeerStats.transport[i].ip == ip &&
  11060. PeerStats.transport[i].type == type &&
  11061. PeerStats.transport[i].localip == localIP)
  11062. {
  11063. addressSaved = true;
  11064. }
  11065. }
  11066. if(addressSaved)
  11067. continue;
  11068. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11069. continue;
  11070. }
  11071. if(now.type == "candidatepair")
  11072. {
  11073. if(now.state == "succeeded")
  11074. continue;
  11075. var local = this.currentStatsReport[now.localCandidateId];
  11076. var remote = this.currentStatsReport[now.remoteCandidateId];
  11077. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11078. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11079. }
  11080. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11081. now.type != "inboundrtp") {
  11082. continue;
  11083. }
  11084. var before = this.baselineStatsReport[idx];
  11085. if (!before) {
  11086. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11087. continue;
  11088. }
  11089. var ssrc = getStatValue(now, 'ssrc');
  11090. if(!ssrc)
  11091. continue;
  11092. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11093. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11094. console.warn("No jid for ssrc: " + ssrc);
  11095. continue;
  11096. }
  11097. var jidStats = this.jid2stats[jid];
  11098. if (!jidStats) {
  11099. jidStats = new PeerStats();
  11100. this.jid2stats[jid] = jidStats;
  11101. }
  11102. var isDownloadStream = true;
  11103. var key = 'packetsReceived';
  11104. if (!getStatValue(now, key))
  11105. {
  11106. isDownloadStream = false;
  11107. key = 'packetsSent';
  11108. if (!getStatValue(now, key))
  11109. {
  11110. console.warn("No packetsReceived nor packetSent stat found");
  11111. continue;
  11112. }
  11113. }
  11114. var packetsNow = getStatValue(now, key);
  11115. if(!packetsNow || packetsNow < 0)
  11116. packetsNow = 0;
  11117. var packetsBefore = getStatValue(before, key);
  11118. if(!packetsBefore || packetsBefore < 0)
  11119. packetsBefore = 0;
  11120. var packetRate = packetsNow - packetsBefore;
  11121. if(!packetRate || packetRate < 0)
  11122. packetRate = 0;
  11123. var currentLoss = getStatValue(now, 'packetsLost');
  11124. if(!currentLoss || currentLoss < 0)
  11125. currentLoss = 0;
  11126. var previousLoss = getStatValue(before, 'packetsLost');
  11127. if(!previousLoss || previousLoss < 0)
  11128. previousLoss = 0;
  11129. var lossRate = currentLoss - previousLoss;
  11130. if(!lossRate || lossRate < 0)
  11131. lossRate = 0;
  11132. var packetsTotal = (packetRate + lossRate);
  11133. jidStats.setSsrcLoss(ssrc,
  11134. {"packetsTotal": packetsTotal,
  11135. "packetsLost": lossRate,
  11136. "isDownloadStream": isDownloadStream});
  11137. var bytesReceived = 0, bytesSent = 0;
  11138. if(getStatValue(now, "bytesReceived"))
  11139. {
  11140. bytesReceived = getStatValue(now, "bytesReceived") -
  11141. getStatValue(before, "bytesReceived");
  11142. }
  11143. if(getStatValue(now, "bytesSent"))
  11144. {
  11145. bytesSent = getStatValue(now, "bytesSent") -
  11146. getStatValue(before, "bytesSent");
  11147. }
  11148. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11149. if(bytesReceived <= 0 || time <= 0)
  11150. {
  11151. bytesReceived = 0;
  11152. }
  11153. else
  11154. {
  11155. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11156. }
  11157. if(bytesSent <= 0 || time <= 0)
  11158. {
  11159. bytesSent = 0;
  11160. }
  11161. else
  11162. {
  11163. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11164. }
  11165. jidStats.setSsrcBitrate(ssrc, {
  11166. "download": bytesReceived,
  11167. "upload": bytesSent});
  11168. var resolution = {height: null, width: null};
  11169. try {
  11170. if (getStatValue(now, "googFrameHeightReceived") &&
  11171. getStatValue(now, "googFrameWidthReceived")) {
  11172. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11173. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11174. }
  11175. else if (getStatValue(now, "googFrameHeightSent") &&
  11176. getStatValue(now, "googFrameWidthSent")) {
  11177. resolution.height = getStatValue(now, "googFrameHeightSent");
  11178. resolution.width = getStatValue(now, "googFrameWidthSent");
  11179. }
  11180. }
  11181. catch(e){/*not supported*/}
  11182. if(resolution.height && resolution.width)
  11183. {
  11184. jidStats.setSsrcResolution(ssrc, resolution);
  11185. }
  11186. else
  11187. {
  11188. jidStats.setSsrcResolution(ssrc, null);
  11189. }
  11190. }
  11191. var self = this;
  11192. // Jid stats
  11193. var totalPackets = {download: 0, upload: 0};
  11194. var lostPackets = {download: 0, upload: 0};
  11195. var bitrateDownload = 0;
  11196. var bitrateUpload = 0;
  11197. var resolutions = {};
  11198. Object.keys(this.jid2stats).forEach(
  11199. function (jid)
  11200. {
  11201. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11202. function (ssrc)
  11203. {
  11204. var type = "upload";
  11205. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11206. type = "download";
  11207. totalPackets[type] +=
  11208. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11209. lostPackets[type] +=
  11210. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11211. }
  11212. );
  11213. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11214. function (ssrc) {
  11215. bitrateDownload +=
  11216. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11217. bitrateUpload +=
  11218. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11219. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11220. }
  11221. );
  11222. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11223. }
  11224. );
  11225. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11226. PeerStats.packetLoss = {
  11227. total:
  11228. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11229. totalPackets.download + totalPackets.upload),
  11230. download:
  11231. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11232. upload:
  11233. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11234. };
  11235. this.eventEmitter.emit("statistics.connectionstats",
  11236. {
  11237. "bitrate": PeerStats.bitrate,
  11238. "packetLoss": PeerStats.packetLoss,
  11239. "bandwidth": PeerStats.bandwidth,
  11240. "resolution": resolutions,
  11241. "transport": PeerStats.transport
  11242. });
  11243. PeerStats.transport = [];
  11244. };
  11245. /**
  11246. * Stats processing logic.
  11247. */
  11248. StatsCollector.prototype.processAudioLevelReport = function ()
  11249. {
  11250. if (!this.baselineAudioLevelsReport)
  11251. {
  11252. return;
  11253. }
  11254. for (var idx in this.currentAudioLevelsReport)
  11255. {
  11256. var now = this.currentAudioLevelsReport[idx];
  11257. if (now.type != 'ssrc')
  11258. {
  11259. continue;
  11260. }
  11261. var before = this.baselineAudioLevelsReport[idx];
  11262. if (!before)
  11263. {
  11264. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11265. continue;
  11266. }
  11267. var ssrc = getStatValue(now, 'ssrc');
  11268. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11269. if (!jid)
  11270. {
  11271. if((Date.now() - now.timestamp) < 3000)
  11272. console.warn("No jid for ssrc: " + ssrc);
  11273. continue;
  11274. }
  11275. var jidStats = this.jid2stats[jid];
  11276. if (!jidStats)
  11277. {
  11278. jidStats = new PeerStats();
  11279. this.jid2stats[jid] = jidStats;
  11280. }
  11281. // Audio level
  11282. var audioLevel = null;
  11283. try {
  11284. audioLevel = getStatValue(now, 'audioInputLevel');
  11285. if (!audioLevel)
  11286. audioLevel = getStatValue(now, 'audioOutputLevel');
  11287. }
  11288. catch(e) {/*not supported*/
  11289. console.warn("Audio Levels are not available in the statistics.");
  11290. clearInterval(this.audioLevelsIntervalId);
  11291. return;
  11292. }
  11293. if (audioLevel)
  11294. {
  11295. // TODO: can't find specs about what this value really is,
  11296. // but it seems to vary between 0 and around 32k.
  11297. audioLevel = audioLevel / 32767;
  11298. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11299. if(jid != APP.xmpp.myJid())
  11300. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11301. }
  11302. }
  11303. };
  11304. },{"../RTC/RTCBrowserType":10}],52:[function(require,module,exports){
  11305. var callStats = null;
  11306. function initCallback (err, msg) {
  11307. console.log("Initializing Status: err="+err+" msg="+msg);
  11308. }
  11309. var CallStats = {
  11310. init: function (jingleSession) {
  11311. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  11312. return;
  11313. callStats = new callstats($,io,jsSHA);
  11314. this.session = jingleSession;
  11315. this.peerconnection = jingleSession.peerconnection.peerconnection;
  11316. this.userID = APP.xmpp.myResource();
  11317. var roomJid = APP.UI.getRoomName();
  11318. this.confID = roomJid? Strophe.getNodeFromJid(roomJid) : null;
  11319. //userID is generated or given by the origin server
  11320. callStats.initialize(config.callStatsID,
  11321. config.callStatsSecret,
  11322. this.userID,
  11323. initCallback);
  11324. var usage = callStats.fabricUsage.unbundled;
  11325. if(config.useBundle)
  11326. usage = callStats.fabricUsage.multiplex;
  11327. callStats.addNewFabric(this.peerconnection,
  11328. Strophe.getResourceFromJid(jingleSession.peerjid),
  11329. usage,
  11330. this.confID,
  11331. this.pcCallback.bind(this));
  11332. },
  11333. pcCallback: function (err, msg) {
  11334. if(!callStats)
  11335. return;
  11336. console.log("Monitoring status: "+ err + " msg: " + msg);
  11337. callStats.sendFabricEvent(this.peerconnection,
  11338. callStats.fabricEvent.fabricSetup, this.confID);
  11339. },
  11340. sendMuteEvent: function (mute, type) {
  11341. if(!callStats)
  11342. return;
  11343. var event = null;
  11344. if(type === "video")
  11345. {
  11346. event = (mute? callStats.fabricEvent.videoPause :
  11347. callStats.fabricEvent.videoResume);
  11348. }
  11349. else
  11350. {
  11351. event = (mute? callStats.fabricEvent.audioMute :
  11352. callStats.fabricEvent.audioUnmute);
  11353. }
  11354. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  11355. },
  11356. sendTerminateEvent: function () {
  11357. if(!callStats)
  11358. return;
  11359. callStats.sendFabricEvent(this.peerconnection,
  11360. callStats.fabricEvent.fabricTerminated, this.confID);
  11361. },
  11362. sendSetupFailedEvent: function () {
  11363. if(!callStats)
  11364. return;
  11365. callStats.sendFabricEvent(this.peerconnection,
  11366. callStats.fabricEvent.fabricSetupFailed, this.confID);
  11367. }
  11368. };
  11369. module.exports = CallStats;
  11370. },{}],53:[function(require,module,exports){
  11371. /**
  11372. * Created by hristo on 8/4/14.
  11373. */
  11374. var LocalStats = require("./LocalStatsCollector.js");
  11375. var RTPStats = require("./RTPStatsCollector.js");
  11376. var EventEmitter = require("events");
  11377. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11378. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11379. var CallStats = require("./callstats");
  11380. var RTCEvents = require("../../service/RTC/RTCEvents");
  11381. var eventEmitter = new EventEmitter();
  11382. var localStats = null;
  11383. var rtpStats = null;
  11384. function stopLocal()
  11385. {
  11386. if(localStats)
  11387. {
  11388. localStats.stop();
  11389. localStats = null;
  11390. }
  11391. }
  11392. function stopRemote()
  11393. {
  11394. if(rtpStats)
  11395. {
  11396. rtpStats.stop();
  11397. eventEmitter.emit("statistics.stop");
  11398. rtpStats = null;
  11399. }
  11400. }
  11401. function startRemoteStats (peerconnection) {
  11402. if(rtpStats)
  11403. {
  11404. rtpStats.stop();
  11405. rtpStats = null;
  11406. }
  11407. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11408. rtpStats.start();
  11409. }
  11410. function onStreamCreated(stream)
  11411. {
  11412. if(stream.getOriginalStream().getAudioTracks().length === 0)
  11413. return;
  11414. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11415. eventEmitter);
  11416. localStats.start();
  11417. }
  11418. function onDisposeConference(onUnload) {
  11419. CallStats.sendTerminateEvent();
  11420. stopRemote();
  11421. if(onUnload) {
  11422. stopLocal();
  11423. eventEmitter.removeAllListeners();
  11424. }
  11425. }
  11426. var statistics =
  11427. {
  11428. /**
  11429. * Indicates that this audio level is for local jid.
  11430. * @type {string}
  11431. */
  11432. LOCAL_JID: 'local',
  11433. addAudioLevelListener: function(listener)
  11434. {
  11435. eventEmitter.on("statistics.audioLevel", listener);
  11436. },
  11437. removeAudioLevelListener: function(listener)
  11438. {
  11439. eventEmitter.removeListener("statistics.audioLevel", listener);
  11440. },
  11441. addConnectionStatsListener: function(listener)
  11442. {
  11443. eventEmitter.on("statistics.connectionstats", listener);
  11444. },
  11445. removeConnectionStatsListener: function(listener)
  11446. {
  11447. eventEmitter.removeListener("statistics.connectionstats", listener);
  11448. },
  11449. addRemoteStatsStopListener: function(listener)
  11450. {
  11451. eventEmitter.on("statistics.stop", listener);
  11452. },
  11453. removeRemoteStatsStopListener: function(listener)
  11454. {
  11455. eventEmitter.removeListener("statistics.stop", listener);
  11456. },
  11457. stop: function () {
  11458. stopLocal();
  11459. stopRemote();
  11460. if(eventEmitter)
  11461. {
  11462. eventEmitter.removeAllListeners();
  11463. }
  11464. },
  11465. stopRemoteStatistics: function()
  11466. {
  11467. stopRemote();
  11468. },
  11469. start: function () {
  11470. APP.RTC.addStreamListener(onStreamCreated,
  11471. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11472. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11473. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11474. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11475. startRemoteStats(event.peerconnection);
  11476. // CallStats.init(event);
  11477. });
  11478. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11479. CallStats.init(session);
  11480. })
  11481. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11482. CallStats.sendMuteEvent(mute, "audio");
  11483. });
  11484. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11485. CallStats.sendSetupFailedEvent();
  11486. })
  11487. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11488. CallStats.sendMuteEvent(mute, "video");
  11489. });
  11490. }
  11491. };
  11492. module.exports = statistics;
  11493. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes.js":103,"../../service/xmpp/XMPPEvents":110,"./LocalStatsCollector.js":50,"./RTPStatsCollector.js":51,"./callstats":52,"events":1}],54:[function(require,module,exports){
  11494. var i18n = require("i18next-client");
  11495. var languages = require("../../service/translation/languages");
  11496. var Settings = require("../settings/Settings");
  11497. var DEFAULT_LANG = languages.EN;
  11498. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11499. return value.replace("__app__", interfaceConfig.APP_NAME);
  11500. });
  11501. var defaultOptions = {
  11502. detectLngQS: "lang",
  11503. useCookie: false,
  11504. fallbackLng: DEFAULT_LANG,
  11505. load: "unspecific",
  11506. resGetPath: 'lang/__ns__-__lng__.json',
  11507. ns: {
  11508. namespaces: ['main', 'languages'],
  11509. defaultNs: 'main'
  11510. },
  11511. lngWhitelist : languages.getLanguages(),
  11512. fallbackOnNull: true,
  11513. fallbackOnEmpty: true,
  11514. useDataAttrOptions: true,
  11515. defaultValueFromContent: false,
  11516. app: interfaceConfig.APP_NAME,
  11517. getAsync: false,
  11518. defaultValueFromContent: false,
  11519. customLoad: function(lng, ns, options, done) {
  11520. var resPath = "lang/__ns__-__lng__.json";
  11521. if(lng === languages.EN)
  11522. resPath = "lang/__ns__.json";
  11523. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11524. i18n.functions.ajax({
  11525. url: url,
  11526. success: function(data, status, xhr) {
  11527. i18n.functions.log('loaded: ' + url);
  11528. done(null, data);
  11529. },
  11530. error : function(xhr, status, error) {
  11531. if ((status && status == 200) ||
  11532. (xhr && xhr.status && xhr.status == 200)) {
  11533. // file loaded but invalid json, stop waste time !
  11534. i18n.functions.error('There is a typo in: ' + url);
  11535. } else if ((status && status == 404) ||
  11536. (xhr && xhr.status && xhr.status == 404)) {
  11537. i18n.functions.log('Does not exist: ' + url);
  11538. } else {
  11539. var theStatus = status ? status :
  11540. ((xhr && xhr.status) ? xhr.status : null);
  11541. i18n.functions.log(theStatus + ' when loading ' + url);
  11542. }
  11543. done(error, {});
  11544. },
  11545. dataType: "json",
  11546. async : options.getAsync
  11547. });
  11548. }
  11549. // options for caching
  11550. // useLocalStorage: true,
  11551. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11552. };
  11553. function initCompleted(t)
  11554. {
  11555. $("[data-i18n]").i18n();
  11556. }
  11557. function checkForParameter() {
  11558. var query = window.location.search.substring(1);
  11559. var vars = query.split("&");
  11560. for (var i=0;i<vars.length;i++) {
  11561. var pair = vars[i].split("=");
  11562. if(pair[0] == "lang")
  11563. {
  11564. return pair[1];
  11565. }
  11566. }
  11567. return null;
  11568. }
  11569. module.exports = {
  11570. init: function (lang) {
  11571. var options = defaultOptions;
  11572. if(!lang)
  11573. {
  11574. lang = checkForParameter();
  11575. if(!lang)
  11576. {
  11577. var settings = Settings.getSettings();
  11578. if(settings)
  11579. lang = settings.language;
  11580. if(!lang && config.defaultLanguage)
  11581. {
  11582. lang = config.defaultLanguage;
  11583. }
  11584. }
  11585. }
  11586. if(lang) {
  11587. options.lng = lang;
  11588. }
  11589. i18n.init(options, initCompleted);
  11590. },
  11591. translateString: function (key, options) {
  11592. return i18n.t(key, options);
  11593. },
  11594. setLanguage: function (lang) {
  11595. if(!lang)
  11596. lang = DEFAULT_LANG;
  11597. i18n.setLng(lang, defaultOptions, initCompleted);
  11598. },
  11599. getCurrentLanguage: function () {
  11600. return i18n.lng();
  11601. },
  11602. translateElement: function (selector) {
  11603. selector.i18n();
  11604. },
  11605. generateTranslationHTML: function (key, options) {
  11606. var str = "<span data-i18n=\"" + key + "\"";
  11607. if(options)
  11608. {
  11609. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11610. }
  11611. str += ">";
  11612. str += this.translateString(key, options);
  11613. str += "</span>";
  11614. return str;
  11615. }
  11616. };
  11617. },{"../../service/translation/languages":109,"../settings/Settings":49,"i18next-client":70}],55:[function(require,module,exports){
  11618. /* jshint -W117 */
  11619. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11620. var SDPDiffer = require("./SDPDiffer");
  11621. var SDPUtil = require("./SDPUtil");
  11622. var SDP = require("./SDP");
  11623. var async = require("async");
  11624. var transform = require("sdp-transform");
  11625. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11626. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11627. // Jingle stuff
  11628. function JingleSession(me, sid, connection, service, eventEmitter) {
  11629. this.me = me;
  11630. this.sid = sid;
  11631. this.connection = connection;
  11632. this.initiator = null;
  11633. this.responder = null;
  11634. this.isInitiator = null;
  11635. this.peerjid = null;
  11636. this.state = null;
  11637. this.localSDP = null;
  11638. this.remoteSDP = null;
  11639. this.relayedStreams = [];
  11640. this.startTime = null;
  11641. this.stopTime = null;
  11642. this.media_constraints = null;
  11643. this.pc_constraints = null;
  11644. this.ice_config = {};
  11645. this.drip_container = [];
  11646. this.service = service;
  11647. this.usetrickle = true;
  11648. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11649. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11650. this.hadstuncandidate = false;
  11651. this.hadturncandidate = false;
  11652. this.lasticecandidate = false;
  11653. this.statsinterval = null;
  11654. this.reason = null;
  11655. this.addssrc = [];
  11656. this.removessrc = [];
  11657. this.pendingop = null;
  11658. this.switchstreams = false;
  11659. this.wait = true;
  11660. this.localStreamsSSRC = null;
  11661. this.eventEmitter = eventEmitter;
  11662. /**
  11663. * The indicator which determines whether the (local) video has been muted
  11664. * in response to a user command in contrast to an automatic decision made
  11665. * by the application logic.
  11666. */
  11667. this.videoMuteByUser = false;
  11668. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11669. // We start with the queue paused. We resume it when the signaling state is
  11670. // stable and the ice connection state is connected.
  11671. this.modifySourcesQueue.pause();
  11672. }
  11673. JingleSession.prototype.updateModifySourcesQueue = function() {
  11674. var signalingState = this.peerconnection.signalingState;
  11675. var iceConnectionState = this.peerconnection.iceConnectionState;
  11676. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11677. this.modifySourcesQueue.resume();
  11678. } else {
  11679. this.modifySourcesQueue.pause();
  11680. }
  11681. };
  11682. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11683. var self = this;
  11684. if (this.state !== null) {
  11685. console.error('attempt to initiate on session ' + this.sid +
  11686. 'in state ' + this.state);
  11687. return;
  11688. }
  11689. this.isInitiator = isInitiator;
  11690. this.state = 'pending';
  11691. this.initiator = isInitiator ? this.me : peerjid;
  11692. this.responder = !isInitiator ? this.me : peerjid;
  11693. this.peerjid = peerjid;
  11694. this.hadstuncandidate = false;
  11695. this.hadturncandidate = false;
  11696. this.lasticecandidate = false;
  11697. this.peerconnection
  11698. = new TraceablePeerConnection(
  11699. this.connection.jingle.ice_config,
  11700. this.connection.jingle.pc_constraints,
  11701. this);
  11702. this.peerconnection.onicecandidate = function (event) {
  11703. self.sendIceCandidate(event.candidate);
  11704. };
  11705. this.peerconnection.onaddstream = function (event) {
  11706. if (event.stream.id !== 'default') {
  11707. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  11708. self.remoteStreamAdded(event);
  11709. } else {
  11710. // This is a recvonly stream. Clients that implement Unified Plan,
  11711. // such as Firefox use recvonly "streams/channels/tracks" for
  11712. // receiving remote stream/tracks, as opposed to Plan B where there
  11713. // are only 3 channels: audio, video and data.
  11714. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11715. }
  11716. };
  11717. this.peerconnection.onremovestream = function (event) {
  11718. // Remove the stream from remoteStreams
  11719. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11720. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11721. };
  11722. this.peerconnection.onsignalingstatechange = function (event) {
  11723. if (!(self && self.peerconnection)) return;
  11724. self.updateModifySourcesQueue();
  11725. };
  11726. this.peerconnection.oniceconnectionstatechange = function (event) {
  11727. if (!(self && self.peerconnection)) return;
  11728. self.updateModifySourcesQueue();
  11729. switch (self.peerconnection.iceConnectionState) {
  11730. case 'connected':
  11731. this.startTime = new Date();
  11732. break;
  11733. case 'disconnected':
  11734. this.stopTime = new Date();
  11735. break;
  11736. case 'failed':
  11737. self.eventEmitter(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11738. break;
  11739. }
  11740. onIceConnectionStateChange(self.sid, self);
  11741. };
  11742. this.peerconnection.onnegotiationneeded = function (event) {
  11743. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  11744. };
  11745. // add any local and relayed stream
  11746. APP.RTC.localStreams.forEach(function(stream) {
  11747. self.peerconnection.addStream(stream.getOriginalStream());
  11748. });
  11749. this.relayedStreams.forEach(function(stream) {
  11750. self.peerconnection.addStream(stream);
  11751. });
  11752. };
  11753. function onIceConnectionStateChange(sid, session) {
  11754. switch (session.peerconnection.iceConnectionState) {
  11755. case 'checking':
  11756. session.timeChecking = (new Date()).getTime();
  11757. session.firstconnect = true;
  11758. break;
  11759. case 'completed': // on caller side
  11760. case 'connected':
  11761. if (session.firstconnect) {
  11762. session.firstconnect = false;
  11763. var metadata = {};
  11764. metadata.setupTime
  11765. = (new Date()).getTime() - session.timeChecking;
  11766. session.peerconnection.getStats(function (res) {
  11767. if(res && res.result) {
  11768. res.result().forEach(function (report) {
  11769. if (report.type == 'googCandidatePair' &&
  11770. report.stat('googActiveConnection') == 'true') {
  11771. metadata.localCandidateType
  11772. = report.stat('googLocalCandidateType');
  11773. metadata.remoteCandidateType
  11774. = report.stat('googRemoteCandidateType');
  11775. // log pair as well so we can get nice pie
  11776. // charts
  11777. metadata.candidatePair
  11778. = report.stat('googLocalCandidateType') +
  11779. ';' +
  11780. report.stat('googRemoteCandidateType');
  11781. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11782. {
  11783. metadata.ipv6 = true;
  11784. }
  11785. }
  11786. });
  11787. }
  11788. });
  11789. }
  11790. break;
  11791. }
  11792. }
  11793. JingleSession.prototype.accept = function () {
  11794. var self = this;
  11795. this.state = 'active';
  11796. var pranswer = this.peerconnection.localDescription;
  11797. if (!pranswer || pranswer.type != 'pranswer') {
  11798. return;
  11799. }
  11800. console.log('going from pranswer to answer');
  11801. if (this.usetrickle) {
  11802. // remove candidates already sent from session-accept
  11803. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11804. for (var i = 0; i < lines.length; i++) {
  11805. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11806. }
  11807. }
  11808. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11809. // FIXME: change any inactive to sendrecv or whatever they were originally
  11810. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11811. }
  11812. var prsdp = new SDP(pranswer.sdp);
  11813. var accept = $iq({to: this.peerjid,
  11814. type: 'set'})
  11815. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11816. action: 'session-accept',
  11817. initiator: this.initiator,
  11818. responder: this.responder,
  11819. sid: this.sid });
  11820. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11821. var sdp = this.peerconnection.localDescription.sdp;
  11822. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11823. // FIXME: change any inactive to sendrecv or whatever they were originally
  11824. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11825. }
  11826. var self = this;
  11827. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11828. function () {
  11829. //console.log('setLocalDescription success');
  11830. self.setLocalDescription();
  11831. self.connection.sendIQ(accept,
  11832. function () {
  11833. var ack = {};
  11834. ack.source = 'answer';
  11835. $(document).trigger('ack.jingle', [self.sid, ack]);
  11836. },
  11837. function (stanza) {
  11838. var error = ($(stanza).find('error').length) ? {
  11839. code: $(stanza).find('error').attr('code'),
  11840. reason: $(stanza).find('error :first')[0].tagName
  11841. }:{};
  11842. error.source = 'answer';
  11843. JingleSession.onJingleError(self.sid, error);
  11844. },
  11845. 10000);
  11846. },
  11847. function (e) {
  11848. console.error('setLocalDescription failed', e);
  11849. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  11850. }
  11851. );
  11852. };
  11853. JingleSession.prototype.terminate = function (reason) {
  11854. this.state = 'ended';
  11855. this.reason = reason;
  11856. this.peerconnection.close();
  11857. if (this.statsinterval !== null) {
  11858. window.clearInterval(this.statsinterval);
  11859. this.statsinterval = null;
  11860. }
  11861. };
  11862. JingleSession.prototype.active = function () {
  11863. return this.state == 'active';
  11864. };
  11865. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11866. var self = this;
  11867. if (candidate && !this.lasticecandidate) {
  11868. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11869. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11870. if (!(ice && jcand)) {
  11871. console.error('failed to get ice && jcand');
  11872. return;
  11873. }
  11874. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11875. if (jcand.type === 'srflx') {
  11876. this.hadstuncandidate = true;
  11877. } else if (jcand.type === 'relay') {
  11878. this.hadturncandidate = true;
  11879. }
  11880. if (this.usetrickle) {
  11881. if (this.usedrip) {
  11882. if (this.drip_container.length === 0) {
  11883. // start 20ms callout
  11884. window.setTimeout(function () {
  11885. if (self.drip_container.length === 0) return;
  11886. self.sendIceCandidates(self.drip_container);
  11887. self.drip_container = [];
  11888. }, 20);
  11889. }
  11890. this.drip_container.push(candidate);
  11891. return;
  11892. } else {
  11893. self.sendIceCandidate([candidate]);
  11894. }
  11895. }
  11896. } else {
  11897. //console.log('sendIceCandidate: last candidate.');
  11898. if (!this.usetrickle) {
  11899. //console.log('should send full offer now...');
  11900. var init = $iq({to: this.peerjid,
  11901. type: 'set'})
  11902. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11903. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11904. initiator: this.initiator,
  11905. sid: this.sid});
  11906. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11907. var self = this;
  11908. var sendJingle = function (ssrc) {
  11909. if(!ssrc)
  11910. ssrc = {};
  11911. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  11912. self.connection.sendIQ(init,
  11913. function () {
  11914. //console.log('session initiate ack');
  11915. var ack = {};
  11916. ack.source = 'offer';
  11917. $(document).trigger('ack.jingle', [self.sid, ack]);
  11918. },
  11919. function (stanza) {
  11920. self.state = 'error';
  11921. self.peerconnection.close();
  11922. var error = ($(stanza).find('error').length) ? {
  11923. code: $(stanza).find('error').attr('code'),
  11924. reason: $(stanza).find('error :first')[0].tagName,
  11925. }:{};
  11926. error.source = 'offer';
  11927. JingleSession.onJingleError(self.sid, error);
  11928. },
  11929. 10000);
  11930. }
  11931. sendJingle();
  11932. }
  11933. this.lasticecandidate = true;
  11934. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11935. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11936. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11937. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11938. }
  11939. }
  11940. };
  11941. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11942. console.log('sendIceCandidates', candidates);
  11943. var cand = $iq({to: this.peerjid, type: 'set'})
  11944. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11945. action: 'transport-info',
  11946. initiator: this.initiator,
  11947. sid: this.sid});
  11948. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11949. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11950. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11951. if (cands.length > 0) {
  11952. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11953. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11954. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11955. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11956. }).c('transport', ice);
  11957. for (var i = 0; i < cands.length; i++) {
  11958. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11959. }
  11960. // add fingerprint
  11961. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11962. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11963. tmp.required = true;
  11964. cand.c(
  11965. 'fingerprint',
  11966. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11967. .t(tmp.fingerprint);
  11968. delete tmp.fingerprint;
  11969. cand.attrs(tmp);
  11970. cand.up();
  11971. }
  11972. cand.up(); // transport
  11973. cand.up(); // content
  11974. }
  11975. }
  11976. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11977. //console.log('was this the last candidate', this.lasticecandidate);
  11978. this.connection.sendIQ(cand,
  11979. function () {
  11980. var ack = {};
  11981. ack.source = 'transportinfo';
  11982. $(document).trigger('ack.jingle', [this.sid, ack]);
  11983. },
  11984. function (stanza) {
  11985. var error = ($(stanza).find('error').length) ? {
  11986. code: $(stanza).find('error').attr('code'),
  11987. reason: $(stanza).find('error :first')[0].tagName,
  11988. }:{};
  11989. error.source = 'transportinfo';
  11990. JingleSession.onJingleError(this.sid, error);
  11991. },
  11992. 10000);
  11993. };
  11994. JingleSession.prototype.sendOffer = function () {
  11995. //console.log('sendOffer...');
  11996. var self = this;
  11997. this.peerconnection.createOffer(function (sdp) {
  11998. self.createdOffer(sdp);
  11999. },
  12000. function (e) {
  12001. console.error('createOffer failed', e);
  12002. },
  12003. this.media_constraints
  12004. );
  12005. };
  12006. JingleSession.prototype.createdOffer = function (sdp) {
  12007. //console.log('createdOffer', sdp);
  12008. var self = this;
  12009. this.localSDP = new SDP(sdp.sdp);
  12010. //this.localSDP.mangle();
  12011. var sendJingle = function () {
  12012. var init = $iq({to: this.peerjid,
  12013. type: 'set'})
  12014. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12015. action: 'session-initiate',
  12016. initiator: this.initiator,
  12017. sid: this.sid});
  12018. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  12019. self.connection.sendIQ(init,
  12020. function () {
  12021. var ack = {};
  12022. ack.source = 'offer';
  12023. $(document).trigger('ack.jingle', [self.sid, ack]);
  12024. },
  12025. function (stanza) {
  12026. self.state = 'error';
  12027. self.peerconnection.close();
  12028. var error = ($(stanza).find('error').length) ? {
  12029. code: $(stanza).find('error').attr('code'),
  12030. reason: $(stanza).find('error :first')[0].tagName,
  12031. }:{};
  12032. error.source = 'offer';
  12033. JingleSession.onJingleError(self.sid, error);
  12034. },
  12035. 10000);
  12036. }
  12037. sdp.sdp = this.localSDP.raw;
  12038. this.peerconnection.setLocalDescription(sdp,
  12039. function () {
  12040. if(self.usetrickle)
  12041. {
  12042. sendJingle();
  12043. }
  12044. self.setLocalDescription();
  12045. //console.log('setLocalDescription success');
  12046. },
  12047. function (e) {
  12048. console.error('setLocalDescription failed', e);
  12049. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12050. }
  12051. );
  12052. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12053. for (var i = 0; i < cands.length; i++) {
  12054. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12055. if (cand.type == 'srflx') {
  12056. this.hadstuncandidate = true;
  12057. } else if (cand.type == 'relay') {
  12058. this.hadturncandidate = true;
  12059. }
  12060. }
  12061. };
  12062. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  12063. //console.log('setting remote description... ', desctype);
  12064. this.remoteSDP = new SDP('');
  12065. this.remoteSDP.fromJingle(elem);
  12066. if (this.peerconnection.remoteDescription !== null) {
  12067. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12068. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12069. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12070. for (var i = 0; i < pranswer.media.length; i++) {
  12071. // make sure we have ice ufrag and pwd
  12072. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12073. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12074. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12075. } else {
  12076. console.warn('no ice ufrag?');
  12077. }
  12078. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12079. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12080. } else {
  12081. console.warn('no ice pwd?');
  12082. }
  12083. }
  12084. // copy over candidates
  12085. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12086. for (var j = 0; j < lines.length; j++) {
  12087. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12088. }
  12089. }
  12090. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12091. }
  12092. }
  12093. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12094. this.peerconnection.setRemoteDescription(remotedesc,
  12095. function () {
  12096. //console.log('setRemoteDescription success');
  12097. },
  12098. function (e) {
  12099. console.error('setRemoteDescription error', e);
  12100. JingleSession.onJingleFatalError(self, e);
  12101. }
  12102. );
  12103. };
  12104. JingleSession.prototype.addIceCandidate = function (elem) {
  12105. var self = this;
  12106. if (this.peerconnection.signalingState == 'closed') {
  12107. return;
  12108. }
  12109. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12110. console.log('trickle ice candidate arriving before session accept...');
  12111. // create a PRANSWER for setRemoteDescription
  12112. if (!this.remoteSDP) {
  12113. var cobbled = 'v=0\r\n' +
  12114. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12115. 's=-\r\n' +
  12116. 't=0 0\r\n';
  12117. // first, take some things from the local description
  12118. for (var i = 0; i < this.localSDP.media.length; i++) {
  12119. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12120. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12121. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12122. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12123. }
  12124. cobbled += 'a=inactive\r\n';
  12125. }
  12126. this.remoteSDP = new SDP(cobbled);
  12127. }
  12128. // then add things like ice and dtls from remote candidate
  12129. elem.each(function () {
  12130. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12131. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12132. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12133. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12134. var tmp = $(this).find('transport');
  12135. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12136. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12137. tmp = $(this).find('transport>fingerprint');
  12138. if (tmp.length) {
  12139. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12140. } else {
  12141. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12142. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12143. }
  12144. break;
  12145. }
  12146. }
  12147. }
  12148. });
  12149. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12150. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12151. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12152. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12153. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12154. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12155. }).length == this.remoteSDP.media.length;
  12156. if (iscomplete) {
  12157. console.log('setting pranswer');
  12158. try {
  12159. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12160. function() {
  12161. },
  12162. function(e) {
  12163. console.log('setRemoteDescription pranswer failed', e.toString());
  12164. });
  12165. } catch (e) {
  12166. console.error('setting pranswer failed', e);
  12167. }
  12168. } else {
  12169. //console.log('not yet setting pranswer');
  12170. }
  12171. }
  12172. // operate on each content element
  12173. elem.each(function () {
  12174. // would love to deactivate this, but firefox still requires it
  12175. var idx = -1;
  12176. var i;
  12177. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12178. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12179. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12180. idx = i;
  12181. break;
  12182. }
  12183. }
  12184. if (idx == -1) { // fall back to localdescription
  12185. for (i = 0; i < self.localSDP.media.length; i++) {
  12186. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12187. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12188. idx = i;
  12189. break;
  12190. }
  12191. }
  12192. }
  12193. var name = $(this).attr('name');
  12194. // TODO: check ice-pwd and ice-ufrag?
  12195. $(this).find('transport>candidate').each(function () {
  12196. var line, candidate;
  12197. line = SDPUtil.candidateFromJingle(this);
  12198. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12199. sdpMid: name,
  12200. candidate: line});
  12201. try {
  12202. self.peerconnection.addIceCandidate(candidate);
  12203. } catch (e) {
  12204. console.error('addIceCandidate failed', e.toString(), line);
  12205. }
  12206. });
  12207. });
  12208. };
  12209. JingleSession.prototype.sendAnswer = function (provisional) {
  12210. //console.log('createAnswer', provisional);
  12211. var self = this;
  12212. this.peerconnection.createAnswer(
  12213. function (sdp) {
  12214. self.createdAnswer(sdp, provisional);
  12215. },
  12216. function (e) {
  12217. console.error('createAnswer failed', e);
  12218. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12219. },
  12220. this.media_constraints
  12221. );
  12222. };
  12223. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  12224. //console.log('createAnswer callback');
  12225. var self = this;
  12226. this.localSDP = new SDP(sdp.sdp);
  12227. //this.localSDP.mangle();
  12228. this.usepranswer = provisional === true;
  12229. if (this.usetrickle) {
  12230. if (this.usepranswer) {
  12231. sdp.type = 'pranswer';
  12232. for (var i = 0; i < this.localSDP.media.length; i++) {
  12233. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12234. }
  12235. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12236. }
  12237. }
  12238. var self = this;
  12239. var sendJingle = function (ssrcs) {
  12240. var accept = $iq({to: self.peerjid,
  12241. type: 'set'})
  12242. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12243. action: 'session-accept',
  12244. initiator: self.initiator,
  12245. responder: self.responder,
  12246. sid: self.sid });
  12247. self.localSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  12248. self.connection.sendIQ(accept,
  12249. function () {
  12250. var ack = {};
  12251. ack.source = 'answer';
  12252. $(document).trigger('ack.jingle', [self.sid, ack]);
  12253. },
  12254. function (stanza) {
  12255. var error = ($(stanza).find('error').length) ? {
  12256. code: $(stanza).find('error').attr('code'),
  12257. reason: $(stanza).find('error :first')[0].tagName,
  12258. }:{};
  12259. error.source = 'answer';
  12260. JingleSession.onJingleError(self.sid, error);
  12261. },
  12262. 10000);
  12263. }
  12264. sdp.sdp = this.localSDP.raw;
  12265. this.peerconnection.setLocalDescription(sdp,
  12266. function () {
  12267. //console.log('setLocalDescription success');
  12268. if (self.usetrickle && !self.usepranswer) {
  12269. sendJingle();
  12270. }
  12271. self.setLocalDescription();
  12272. },
  12273. function (e) {
  12274. console.error('setLocalDescription failed', e);
  12275. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12276. }
  12277. );
  12278. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12279. for (var j = 0; j < cands.length; j++) {
  12280. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12281. if (cand.type == 'srflx') {
  12282. this.hadstuncandidate = true;
  12283. } else if (cand.type == 'relay') {
  12284. this.hadturncandidate = true;
  12285. }
  12286. }
  12287. };
  12288. JingleSession.prototype.sendTerminate = function (reason, text) {
  12289. var self = this,
  12290. term = $iq({to: this.peerjid,
  12291. type: 'set'})
  12292. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12293. action: 'session-terminate',
  12294. initiator: this.initiator,
  12295. sid: this.sid})
  12296. .c('reason')
  12297. .c(reason || 'success');
  12298. if (text) {
  12299. term.up().c('text').t(text);
  12300. }
  12301. this.connection.sendIQ(term,
  12302. function () {
  12303. self.peerconnection.close();
  12304. self.peerconnection = null;
  12305. self.terminate();
  12306. var ack = {};
  12307. ack.source = 'terminate';
  12308. $(document).trigger('ack.jingle', [self.sid, ack]);
  12309. },
  12310. function (stanza) {
  12311. var error = ($(stanza).find('error').length) ? {
  12312. code: $(stanza).find('error').attr('code'),
  12313. reason: $(stanza).find('error :first')[0].tagName,
  12314. }:{};
  12315. $(document).trigger('ack.jingle', [self.sid, error]);
  12316. },
  12317. 10000);
  12318. if (this.statsinterval !== null) {
  12319. window.clearInterval(this.statsinterval);
  12320. this.statsinterval = null;
  12321. }
  12322. };
  12323. JingleSession.prototype.addSource = function (elem, fromJid) {
  12324. var self = this;
  12325. // FIXME: dirty waiting
  12326. if (!this.peerconnection.localDescription)
  12327. {
  12328. console.warn("addSource - localDescription not ready yet")
  12329. setTimeout(function()
  12330. {
  12331. self.addSource(elem, fromJid);
  12332. },
  12333. 200
  12334. );
  12335. return;
  12336. }
  12337. console.log('addssrc', new Date().getTime());
  12338. console.log('ice', this.peerconnection.iceConnectionState);
  12339. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12340. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12341. $(elem).each(function (idx, content) {
  12342. var name = $(content).attr('name');
  12343. var lines = '';
  12344. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12345. var semantics = this.getAttribute('semantics');
  12346. var ssrcs = $(this).find('>source').map(function () {
  12347. return this.getAttribute('ssrc');
  12348. }).get();
  12349. if (ssrcs.length != 0) {
  12350. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12351. }
  12352. });
  12353. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12354. tmp.each(function () {
  12355. var ssrc = $(this).attr('ssrc');
  12356. if(mySdp.containsSSRC(ssrc)){
  12357. /**
  12358. * This happens when multiple participants change their streams at the same time and
  12359. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12360. * addssrc are scheduled for update IQ. See
  12361. */
  12362. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12363. return;
  12364. }
  12365. $(this).find('>parameter').each(function () {
  12366. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12367. if ($(this).attr('value') && $(this).attr('value').length)
  12368. lines += ':' + $(this).attr('value');
  12369. lines += '\r\n';
  12370. });
  12371. });
  12372. sdp.media.forEach(function(media, idx) {
  12373. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12374. return;
  12375. sdp.media[idx] += lines;
  12376. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12377. self.addssrc[idx] += lines;
  12378. });
  12379. sdp.raw = sdp.session + sdp.media.join('');
  12380. });
  12381. this.modifySourcesQueue.push(function() {
  12382. // When a source is added and if this is FF, a new channel is allocated
  12383. // for receiving the added source. We need to diffuse the SSRC of this
  12384. // new recvonly channel to the rest of the peers.
  12385. console.log('modify sources done');
  12386. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12387. console.log("SDPs", mySdp, newSdp);
  12388. self.notifyMySSRCUpdate(mySdp, newSdp);
  12389. });
  12390. };
  12391. JingleSession.prototype.removeSource = function (elem, fromJid) {
  12392. var self = this;
  12393. // FIXME: dirty waiting
  12394. if (!this.peerconnection.localDescription)
  12395. {
  12396. console.warn("removeSource - localDescription not ready yet")
  12397. setTimeout(function()
  12398. {
  12399. self.removeSource(elem, fromJid);
  12400. },
  12401. 200
  12402. );
  12403. return;
  12404. }
  12405. console.log('removessrc', new Date().getTime());
  12406. console.log('ice', this.peerconnection.iceConnectionState);
  12407. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12408. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12409. $(elem).each(function (idx, content) {
  12410. var name = $(content).attr('name');
  12411. var lines = '';
  12412. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12413. var semantics = this.getAttribute('semantics');
  12414. var ssrcs = $(this).find('>source').map(function () {
  12415. return this.getAttribute('ssrc');
  12416. }).get();
  12417. if (ssrcs.length != 0) {
  12418. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12419. }
  12420. });
  12421. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12422. tmp.each(function () {
  12423. var ssrc = $(this).attr('ssrc');
  12424. // This should never happen, but can be useful for bug detection
  12425. if(mySdp.containsSSRC(ssrc)){
  12426. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12427. return;
  12428. }
  12429. $(this).find('>parameter').each(function () {
  12430. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12431. if ($(this).attr('value') && $(this).attr('value').length)
  12432. lines += ':' + $(this).attr('value');
  12433. lines += '\r\n';
  12434. });
  12435. });
  12436. sdp.media.forEach(function(media, idx) {
  12437. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12438. return;
  12439. sdp.media[idx] += lines;
  12440. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12441. self.removessrc[idx] += lines;
  12442. });
  12443. sdp.raw = sdp.session + sdp.media.join('');
  12444. });
  12445. this.modifySourcesQueue.push(function() {
  12446. // When a source is removed and if this is FF, the recvonly channel that
  12447. // receives the remote stream is deactivated . We need to diffuse the
  12448. // recvonly SSRC removal to the rest of the peers.
  12449. console.log('modify sources done');
  12450. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12451. console.log("SDPs", mySdp, newSdp);
  12452. self.notifyMySSRCUpdate(mySdp, newSdp);
  12453. });
  12454. };
  12455. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  12456. var self = this;
  12457. if (this.peerconnection.signalingState == 'closed') return;
  12458. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12459. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12460. this.setLocalDescription();
  12461. if(successCallback){
  12462. successCallback();
  12463. }
  12464. queueCallback();
  12465. return;
  12466. }
  12467. // Reset switch streams flag
  12468. this.switchstreams = false;
  12469. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12470. // add sources
  12471. this.addssrc.forEach(function(lines, idx) {
  12472. sdp.media[idx] += lines;
  12473. });
  12474. this.addssrc = [];
  12475. // remove sources
  12476. this.removessrc.forEach(function(lines, idx) {
  12477. lines = lines.split('\r\n');
  12478. lines.pop(); // remove empty last element;
  12479. lines.forEach(function(line) {
  12480. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12481. });
  12482. });
  12483. this.removessrc = [];
  12484. // FIXME:
  12485. // this was a hack for the situation when only one peer exists
  12486. // in the conference.
  12487. // check if still required and remove
  12488. if (sdp.media[0])
  12489. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  12490. if (sdp.media[1])
  12491. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12492. sdp.raw = sdp.session + sdp.media.join('');
  12493. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12494. function() {
  12495. if(self.signalingState == 'closed') {
  12496. console.error("createAnswer attempt on closed state");
  12497. queueCallback("createAnswer attempt on closed state");
  12498. return;
  12499. }
  12500. self.peerconnection.createAnswer(
  12501. function(modifiedAnswer) {
  12502. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12503. if (self.pendingop !== null) {
  12504. var sdp = new SDP(modifiedAnswer.sdp);
  12505. if (sdp.media.length > 1) {
  12506. switch(self.pendingop) {
  12507. case 'mute':
  12508. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12509. break;
  12510. case 'unmute':
  12511. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12512. break;
  12513. }
  12514. sdp.raw = sdp.session + sdp.media.join('');
  12515. modifiedAnswer.sdp = sdp.raw;
  12516. }
  12517. self.pendingop = null;
  12518. }
  12519. // FIXME: pushing down an answer while ice connection state
  12520. // is still checking is bad...
  12521. //console.log(self.peerconnection.iceConnectionState);
  12522. // trying to work around another chrome bug
  12523. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12524. self.peerconnection.setLocalDescription(modifiedAnswer,
  12525. function() {
  12526. //console.log('modified setLocalDescription ok');
  12527. self.setLocalDescription();
  12528. if(successCallback){
  12529. successCallback();
  12530. }
  12531. queueCallback();
  12532. },
  12533. function(error) {
  12534. console.error('modified setLocalDescription failed', error);
  12535. queueCallback(error);
  12536. }
  12537. );
  12538. },
  12539. function(error) {
  12540. console.error('modified answer failed', error);
  12541. queueCallback(error);
  12542. }
  12543. );
  12544. },
  12545. function(error) {
  12546. console.error('modify failed', error);
  12547. queueCallback(error);
  12548. }
  12549. );
  12550. };
  12551. /**
  12552. * Switches video streams.
  12553. * @param new_stream new stream that will be used as video of this session.
  12554. * @param oldStream old video stream of this session.
  12555. * @param success_callback callback executed after successful stream switch.
  12556. */
  12557. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12558. var self = this;
  12559. // Remember SDP to figure out added/removed SSRCs
  12560. var oldSdp = null;
  12561. if(self.peerconnection) {
  12562. if(self.peerconnection.localDescription) {
  12563. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12564. }
  12565. self.peerconnection.removeStream(oldStream, true);
  12566. if(new_stream)
  12567. self.peerconnection.addStream(new_stream);
  12568. }
  12569. // Conference is not active
  12570. if(!oldSdp || !self.peerconnection) {
  12571. success_callback();
  12572. return;
  12573. }
  12574. self.switchstreams = true;
  12575. self.modifySourcesQueue.push(function() {
  12576. console.log('modify sources done');
  12577. success_callback();
  12578. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12579. console.log("SDPs", oldSdp, newSdp);
  12580. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12581. });
  12582. };
  12583. /**
  12584. * Figures out added/removed ssrcs and send update IQs.
  12585. * @param old_sdp SDP object for old description.
  12586. * @param new_sdp SDP object for new description.
  12587. */
  12588. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12589. if (!(this.peerconnection.signalingState == 'stable' &&
  12590. this.peerconnection.iceConnectionState == 'connected')){
  12591. console.log("Too early to send updates");
  12592. return;
  12593. }
  12594. // send source-remove IQ.
  12595. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12596. var remove = $iq({to: this.peerjid, type: 'set'})
  12597. .c('jingle', {
  12598. xmlns: 'urn:xmpp:jingle:1',
  12599. action: 'source-remove',
  12600. initiator: this.initiator,
  12601. sid: this.sid
  12602. }
  12603. );
  12604. var removed = sdpDiffer.toJingle(remove);
  12605. if (removed) {
  12606. this.connection.sendIQ(remove,
  12607. function (res) {
  12608. console.info('got remove result', res);
  12609. },
  12610. function (err) {
  12611. console.error('got remove error', err);
  12612. }
  12613. );
  12614. } else {
  12615. console.log('removal not necessary');
  12616. }
  12617. // send source-add IQ.
  12618. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  12619. var add = $iq({to: this.peerjid, type: 'set'})
  12620. .c('jingle', {
  12621. xmlns: 'urn:xmpp:jingle:1',
  12622. action: 'source-add',
  12623. initiator: this.initiator,
  12624. sid: this.sid
  12625. }
  12626. );
  12627. var added = sdpDiffer.toJingle(add);
  12628. if (added) {
  12629. this.connection.sendIQ(add,
  12630. function (res) {
  12631. console.info('got add result', res);
  12632. },
  12633. function (err) {
  12634. console.error('got add error', err);
  12635. }
  12636. );
  12637. } else {
  12638. console.log('addition not necessary');
  12639. }
  12640. };
  12641. /**
  12642. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12643. *
  12644. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12645. * tracks; otherwise, <tt>false</tt>
  12646. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12647. * tracks have been enabled/disabled. The function may, optionally, return
  12648. * another function which is to be invoked after the whole mute/unmute operation
  12649. * has completed successfully.
  12650. * @param options an object which specifies optional arguments such as the
  12651. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12652. * specifies whether the method was initiated in response to a user command (in
  12653. * contrast to an automatic decision made by the application logic)
  12654. */
  12655. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12656. var byUser;
  12657. if (options) {
  12658. byUser = options.byUser;
  12659. if (typeof byUser === 'undefined') {
  12660. byUser = true;
  12661. }
  12662. } else {
  12663. byUser = true;
  12664. }
  12665. // The user's command to mute the (local) video takes precedence over any
  12666. // automatic decision made by the application logic.
  12667. if (byUser) {
  12668. this.videoMuteByUser = mute;
  12669. } else if (this.videoMuteByUser) {
  12670. return;
  12671. }
  12672. this.hardMuteVideo(mute);
  12673. var self = this;
  12674. var oldSdp = null;
  12675. if(self.peerconnection) {
  12676. if(self.peerconnection.localDescription) {
  12677. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12678. }
  12679. }
  12680. this.modifySourcesQueue.push(function() {
  12681. console.log('modify sources done');
  12682. callback(mute);
  12683. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12684. console.log("SDPs", oldSdp, newSdp);
  12685. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12686. });
  12687. };
  12688. JingleSession.prototype.hardMuteVideo = function (muted) {
  12689. this.pendingop = muted ? 'mute' : 'unmute';
  12690. };
  12691. JingleSession.prototype.sendMute = function (muted, content) {
  12692. var info = $iq({to: this.peerjid,
  12693. type: 'set'})
  12694. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12695. action: 'session-info',
  12696. initiator: this.initiator,
  12697. sid: this.sid });
  12698. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12699. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12700. if (content) {
  12701. info.attrs({'name': content});
  12702. }
  12703. this.connection.send(info);
  12704. };
  12705. JingleSession.prototype.sendRinging = function () {
  12706. var info = $iq({to: this.peerjid,
  12707. type: 'set'})
  12708. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12709. action: 'session-info',
  12710. initiator: this.initiator,
  12711. sid: this.sid });
  12712. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12713. this.connection.send(info);
  12714. };
  12715. JingleSession.prototype.getStats = function (interval) {
  12716. var self = this;
  12717. var recv = {audio: 0, video: 0};
  12718. var lost = {audio: 0, video: 0};
  12719. var lastrecv = {audio: 0, video: 0};
  12720. var lastlost = {audio: 0, video: 0};
  12721. var loss = {audio: 0, video: 0};
  12722. var delta = {audio: 0, video: 0};
  12723. this.statsinterval = window.setInterval(function () {
  12724. if (self && self.peerconnection && self.peerconnection.getStats) {
  12725. self.peerconnection.getStats(function (stats) {
  12726. var results = stats.result();
  12727. // TODO: there are so much statistics you can get from this..
  12728. for (var i = 0; i < results.length; ++i) {
  12729. if (results[i].type == 'ssrc') {
  12730. var packetsrecv = results[i].stat('packetsReceived');
  12731. var packetslost = results[i].stat('packetsLost');
  12732. if (packetsrecv && packetslost) {
  12733. packetsrecv = parseInt(packetsrecv, 10);
  12734. packetslost = parseInt(packetslost, 10);
  12735. if (results[i].stat('googFrameRateReceived')) {
  12736. lastlost.video = lost.video;
  12737. lastrecv.video = recv.video;
  12738. recv.video = packetsrecv;
  12739. lost.video = packetslost;
  12740. } else {
  12741. lastlost.audio = lost.audio;
  12742. lastrecv.audio = recv.audio;
  12743. recv.audio = packetsrecv;
  12744. lost.audio = packetslost;
  12745. }
  12746. }
  12747. }
  12748. }
  12749. delta.audio = recv.audio - lastrecv.audio;
  12750. delta.video = recv.video - lastrecv.video;
  12751. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12752. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12753. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12754. });
  12755. }
  12756. }, interval || 3000);
  12757. return this.statsinterval;
  12758. };
  12759. JingleSession.onJingleError = function (session, error)
  12760. {
  12761. console.error("Jingle error", error);
  12762. }
  12763. JingleSession.onJingleFatalError = function (session, error)
  12764. {
  12765. this.service.sessionTerminated = true;
  12766. this.connection.emuc.doLeave();
  12767. APP.UI.messageHandler.showError("dialog.sorry",
  12768. "dialog.internalError");
  12769. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12770. }
  12771. JingleSession.prototype.setLocalDescription = function () {
  12772. // put our ssrcs into presence so other clients can identify our stream
  12773. var newssrcs = [];
  12774. var session = transform.parse(this.peerconnection.localDescription.sdp);
  12775. session.media.forEach(function (media) {
  12776. if (media.ssrcs != null && media.ssrcs.length > 0) {
  12777. // TODO(gp) maybe exclude FID streams?
  12778. media.ssrcs.forEach(function (ssrc) {
  12779. if (ssrc.attribute !== 'cname') {
  12780. return;
  12781. }
  12782. newssrcs.push({
  12783. 'ssrc': ssrc.id,
  12784. 'type': media.type,
  12785. 'direction': media.direction
  12786. });
  12787. });
  12788. }
  12789. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  12790. {
  12791. newssrcs.push({
  12792. 'ssrc': this.localStreamsSSRC[media.type],
  12793. 'type': media.type,
  12794. 'direction': media.direction
  12795. });
  12796. }
  12797. });
  12798. console.log('new ssrcs', newssrcs);
  12799. // Have to clear presence map to get rid of removed streams
  12800. this.connection.emuc.clearPresenceMedia();
  12801. if (newssrcs.length > 0) {
  12802. for (var i = 1; i <= newssrcs.length; i ++) {
  12803. // Change video type to screen
  12804. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  12805. newssrcs[i-1].type = 'screen';
  12806. }
  12807. this.connection.emuc.addMediaToPresence(i,
  12808. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  12809. }
  12810. this.connection.emuc.sendPresence();
  12811. }
  12812. }
  12813. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12814. function sendKeyframe(pc) {
  12815. console.log('sendkeyframe', pc.iceConnectionState);
  12816. if (pc.iceConnectionState !== 'connected') return; // safe...
  12817. var self = this;
  12818. pc.setRemoteDescription(
  12819. pc.remoteDescription,
  12820. function () {
  12821. pc.createAnswer(
  12822. function (modifiedAnswer) {
  12823. pc.setLocalDescription(
  12824. modifiedAnswer,
  12825. function () {
  12826. // noop
  12827. },
  12828. function (error) {
  12829. console.log('triggerKeyframe setLocalDescription failed', error);
  12830. APP.UI.messageHandler.showError();
  12831. }
  12832. );
  12833. },
  12834. function (error) {
  12835. console.log('triggerKeyframe createAnswer failed', error);
  12836. APP.UI.messageHandler.showError();
  12837. }
  12838. );
  12839. },
  12840. function (error) {
  12841. console.log('triggerKeyframe setRemoteDescription failed', error);
  12842. APP.UI.messageHandler.showError();
  12843. }
  12844. );
  12845. }
  12846. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12847. var self = this;
  12848. var thessrc;
  12849. var ssrc2jid = this.connection.emuc.ssrc2jid;
  12850. var streamId = APP.RTC.getStreamID(data.stream);
  12851. // look up an associated JID for a stream id
  12852. if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  12853. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12854. var ssrclines
  12855. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12856. ssrclines = ssrclines.filter(function (line) {
  12857. // NOTE(gp) previously we filtered on the mslabel, but that property
  12858. // is not always present.
  12859. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12860. if (RTCBrowserType.isTemasysPluginUsed()) {
  12861. return ((line.indexOf('mslabel:' + streamId) !== -1));
  12862. } else {
  12863. return ((line.indexOf('msid:' + streamId) !== -1));
  12864. }
  12865. });
  12866. if (ssrclines.length) {
  12867. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12868. // We signal our streams (through Jingle to the focus) before we set
  12869. // our presence (through which peers associate remote streams to
  12870. // jids). So, it might arrive that a remote stream is added but
  12871. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  12872. // successfully set. Here we wait for up to a second for the
  12873. // presence to arrive.
  12874. if (!ssrc2jid[thessrc]) {
  12875. if (typeof times === 'undefined')
  12876. {
  12877. times = 0;
  12878. }
  12879. if (times > 10)
  12880. {
  12881. console.warning('Waiting for jid timed out', thessrc);
  12882. }
  12883. else
  12884. {
  12885. setTimeout(function(d) {
  12886. return function() {
  12887. self.remoteStreamAdded(d, times++);
  12888. }
  12889. }(data), 250);
  12890. }
  12891. return;
  12892. }
  12893. // ok to overwrite the one from focus? might save work in colibri.js
  12894. console.log('associated jid', ssrc2jid[thessrc], thessrc);
  12895. if (ssrc2jid[thessrc]) {
  12896. data.peerjid = ssrc2jid[thessrc];
  12897. }
  12898. }
  12899. }
  12900. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12901. var isVideo = data.stream.getVideoTracks().length > 0;
  12902. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12903. if (isVideo &&
  12904. data.peerjid && this.peerjid === data.peerjid &&
  12905. data.stream.getVideoTracks().length === 0 &&
  12906. APP.RTC.localVideo.getTracks().length > 0) {
  12907. window.setTimeout(function () {
  12908. sendKeyframe(self.peerconnection);
  12909. }, 3000);
  12910. }
  12911. }
  12912. module.exports = JingleSession;
  12913. },{"../../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){
  12914. /* jshint -W117 */
  12915. var SDPUtil = require("./SDPUtil");
  12916. // SDP STUFF
  12917. function SDP(sdp) {
  12918. this.media = sdp.split('\r\nm=');
  12919. for (var i = 1; i < this.media.length; i++) {
  12920. this.media[i] = 'm=' + this.media[i];
  12921. if (i != this.media.length - 1) {
  12922. this.media[i] += '\r\n';
  12923. }
  12924. }
  12925. this.session = this.media.shift() + '\r\n';
  12926. this.raw = this.session + this.media.join('');
  12927. }
  12928. /**
  12929. * Returns map of MediaChannel mapped per channel idx.
  12930. */
  12931. SDP.prototype.getMediaSsrcMap = function() {
  12932. var self = this;
  12933. var media_ssrcs = {};
  12934. var tmp;
  12935. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12936. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12937. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12938. var media = {
  12939. mediaindex: mediaindex,
  12940. mid: mid,
  12941. ssrcs: {},
  12942. ssrcGroups: []
  12943. };
  12944. media_ssrcs[mediaindex] = media;
  12945. tmp.forEach(function (line) {
  12946. var linessrc = line.substring(7).split(' ')[0];
  12947. // allocate new ChannelSsrc
  12948. if(!media.ssrcs[linessrc]) {
  12949. media.ssrcs[linessrc] = {
  12950. ssrc: linessrc,
  12951. lines: []
  12952. };
  12953. }
  12954. media.ssrcs[linessrc].lines.push(line);
  12955. });
  12956. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12957. tmp.forEach(function(line){
  12958. var semantics = line.substr(0, idx).substr(13);
  12959. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12960. if (ssrcs.length != 0) {
  12961. media.ssrcGroups.push({
  12962. semantics: semantics,
  12963. ssrcs: ssrcs
  12964. });
  12965. }
  12966. });
  12967. }
  12968. return media_ssrcs;
  12969. };
  12970. /**
  12971. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12972. * @param ssrc the ssrc to check.
  12973. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12974. */
  12975. SDP.prototype.containsSSRC = function(ssrc) {
  12976. var medias = this.getMediaSsrcMap();
  12977. var contains = false;
  12978. Object.keys(medias).forEach(function(mediaindex){
  12979. var media = medias[mediaindex];
  12980. //console.log("Check", channel, ssrc);
  12981. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12982. contains = true;
  12983. }
  12984. });
  12985. return contains;
  12986. };
  12987. // remove iSAC and CN from SDP
  12988. SDP.prototype.mangle = function () {
  12989. var i, j, mline, lines, rtpmap, newdesc;
  12990. for (i = 0; i < this.media.length; i++) {
  12991. lines = this.media[i].split('\r\n');
  12992. lines.pop(); // remove empty last element
  12993. mline = SDPUtil.parse_mline(lines.shift());
  12994. if (mline.media != 'audio')
  12995. continue;
  12996. newdesc = '';
  12997. mline.fmt.length = 0;
  12998. for (j = 0; j < lines.length; j++) {
  12999. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13000. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13001. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13002. continue;
  13003. mline.fmt.push(rtpmap.id);
  13004. newdesc += lines[j] + '\r\n';
  13005. } else {
  13006. newdesc += lines[j] + '\r\n';
  13007. }
  13008. }
  13009. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13010. this.media[i] += newdesc;
  13011. }
  13012. this.raw = this.session + this.media.join('');
  13013. };
  13014. // remove lines matching prefix from session section
  13015. SDP.prototype.removeSessionLines = function(prefix) {
  13016. var self = this;
  13017. var lines = SDPUtil.find_lines(this.session, prefix);
  13018. lines.forEach(function(line) {
  13019. self.session = self.session.replace(line + '\r\n', '');
  13020. });
  13021. this.raw = this.session + this.media.join('');
  13022. return lines;
  13023. }
  13024. // remove lines matching prefix from a media section specified by mediaindex
  13025. // TODO: non-numeric mediaindex could match mid
  13026. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13027. var self = this;
  13028. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13029. lines.forEach(function(line) {
  13030. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13031. });
  13032. this.raw = this.session + this.media.join('');
  13033. return lines;
  13034. }
  13035. // add content's to a jingle element
  13036. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13037. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13038. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13039. var self = this;
  13040. // new bundle plan
  13041. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13042. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13043. for (i = 0; i < lines.length; i++) {
  13044. tmp = lines[i].split(' ');
  13045. var semantics = tmp.shift().substr(8);
  13046. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13047. for (j = 0; j < tmp.length; j++) {
  13048. elem.c('content', {name: tmp[j]}).up();
  13049. }
  13050. elem.up();
  13051. }
  13052. }
  13053. for (i = 0; i < this.media.length; i++) {
  13054. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13055. if (!(mline.media === 'audio' ||
  13056. mline.media === 'video' ||
  13057. mline.media === 'application'))
  13058. {
  13059. continue;
  13060. }
  13061. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13062. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13063. } else {
  13064. if(ssrcs && ssrcs[mline.media])
  13065. {
  13066. ssrc = ssrcs[mline.media];
  13067. }
  13068. else
  13069. ssrc = false;
  13070. }
  13071. elem.c('content', {creator: thecreator, name: mline.media});
  13072. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13073. // prefer identifier from a=mid if present
  13074. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13075. elem.attrs({ name: mid });
  13076. }
  13077. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13078. {
  13079. elem.c('description',
  13080. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13081. media: mline.media });
  13082. if (ssrc) {
  13083. elem.attrs({ssrc: ssrc});
  13084. }
  13085. for (j = 0; j < mline.fmt.length; j++) {
  13086. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13087. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13088. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13089. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13090. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13091. for (k = 0; k < tmp.length; k++) {
  13092. elem.c('parameter', tmp[k]).up();
  13093. }
  13094. }
  13095. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13096. elem.up();
  13097. }
  13098. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13099. elem.c('encryption', {required: 1});
  13100. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13101. crypto.forEach(function(line) {
  13102. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13103. });
  13104. elem.up(); // end of encryption
  13105. }
  13106. if (ssrc) {
  13107. // new style mapping
  13108. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13109. // FIXME: group by ssrc and support multiple different ssrcs
  13110. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13111. if(ssrclines.length > 0) {
  13112. ssrclines.forEach(function (line) {
  13113. idx = line.indexOf(' ');
  13114. var linessrc = line.substr(0, idx).substr(7);
  13115. if (linessrc != ssrc) {
  13116. elem.up();
  13117. ssrc = linessrc;
  13118. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13119. }
  13120. var kv = line.substr(idx + 1);
  13121. elem.c('parameter');
  13122. if (kv.indexOf(':') == -1) {
  13123. elem.attrs({ name: kv });
  13124. } else {
  13125. var k = kv.split(':', 2)[0];
  13126. elem.attrs({ name: k });
  13127. var v = kv.split(':', 2)[1];
  13128. v = SDPUtil.filter_special_chars(v);
  13129. elem.attrs({ value: v });
  13130. }
  13131. elem.up();
  13132. });
  13133. elem.up();
  13134. }
  13135. else
  13136. {
  13137. elem.up();
  13138. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13139. elem.c('parameter');
  13140. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13141. elem.up();
  13142. var msid = null;
  13143. if(mline.media == "audio")
  13144. {
  13145. msid = APP.RTC.localAudio.getId();
  13146. }
  13147. else
  13148. {
  13149. msid = APP.RTC.localVideo.getId();
  13150. }
  13151. if(msid != null)
  13152. {
  13153. msid = SDPUtil.filter_special_chars(msid);
  13154. elem.c('parameter');
  13155. elem.attrs({name: "msid", value:msid});
  13156. elem.up();
  13157. elem.c('parameter');
  13158. elem.attrs({name: "mslabel", value:msid});
  13159. elem.up();
  13160. elem.c('parameter');
  13161. elem.attrs({name: "label", value:msid});
  13162. elem.up();
  13163. elem.up();
  13164. }
  13165. }
  13166. // XEP-0339 handle ssrc-group attributes
  13167. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13168. ssrc_group_lines.forEach(function(line) {
  13169. idx = line.indexOf(' ');
  13170. var semantics = line.substr(0, idx).substr(13);
  13171. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13172. if (ssrcs.length != 0) {
  13173. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13174. ssrcs.forEach(function(ssrc) {
  13175. elem.c('source', { ssrc: ssrc })
  13176. .up();
  13177. });
  13178. elem.up();
  13179. }
  13180. });
  13181. }
  13182. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13183. elem.c('rtcp-mux').up();
  13184. }
  13185. // XEP-0293 -- map a=rtcp-fb:*
  13186. this.RtcpFbToJingle(i, elem, '*');
  13187. // XEP-0294
  13188. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13189. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13190. for (j = 0; j < lines.length; j++) {
  13191. tmp = SDPUtil.parse_extmap(lines[j]);
  13192. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13193. uri: tmp.uri,
  13194. id: tmp.value });
  13195. if (tmp.hasOwnProperty('direction')) {
  13196. switch (tmp.direction) {
  13197. case 'sendonly':
  13198. elem.attrs({senders: 'responder'});
  13199. break;
  13200. case 'recvonly':
  13201. elem.attrs({senders: 'initiator'});
  13202. break;
  13203. case 'sendrecv':
  13204. elem.attrs({senders: 'both'});
  13205. break;
  13206. case 'inactive':
  13207. elem.attrs({senders: 'none'});
  13208. break;
  13209. }
  13210. }
  13211. // TODO: handle params
  13212. elem.up();
  13213. }
  13214. }
  13215. elem.up(); // end of description
  13216. }
  13217. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13218. this.TransportToJingle(i, elem);
  13219. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13220. elem.attrs({senders: 'both'});
  13221. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13222. elem.attrs({senders: 'initiator'});
  13223. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13224. elem.attrs({senders: 'responder'});
  13225. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13226. elem.attrs({senders: 'none'});
  13227. }
  13228. if (mline.port == '0') {
  13229. // estos hack to reject an m-line
  13230. elem.attrs({senders: 'rejected'});
  13231. }
  13232. elem.up(); // end of content
  13233. }
  13234. elem.up();
  13235. return elem;
  13236. };
  13237. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13238. var i = mediaindex;
  13239. var tmp;
  13240. var self = this;
  13241. elem.c('transport');
  13242. // XEP-0343 DTLS/SCTP
  13243. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13244. {
  13245. var sctpmap = SDPUtil.find_line(
  13246. this.media[i], 'a=sctpmap:', self.session);
  13247. if (sctpmap)
  13248. {
  13249. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13250. elem.c('sctpmap',
  13251. {
  13252. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13253. number: sctpAttrs[0], /* SCTP port */
  13254. protocol: sctpAttrs[1], /* protocol */
  13255. });
  13256. // Optional stream count attribute
  13257. if (sctpAttrs.length > 2)
  13258. elem.attrs({ streams: sctpAttrs[2]});
  13259. elem.up();
  13260. }
  13261. }
  13262. // XEP-0320
  13263. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13264. fingerprints.forEach(function(line) {
  13265. tmp = SDPUtil.parse_fingerprint(line);
  13266. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13267. elem.c('fingerprint').t(tmp.fingerprint);
  13268. delete tmp.fingerprint;
  13269. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13270. if (line) {
  13271. tmp.setup = line.substr(8);
  13272. }
  13273. elem.attrs(tmp);
  13274. elem.up(); // end of fingerprint
  13275. });
  13276. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13277. if (tmp) {
  13278. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13279. elem.attrs(tmp);
  13280. // XEP-0176
  13281. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13282. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13283. lines.forEach(function (line) {
  13284. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13285. });
  13286. }
  13287. }
  13288. elem.up(); // end of transport
  13289. }
  13290. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13291. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13292. lines.forEach(function (line) {
  13293. var tmp = SDPUtil.parse_rtcpfb(line);
  13294. if (tmp.type == 'trr-int') {
  13295. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13296. elem.up();
  13297. } else {
  13298. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13299. if (tmp.params.length > 0) {
  13300. elem.attrs({'subtype': tmp.params[0]});
  13301. }
  13302. elem.up();
  13303. }
  13304. });
  13305. };
  13306. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13307. var media = '';
  13308. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13309. if (tmp.length) {
  13310. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13311. if (tmp.attr('value')) {
  13312. media += tmp.attr('value');
  13313. } else {
  13314. media += '0';
  13315. }
  13316. media += '\r\n';
  13317. }
  13318. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13319. tmp.each(function () {
  13320. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13321. if ($(this).attr('subtype')) {
  13322. media += ' ' + $(this).attr('subtype');
  13323. }
  13324. media += '\r\n';
  13325. });
  13326. return media;
  13327. };
  13328. // construct an SDP from a jingle stanza
  13329. SDP.prototype.fromJingle = function (jingle) {
  13330. var self = this;
  13331. this.raw = 'v=0\r\n' +
  13332. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13333. 's=-\r\n' +
  13334. 't=0 0\r\n';
  13335. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13336. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13337. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13338. var contents = $(group).find('>content').map(function (idx, content) {
  13339. return content.getAttribute('name');
  13340. }).get();
  13341. if (contents.length > 0) {
  13342. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13343. }
  13344. });
  13345. }
  13346. this.session = this.raw;
  13347. jingle.find('>content').each(function () {
  13348. var m = self.jingle2media($(this));
  13349. self.media.push(m);
  13350. });
  13351. // reconstruct msid-semantic -- apparently not necessary
  13352. /*
  13353. var msid = SDPUtil.parse_ssrc(this.raw);
  13354. if (msid.hasOwnProperty('mslabel')) {
  13355. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13356. }
  13357. */
  13358. this.raw = this.session + this.media.join('');
  13359. };
  13360. // translate a jingle content element into an an SDP media part
  13361. SDP.prototype.jingle2media = function (content) {
  13362. var media = '',
  13363. desc = content.find('description'),
  13364. ssrc = desc.attr('ssrc'),
  13365. self = this,
  13366. tmp;
  13367. var sctp = content.find(
  13368. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13369. tmp = { media: desc.attr('media') };
  13370. tmp.port = '1';
  13371. if (content.attr('senders') == 'rejected') {
  13372. // estos hack to reject an m-line.
  13373. tmp.port = '0';
  13374. }
  13375. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13376. if (sctp.length)
  13377. tmp.proto = 'DTLS/SCTP';
  13378. else
  13379. tmp.proto = 'RTP/SAVPF';
  13380. } else {
  13381. tmp.proto = 'RTP/AVPF';
  13382. }
  13383. if (!sctp.length)
  13384. {
  13385. tmp.fmt = desc.find('payload-type').map(
  13386. function () { return this.getAttribute('id'); }).get();
  13387. media += SDPUtil.build_mline(tmp) + '\r\n';
  13388. }
  13389. else
  13390. {
  13391. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13392. media += 'a=sctpmap:' + sctp.attr('number') +
  13393. ' ' + sctp.attr('protocol');
  13394. var streamCount = sctp.attr('streams');
  13395. if (streamCount)
  13396. media += ' ' + streamCount + '\r\n';
  13397. else
  13398. media += '\r\n';
  13399. }
  13400. media += 'c=IN IP4 0.0.0.0\r\n';
  13401. if (!sctp.length)
  13402. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13403. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13404. if (tmp.length) {
  13405. if (tmp.attr('ufrag')) {
  13406. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13407. }
  13408. if (tmp.attr('pwd')) {
  13409. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13410. }
  13411. tmp.find('>fingerprint').each(function () {
  13412. // FIXME: check namespace at some point
  13413. media += 'a=fingerprint:' + this.getAttribute('hash');
  13414. media += ' ' + $(this).text();
  13415. media += '\r\n';
  13416. if (this.getAttribute('setup')) {
  13417. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  13418. }
  13419. });
  13420. }
  13421. switch (content.attr('senders')) {
  13422. case 'initiator':
  13423. media += 'a=sendonly\r\n';
  13424. break;
  13425. case 'responder':
  13426. media += 'a=recvonly\r\n';
  13427. break;
  13428. case 'none':
  13429. media += 'a=inactive\r\n';
  13430. break;
  13431. case 'both':
  13432. media += 'a=sendrecv\r\n';
  13433. break;
  13434. }
  13435. media += 'a=mid:' + content.attr('name') + '\r\n';
  13436. // <description><rtcp-mux/></description>
  13437. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  13438. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  13439. if (desc.find('rtcp-mux').length) {
  13440. media += 'a=rtcp-mux\r\n';
  13441. }
  13442. if (desc.find('encryption').length) {
  13443. desc.find('encryption>crypto').each(function () {
  13444. media += 'a=crypto:' + this.getAttribute('tag');
  13445. media += ' ' + this.getAttribute('crypto-suite');
  13446. media += ' ' + this.getAttribute('key-params');
  13447. if (this.getAttribute('session-params')) {
  13448. media += ' ' + this.getAttribute('session-params');
  13449. }
  13450. media += '\r\n';
  13451. });
  13452. }
  13453. desc.find('payload-type').each(function () {
  13454. media += SDPUtil.build_rtpmap(this) + '\r\n';
  13455. if ($(this).find('>parameter').length) {
  13456. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  13457. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  13458. media += '\r\n';
  13459. }
  13460. // xep-0293
  13461. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  13462. });
  13463. // xep-0293
  13464. media += self.RtcpFbFromJingle(desc, '*');
  13465. // xep-0294
  13466. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  13467. tmp.each(function () {
  13468. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  13469. });
  13470. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  13471. media += SDPUtil.candidateFromJingle(this);
  13472. });
  13473. // XEP-0339 handle ssrc-group attributes
  13474. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  13475. var semantics = this.getAttribute('semantics');
  13476. var ssrcs = $(this).find('>source').map(function() {
  13477. return this.getAttribute('ssrc');
  13478. }).get();
  13479. if (ssrcs.length != 0) {
  13480. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  13481. }
  13482. });
  13483. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  13484. tmp.each(function () {
  13485. var ssrc = this.getAttribute('ssrc');
  13486. $(this).find('>parameter').each(function () {
  13487. var name = this.getAttribute('name');
  13488. var value = this.getAttribute('value');
  13489. value = SDPUtil.filter_special_chars(value);
  13490. media += 'a=ssrc:' + ssrc + ' ' + name;
  13491. if (value && value.length)
  13492. media += ':' + value;
  13493. media += '\r\n';
  13494. });
  13495. });
  13496. return media;
  13497. };
  13498. module.exports = SDP;
  13499. },{"./SDPUtil":58}],57:[function(require,module,exports){
  13500. var SDPUtil = require("./SDPUtil");
  13501. function SDPDiffer(mySDP, otherSDP) {
  13502. this.mySDP = mySDP;
  13503. this.otherSDP = otherSDP;
  13504. }
  13505. /**
  13506. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  13507. * @param otherSdp the other SDP to check ssrc with.
  13508. */
  13509. SDPDiffer.prototype.getNewMedia = function() {
  13510. // this could be useful in Array.prototype.
  13511. function arrayEquals(array) {
  13512. // if the other array is a falsy value, return
  13513. if (!array)
  13514. return false;
  13515. // compare lengths - can save a lot of time
  13516. if (this.length != array.length)
  13517. return false;
  13518. for (var i = 0, l=this.length; i < l; i++) {
  13519. // Check if we have nested arrays
  13520. if (this[i] instanceof Array && array[i] instanceof Array) {
  13521. // recurse into the nested arrays
  13522. if (!this[i].equals(array[i]))
  13523. return false;
  13524. }
  13525. else if (this[i] != array[i]) {
  13526. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  13527. return false;
  13528. }
  13529. }
  13530. return true;
  13531. }
  13532. var myMedias = this.mySDP.getMediaSsrcMap();
  13533. var othersMedias = this.otherSDP.getMediaSsrcMap();
  13534. var newMedia = {};
  13535. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  13536. var myMedia = myMedias[othersMediaIdx];
  13537. var othersMedia = othersMedias[othersMediaIdx];
  13538. if(!myMedia && othersMedia) {
  13539. // Add whole channel
  13540. newMedia[othersMediaIdx] = othersMedia;
  13541. return;
  13542. }
  13543. // Look for new ssrcs accross the channel
  13544. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  13545. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  13546. // Allocate channel if we've found ssrc that doesn't exist in our channel
  13547. if(!newMedia[othersMediaIdx]){
  13548. newMedia[othersMediaIdx] = {
  13549. mediaindex: othersMedia.mediaindex,
  13550. mid: othersMedia.mid,
  13551. ssrcs: {},
  13552. ssrcGroups: []
  13553. };
  13554. }
  13555. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  13556. }
  13557. });
  13558. // Look for new ssrc groups across the channels
  13559. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  13560. // try to match the other ssrc-group with an ssrc-group of ours
  13561. var matched = false;
  13562. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  13563. var mySsrcGroup = myMedia.ssrcGroups[i];
  13564. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  13565. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  13566. matched = true;
  13567. break;
  13568. }
  13569. }
  13570. if (!matched) {
  13571. // Allocate channel if we've found an ssrc-group that doesn't
  13572. // exist in our channel
  13573. if(!newMedia[othersMediaIdx]){
  13574. newMedia[othersMediaIdx] = {
  13575. mediaindex: othersMedia.mediaindex,
  13576. mid: othersMedia.mid,
  13577. ssrcs: {},
  13578. ssrcGroups: []
  13579. };
  13580. }
  13581. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  13582. }
  13583. });
  13584. });
  13585. return newMedia;
  13586. };
  13587. /**
  13588. * Sends SSRC update IQ.
  13589. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  13590. * @param sid session identifier that will be put into the IQ.
  13591. * @param initiator initiator identifier.
  13592. * @param toJid destination Jid
  13593. * @param isAdd indicates if this is remove or add operation.
  13594. */
  13595. SDPDiffer.prototype.toJingle = function(modify) {
  13596. var sdpMediaSsrcs = this.getNewMedia();
  13597. var self = this;
  13598. // FIXME: only announce video ssrcs since we mix audio and dont need
  13599. // the audio ssrcs therefore
  13600. var modified = false;
  13601. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  13602. modified = true;
  13603. var media = sdpMediaSsrcs[mediaindex];
  13604. modify.c('content', {name: media.mid});
  13605. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  13606. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  13607. // generate sources from lines
  13608. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  13609. var mediaSsrc = media.ssrcs[ssrcNum];
  13610. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13611. modify.attrs({ssrc: mediaSsrc.ssrc});
  13612. // iterate over ssrc lines
  13613. mediaSsrc.lines.forEach(function (line) {
  13614. var idx = line.indexOf(' ');
  13615. var kv = line.substr(idx + 1);
  13616. modify.c('parameter');
  13617. if (kv.indexOf(':') == -1) {
  13618. modify.attrs({ name: kv });
  13619. } else {
  13620. var nv = kv.split(':', 2);
  13621. var name = nv[0];
  13622. var value = SDPUtil.filter_special_chars(nv[1]);
  13623. modify.attrs({ name: name });
  13624. modify.attrs({ value: value });
  13625. }
  13626. modify.up(); // end of parameter
  13627. });
  13628. modify.up(); // end of source
  13629. });
  13630. // generate source groups from lines
  13631. media.ssrcGroups.forEach(function(ssrcGroup) {
  13632. if (ssrcGroup.ssrcs.length != 0) {
  13633. modify.c('ssrc-group', {
  13634. semantics: ssrcGroup.semantics,
  13635. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  13636. });
  13637. ssrcGroup.ssrcs.forEach(function (ssrc) {
  13638. modify.c('source', { ssrc: ssrc })
  13639. .up(); // end of source
  13640. });
  13641. modify.up(); // end of ssrc-group
  13642. }
  13643. });
  13644. modify.up(); // end of description
  13645. modify.up(); // end of content
  13646. });
  13647. return modified;
  13648. };
  13649. module.exports = SDPDiffer;
  13650. },{"./SDPUtil":58}],58:[function(require,module,exports){
  13651. SDPUtil = {
  13652. filter_special_chars: function (text) {
  13653. return text.replace(/[\\\/\{,\}\+]/g, "");
  13654. },
  13655. iceparams: function (mediadesc, sessiondesc) {
  13656. var data = null;
  13657. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13658. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13659. data = {
  13660. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13661. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13662. };
  13663. }
  13664. return data;
  13665. },
  13666. parse_iceufrag: function (line) {
  13667. return line.substring(12);
  13668. },
  13669. build_iceufrag: function (frag) {
  13670. return 'a=ice-ufrag:' + frag;
  13671. },
  13672. parse_icepwd: function (line) {
  13673. return line.substring(10);
  13674. },
  13675. build_icepwd: function (pwd) {
  13676. return 'a=ice-pwd:' + pwd;
  13677. },
  13678. parse_mid: function (line) {
  13679. return line.substring(6);
  13680. },
  13681. parse_mline: function (line) {
  13682. var parts = line.substring(2).split(' '),
  13683. data = {};
  13684. data.media = parts.shift();
  13685. data.port = parts.shift();
  13686. data.proto = parts.shift();
  13687. if (parts[parts.length - 1] === '') { // trailing whitespace
  13688. parts.pop();
  13689. }
  13690. data.fmt = parts;
  13691. return data;
  13692. },
  13693. build_mline: function (mline) {
  13694. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13695. },
  13696. parse_rtpmap: function (line) {
  13697. var parts = line.substring(9).split(' '),
  13698. data = {};
  13699. data.id = parts.shift();
  13700. parts = parts[0].split('/');
  13701. data.name = parts.shift();
  13702. data.clockrate = parts.shift();
  13703. data.channels = parts.length ? parts.shift() : '1';
  13704. return data;
  13705. },
  13706. /**
  13707. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13708. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13709. * @returns [SCTP port number, protocol, streams]
  13710. */
  13711. parse_sctpmap: function (line)
  13712. {
  13713. var parts = line.substring(10).split(' ');
  13714. var sctpPort = parts[0];
  13715. var protocol = parts[1];
  13716. // Stream count is optional
  13717. var streamCount = parts.length > 2 ? parts[2] : null;
  13718. return [sctpPort, protocol, streamCount];// SCTP port
  13719. },
  13720. build_rtpmap: function (el) {
  13721. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13722. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13723. line += '/' + el.getAttribute('channels');
  13724. }
  13725. return line;
  13726. },
  13727. parse_crypto: function (line) {
  13728. var parts = line.substring(9).split(' '),
  13729. data = {};
  13730. data.tag = parts.shift();
  13731. data['crypto-suite'] = parts.shift();
  13732. data['key-params'] = parts.shift();
  13733. if (parts.length) {
  13734. data['session-params'] = parts.join(' ');
  13735. }
  13736. return data;
  13737. },
  13738. parse_fingerprint: function (line) { // RFC 4572
  13739. var parts = line.substring(14).split(' '),
  13740. data = {};
  13741. data.hash = parts.shift();
  13742. data.fingerprint = parts.shift();
  13743. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13744. return data;
  13745. },
  13746. parse_fmtp: function (line) {
  13747. var parts = line.split(' '),
  13748. i, key, value,
  13749. data = [];
  13750. parts.shift();
  13751. parts = parts.join(' ').split(';');
  13752. for (i = 0; i < parts.length; i++) {
  13753. key = parts[i].split('=')[0];
  13754. while (key.length && key[0] == ' ') {
  13755. key = key.substring(1);
  13756. }
  13757. value = parts[i].split('=')[1];
  13758. if (key && value) {
  13759. data.push({name: key, value: value});
  13760. } else if (key) {
  13761. // rfc 4733 (DTMF) style stuff
  13762. data.push({name: '', value: key});
  13763. }
  13764. }
  13765. return data;
  13766. },
  13767. parse_icecandidate: function (line) {
  13768. var candidate = {},
  13769. elems = line.split(' ');
  13770. candidate.foundation = elems[0].substring(12);
  13771. candidate.component = elems[1];
  13772. candidate.protocol = elems[2].toLowerCase();
  13773. candidate.priority = elems[3];
  13774. candidate.ip = elems[4];
  13775. candidate.port = elems[5];
  13776. // elems[6] => "typ"
  13777. candidate.type = elems[7];
  13778. candidate.generation = 0; // default value, may be overwritten below
  13779. for (var i = 8; i < elems.length; i += 2) {
  13780. switch (elems[i]) {
  13781. case 'raddr':
  13782. candidate['rel-addr'] = elems[i + 1];
  13783. break;
  13784. case 'rport':
  13785. candidate['rel-port'] = elems[i + 1];
  13786. break;
  13787. case 'generation':
  13788. candidate.generation = elems[i + 1];
  13789. break;
  13790. case 'tcptype':
  13791. candidate.tcptype = elems[i + 1];
  13792. break;
  13793. default: // TODO
  13794. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13795. }
  13796. }
  13797. candidate.network = '1';
  13798. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13799. return candidate;
  13800. },
  13801. build_icecandidate: function (cand) {
  13802. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13803. line += ' ';
  13804. switch (cand.type) {
  13805. case 'srflx':
  13806. case 'prflx':
  13807. case 'relay':
  13808. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13809. line += 'raddr';
  13810. line += ' ';
  13811. line += cand['rel-addr'];
  13812. line += ' ';
  13813. line += 'rport';
  13814. line += ' ';
  13815. line += cand['rel-port'];
  13816. line += ' ';
  13817. }
  13818. break;
  13819. }
  13820. if (cand.hasOwnAttribute('tcptype')) {
  13821. line += 'tcptype';
  13822. line += ' ';
  13823. line += cand.tcptype;
  13824. line += ' ';
  13825. }
  13826. line += 'generation';
  13827. line += ' ';
  13828. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13829. return line;
  13830. },
  13831. parse_ssrc: function (desc) {
  13832. // proprietary mapping of a=ssrc lines
  13833. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13834. // and parse according to that
  13835. var lines = desc.split('\r\n'),
  13836. data = {};
  13837. for (var i = 0; i < lines.length; i++) {
  13838. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13839. var idx = lines[i].indexOf(' ');
  13840. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13841. }
  13842. }
  13843. return data;
  13844. },
  13845. parse_rtcpfb: function (line) {
  13846. var parts = line.substr(10).split(' ');
  13847. var data = {};
  13848. data.pt = parts.shift();
  13849. data.type = parts.shift();
  13850. data.params = parts;
  13851. return data;
  13852. },
  13853. parse_extmap: function (line) {
  13854. var parts = line.substr(9).split(' ');
  13855. var data = {};
  13856. data.value = parts.shift();
  13857. if (data.value.indexOf('/') != -1) {
  13858. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13859. data.value = data.value.substr(0, data.value.indexOf('/'));
  13860. } else {
  13861. data.direction = 'both';
  13862. }
  13863. data.uri = parts.shift();
  13864. data.params = parts;
  13865. return data;
  13866. },
  13867. find_line: function (haystack, needle, sessionpart) {
  13868. var lines = haystack.split('\r\n');
  13869. for (var i = 0; i < lines.length; i++) {
  13870. if (lines[i].substring(0, needle.length) == needle) {
  13871. return lines[i];
  13872. }
  13873. }
  13874. if (!sessionpart) {
  13875. return false;
  13876. }
  13877. // search session part
  13878. lines = sessionpart.split('\r\n');
  13879. for (var j = 0; j < lines.length; j++) {
  13880. if (lines[j].substring(0, needle.length) == needle) {
  13881. return lines[j];
  13882. }
  13883. }
  13884. return false;
  13885. },
  13886. find_lines: function (haystack, needle, sessionpart) {
  13887. var lines = haystack.split('\r\n'),
  13888. needles = [];
  13889. for (var i = 0; i < lines.length; i++) {
  13890. if (lines[i].substring(0, needle.length) == needle)
  13891. needles.push(lines[i]);
  13892. }
  13893. if (needles.length || !sessionpart) {
  13894. return needles;
  13895. }
  13896. // search session part
  13897. lines = sessionpart.split('\r\n');
  13898. for (var j = 0; j < lines.length; j++) {
  13899. if (lines[j].substring(0, needle.length) == needle) {
  13900. needles.push(lines[j]);
  13901. }
  13902. }
  13903. return needles;
  13904. },
  13905. candidateToJingle: function (line) {
  13906. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13907. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13908. if (line.indexOf('candidate:') === 0) {
  13909. line = 'a=' + line;
  13910. } else if (line.substring(0, 12) != 'a=candidate:') {
  13911. console.log('parseCandidate called with a line that is not a candidate line');
  13912. console.log(line);
  13913. return null;
  13914. }
  13915. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13916. line = line.substring(0, line.length - 2);
  13917. var candidate = {},
  13918. elems = line.split(' '),
  13919. i;
  13920. if (elems[6] != 'typ') {
  13921. console.log('did not find typ in the right place');
  13922. console.log(line);
  13923. return null;
  13924. }
  13925. candidate.foundation = elems[0].substring(12);
  13926. candidate.component = elems[1];
  13927. candidate.protocol = elems[2].toLowerCase();
  13928. candidate.priority = elems[3];
  13929. candidate.ip = elems[4];
  13930. candidate.port = elems[5];
  13931. // elems[6] => "typ"
  13932. candidate.type = elems[7];
  13933. candidate.generation = '0'; // default, may be overwritten below
  13934. for (i = 8; i < elems.length; i += 2) {
  13935. switch (elems[i]) {
  13936. case 'raddr':
  13937. candidate['rel-addr'] = elems[i + 1];
  13938. break;
  13939. case 'rport':
  13940. candidate['rel-port'] = elems[i + 1];
  13941. break;
  13942. case 'generation':
  13943. candidate.generation = elems[i + 1];
  13944. break;
  13945. case 'tcptype':
  13946. candidate.tcptype = elems[i + 1];
  13947. break;
  13948. default: // TODO
  13949. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13950. }
  13951. }
  13952. candidate.network = '1';
  13953. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13954. return candidate;
  13955. },
  13956. candidateFromJingle: function (cand) {
  13957. var line = 'a=candidate:';
  13958. line += cand.getAttribute('foundation');
  13959. line += ' ';
  13960. line += cand.getAttribute('component');
  13961. line += ' ';
  13962. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13963. line += ' ';
  13964. line += cand.getAttribute('priority');
  13965. line += ' ';
  13966. line += cand.getAttribute('ip');
  13967. line += ' ';
  13968. line += cand.getAttribute('port');
  13969. line += ' ';
  13970. line += 'typ';
  13971. line += ' ' + cand.getAttribute('type');
  13972. line += ' ';
  13973. switch (cand.getAttribute('type')) {
  13974. case 'srflx':
  13975. case 'prflx':
  13976. case 'relay':
  13977. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13978. line += 'raddr';
  13979. line += ' ';
  13980. line += cand.getAttribute('rel-addr');
  13981. line += ' ';
  13982. line += 'rport';
  13983. line += ' ';
  13984. line += cand.getAttribute('rel-port');
  13985. line += ' ';
  13986. }
  13987. break;
  13988. }
  13989. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13990. line += 'tcptype';
  13991. line += ' ';
  13992. line += cand.getAttribute('tcptype');
  13993. line += ' ';
  13994. }
  13995. line += 'generation';
  13996. line += ' ';
  13997. line += cand.getAttribute('generation') || '0';
  13998. return line + '\r\n';
  13999. }
  14000. };
  14001. module.exports = SDPUtil;
  14002. },{}],59:[function(require,module,exports){
  14003. var RTC = require('../RTC/RTC');
  14004. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14005. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14006. function TraceablePeerConnection(ice_config, constraints, session) {
  14007. var self = this;
  14008. var RTCPeerconnectionType = null;
  14009. if (RTCBrowserType.isFirefox()) {
  14010. RTCPeerconnectionType = mozRTCPeerConnection;
  14011. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14012. RTCPeerconnectionType = RTCPeerConnection;
  14013. } else {
  14014. RTCPeerconnectionType = webkitRTCPeerConnection;
  14015. }
  14016. this.peerconnection = new RTCPeerconnectionType(ice_config, constraints);
  14017. this.updateLog = [];
  14018. this.stats = {};
  14019. this.statsinterval = null;
  14020. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14021. var Interop = require('sdp-interop').Interop;
  14022. this.interop = new Interop();
  14023. var Simulcast = require('sdp-simulcast');
  14024. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14025. // override as desired
  14026. this.trace = function (what, info) {
  14027. /*console.warn('WTRACE', what, info);
  14028. if (info && RTCBrowserType.isIExplorer()) {
  14029. if (info.length > 1024) {
  14030. console.warn('WTRACE', what, info.substr(1024));
  14031. }
  14032. if (info.length > 2048) {
  14033. console.warn('WTRACE', what, info.substr(2048));
  14034. }
  14035. }*/
  14036. self.updateLog.push({
  14037. time: new Date(),
  14038. type: what,
  14039. value: info || ""
  14040. });
  14041. };
  14042. this.onicecandidate = null;
  14043. this.peerconnection.onicecandidate = function (event) {
  14044. // FIXME: this causes stack overflow with Temasys Plugin
  14045. if (!RTCBrowserType.isTemasysPluginUsed())
  14046. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14047. if (self.onicecandidate !== null) {
  14048. self.onicecandidate(event);
  14049. }
  14050. };
  14051. this.onaddstream = null;
  14052. this.peerconnection.onaddstream = function (event) {
  14053. self.trace('onaddstream', event.stream.id);
  14054. if (self.onaddstream !== null) {
  14055. self.onaddstream(event);
  14056. }
  14057. };
  14058. this.onremovestream = null;
  14059. this.peerconnection.onremovestream = function (event) {
  14060. self.trace('onremovestream', event.stream.id);
  14061. if (self.onremovestream !== null) {
  14062. self.onremovestream(event);
  14063. }
  14064. };
  14065. this.onsignalingstatechange = null;
  14066. this.peerconnection.onsignalingstatechange = function (event) {
  14067. self.trace('onsignalingstatechange', self.signalingState);
  14068. if (self.onsignalingstatechange !== null) {
  14069. self.onsignalingstatechange(event);
  14070. }
  14071. };
  14072. this.oniceconnectionstatechange = null;
  14073. this.peerconnection.oniceconnectionstatechange = function (event) {
  14074. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14075. if (self.oniceconnectionstatechange !== null) {
  14076. self.oniceconnectionstatechange(event);
  14077. }
  14078. };
  14079. this.onnegotiationneeded = null;
  14080. this.peerconnection.onnegotiationneeded = function (event) {
  14081. self.trace('onnegotiationneeded');
  14082. if (self.onnegotiationneeded !== null) {
  14083. self.onnegotiationneeded(event);
  14084. }
  14085. };
  14086. self.ondatachannel = null;
  14087. this.peerconnection.ondatachannel = function (event) {
  14088. self.trace('ondatachannel', event);
  14089. if (self.ondatachannel !== null) {
  14090. self.ondatachannel(event);
  14091. }
  14092. };
  14093. if (!navigator.mozGetUserMedia && this.maxstats) {
  14094. this.statsinterval = window.setInterval(function() {
  14095. self.peerconnection.getStats(function(stats) {
  14096. var results = stats.result();
  14097. for (var i = 0; i < results.length; ++i) {
  14098. //console.log(results[i].type, results[i].id, results[i].names())
  14099. var now = new Date();
  14100. results[i].names().forEach(function (name) {
  14101. var id = results[i].id + '-' + name;
  14102. if (!self.stats[id]) {
  14103. self.stats[id] = {
  14104. startTime: now,
  14105. endTime: now,
  14106. values: [],
  14107. times: []
  14108. };
  14109. }
  14110. self.stats[id].values.push(results[i].stat(name));
  14111. self.stats[id].times.push(now.getTime());
  14112. if (self.stats[id].values.length > self.maxstats) {
  14113. self.stats[id].values.shift();
  14114. self.stats[id].times.shift();
  14115. }
  14116. self.stats[id].endTime = now;
  14117. });
  14118. }
  14119. });
  14120. }, 1000);
  14121. }
  14122. };
  14123. dumpSDP = function(description) {
  14124. if (typeof description === 'undefined' || description == null) {
  14125. return '';
  14126. }
  14127. return 'type: ' + description.type + '\r\n' + description.sdp;
  14128. };
  14129. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14130. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  14131. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  14132. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  14133. var desc = this.peerconnection.localDescription;
  14134. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14135. // if we're running on FF, transform to Plan B first.
  14136. if (navigator.mozGetUserMedia) {
  14137. desc = this.interop.toPlanB(desc);
  14138. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14139. }
  14140. return desc;
  14141. });
  14142. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  14143. var desc = this.peerconnection.remoteDescription;
  14144. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14145. // if we're running on FF, transform to Plan B first.
  14146. if (navigator.mozGetUserMedia) {
  14147. desc = this.interop.toPlanB(desc);
  14148. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14149. }
  14150. return desc;
  14151. });
  14152. }
  14153. TraceablePeerConnection.prototype.addStream = function (stream) {
  14154. this.trace('addStream', stream.id);
  14155. try
  14156. {
  14157. this.peerconnection.addStream(stream);
  14158. }
  14159. catch (e)
  14160. {
  14161. console.error(e);
  14162. return;
  14163. }
  14164. };
  14165. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14166. this.trace('removeStream', stream.id);
  14167. if(stopStreams) {
  14168. stream.getAudioTracks().forEach(function (track) {
  14169. // stop() not supported with IE
  14170. if (track.stop) {
  14171. track.stop();
  14172. }
  14173. });
  14174. stream.getVideoTracks().forEach(function (track) {
  14175. // stop() not supported with IE
  14176. if (track.stop) {
  14177. track.stop();
  14178. }
  14179. });
  14180. if (stream.stop) {
  14181. stream.stop();
  14182. }
  14183. }
  14184. try {
  14185. // FF doesn't support this yet.
  14186. if (this.peerconnection.removeStream)
  14187. this.peerconnection.removeStream(stream);
  14188. } catch (e) {
  14189. console.error(e);
  14190. }
  14191. };
  14192. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14193. this.trace('createDataChannel', label, opts);
  14194. return this.peerconnection.createDataChannel(label, opts);
  14195. };
  14196. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  14197. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14198. // if we're running on FF, transform to Plan A first.
  14199. if (navigator.mozGetUserMedia) {
  14200. description = this.interop.toUnifiedPlan(description);
  14201. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14202. }
  14203. var self = this;
  14204. this.peerconnection.setLocalDescription(description,
  14205. function () {
  14206. self.trace('setLocalDescriptionOnSuccess');
  14207. successCallback();
  14208. },
  14209. function (err) {
  14210. self.trace('setLocalDescriptionOnFailure', err);
  14211. failureCallback(err);
  14212. }
  14213. );
  14214. /*
  14215. if (this.statsinterval === null && this.maxstats > 0) {
  14216. // start gathering stats
  14217. }
  14218. */
  14219. };
  14220. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  14221. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14222. // TODO the focus should squeze or explode the remote simulcast
  14223. description = this.simulcast.mungeRemoteDescription(description);
  14224. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14225. // if we're running on FF, transform to Plan A first.
  14226. if (navigator.mozGetUserMedia) {
  14227. description = this.interop.toUnifiedPlan(description);
  14228. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14229. }
  14230. var self = this;
  14231. this.peerconnection.setRemoteDescription(description,
  14232. function () {
  14233. self.trace('setRemoteDescriptionOnSuccess');
  14234. successCallback();
  14235. },
  14236. function (err) {
  14237. self.trace('setRemoteDescriptionOnFailure', err);
  14238. failureCallback(err);
  14239. }
  14240. );
  14241. /*
  14242. if (this.statsinterval === null && this.maxstats > 0) {
  14243. // start gathering stats
  14244. }
  14245. */
  14246. };
  14247. TraceablePeerConnection.prototype.close = function () {
  14248. this.trace('stop');
  14249. if (this.statsinterval !== null) {
  14250. window.clearInterval(this.statsinterval);
  14251. this.statsinterval = null;
  14252. }
  14253. this.peerconnection.close();
  14254. };
  14255. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  14256. var self = this;
  14257. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14258. this.peerconnection.createOffer(
  14259. function (offer) {
  14260. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14261. // if we're running on FF, transform to Plan B first.
  14262. // NOTE this is not tested because in meet the focus generates the
  14263. // offer.
  14264. if (navigator.mozGetUserMedia) {
  14265. offer = self.interop.toPlanB(offer);
  14266. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14267. }
  14268. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14269. offer = self.simulcast.mungeLocalDescription(offer);
  14270. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14271. }
  14272. successCallback(offer);
  14273. },
  14274. function(err) {
  14275. self.trace('createOfferOnFailure', err);
  14276. failureCallback(err);
  14277. },
  14278. constraints
  14279. );
  14280. };
  14281. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  14282. var self = this;
  14283. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14284. this.peerconnection.createAnswer(
  14285. function (answer) {
  14286. self.trace('createAnswerOnSuccess::preTransfom', dumpSDP(answer));
  14287. // if we're running on FF, transform to Plan A first.
  14288. if (navigator.mozGetUserMedia) {
  14289. answer = self.interop.toPlanB(answer);
  14290. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  14291. }
  14292. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14293. answer = self.simulcast.mungeLocalDescription(answer);
  14294. self.trace('createAnswerOnSuccess::postTransfom (simulcast)', dumpSDP(answer));
  14295. }
  14296. successCallback(answer);
  14297. },
  14298. function(err) {
  14299. self.trace('createAnswerOnFailure', err);
  14300. failureCallback(err);
  14301. },
  14302. constraints
  14303. );
  14304. };
  14305. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  14306. var self = this;
  14307. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14308. this.peerconnection.addIceCandidate(candidate);
  14309. /* maybe later
  14310. this.peerconnection.addIceCandidate(candidate,
  14311. function () {
  14312. self.trace('addIceCandidateOnSuccess');
  14313. successCallback();
  14314. },
  14315. function (err) {
  14316. self.trace('addIceCandidateOnFailure', err);
  14317. failureCallback(err);
  14318. }
  14319. );
  14320. */
  14321. };
  14322. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14323. if (navigator.mozGetUserMedia) {
  14324. // ignore for now...
  14325. if(!errback)
  14326. errback = function () {
  14327. }
  14328. this.peerconnection.getStats(null,callback,errback);
  14329. } else {
  14330. this.peerconnection.getStats(callback);
  14331. }
  14332. };
  14333. module.exports = TraceablePeerConnection;
  14334. },{"../../service/xmpp/XMPPEvents":110,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"sdp-interop":91,"sdp-simulcast":94}],60:[function(require,module,exports){
  14335. /* global $, $iq, APP, config, connection, UI, messageHandler,
  14336. roomName, sessionTerminated, Strophe, Util */
  14337. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14338. var Settings = require("../settings/Settings");
  14339. var AuthenticationEvents
  14340. = require("../../service/authentication/AuthenticationEvents");
  14341. /**
  14342. * Contains logic responsible for enabling/disabling functionality available
  14343. * only to moderator users.
  14344. */
  14345. var connection = null;
  14346. var focusUserJid;
  14347. function createExpBackoffTimer(step) {
  14348. var count = 1;
  14349. return function (reset) {
  14350. // Reset call
  14351. if (reset) {
  14352. count = 1;
  14353. return;
  14354. }
  14355. // Calculate next timeout
  14356. var timeout = Math.pow(2, count - 1);
  14357. count += 1;
  14358. return timeout * step;
  14359. };
  14360. }
  14361. var getNextTimeout = createExpBackoffTimer(1000);
  14362. var getNextErrorTimeout = createExpBackoffTimer(1000);
  14363. // External authentication stuff
  14364. var externalAuthEnabled = false;
  14365. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  14366. // it will be enabled automatically if focus detects the component through
  14367. // service discovery.
  14368. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  14369. var eventEmitter = null;
  14370. var Moderator = {
  14371. isModerator: function () {
  14372. return connection && connection.emuc.isModerator();
  14373. },
  14374. isPeerModerator: function (peerJid) {
  14375. return connection &&
  14376. connection.emuc.getMemberRole(peerJid) === 'moderator';
  14377. },
  14378. isExternalAuthEnabled: function () {
  14379. return externalAuthEnabled;
  14380. },
  14381. isSipGatewayEnabled: function () {
  14382. return sipGatewayEnabled;
  14383. },
  14384. setConnection: function (con) {
  14385. connection = con;
  14386. },
  14387. init: function (xmpp, emitter) {
  14388. this.xmppService = xmpp;
  14389. eventEmitter = emitter;
  14390. // Message listener that talks to POPUP window
  14391. function listener(event) {
  14392. if (event.data && event.data.sessionId) {
  14393. if (event.origin !== window.location.origin) {
  14394. console.warn(
  14395. "Ignoring sessionId from different origin: " + event.origin);
  14396. return;
  14397. }
  14398. localStorage.setItem('sessionId', event.data.sessionId);
  14399. // After popup is closed we will authenticate
  14400. }
  14401. }
  14402. // Register
  14403. if (window.addEventListener) {
  14404. window.addEventListener("message", listener, false);
  14405. } else {
  14406. window.attachEvent("onmessage", listener);
  14407. }
  14408. },
  14409. onMucMemberLeft: function (jid) {
  14410. console.info("Someone left is it focus ? " + jid);
  14411. var resource = Strophe.getResourceFromJid(jid);
  14412. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  14413. console.info(
  14414. "Focus has left the room - leaving conference");
  14415. //hangUp();
  14416. // We'd rather reload to have everything re-initialized
  14417. // FIXME: show some message before reload
  14418. location.reload();
  14419. }
  14420. },
  14421. setFocusUserJid: function (focusJid) {
  14422. if (!focusUserJid) {
  14423. focusUserJid = focusJid;
  14424. console.info("Focus jid set to: " + focusUserJid);
  14425. }
  14426. },
  14427. getFocusUserJid: function () {
  14428. return focusUserJid;
  14429. },
  14430. getFocusComponent: function () {
  14431. // Get focus component address
  14432. var focusComponent = config.hosts.focus;
  14433. // If not specified use default: 'focus.domain'
  14434. if (!focusComponent) {
  14435. focusComponent = 'focus.' + config.hosts.domain;
  14436. }
  14437. return focusComponent;
  14438. },
  14439. createConferenceIq: function (roomName) {
  14440. // Generate create conference IQ
  14441. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14442. // Session Id used for authentication
  14443. var sessionId = localStorage.getItem('sessionId');
  14444. var machineUID = Settings.getSettings().uid;
  14445. console.info(
  14446. "Session ID: " + sessionId + " machine UID: " + machineUID);
  14447. elem.c('conference', {
  14448. xmlns: 'http://jitsi.org/protocol/focus',
  14449. room: roomName,
  14450. 'machine-uid': machineUID
  14451. });
  14452. if (sessionId) {
  14453. elem.attrs({ 'session-id': sessionId});
  14454. }
  14455. if (config.hosts.bridge !== undefined) {
  14456. elem.c(
  14457. 'property',
  14458. { name: 'bridge', value: config.hosts.bridge})
  14459. .up();
  14460. }
  14461. // Tell the focus we have Jigasi configured
  14462. if (config.hosts.call_control !== undefined) {
  14463. elem.c(
  14464. 'property',
  14465. { name: 'call_control', value: config.hosts.call_control})
  14466. .up();
  14467. }
  14468. if (config.channelLastN !== undefined) {
  14469. elem.c(
  14470. 'property',
  14471. { name: 'channelLastN', value: config.channelLastN})
  14472. .up();
  14473. }
  14474. if (config.adaptiveLastN !== undefined) {
  14475. elem.c(
  14476. 'property',
  14477. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  14478. .up();
  14479. }
  14480. if (config.adaptiveSimulcast !== undefined) {
  14481. elem.c(
  14482. 'property',
  14483. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  14484. .up();
  14485. }
  14486. if (config.openSctp !== undefined) {
  14487. elem.c(
  14488. 'property',
  14489. { name: 'openSctp', value: config.openSctp})
  14490. .up();
  14491. }
  14492. if(config.startAudioMuted !== undefined)
  14493. {
  14494. elem.c(
  14495. 'property',
  14496. { name: 'startAudioMuted', value: config.startAudioMuted})
  14497. .up();
  14498. }
  14499. if(config.startVideoMuted !== undefined)
  14500. {
  14501. elem.c(
  14502. 'property',
  14503. { name: 'startVideoMuted', value: config.startVideoMuted})
  14504. .up();
  14505. }
  14506. elem.c(
  14507. 'property',
  14508. { name: 'simulcastMode', value: 'rewriting'})
  14509. .up();
  14510. elem.up();
  14511. return elem;
  14512. },
  14513. parseSessionId: function (resultIq) {
  14514. var sessionId = $(resultIq).find('conference').attr('session-id');
  14515. if (sessionId) {
  14516. console.info('Received sessionId: ' + sessionId);
  14517. localStorage.setItem('sessionId', sessionId);
  14518. }
  14519. },
  14520. parseConfigOptions: function (resultIq) {
  14521. Moderator.setFocusUserJid(
  14522. $(resultIq).find('conference').attr('focusjid'));
  14523. var authenticationEnabled
  14524. = $(resultIq).find(
  14525. '>conference>property' +
  14526. '[name=\'authentication\'][value=\'true\']').length > 0;
  14527. console.info("Authentication enabled: " + authenticationEnabled);
  14528. externalAuthEnabled
  14529. = $(resultIq).find(
  14530. '>conference>property' +
  14531. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  14532. console.info('External authentication enabled: ' + externalAuthEnabled);
  14533. if (!externalAuthEnabled) {
  14534. // We expect to receive sessionId in 'internal' authentication mode
  14535. Moderator.parseSessionId(resultIq);
  14536. }
  14537. var authIdentity = $(resultIq).find('>conference').attr('identity');
  14538. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  14539. authenticationEnabled, authIdentity);
  14540. // Check if focus has auto-detected Jigasi component(this will be also
  14541. // included if we have passed our host from the config)
  14542. if ($(resultIq).find(
  14543. '>conference>property' +
  14544. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  14545. sipGatewayEnabled = true;
  14546. }
  14547. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  14548. },
  14549. // FIXME: we need to show the fact that we're waiting for the focus
  14550. // to the user(or that focus is not available)
  14551. allocateConferenceFocus: function (roomName, callback) {
  14552. // Try to use focus user JID from the config
  14553. Moderator.setFocusUserJid(config.focusUserJid);
  14554. // Send create conference IQ
  14555. var iq = Moderator.createConferenceIq(roomName);
  14556. var self = this;
  14557. connection.sendIQ(
  14558. iq,
  14559. function (result) {
  14560. // Setup config options
  14561. Moderator.parseConfigOptions(result);
  14562. if ('true' === $(result).find('conference').attr('ready')) {
  14563. // Reset both timers
  14564. getNextTimeout(true);
  14565. getNextErrorTimeout(true);
  14566. // Exec callback
  14567. callback();
  14568. } else {
  14569. var waitMs = getNextTimeout();
  14570. console.info("Waiting for the focus... " + waitMs);
  14571. // Reset error timeout
  14572. getNextErrorTimeout(true);
  14573. window.setTimeout(
  14574. function () {
  14575. Moderator.allocateConferenceFocus(
  14576. roomName, callback);
  14577. }, waitMs);
  14578. }
  14579. },
  14580. function (error) {
  14581. // Invalid session ? remove and try again
  14582. // without session ID to get a new one
  14583. var invalidSession
  14584. = $(error).find('>error>session-invalid').length;
  14585. if (invalidSession) {
  14586. console.info("Session expired! - removing");
  14587. localStorage.removeItem("sessionId");
  14588. }
  14589. if ($(error).find('>error>graceful-shutdown').length) {
  14590. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  14591. return;
  14592. }
  14593. // Check for error returned by the reservation system
  14594. var reservationErr = $(error).find('>error>reservation-error');
  14595. if (reservationErr.length) {
  14596. // Trigger error event
  14597. var errorCode = reservationErr.attr('error-code');
  14598. var errorMsg;
  14599. if ($(error).find('>error>text')) {
  14600. errorMsg = $(error).find('>error>text').text();
  14601. }
  14602. eventEmitter.emit(
  14603. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  14604. return;
  14605. }
  14606. // Not authorized to create new room
  14607. if ($(error).find('>error>not-authorized').length) {
  14608. console.warn("Unauthorized to start the conference", error);
  14609. var toDomain
  14610. = Strophe.getDomainFromJid(error.getAttribute('to'));
  14611. if (toDomain !== config.hosts.anonymousdomain) {
  14612. // FIXME: "is external" should come either from
  14613. // the focus or config.js
  14614. externalAuthEnabled = true;
  14615. }
  14616. eventEmitter.emit(
  14617. XMPPEvents.AUTHENTICATION_REQUIRED,
  14618. function () {
  14619. Moderator.allocateConferenceFocus(
  14620. roomName, callback);
  14621. });
  14622. return;
  14623. }
  14624. var waitMs = getNextErrorTimeout();
  14625. console.error("Focus error, retry after " + waitMs, error);
  14626. // Show message
  14627. var focusComponent = Moderator.getFocusComponent();
  14628. var retrySec = waitMs / 1000;
  14629. // FIXME: message is duplicated ?
  14630. // Do not show in case of session invalid
  14631. // which means just a retry
  14632. if (!invalidSession) {
  14633. APP.UI.messageHandler.notify(
  14634. null, "notify.focus",
  14635. 'disconnected', "notify.focusFail",
  14636. {component: focusComponent, ms: retrySec});
  14637. }
  14638. // Reset response timeout
  14639. getNextTimeout(true);
  14640. window.setTimeout(
  14641. function () {
  14642. Moderator.allocateConferenceFocus(roomName, callback);
  14643. }, waitMs);
  14644. }
  14645. );
  14646. },
  14647. getLoginUrl: function (roomName, urlCallback) {
  14648. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14649. iq.c('login-url', {
  14650. xmlns: 'http://jitsi.org/protocol/focus',
  14651. room: roomName,
  14652. 'machine-uid': Settings.getSettings().uid
  14653. });
  14654. connection.sendIQ(
  14655. iq,
  14656. function (result) {
  14657. var url = $(result).find('login-url').attr('url');
  14658. url = url = decodeURIComponent(url);
  14659. if (url) {
  14660. console.info("Got auth url: " + url);
  14661. urlCallback(url);
  14662. } else {
  14663. console.error(
  14664. "Failed to get auth url from the focus", result);
  14665. }
  14666. },
  14667. function (error) {
  14668. console.error("Get auth url error", error);
  14669. }
  14670. );
  14671. },
  14672. getPopupLoginUrl: function (roomName, urlCallback) {
  14673. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  14674. iq.c('login-url', {
  14675. xmlns: 'http://jitsi.org/protocol/focus',
  14676. room: roomName,
  14677. 'machine-uid': Settings.getSettings().uid,
  14678. popup: true
  14679. });
  14680. connection.sendIQ(
  14681. iq,
  14682. function (result) {
  14683. var url = $(result).find('login-url').attr('url');
  14684. url = url = decodeURIComponent(url);
  14685. if (url) {
  14686. console.info("Got POPUP auth url: " + url);
  14687. urlCallback(url);
  14688. } else {
  14689. console.error(
  14690. "Failed to get POPUP auth url from the focus", result);
  14691. }
  14692. },
  14693. function (error) {
  14694. console.error('Get POPUP auth url error', error);
  14695. }
  14696. );
  14697. },
  14698. logout: function (callback) {
  14699. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14700. var sessionId = localStorage.getItem('sessionId');
  14701. if (!sessionId) {
  14702. callback();
  14703. return;
  14704. }
  14705. iq.c('logout', {
  14706. xmlns: 'http://jitsi.org/protocol/focus',
  14707. 'session-id': sessionId
  14708. });
  14709. connection.sendIQ(
  14710. iq,
  14711. function (result) {
  14712. var logoutUrl = $(result).find('logout').attr('logout-url');
  14713. if (logoutUrl) {
  14714. logoutUrl = decodeURIComponent(logoutUrl);
  14715. }
  14716. console.info("Log out OK, url: " + logoutUrl, result);
  14717. localStorage.removeItem('sessionId');
  14718. callback(logoutUrl);
  14719. },
  14720. function (error) {
  14721. console.error("Logout error", error);
  14722. }
  14723. );
  14724. }
  14725. };
  14726. module.exports = Moderator;
  14727. },{"../../service/authentication/AuthenticationEvents":105,"../../service/xmpp/XMPPEvents":110,"../settings/Settings":49}],61:[function(require,module,exports){
  14728. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14729. Toolbar, Util */
  14730. var Moderator = require("./moderator");
  14731. var recordingToken = null;
  14732. var recordingEnabled;
  14733. /**
  14734. * Whether to use a jirecon component for recording, or use the videobridge
  14735. * through COLIBRI.
  14736. */
  14737. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14738. /**
  14739. * The ID of the jirecon recording session. Jirecon generates it when we
  14740. * initially start recording, and it needs to be used in subsequent requests
  14741. * to jirecon.
  14742. */
  14743. var jireconRid = null;
  14744. function setRecordingToken(token) {
  14745. recordingToken = token;
  14746. }
  14747. function setRecording(state, token, callback, connection) {
  14748. if (useJirecon){
  14749. setRecordingJirecon(state, token, callback, connection);
  14750. } else {
  14751. setRecordingColibri(state, token, callback, connection);
  14752. }
  14753. }
  14754. function setRecordingJirecon(state, token, callback, connection) {
  14755. if (state == recordingEnabled){
  14756. return;
  14757. }
  14758. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14759. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14760. action: state ? 'start' : 'stop',
  14761. mucjid: connection.emuc.roomjid});
  14762. if (!state){
  14763. iq.attrs({rid: jireconRid});
  14764. }
  14765. console.log('Start recording');
  14766. connection.sendIQ(
  14767. iq,
  14768. function (result) {
  14769. // TODO wait for an IQ with the real status, since this is
  14770. // provisional?
  14771. jireconRid = $(result).find('recording').attr('rid');
  14772. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14773. '(jirecon)' + result);
  14774. recordingEnabled = state;
  14775. if (!state){
  14776. jireconRid = null;
  14777. }
  14778. callback(state);
  14779. },
  14780. function (error) {
  14781. console.log('Failed to start recording, error: ', error);
  14782. callback(recordingEnabled);
  14783. });
  14784. }
  14785. // Sends a COLIBRI message which enables or disables (according to 'state')
  14786. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14787. // with the new recording state, according to the IQ.
  14788. function setRecordingColibri(state, token, callback, connection) {
  14789. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14790. elem.c('conference', {
  14791. xmlns: 'http://jitsi.org/protocol/colibri'
  14792. });
  14793. elem.c('recording', {state: state, token: token});
  14794. connection.sendIQ(elem,
  14795. function (result) {
  14796. console.log('Set recording "', state, '". Result:', result);
  14797. var recordingElem = $(result).find('>conference>recording');
  14798. var newState = ('true' === recordingElem.attr('state'));
  14799. recordingEnabled = newState;
  14800. callback(newState);
  14801. },
  14802. function (error) {
  14803. console.warn(error);
  14804. callback(recordingEnabled);
  14805. }
  14806. );
  14807. }
  14808. var Recording = {
  14809. toggleRecording: function (tokenEmptyCallback,
  14810. startingCallback, startedCallback, connection) {
  14811. if (!Moderator.isModerator()) {
  14812. console.log(
  14813. 'non-focus, or conference not yet organized:' +
  14814. ' not enabling recording');
  14815. return;
  14816. }
  14817. var self = this;
  14818. // Jirecon does not (currently) support a token.
  14819. if (!recordingToken && !useJirecon) {
  14820. tokenEmptyCallback(function (value) {
  14821. setRecordingToken(value);
  14822. self.toggleRecording(tokenEmptyCallback,
  14823. startingCallback, startedCallback, connection);
  14824. });
  14825. return;
  14826. }
  14827. var oldState = recordingEnabled;
  14828. startingCallback(!oldState);
  14829. setRecording(!oldState,
  14830. recordingToken,
  14831. function (state) {
  14832. console.log("New recording state: ", state);
  14833. if (state === oldState) {
  14834. // FIXME: new focus:
  14835. // this will not work when moderator changes
  14836. // during active session. Then it will assume that
  14837. // recording status has changed to true, but it might have
  14838. // been already true(and we only received actual status from
  14839. // the focus).
  14840. //
  14841. // SO we start with status null, so that it is initialized
  14842. // here and will fail only after second click, so if invalid
  14843. // token was used we have to press the button twice before
  14844. // current status will be fetched and token will be reset.
  14845. //
  14846. // Reliable way would be to return authentication error.
  14847. // Or status update when moderator connects.
  14848. // Or we have to stop recording session when current
  14849. // moderator leaves the room.
  14850. // Failed to change, reset the token because it might
  14851. // have been wrong
  14852. setRecordingToken(null);
  14853. }
  14854. startedCallback(state);
  14855. },
  14856. connection
  14857. );
  14858. }
  14859. }
  14860. module.exports = Recording;
  14861. },{"./moderator":60}],62:[function(require,module,exports){
  14862. /* jshint -W117 */
  14863. /* a simple MUC connection plugin
  14864. * can only handle a single MUC room
  14865. */
  14866. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14867. var Moderator = require("./moderator");
  14868. var JingleSession = require("./JingleSession");
  14869. var bridgeIsDown = false;
  14870. module.exports = function(XMPP, eventEmitter) {
  14871. Strophe.addConnectionPlugin('emuc', {
  14872. connection: null,
  14873. roomjid: null,
  14874. myroomjid: null,
  14875. members: {},
  14876. list_members: [], // so we can elect a new focus
  14877. presMap: {},
  14878. preziMap: {},
  14879. joined: false,
  14880. isOwner: false,
  14881. role: null,
  14882. focusMucJid: null,
  14883. ssrc2jid: {},
  14884. init: function (conn) {
  14885. this.connection = conn;
  14886. },
  14887. initPresenceMap: function (myroomjid) {
  14888. this.presMap['to'] = myroomjid;
  14889. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14890. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted())
  14891. {
  14892. this.addAudioInfoToPresence(true);
  14893. }
  14894. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted())
  14895. {
  14896. this.addVideoInfoToPresence(true);
  14897. }
  14898. },
  14899. doJoin: function (jid, password) {
  14900. this.myroomjid = jid;
  14901. console.info("Joined MUC as " + this.myroomjid);
  14902. this.initPresenceMap(this.myroomjid);
  14903. if (!this.roomjid) {
  14904. this.roomjid = Strophe.getBareJidFromJid(jid);
  14905. // add handlers (just once)
  14906. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14907. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14908. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14909. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14910. }
  14911. if (password !== undefined) {
  14912. this.presMap['password'] = password;
  14913. }
  14914. this.sendPresence();
  14915. },
  14916. doLeave: function () {
  14917. console.log("do leave", this.myroomjid);
  14918. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14919. this.presMap.length = 0;
  14920. this.connection.send(pres);
  14921. },
  14922. createNonAnonymousRoom: function () {
  14923. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14924. var getForm = $iq({type: 'get', to: this.roomjid})
  14925. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14926. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14927. var self = this;
  14928. this.connection.sendIQ(getForm, function (form) {
  14929. if (!$(form).find(
  14930. '>query>x[xmlns="jabber:x:data"]' +
  14931. '>field[var="muc#roomconfig_whois"]').length) {
  14932. console.error('non-anonymous rooms not supported');
  14933. return;
  14934. }
  14935. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14936. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14937. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14938. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14939. .c('value')
  14940. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14941. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14942. .c('value').t('anyone').up().up();
  14943. self.connection.sendIQ(formSubmit);
  14944. }, function (error) {
  14945. console.error("Error getting room configuration form");
  14946. });
  14947. },
  14948. onPresence: function (pres) {
  14949. var from = pres.getAttribute('from');
  14950. // What is this for? A workaround for something?
  14951. if (pres.getAttribute('type')) {
  14952. return true;
  14953. }
  14954. // Parse etherpad tag.
  14955. var etherpad = $(pres).find('>etherpad');
  14956. if (etherpad.length) {
  14957. if (config.etherpad_base) {
  14958. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14959. }
  14960. }
  14961. // Parse prezi tag.
  14962. var presentation = $(pres).find('>prezi');
  14963. if (presentation.length) {
  14964. var url = presentation.attr('url');
  14965. var current = presentation.find('>current').text();
  14966. console.log('presentation info received from', from, url);
  14967. if (this.preziMap[from] == null) {
  14968. this.preziMap[from] = url;
  14969. $(document).trigger('presentationadded.muc', [from, url, current]);
  14970. }
  14971. else {
  14972. $(document).trigger('gotoslide.muc', [from, url, current]);
  14973. }
  14974. }
  14975. else if (this.preziMap[from] != null) {
  14976. var url = this.preziMap[from];
  14977. delete this.preziMap[from];
  14978. $(document).trigger('presentationremoved.muc', [from, url]);
  14979. }
  14980. // Parse audio info tag.
  14981. var audioMuted = $(pres).find('>audiomuted');
  14982. if (audioMuted.length) {
  14983. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  14984. from, (audioMuted.text() === "true"));
  14985. }
  14986. // Parse video info tag.
  14987. var videoMuted = $(pres).find('>videomuted');
  14988. if (videoMuted.length) {
  14989. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  14990. from, (videoMuted.text() === "true"));
  14991. }
  14992. var startMuted = $(pres).find('>startmuted');
  14993. if (startMuted.length)
  14994. {
  14995. eventEmitter.emit(XMPPEvents.START_MUTED,
  14996. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14997. }
  14998. var devices = $(pres).find('>devices');
  14999. if(devices.length)
  15000. {
  15001. var audio = devices.find('>audio');
  15002. var video = devices.find('>video');
  15003. var devicesValues = {audio: false, video: false};
  15004. if(audio.length && audio.text() === "true")
  15005. {
  15006. devicesValues.audio = true;
  15007. }
  15008. if(video.length && video.text() === "true")
  15009. {
  15010. devicesValues.video = true;
  15011. }
  15012. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15013. Strophe.getResourceFromJid(from), devicesValues);
  15014. }
  15015. var stats = $(pres).find('>stats');
  15016. if (stats.length) {
  15017. var statsObj = {};
  15018. Strophe.forEachChild(stats[0], "stat", function (el) {
  15019. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15020. });
  15021. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15022. }
  15023. // Parse status.
  15024. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15025. this.isOwner = true;
  15026. this.createNonAnonymousRoom();
  15027. }
  15028. // Parse roles.
  15029. var member = {};
  15030. member.show = $(pres).find('>show').text();
  15031. member.status = $(pres).find('>status').text();
  15032. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15033. member.affiliation = tmp.attr('affiliation');
  15034. member.role = tmp.attr('role');
  15035. // Focus recognition
  15036. member.jid = tmp.attr('jid');
  15037. member.isFocus = false;
  15038. if (member.jid
  15039. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15040. member.isFocus = true;
  15041. }
  15042. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15043. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15044. if (from == this.myroomjid) {
  15045. if (member.affiliation == 'owner') this.isOwner = true;
  15046. if (this.role !== member.role) {
  15047. this.role = member.role;
  15048. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15049. from, member, pres, Moderator.isModerator());
  15050. }
  15051. if (!this.joined) {
  15052. this.joined = true;
  15053. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15054. this.list_members.push(from);
  15055. }
  15056. } else if (this.members[from] === undefined) {
  15057. // new participant
  15058. this.members[from] = member;
  15059. this.list_members.push(from);
  15060. console.log('entered', from, member);
  15061. if (member.isFocus) {
  15062. this.focusMucJid = from;
  15063. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15064. }
  15065. else {
  15066. var id = $(pres).find('>userId').text();
  15067. var email = $(pres).find('>email');
  15068. if (email.length > 0) {
  15069. id = email.text();
  15070. }
  15071. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15072. }
  15073. } else {
  15074. // Presence update for existing participant
  15075. // Watch role change:
  15076. if (this.members[from].role != member.role) {
  15077. this.members[from].role = member.role;
  15078. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15079. member.role, member.displayName);
  15080. }
  15081. }
  15082. // Always trigger presence to update bindings
  15083. this.parsePresence(from, member, pres);
  15084. // Trigger status message update
  15085. if (member.status) {
  15086. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15087. }
  15088. return true;
  15089. },
  15090. onPresenceUnavailable: function (pres) {
  15091. var from = pres.getAttribute('from');
  15092. // room destroyed ?
  15093. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15094. '>destroy').length) {
  15095. var reason;
  15096. var reasonSelect = $(pres).find(
  15097. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15098. '>destroy>reason');
  15099. if (reasonSelect.length) {
  15100. reason = reasonSelect.text();
  15101. }
  15102. XMPP.disposeConference(false);
  15103. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15104. return true;
  15105. }
  15106. var self = this;
  15107. // Remove old ssrcs coming from the jid
  15108. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  15109. if (self.ssrc2jid[ssrc] == from) {
  15110. delete self.ssrc2jid[ssrc];
  15111. }
  15112. });
  15113. // Status code 110 indicates that this notification is "self-presence".
  15114. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15115. delete this.members[from];
  15116. this.list_members.splice(this.list_members.indexOf(from), 1);
  15117. this.onParticipantLeft(from);
  15118. }
  15119. // If the status code is 110 this means we're leaving and we would like
  15120. // to remove everyone else from our view, so we trigger the event.
  15121. else if (this.list_members.length > 1) {
  15122. for (var i = 0; i < this.list_members.length; i++) {
  15123. var member = this.list_members[i];
  15124. delete this.members[i];
  15125. this.list_members.splice(i, 1);
  15126. this.onParticipantLeft(member);
  15127. }
  15128. }
  15129. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15130. $(document).trigger('kicked.muc', [from]);
  15131. if (this.myroomjid === from) {
  15132. XMPP.disposeConference(false);
  15133. eventEmitter.emit(XMPPEvents.KICKED);
  15134. }
  15135. }
  15136. return true;
  15137. },
  15138. onPresenceError: function (pres) {
  15139. var from = pres.getAttribute('from');
  15140. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15141. console.log('on password required', from);
  15142. var self = this;
  15143. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15144. self.doJoin(from, value);
  15145. });
  15146. } else if ($(pres).find(
  15147. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15148. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15149. if (toDomain === config.hosts.anonymousdomain) {
  15150. // enter the room by replying with 'not-authorized'. This would
  15151. // result in reconnection from authorized domain.
  15152. // We're either missing Jicofo/Prosody config for anonymous
  15153. // domains or something is wrong.
  15154. // XMPP.promptLogin();
  15155. APP.UI.messageHandler.openReportDialog(null,
  15156. "dialog.joinError", pres);
  15157. } else {
  15158. console.warn('onPresError ', pres);
  15159. APP.UI.messageHandler.openReportDialog(null,
  15160. "dialog.connectError",
  15161. pres);
  15162. }
  15163. } else {
  15164. console.warn('onPresError ', pres);
  15165. APP.UI.messageHandler.openReportDialog(null,
  15166. "dialog.connectError",
  15167. pres);
  15168. }
  15169. return true;
  15170. },
  15171. sendMessage: function (body, nickname) {
  15172. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15173. msg.c('body', body).up();
  15174. if (nickname) {
  15175. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15176. }
  15177. this.connection.send(msg);
  15178. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15179. },
  15180. setSubject: function (subject) {
  15181. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15182. msg.c('subject', subject);
  15183. this.connection.send(msg);
  15184. console.log("topic changed to " + subject);
  15185. },
  15186. onMessage: function (msg) {
  15187. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15188. var from = msg.getAttribute('from');
  15189. var nick =
  15190. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15191. .text() ||
  15192. Strophe.getResourceFromJid(from);
  15193. var txt = $(msg).find('>body').text();
  15194. var type = msg.getAttribute("type");
  15195. if (type == "error") {
  15196. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15197. $(msg).find('>text').text(), txt);
  15198. return true;
  15199. }
  15200. var subject = $(msg).find('>subject');
  15201. if (subject.length) {
  15202. var subjectText = subject.text();
  15203. if (subjectText || subjectText == "") {
  15204. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15205. console.log("Subject is changed to " + subjectText);
  15206. }
  15207. }
  15208. // xep-0203 delay
  15209. var stamp = $(msg).find('>delay').attr('stamp');
  15210. if (!stamp) {
  15211. // or xep-0091 delay, UTC timestamp
  15212. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15213. if (stamp) {
  15214. // the format is CCYYMMDDThh:mm:ss
  15215. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15216. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15217. }
  15218. }
  15219. if (txt) {
  15220. console.log('chat', nick, txt);
  15221. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15222. from, nick, txt, this.myroomjid, stamp);
  15223. }
  15224. return true;
  15225. },
  15226. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15227. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15228. var ob = this;
  15229. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15230. function (res) {
  15231. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15232. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15233. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15234. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15235. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15236. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15237. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15238. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15239. ob.connection.sendIQ(formsubmit,
  15240. onSuccess,
  15241. onError);
  15242. } else {
  15243. onNotSupported();
  15244. }
  15245. }, onError);
  15246. },
  15247. kick: function (jid) {
  15248. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15249. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15250. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15251. .c('reason').t('You have been kicked.').up().up().up();
  15252. this.connection.sendIQ(
  15253. kickIQ,
  15254. function (result) {
  15255. console.log('Kick participant with jid: ', jid, result);
  15256. },
  15257. function (error) {
  15258. console.log('Kick participant error: ', error);
  15259. });
  15260. },
  15261. sendPresence: function () {
  15262. if (!this.presMap['to']) {
  15263. // Too early to send presence - not initialized
  15264. return;
  15265. }
  15266. var pres = $pres({to: this.presMap['to'] });
  15267. pres.c('x', {xmlns: this.presMap['xns']});
  15268. if (this.presMap['password']) {
  15269. pres.c('password').t(this.presMap['password']).up();
  15270. }
  15271. pres.up();
  15272. // Send XEP-0115 'c' stanza that contains our capabilities info
  15273. if (this.connection.caps) {
  15274. this.connection.caps.node = config.clientNode;
  15275. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15276. }
  15277. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15278. .t(navigator.userAgent).up();
  15279. if (this.presMap['bridgeIsDown']) {
  15280. pres.c('bridgeIsDown').up();
  15281. }
  15282. if (this.presMap['email']) {
  15283. pres.c('email').t(this.presMap['email']).up();
  15284. }
  15285. if (this.presMap['userId']) {
  15286. pres.c('userId').t(this.presMap['userId']).up();
  15287. }
  15288. if (this.presMap['displayName']) {
  15289. // XEP-0172
  15290. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15291. .t(this.presMap['displayName']).up();
  15292. }
  15293. if(this.presMap["devices"])
  15294. {
  15295. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15296. .c('video').t(this.presMap['devices'].video).up().up();
  15297. }
  15298. if (this.presMap['audions']) {
  15299. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15300. .t(this.presMap['audiomuted']).up();
  15301. }
  15302. if (this.presMap['videons']) {
  15303. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15304. .t(this.presMap['videomuted']).up();
  15305. }
  15306. if (this.presMap['statsns']) {
  15307. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15308. for (var stat in this.presMap["stats"])
  15309. if (this.presMap["stats"][stat] != null)
  15310. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15311. pres.up();
  15312. }
  15313. if (this.presMap['prezins']) {
  15314. pres.c('prezi',
  15315. {xmlns: this.presMap['prezins'],
  15316. 'url': this.presMap['preziurl']})
  15317. .c('current').t(this.presMap['prezicurrent']).up().up();
  15318. }
  15319. if (this.presMap['medians']) {
  15320. pres.c('media', {xmlns: this.presMap['medians']});
  15321. var sourceNumber = 0;
  15322. Object.keys(this.presMap).forEach(function (key) {
  15323. if (key.indexOf('source') >= 0) {
  15324. sourceNumber++;
  15325. }
  15326. });
  15327. if (sourceNumber > 0)
  15328. for (var i = 1; i <= sourceNumber / 3; i++) {
  15329. pres.c('source',
  15330. {type: this.presMap['source' + i + '_type'],
  15331. ssrc: this.presMap['source' + i + '_ssrc'],
  15332. direction: this.presMap['source' + i + '_direction']
  15333. || 'sendrecv' }
  15334. ).up();
  15335. }
  15336. pres.up();
  15337. }
  15338. if(this.presMap["startMuted"] !== undefined)
  15339. {
  15340. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15341. video: this.presMap["startMuted"].video,
  15342. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15343. delete this.presMap["startMuted"];
  15344. }
  15345. pres.up();
  15346. this.connection.send(pres);
  15347. },
  15348. addDisplayNameToPresence: function (displayName) {
  15349. this.presMap['displayName'] = displayName;
  15350. },
  15351. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  15352. if (!this.presMap['medians'])
  15353. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  15354. this.presMap['source' + sourceNumber + '_type'] = mtype;
  15355. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  15356. this.presMap['source' + sourceNumber + '_direction'] = direction;
  15357. },
  15358. addDevicesToPresence: function (devices) {
  15359. this.presMap['devices'] = devices;
  15360. },
  15361. clearPresenceMedia: function () {
  15362. var self = this;
  15363. Object.keys(this.presMap).forEach(function (key) {
  15364. if (key.indexOf('source') != -1) {
  15365. delete self.presMap[key];
  15366. }
  15367. });
  15368. },
  15369. addPreziToPresence: function (url, currentSlide) {
  15370. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  15371. this.presMap['preziurl'] = url;
  15372. this.presMap['prezicurrent'] = currentSlide;
  15373. },
  15374. removePreziFromPresence: function () {
  15375. delete this.presMap['prezins'];
  15376. delete this.presMap['preziurl'];
  15377. delete this.presMap['prezicurrent'];
  15378. },
  15379. addCurrentSlideToPresence: function (currentSlide) {
  15380. this.presMap['prezicurrent'] = currentSlide;
  15381. },
  15382. getPrezi: function (roomjid) {
  15383. return this.preziMap[roomjid];
  15384. },
  15385. addAudioInfoToPresence: function (isMuted) {
  15386. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  15387. this.presMap['audiomuted'] = isMuted.toString();
  15388. },
  15389. addVideoInfoToPresence: function (isMuted) {
  15390. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  15391. this.presMap['videomuted'] = isMuted.toString();
  15392. },
  15393. addConnectionInfoToPresence: function (stats) {
  15394. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  15395. this.presMap['stats'] = stats;
  15396. },
  15397. findJidFromResource: function (resourceJid) {
  15398. if (resourceJid &&
  15399. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  15400. return this.myroomjid;
  15401. }
  15402. var peerJid = null;
  15403. Object.keys(this.members).some(function (jid) {
  15404. peerJid = jid;
  15405. return Strophe.getResourceFromJid(jid) === resourceJid;
  15406. });
  15407. return peerJid;
  15408. },
  15409. addBridgeIsDownToPresence: function () {
  15410. this.presMap['bridgeIsDown'] = true;
  15411. },
  15412. addEmailToPresence: function (email) {
  15413. this.presMap['email'] = email;
  15414. },
  15415. addUserIdToPresence: function (userId) {
  15416. this.presMap['userId'] = userId;
  15417. },
  15418. addStartMutedToPresence: function (audio, video) {
  15419. this.presMap["startMuted"] = {audio: audio, video: video};
  15420. },
  15421. isModerator: function () {
  15422. return this.role === 'moderator';
  15423. },
  15424. getMemberRole: function (peerJid) {
  15425. if (this.members[peerJid]) {
  15426. return this.members[peerJid].role;
  15427. }
  15428. return null;
  15429. },
  15430. onParticipantLeft: function (jid) {
  15431. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  15432. this.connection.jingle.terminateByJid(jid);
  15433. if (this.getPrezi(jid)) {
  15434. $(document).trigger('presentationremoved.muc',
  15435. [jid, this.getPrezi(jid)]);
  15436. }
  15437. Moderator.onMucMemberLeft(jid);
  15438. },
  15439. parsePresence: function (from, memeber, pres) {
  15440. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  15441. bridgeIsDown = true;
  15442. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  15443. }
  15444. if(memeber.isFocus)
  15445. return;
  15446. var self = this;
  15447. // Remove old ssrcs coming from the jid
  15448. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  15449. if (self.ssrc2jid[ssrc] == from) {
  15450. delete self.ssrc2jid[ssrc];
  15451. }
  15452. });
  15453. var changedStreams = [];
  15454. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  15455. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  15456. var ssrcV = ssrc.getAttribute('ssrc');
  15457. self.ssrc2jid[ssrcV] = from;
  15458. var type = ssrc.getAttribute('type');
  15459. var direction = ssrc.getAttribute('direction');
  15460. changedStreams.push({type: type, direction: direction});
  15461. });
  15462. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  15463. var displayName = !config.displayJids
  15464. ? memeber.displayName : Strophe.getResourceFromJid(from);
  15465. if (displayName && displayName.length > 0)
  15466. {
  15467. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  15468. }
  15469. var id = $(pres).find('>userID').text();
  15470. var email = $(pres).find('>email');
  15471. if(email.length > 0) {
  15472. id = email.text();
  15473. }
  15474. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  15475. }
  15476. });
  15477. };
  15478. },{"../../service/xmpp/XMPPEvents":110,"./JingleSession":55,"./moderator":60}],63:[function(require,module,exports){
  15479. /* jshint -W117 */
  15480. var JingleSession = require("./JingleSession");
  15481. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15482. module.exports = function(XMPP, eventEmitter)
  15483. {
  15484. function CallIncomingJingle(sid, connection) {
  15485. var sess = connection.jingle.sessions[sid];
  15486. // TODO: do we check activecall == null?
  15487. connection.jingle.activecall = sess;
  15488. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  15489. // TODO: check affiliation and/or role
  15490. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  15491. sess.usedrip = true; // not-so-naive trickle ice
  15492. sess.sendAnswer();
  15493. sess.accept();
  15494. };
  15495. Strophe.addConnectionPlugin('jingle', {
  15496. connection: null,
  15497. sessions: {},
  15498. jid2session: {},
  15499. ice_config: {iceServers: []},
  15500. pc_constraints: {},
  15501. activecall: null,
  15502. media_constraints: {
  15503. mandatory: {
  15504. 'OfferToReceiveAudio': true,
  15505. 'OfferToReceiveVideo': true
  15506. }
  15507. // MozDontOfferDataChannel: true when this is firefox
  15508. },
  15509. init: function (conn) {
  15510. this.connection = conn;
  15511. if (this.connection.disco) {
  15512. // http://xmpp.org/extensions/xep-0167.html#support
  15513. // http://xmpp.org/extensions/xep-0176.html#support
  15514. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  15515. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  15516. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  15517. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  15518. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  15519. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  15520. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  15521. // this is dealt with by SDP O/A so we don't need to annouce this
  15522. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  15523. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  15524. if (config.useRtcpMux) {
  15525. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  15526. }
  15527. if (config.useBundle) {
  15528. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  15529. }
  15530. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  15531. }
  15532. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  15533. },
  15534. onJingle: function (iq) {
  15535. var sid = $(iq).find('jingle').attr('sid');
  15536. var action = $(iq).find('jingle').attr('action');
  15537. var fromJid = iq.getAttribute('from');
  15538. // send ack first
  15539. var ack = $iq({type: 'result',
  15540. to: fromJid,
  15541. id: iq.getAttribute('id')
  15542. });
  15543. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  15544. var sess = this.sessions[sid];
  15545. if ('session-initiate' != action) {
  15546. if (sess === null) {
  15547. ack.type = 'error';
  15548. ack.c('error', {type: 'cancel'})
  15549. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15550. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15551. this.connection.send(ack);
  15552. return true;
  15553. }
  15554. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  15555. // local jid is not checked
  15556. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  15557. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  15558. ack.type = 'error';
  15559. ack.c('error', {type: 'cancel'})
  15560. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  15561. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  15562. this.connection.send(ack);
  15563. return true;
  15564. }
  15565. } else if (sess !== undefined) {
  15566. // existing session with same session id
  15567. // this might be out-of-order if the sess.peerjid is the same as from
  15568. ack.type = 'error';
  15569. ack.c('error', {type: 'cancel'})
  15570. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  15571. console.warn('duplicate session id', sid);
  15572. this.connection.send(ack);
  15573. return true;
  15574. }
  15575. // FIXME: check for a defined action
  15576. this.connection.send(ack);
  15577. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  15578. switch (action) {
  15579. case 'session-initiate':
  15580. var startMuted = $(iq).find('jingle>startmuted');
  15581. if(startMuted && startMuted.length > 0)
  15582. {
  15583. var audioMuted = startMuted.attr("audio");
  15584. var videoMuted = startMuted.attr("video");
  15585. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  15586. (videoMuted === "true"));
  15587. }
  15588. sess = new JingleSession(
  15589. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  15590. this.connection, XMPP, eventEmitter);
  15591. // configure session
  15592. sess.media_constraints = this.media_constraints;
  15593. sess.pc_constraints = this.pc_constraints;
  15594. sess.ice_config = this.ice_config;
  15595. sess.initiate(fromJid, false);
  15596. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  15597. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  15598. this.sessions[sess.sid] = sess;
  15599. this.jid2session[sess.peerjid] = sess;
  15600. // the callback should either
  15601. // .sendAnswer and .accept
  15602. // or .sendTerminate -- not necessarily synchronus
  15603. CallIncomingJingle(sess.sid, this.connection);
  15604. break;
  15605. case 'session-accept':
  15606. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  15607. sess.accept();
  15608. $(document).trigger('callaccepted.jingle', [sess.sid]);
  15609. break;
  15610. case 'session-terminate':
  15611. // If this is not the focus sending the terminate, we have
  15612. // nothing more to do here.
  15613. if (Object.keys(this.sessions).length < 1
  15614. || !(this.sessions[Object.keys(this.sessions)[0]]
  15615. instanceof JingleSession))
  15616. {
  15617. break;
  15618. }
  15619. console.log('terminating...', sess.sid);
  15620. sess.terminate();
  15621. this.terminate(sess.sid);
  15622. if ($(iq).find('>jingle>reason').length) {
  15623. $(document).trigger('callterminated.jingle', [
  15624. sess.sid,
  15625. sess.peerjid,
  15626. $(iq).find('>jingle>reason>:first')[0].tagName,
  15627. $(iq).find('>jingle>reason>text').text()
  15628. ]);
  15629. } else {
  15630. $(document).trigger('callterminated.jingle',
  15631. [sess.sid, sess.peerjid]);
  15632. }
  15633. break;
  15634. case 'transport-info':
  15635. sess.addIceCandidate($(iq).find('>jingle>content'));
  15636. break;
  15637. case 'session-info':
  15638. var affected;
  15639. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15640. $(document).trigger('ringing.jingle', [sess.sid]);
  15641. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15642. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15643. $(document).trigger('mute.jingle', [sess.sid, affected]);
  15644. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  15645. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  15646. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  15647. }
  15648. break;
  15649. case 'addsource': // FIXME: proprietary, un-jingleish
  15650. case 'source-add': // FIXME: proprietary
  15651. sess.addSource($(iq).find('>jingle>content'), fromJid);
  15652. break;
  15653. case 'removesource': // FIXME: proprietary, un-jingleish
  15654. case 'source-remove': // FIXME: proprietary
  15655. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  15656. break;
  15657. default:
  15658. console.warn('jingle action not implemented', action);
  15659. break;
  15660. }
  15661. return true;
  15662. },
  15663. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  15664. var sess = new JingleSession(myjid || this.connection.jid,
  15665. Math.random().toString(36).substr(2, 12), // random string
  15666. this.connection, XMPP, eventEmitter);
  15667. // configure session
  15668. sess.media_constraints = this.media_constraints;
  15669. sess.pc_constraints = this.pc_constraints;
  15670. sess.ice_config = this.ice_config;
  15671. sess.initiate(peerjid, true);
  15672. this.sessions[sess.sid] = sess;
  15673. this.jid2session[sess.peerjid] = sess;
  15674. sess.sendOffer();
  15675. return sess;
  15676. },
  15677. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  15678. if (sid === null || sid === undefined) {
  15679. for (sid in this.sessions) {
  15680. if (this.sessions[sid].state != 'ended') {
  15681. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15682. this.sessions[sid].terminate();
  15683. }
  15684. delete this.jid2session[this.sessions[sid].peerjid];
  15685. delete this.sessions[sid];
  15686. }
  15687. } else if (this.sessions.hasOwnProperty(sid)) {
  15688. if (this.sessions[sid].state != 'ended') {
  15689. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  15690. this.sessions[sid].terminate();
  15691. }
  15692. delete this.jid2session[this.sessions[sid].peerjid];
  15693. delete this.sessions[sid];
  15694. }
  15695. },
  15696. // Used to terminate a session when an unavailable presence is received.
  15697. terminateByJid: function (jid) {
  15698. if (this.jid2session.hasOwnProperty(jid)) {
  15699. var sess = this.jid2session[jid];
  15700. if (sess) {
  15701. sess.terminate();
  15702. console.log('peer went away silently', jid);
  15703. delete this.sessions[sess.sid];
  15704. delete this.jid2session[jid];
  15705. $(document).trigger('callterminated.jingle',
  15706. [sess.sid, jid], 'gone');
  15707. }
  15708. }
  15709. },
  15710. terminateRemoteByJid: function (jid, reason) {
  15711. if (this.jid2session.hasOwnProperty(jid)) {
  15712. var sess = this.jid2session[jid];
  15713. if (sess) {
  15714. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15715. sess.terminate();
  15716. console.log('terminate peer with jid', sess.sid, jid);
  15717. delete this.sessions[sess.sid];
  15718. delete this.jid2session[jid];
  15719. $(document).trigger('callterminated.jingle',
  15720. [sess.sid, jid, 'kicked']);
  15721. }
  15722. }
  15723. },
  15724. getStunAndTurnCredentials: function () {
  15725. // get stun and turn configuration from server via xep-0215
  15726. // uses time-limited credentials as described in
  15727. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15728. //
  15729. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15730. // for a prosody module which implements this
  15731. //
  15732. // currently, this doesn't work with updateIce and therefore credentials with a long
  15733. // validity have to be fetched before creating the peerconnection
  15734. // TODO: implement refresh via updateIce as described in
  15735. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15736. var self = this;
  15737. this.connection.sendIQ(
  15738. $iq({type: 'get', to: this.connection.domain})
  15739. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15740. function (res) {
  15741. var iceservers = [];
  15742. $(res).find('>services>service').each(function (idx, el) {
  15743. el = $(el);
  15744. var dict = {};
  15745. var type = el.attr('type');
  15746. switch (type) {
  15747. case 'stun':
  15748. dict.url = 'stun:' + el.attr('host');
  15749. if (el.attr('port')) {
  15750. dict.url += ':' + el.attr('port');
  15751. }
  15752. iceservers.push(dict);
  15753. break;
  15754. case 'turn':
  15755. case 'turns':
  15756. dict.url = type + ':';
  15757. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15758. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15759. dict.url += el.attr('username') + '@';
  15760. } else {
  15761. dict.username = el.attr('username'); // only works in M28
  15762. }
  15763. }
  15764. dict.url += el.attr('host');
  15765. if (el.attr('port') && el.attr('port') != '3478') {
  15766. dict.url += ':' + el.attr('port');
  15767. }
  15768. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15769. dict.url += '?transport=' + el.attr('transport');
  15770. }
  15771. if (el.attr('password')) {
  15772. dict.credential = el.attr('password');
  15773. }
  15774. iceservers.push(dict);
  15775. break;
  15776. }
  15777. });
  15778. self.ice_config.iceServers = iceservers;
  15779. },
  15780. function (err) {
  15781. console.warn('getting turn credentials failed', err);
  15782. console.warn('is mod_turncredentials or similar installed?');
  15783. }
  15784. );
  15785. // implement push?
  15786. },
  15787. /**
  15788. * Populates the log data
  15789. */
  15790. populateData: function () {
  15791. var data = {};
  15792. var self = this;
  15793. Object.keys(this.sessions).forEach(function (sid) {
  15794. var session = self.sessions[sid];
  15795. if (session.peerconnection && session.peerconnection.updateLog) {
  15796. // FIXME: should probably be a .dump call
  15797. data["jingle_" + session.sid] = {
  15798. updateLog: session.peerconnection.updateLog,
  15799. stats: session.peerconnection.stats,
  15800. url: window.location.href
  15801. };
  15802. }
  15803. });
  15804. return data;
  15805. }
  15806. });
  15807. };
  15808. },{"../../service/xmpp/XMPPEvents":110,"./JingleSession":55}],64:[function(require,module,exports){
  15809. /* global Strophe */
  15810. module.exports = function () {
  15811. Strophe.addConnectionPlugin('logger', {
  15812. // logs raw stanzas and makes them available for download as JSON
  15813. connection: null,
  15814. log: [],
  15815. init: function (conn) {
  15816. this.connection = conn;
  15817. this.connection.rawInput = this.log_incoming.bind(this);
  15818. this.connection.rawOutput = this.log_outgoing.bind(this);
  15819. },
  15820. log_incoming: function (stanza) {
  15821. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15822. },
  15823. log_outgoing: function (stanza) {
  15824. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15825. }
  15826. });
  15827. };
  15828. },{}],65:[function(require,module,exports){
  15829. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15830. setAudioMuted, Strophe */
  15831. /**
  15832. * Moderate connection plugin.
  15833. */
  15834. module.exports = function (XMPP) {
  15835. Strophe.addConnectionPlugin('moderate', {
  15836. connection: null,
  15837. init: function (conn) {
  15838. this.connection = conn;
  15839. this.connection.addHandler(this.onMute.bind(this),
  15840. 'http://jitsi.org/jitmeet/audio',
  15841. 'iq',
  15842. 'set',
  15843. null,
  15844. null);
  15845. },
  15846. setMute: function (jid, mute) {
  15847. console.info("set mute", mute);
  15848. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15849. .c('mute', {
  15850. xmlns: 'http://jitsi.org/jitmeet/audio',
  15851. jid: jid
  15852. })
  15853. .t(mute.toString())
  15854. .up();
  15855. this.connection.sendIQ(
  15856. iqToFocus,
  15857. function (result) {
  15858. console.log('set mute', result);
  15859. },
  15860. function (error) {
  15861. console.log('set mute error', error);
  15862. });
  15863. },
  15864. onMute: function (iq) {
  15865. var from = iq.getAttribute('from');
  15866. if (from !== this.connection.emuc.focusMucJid) {
  15867. console.warn("Ignored mute from non focus peer");
  15868. return false;
  15869. }
  15870. var mute = $(iq).find('mute');
  15871. if (mute.length) {
  15872. var doMuteAudio = mute.text() === "true";
  15873. APP.UI.setAudioMuted(doMuteAudio);
  15874. XMPP.forceMuted = doMuteAudio;
  15875. }
  15876. return true;
  15877. },
  15878. eject: function (jid) {
  15879. // We're not the focus, so can't terminate
  15880. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15881. this.connection.emuc.kick(jid);
  15882. }
  15883. });
  15884. }
  15885. },{}],66:[function(require,module,exports){
  15886. /* jshint -W117 */
  15887. module.exports = function() {
  15888. Strophe.addConnectionPlugin('rayo',
  15889. {
  15890. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15891. connection: null,
  15892. init: function (conn) {
  15893. this.connection = conn;
  15894. if (this.connection.disco) {
  15895. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15896. }
  15897. this.connection.addHandler(
  15898. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15899. },
  15900. onRayo: function (iq) {
  15901. console.info("Rayo IQ", iq);
  15902. },
  15903. dial: function (to, from, roomName, roomPass) {
  15904. var self = this;
  15905. var req = $iq(
  15906. {
  15907. type: 'set',
  15908. to: this.connection.emuc.focusMucJid
  15909. }
  15910. );
  15911. req.c('dial',
  15912. {
  15913. xmlns: this.RAYO_XMLNS,
  15914. to: to,
  15915. from: from
  15916. });
  15917. req.c('header',
  15918. {
  15919. name: 'JvbRoomName',
  15920. value: roomName
  15921. }).up();
  15922. if (roomPass !== null && roomPass.length) {
  15923. req.c('header',
  15924. {
  15925. name: 'JvbRoomPassword',
  15926. value: roomPass
  15927. }).up();
  15928. }
  15929. this.connection.sendIQ(
  15930. req,
  15931. function (result) {
  15932. console.info('Dial result ', result);
  15933. var resource = $(result).find('ref').attr('uri');
  15934. this.call_resource = resource.substr('xmpp:'.length);
  15935. console.info(
  15936. "Received call resource: " + this.call_resource);
  15937. },
  15938. function (error) {
  15939. console.info('Dial error ', error);
  15940. }
  15941. );
  15942. },
  15943. hang_up: function () {
  15944. if (!this.call_resource) {
  15945. console.warn("No call in progress");
  15946. return;
  15947. }
  15948. var self = this;
  15949. var req = $iq(
  15950. {
  15951. type: 'set',
  15952. to: this.call_resource
  15953. }
  15954. );
  15955. req.c('hangup',
  15956. {
  15957. xmlns: this.RAYO_XMLNS
  15958. });
  15959. this.connection.sendIQ(
  15960. req,
  15961. function (result) {
  15962. console.info('Hangup result ', result);
  15963. self.call_resource = null;
  15964. },
  15965. function (error) {
  15966. console.info('Hangup error ', error);
  15967. self.call_resource = null;
  15968. }
  15969. );
  15970. }
  15971. }
  15972. );
  15973. };
  15974. },{}],67:[function(require,module,exports){
  15975. /**
  15976. * Strophe logger implementation. Logs from level WARN and above.
  15977. */
  15978. module.exports = function () {
  15979. Strophe.log = function (level, msg) {
  15980. switch (level) {
  15981. case Strophe.LogLevel.WARN:
  15982. console.warn("Strophe: " + msg);
  15983. break;
  15984. case Strophe.LogLevel.ERROR:
  15985. case Strophe.LogLevel.FATAL:
  15986. console.error("Strophe: " + msg);
  15987. break;
  15988. }
  15989. };
  15990. Strophe.getStatusString = function (status) {
  15991. switch (status) {
  15992. case Strophe.Status.ERROR:
  15993. return "ERROR";
  15994. case Strophe.Status.CONNECTING:
  15995. return "CONNECTING";
  15996. case Strophe.Status.CONNFAIL:
  15997. return "CONNFAIL";
  15998. case Strophe.Status.AUTHENTICATING:
  15999. return "AUTHENTICATING";
  16000. case Strophe.Status.AUTHFAIL:
  16001. return "AUTHFAIL";
  16002. case Strophe.Status.CONNECTED:
  16003. return "CONNECTED";
  16004. case Strophe.Status.DISCONNECTED:
  16005. return "DISCONNECTED";
  16006. case Strophe.Status.DISCONNECTING:
  16007. return "DISCONNECTING";
  16008. case Strophe.Status.ATTACHED:
  16009. return "ATTACHED";
  16010. default:
  16011. return "unknown";
  16012. }
  16013. };
  16014. };
  16015. },{}],68:[function(require,module,exports){
  16016. /* global $, APP, config, Strophe*/
  16017. var Moderator = require("./moderator");
  16018. var EventEmitter = require("events");
  16019. var Recording = require("./recording");
  16020. var SDP = require("./SDP");
  16021. var Settings = require("../settings/Settings");
  16022. var Pako = require("pako");
  16023. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16024. var RTCEvents = require("../../service/RTC/RTCEvents");
  16025. var UIEvents = require("../../service/UI/UIEvents");
  16026. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16027. var retry = require('retry');
  16028. var eventEmitter = new EventEmitter();
  16029. var connection = null;
  16030. var authenticatedUser = false;
  16031. function connect(jid, password) {
  16032. var faultTolerantConnect = retry.operation({
  16033. retries: 3
  16034. });
  16035. // fault tolerant connect
  16036. faultTolerantConnect.attempt(function () {
  16037. connection = XMPP.createConnection();
  16038. Moderator.setConnection(connection);
  16039. if (connection.disco) {
  16040. // for chrome, add multistream cap
  16041. }
  16042. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16043. if (config.useIPv6) {
  16044. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16045. if (!connection.jingle.pc_constraints.optional)
  16046. connection.jingle.pc_constraints.optional = [];
  16047. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16048. }
  16049. // Include user info in MUC presence
  16050. var settings = Settings.getSettings();
  16051. if (settings.email) {
  16052. connection.emuc.addEmailToPresence(settings.email);
  16053. }
  16054. if (settings.uid) {
  16055. connection.emuc.addUserIdToPresence(settings.uid);
  16056. }
  16057. if (settings.displayName) {
  16058. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16059. }
  16060. // connection.connect() starts the connection process.
  16061. //
  16062. // As the connection process proceeds, the user supplied callback will
  16063. // be triggered multiple times with status updates. The callback should
  16064. // take two arguments - the status code and the error condition.
  16065. //
  16066. // The status code will be one of the values in the Strophe.Status
  16067. // constants. The error condition will be one of the conditions defined
  16068. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16069. //
  16070. // The Parameters wait, hold and route are optional and only relevant
  16071. // for BOSH connections. Please see XEP 124 for a more detailed
  16072. // explanation of the optional parameters.
  16073. //
  16074. // Connection status constants for use by the connection handler
  16075. // callback.
  16076. //
  16077. // Status.ERROR - An error has occurred (websockets specific)
  16078. // Status.CONNECTING - The connection is currently being made
  16079. // Status.CONNFAIL - The connection attempt failed
  16080. // Status.AUTHENTICATING - The connection is authenticating
  16081. // Status.AUTHFAIL - The authentication attempt failed
  16082. // Status.CONNECTED - The connection has succeeded
  16083. // Status.DISCONNECTED - The connection has been terminated
  16084. // Status.DISCONNECTING - The connection is currently being terminated
  16085. // Status.ATTACHED - The connection has been attached
  16086. var anonymousConnectionFailed = false;
  16087. var connectionFailed = false;
  16088. var lastErrorMsg;
  16089. connection.connect(jid, password, function (status, msg) {
  16090. console.log('Strophe status changed to',
  16091. Strophe.getStatusString(status), msg);
  16092. if (status === Strophe.Status.CONNECTED) {
  16093. if (config.useStunTurn) {
  16094. connection.jingle.getStunAndTurnCredentials();
  16095. }
  16096. console.info("My Jabber ID: " + connection.jid);
  16097. if (password)
  16098. authenticatedUser = true;
  16099. maybeDoJoin();
  16100. } else if (status === Strophe.Status.CONNFAIL) {
  16101. if (msg === 'x-strophe-bad-non-anon-jid') {
  16102. anonymousConnectionFailed = true;
  16103. } else {
  16104. connectionFailed = true;
  16105. }
  16106. lastErrorMsg = msg;
  16107. } else if (status === Strophe.Status.DISCONNECTED) {
  16108. if (anonymousConnectionFailed) {
  16109. // prompt user for username and password
  16110. XMPP.promptLogin();
  16111. } else {
  16112. // Strophe already has built-in HTTP/BOSH error handling and
  16113. // request retry logic. Requests are resent automatically
  16114. // until their error count reaches 5. Strophe.js disconnects
  16115. // if the error count is > 5. We are not replicating this
  16116. // here.
  16117. //
  16118. // The "problem" is that failed HTTP/BOSH requests don't
  16119. // trigger a callback with a status update, so when a
  16120. // callback with status Strophe.Status.DISCONNECTED arrives,
  16121. // we can't be sure if it's a graceful disconnect or if it's
  16122. // triggered by some HTTP/BOSH error.
  16123. //
  16124. // But that's a minor issue in Jitsi Meet as we never
  16125. // disconnect anyway, not even when the user closes the
  16126. // browser window (which is kind of wrong, but the point is
  16127. // that we should never ever get disconnected).
  16128. //
  16129. // On the other hand, failed connections due to XMPP layer
  16130. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16131. //
  16132. // Here we implement retry logic for failed connections due
  16133. // to XMPP layer errors and we display an error to the user
  16134. // if we get disconnected from the XMPP server permanently.
  16135. // If the connection failed, retry.
  16136. if (connectionFailed
  16137. && faultTolerantConnect.retry("connection-failed")) {
  16138. return;
  16139. }
  16140. // If we failed to connect to the XMPP server, fire an event
  16141. // to let all the interested module now about it.
  16142. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16143. msg ? msg : lastErrorMsg);
  16144. }
  16145. } else if (status === Strophe.Status.AUTHFAIL) {
  16146. // wrong password or username, prompt user
  16147. XMPP.promptLogin();
  16148. }
  16149. });
  16150. });
  16151. }
  16152. function maybeDoJoin() {
  16153. if (connection && connection.connected &&
  16154. Strophe.getResourceFromJid(connection.jid)
  16155. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16156. // .connected is true while connecting?
  16157. doJoin();
  16158. }
  16159. }
  16160. function doJoin() {
  16161. var roomName = APP.UI.generateRoomName();
  16162. Moderator.allocateConferenceFocus(
  16163. roomName, APP.UI.checkForNicknameAndJoin);
  16164. }
  16165. function initStrophePlugins()
  16166. {
  16167. require("./strophe.emuc")(XMPP, eventEmitter);
  16168. require("./strophe.jingle")(XMPP, eventEmitter);
  16169. require("./strophe.moderate")(XMPP);
  16170. require("./strophe.util")();
  16171. require("./strophe.rayo")();
  16172. require("./strophe.logger")();
  16173. }
  16174. function registerListeners() {
  16175. APP.RTC.addStreamListener(maybeDoJoin,
  16176. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  16177. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16178. XMPP.addToPresence("devices", devices);
  16179. })
  16180. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  16181. XMPP.addToPresence("displayName", nickname);
  16182. });
  16183. }
  16184. var unload = (function () {
  16185. var unloaded = false;
  16186. return function () {
  16187. if (unloaded) { return; }
  16188. unloaded = true;
  16189. if (connection && connection.connected) {
  16190. // ensure signout
  16191. $.ajax({
  16192. type: 'POST',
  16193. url: config.bosh,
  16194. async: false,
  16195. cache: false,
  16196. contentType: 'application/xml',
  16197. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  16198. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16199. (connection.sid || connection._proto.sid) +
  16200. "' type='terminate'>" +
  16201. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16202. "</body>",
  16203. success: function (data) {
  16204. console.log('signed out');
  16205. console.log(data);
  16206. },
  16207. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16208. console.log('signout error',
  16209. textStatus + ' (' + errorThrown + ')');
  16210. }
  16211. });
  16212. }
  16213. XMPP.disposeConference(true);
  16214. };
  16215. })();
  16216. function setupEvents() {
  16217. // In recent versions of FF the 'beforeunload' event is not fired when the
  16218. // window or the tab is closed. It is only fired when we leave the page
  16219. // (change URL). If this participant doesn't unload properly, then it
  16220. // becomes a ghost for the rest of the participants that stay in the
  16221. // conference. Thankfully handling the 'unload' event in addition to the
  16222. // 'beforeunload' event seems to garante the execution of the 'unload'
  16223. // method at least once.
  16224. //
  16225. // The 'unload' method can safely be run multiple times, it will actually do
  16226. // something only the first time that it's run, so we're don't have to worry
  16227. // about browsers that fire both events.
  16228. $(window).bind('beforeunload', unload);
  16229. $(window).bind('unload', unload);
  16230. }
  16231. var XMPP = {
  16232. getConnection: function(){ return connection; },
  16233. sessionTerminated: false,
  16234. /**
  16235. * XMPP connection status
  16236. */
  16237. Status: Strophe.Status,
  16238. /**
  16239. * Remembers if we were muted by the focus.
  16240. * @type {boolean}
  16241. */
  16242. forceMuted: false,
  16243. start: function () {
  16244. setupEvents();
  16245. initStrophePlugins();
  16246. registerListeners();
  16247. Moderator.init(this, eventEmitter);
  16248. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16249. // Force authenticated domain if room is appended with '?login=true'
  16250. if (config.hosts.anonymousdomain &&
  16251. window.location.search.indexOf("login=true") !== -1) {
  16252. configDomain = config.hosts.domain;
  16253. }
  16254. var jid = configDomain || window.location.hostname;
  16255. connect(jid, null);
  16256. },
  16257. createConnection: function () {
  16258. var bosh = config.bosh || '/http-bind';
  16259. return new Strophe.Connection(bosh);
  16260. },
  16261. getStatusString: function (status) {
  16262. return Strophe.getStatusString(status);
  16263. },
  16264. promptLogin: function () {
  16265. // FIXME: re-use LoginDialog which supports retries
  16266. APP.UI.showLoginPopup(connect);
  16267. },
  16268. joinRoom: function(roomName, useNicks, nick)
  16269. {
  16270. var roomjid;
  16271. roomjid = roomName;
  16272. if (useNicks) {
  16273. if (nick) {
  16274. roomjid += '/' + nick;
  16275. } else {
  16276. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16277. }
  16278. } else {
  16279. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16280. if(!authenticatedUser)
  16281. tmpJid = tmpJid.substr(0, 8);
  16282. roomjid += '/' + tmpJid;
  16283. }
  16284. connection.emuc.doJoin(roomjid);
  16285. },
  16286. myJid: function () {
  16287. if(!connection)
  16288. return null;
  16289. return connection.emuc.myroomjid;
  16290. },
  16291. myResource: function () {
  16292. if(!connection || ! connection.emuc.myroomjid)
  16293. return null;
  16294. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16295. },
  16296. disposeConference: function (onUnload) {
  16297. var handler = connection.jingle.activecall;
  16298. if (handler && handler.peerconnection) {
  16299. // FIXME: probably removing streams is not required and close() should
  16300. // be enough
  16301. if (APP.RTC.localAudio) {
  16302. handler.peerconnection.removeStream(
  16303. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16304. }
  16305. if (APP.RTC.localVideo) {
  16306. handler.peerconnection.removeStream(
  16307. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16308. }
  16309. handler.peerconnection.close();
  16310. }
  16311. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16312. connection.jingle.activecall = null;
  16313. if(!onUnload)
  16314. {
  16315. this.sessionTerminated = true;
  16316. connection.emuc.doLeave();
  16317. }
  16318. },
  16319. addListener: function(type, listener)
  16320. {
  16321. eventEmitter.on(type, listener);
  16322. },
  16323. removeListener: function (type, listener) {
  16324. eventEmitter.removeListener(type, listener);
  16325. },
  16326. allocateConferenceFocus: function(roomName, callback) {
  16327. Moderator.allocateConferenceFocus(roomName, callback);
  16328. },
  16329. getLoginUrl: function (roomName, callback) {
  16330. Moderator.getLoginUrl(roomName, callback);
  16331. },
  16332. getPopupLoginUrl: function (roomName, callback) {
  16333. Moderator.getPopupLoginUrl(roomName, callback);
  16334. },
  16335. isModerator: function () {
  16336. return Moderator.isModerator();
  16337. },
  16338. isSipGatewayEnabled: function () {
  16339. return Moderator.isSipGatewayEnabled();
  16340. },
  16341. isExternalAuthEnabled: function () {
  16342. return Moderator.isExternalAuthEnabled();
  16343. },
  16344. isConferenceInProgress: function () {
  16345. return connection && connection.jingle.activecall &&
  16346. connection.jingle.activecall.peerconnection;
  16347. },
  16348. switchStreams: function (stream, oldStream, callback, isAudio) {
  16349. if (this.isConferenceInProgress()) {
  16350. // FIXME: will block switchInProgress on true value in case of exception
  16351. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16352. } else {
  16353. // We are done immediately
  16354. console.warn("No conference handler or conference not started yet");
  16355. callback();
  16356. }
  16357. },
  16358. sendVideoInfoPresence: function (mute) {
  16359. if(!connection)
  16360. return;
  16361. connection.emuc.addVideoInfoToPresence(mute);
  16362. connection.emuc.sendPresence();
  16363. },
  16364. setVideoMute: function (mute, callback, options) {
  16365. if(!connection)
  16366. return;
  16367. var self = this;
  16368. var localCallback = function (mute) {
  16369. self.sendVideoInfoPresence(mute);
  16370. return callback(mute);
  16371. };
  16372. if(connection.jingle.activecall)
  16373. {
  16374. connection.jingle.activecall.setVideoMute(
  16375. mute, localCallback, options);
  16376. }
  16377. else {
  16378. localCallback(mute);
  16379. }
  16380. },
  16381. setAudioMute: function (mute, callback) {
  16382. if (!(connection && APP.RTC.localAudio)) {
  16383. return false;
  16384. }
  16385. if (this.forceMuted && !mute) {
  16386. console.info("Asking focus for unmute");
  16387. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  16388. // FIXME: wait for result before resetting muted status
  16389. this.forceMuted = false;
  16390. }
  16391. if (mute == APP.RTC.localAudio.isMuted()) {
  16392. // Nothing to do
  16393. return true;
  16394. }
  16395. // It is not clear what is the right way to handle multiple tracks.
  16396. // So at least make sure that they are all muted or all unmuted and
  16397. // that we send presence just once.
  16398. APP.RTC.localAudio.setMute(!mute);
  16399. // isMuted is the opposite of audioEnabled
  16400. this.sendAudioInfoPresence(mute, callback);
  16401. return true;
  16402. },
  16403. sendAudioInfoPresence: function(mute, callback)
  16404. {
  16405. if(connection) {
  16406. connection.emuc.addAudioInfoToPresence(mute);
  16407. connection.emuc.sendPresence();
  16408. }
  16409. callback();
  16410. return true;
  16411. },
  16412. // Really mute video, i.e. dont even send black frames
  16413. muteVideo: function (pc, unmute) {
  16414. // FIXME: this probably needs another of those lovely state safeguards...
  16415. // which checks for iceconn == connected and sigstate == stable
  16416. pc.setRemoteDescription(pc.remoteDescription,
  16417. function () {
  16418. pc.createAnswer(
  16419. function (answer) {
  16420. var sdp = new SDP(answer.sdp);
  16421. if (sdp.media.length > 1) {
  16422. if (unmute)
  16423. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  16424. else
  16425. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  16426. sdp.raw = sdp.session + sdp.media.join('');
  16427. answer.sdp = sdp.raw;
  16428. }
  16429. pc.setLocalDescription(answer,
  16430. function () {
  16431. console.log('mute SLD ok');
  16432. },
  16433. function (error) {
  16434. console.log('mute SLD error');
  16435. APP.UI.messageHandler.showError("dialog.error",
  16436. "dialog.SLDFailure");
  16437. }
  16438. );
  16439. },
  16440. function (error) {
  16441. console.log(error);
  16442. APP.UI.messageHandler.showError();
  16443. }
  16444. );
  16445. },
  16446. function (error) {
  16447. console.log('muteVideo SRD error');
  16448. APP.UI.messageHandler.showError("dialog.error",
  16449. "dialog.SRDFailure");
  16450. }
  16451. );
  16452. },
  16453. toggleRecording: function (tokenEmptyCallback,
  16454. startingCallback, startedCallback) {
  16455. Recording.toggleRecording(tokenEmptyCallback,
  16456. startingCallback, startedCallback, connection);
  16457. },
  16458. addToPresence: function (name, value, dontSend) {
  16459. switch (name)
  16460. {
  16461. case "displayName":
  16462. connection.emuc.addDisplayNameToPresence(value);
  16463. break;
  16464. case "prezi":
  16465. connection.emuc.addPreziToPresence(value, 0);
  16466. break;
  16467. case "preziSlide":
  16468. connection.emuc.addCurrentSlideToPresence(value);
  16469. break;
  16470. case "connectionQuality":
  16471. connection.emuc.addConnectionInfoToPresence(value);
  16472. break;
  16473. case "email":
  16474. connection.emuc.addEmailToPresence(value);
  16475. break;
  16476. case "devices":
  16477. connection.emuc.addDevicesToPresence(value);
  16478. break;
  16479. case "startMuted":
  16480. if(!Moderator.isModerator())
  16481. return;
  16482. connection.emuc.addStartMutedToPresence(value[0],
  16483. value[1]);
  16484. break;
  16485. default :
  16486. console.log("Unknown tag for presence: " + name);
  16487. return;
  16488. }
  16489. if (!dontSend)
  16490. connection.emuc.sendPresence();
  16491. },
  16492. /**
  16493. * Sends 'data' as a log message to the focus. Returns true iff a message
  16494. * was sent.
  16495. * @param data
  16496. * @returns {boolean} true iff a message was sent.
  16497. */
  16498. sendLogs: function (data) {
  16499. if(!connection.emuc.focusMucJid)
  16500. return false;
  16501. var deflate = true;
  16502. var content = JSON.stringify(data);
  16503. if (deflate) {
  16504. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  16505. }
  16506. content = Base64.encode(content);
  16507. // XEP-0337-ish
  16508. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  16509. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  16510. id: 'PeerConnectionStats'});
  16511. message.c('message').t(content).up();
  16512. if (deflate) {
  16513. message.c('tag', {name: "deflated", value: "true"}).up();
  16514. }
  16515. message.up();
  16516. connection.send(message);
  16517. return true;
  16518. },
  16519. populateData: function () {
  16520. var data = {};
  16521. if (connection.jingle) {
  16522. data = connection.jingle.populateData();
  16523. }
  16524. return data;
  16525. },
  16526. getLogger: function () {
  16527. if(connection.logger)
  16528. return connection.logger.log;
  16529. return null;
  16530. },
  16531. getPrezi: function () {
  16532. return connection.emuc.getPrezi(this.myJid());
  16533. },
  16534. removePreziFromPresence: function () {
  16535. connection.emuc.removePreziFromPresence();
  16536. connection.emuc.sendPresence();
  16537. },
  16538. sendChatMessage: function (message, nickname) {
  16539. connection.emuc.sendMessage(message, nickname);
  16540. },
  16541. setSubject: function (topic) {
  16542. connection.emuc.setSubject(topic);
  16543. },
  16544. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  16545. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  16546. },
  16547. dial: function (to, from, roomName,roomPass) {
  16548. connection.rayo.dial(to, from, roomName,roomPass);
  16549. },
  16550. setMute: function (jid, mute) {
  16551. connection.moderate.setMute(jid, mute);
  16552. },
  16553. eject: function (jid) {
  16554. connection.moderate.eject(jid);
  16555. },
  16556. logout: function (callback) {
  16557. Moderator.logout(callback);
  16558. },
  16559. findJidFromResource: function (resource) {
  16560. return connection.emuc.findJidFromResource(resource);
  16561. },
  16562. getMembers: function () {
  16563. return connection.emuc.members;
  16564. },
  16565. getJidFromSSRC: function (ssrc) {
  16566. if(!connection)
  16567. return null;
  16568. return connection.emuc.ssrc2jid[ssrc];
  16569. },
  16570. getMUCJoined: function () {
  16571. return connection.emuc.joined;
  16572. },
  16573. getSessions: function () {
  16574. return connection.jingle.sessions;
  16575. },
  16576. removeStream: function (stream) {
  16577. if (!this.isConferenceInProgress())
  16578. return;
  16579. connection.jingle.activecall.peerconnection.removeStream(stream);
  16580. }
  16581. };
  16582. module.exports = XMPP;
  16583. },{"../../service/RTC/RTCEvents":101,"../../service/RTC/StreamEventTypes":103,"../../service/UI/UIEvents":104,"../../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){
  16584. (function (process){
  16585. /*!
  16586. * async
  16587. * https://github.com/caolan/async
  16588. *
  16589. * Copyright 2010-2014 Caolan McMahon
  16590. * Released under the MIT license
  16591. */
  16592. /*jshint onevar: false, indent:4 */
  16593. /*global setImmediate: false, setTimeout: false, console: false */
  16594. (function () {
  16595. var async = {};
  16596. // global on the server, window in the browser
  16597. var root, previous_async;
  16598. root = this;
  16599. if (root != null) {
  16600. previous_async = root.async;
  16601. }
  16602. async.noConflict = function () {
  16603. root.async = previous_async;
  16604. return async;
  16605. };
  16606. function only_once(fn) {
  16607. var called = false;
  16608. return function() {
  16609. if (called) throw new Error("Callback was already called.");
  16610. called = true;
  16611. fn.apply(root, arguments);
  16612. }
  16613. }
  16614. //// cross-browser compatiblity functions ////
  16615. var _toString = Object.prototype.toString;
  16616. var _isArray = Array.isArray || function (obj) {
  16617. return _toString.call(obj) === '[object Array]';
  16618. };
  16619. var _each = function (arr, iterator) {
  16620. if (arr.forEach) {
  16621. return arr.forEach(iterator);
  16622. }
  16623. for (var i = 0; i < arr.length; i += 1) {
  16624. iterator(arr[i], i, arr);
  16625. }
  16626. };
  16627. var _map = function (arr, iterator) {
  16628. if (arr.map) {
  16629. return arr.map(iterator);
  16630. }
  16631. var results = [];
  16632. _each(arr, function (x, i, a) {
  16633. results.push(iterator(x, i, a));
  16634. });
  16635. return results;
  16636. };
  16637. var _reduce = function (arr, iterator, memo) {
  16638. if (arr.reduce) {
  16639. return arr.reduce(iterator, memo);
  16640. }
  16641. _each(arr, function (x, i, a) {
  16642. memo = iterator(memo, x, i, a);
  16643. });
  16644. return memo;
  16645. };
  16646. var _keys = function (obj) {
  16647. if (Object.keys) {
  16648. return Object.keys(obj);
  16649. }
  16650. var keys = [];
  16651. for (var k in obj) {
  16652. if (obj.hasOwnProperty(k)) {
  16653. keys.push(k);
  16654. }
  16655. }
  16656. return keys;
  16657. };
  16658. //// exported async module functions ////
  16659. //// nextTick implementation with browser-compatible fallback ////
  16660. if (typeof process === 'undefined' || !(process.nextTick)) {
  16661. if (typeof setImmediate === 'function') {
  16662. async.nextTick = function (fn) {
  16663. // not a direct alias for IE10 compatibility
  16664. setImmediate(fn);
  16665. };
  16666. async.setImmediate = async.nextTick;
  16667. }
  16668. else {
  16669. async.nextTick = function (fn) {
  16670. setTimeout(fn, 0);
  16671. };
  16672. async.setImmediate = async.nextTick;
  16673. }
  16674. }
  16675. else {
  16676. async.nextTick = process.nextTick;
  16677. if (typeof setImmediate !== 'undefined') {
  16678. async.setImmediate = function (fn) {
  16679. // not a direct alias for IE10 compatibility
  16680. setImmediate(fn);
  16681. };
  16682. }
  16683. else {
  16684. async.setImmediate = async.nextTick;
  16685. }
  16686. }
  16687. async.each = function (arr, iterator, callback) {
  16688. callback = callback || function () {};
  16689. if (!arr.length) {
  16690. return callback();
  16691. }
  16692. var completed = 0;
  16693. _each(arr, function (x) {
  16694. iterator(x, only_once(done) );
  16695. });
  16696. function done(err) {
  16697. if (err) {
  16698. callback(err);
  16699. callback = function () {};
  16700. }
  16701. else {
  16702. completed += 1;
  16703. if (completed >= arr.length) {
  16704. callback();
  16705. }
  16706. }
  16707. }
  16708. };
  16709. async.forEach = async.each;
  16710. async.eachSeries = function (arr, iterator, callback) {
  16711. callback = callback || function () {};
  16712. if (!arr.length) {
  16713. return callback();
  16714. }
  16715. var completed = 0;
  16716. var iterate = function () {
  16717. iterator(arr[completed], function (err) {
  16718. if (err) {
  16719. callback(err);
  16720. callback = function () {};
  16721. }
  16722. else {
  16723. completed += 1;
  16724. if (completed >= arr.length) {
  16725. callback();
  16726. }
  16727. else {
  16728. iterate();
  16729. }
  16730. }
  16731. });
  16732. };
  16733. iterate();
  16734. };
  16735. async.forEachSeries = async.eachSeries;
  16736. async.eachLimit = function (arr, limit, iterator, callback) {
  16737. var fn = _eachLimit(limit);
  16738. fn.apply(null, [arr, iterator, callback]);
  16739. };
  16740. async.forEachLimit = async.eachLimit;
  16741. var _eachLimit = function (limit) {
  16742. return function (arr, iterator, callback) {
  16743. callback = callback || function () {};
  16744. if (!arr.length || limit <= 0) {
  16745. return callback();
  16746. }
  16747. var completed = 0;
  16748. var started = 0;
  16749. var running = 0;
  16750. (function replenish () {
  16751. if (completed >= arr.length) {
  16752. return callback();
  16753. }
  16754. while (running < limit && started < arr.length) {
  16755. started += 1;
  16756. running += 1;
  16757. iterator(arr[started - 1], function (err) {
  16758. if (err) {
  16759. callback(err);
  16760. callback = function () {};
  16761. }
  16762. else {
  16763. completed += 1;
  16764. running -= 1;
  16765. if (completed >= arr.length) {
  16766. callback();
  16767. }
  16768. else {
  16769. replenish();
  16770. }
  16771. }
  16772. });
  16773. }
  16774. })();
  16775. };
  16776. };
  16777. var doParallel = function (fn) {
  16778. return function () {
  16779. var args = Array.prototype.slice.call(arguments);
  16780. return fn.apply(null, [async.each].concat(args));
  16781. };
  16782. };
  16783. var doParallelLimit = function(limit, fn) {
  16784. return function () {
  16785. var args = Array.prototype.slice.call(arguments);
  16786. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16787. };
  16788. };
  16789. var doSeries = function (fn) {
  16790. return function () {
  16791. var args = Array.prototype.slice.call(arguments);
  16792. return fn.apply(null, [async.eachSeries].concat(args));
  16793. };
  16794. };
  16795. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16796. arr = _map(arr, function (x, i) {
  16797. return {index: i, value: x};
  16798. });
  16799. if (!callback) {
  16800. eachfn(arr, function (x, callback) {
  16801. iterator(x.value, function (err) {
  16802. callback(err);
  16803. });
  16804. });
  16805. } else {
  16806. var results = [];
  16807. eachfn(arr, function (x, callback) {
  16808. iterator(x.value, function (err, v) {
  16809. results[x.index] = v;
  16810. callback(err);
  16811. });
  16812. }, function (err) {
  16813. callback(err, results);
  16814. });
  16815. }
  16816. };
  16817. async.map = doParallel(_asyncMap);
  16818. async.mapSeries = doSeries(_asyncMap);
  16819. async.mapLimit = function (arr, limit, iterator, callback) {
  16820. return _mapLimit(limit)(arr, iterator, callback);
  16821. };
  16822. var _mapLimit = function(limit) {
  16823. return doParallelLimit(limit, _asyncMap);
  16824. };
  16825. // reduce only has a series version, as doing reduce in parallel won't
  16826. // work in many situations.
  16827. async.reduce = function (arr, memo, iterator, callback) {
  16828. async.eachSeries(arr, function (x, callback) {
  16829. iterator(memo, x, function (err, v) {
  16830. memo = v;
  16831. callback(err);
  16832. });
  16833. }, function (err) {
  16834. callback(err, memo);
  16835. });
  16836. };
  16837. // inject alias
  16838. async.inject = async.reduce;
  16839. // foldl alias
  16840. async.foldl = async.reduce;
  16841. async.reduceRight = function (arr, memo, iterator, callback) {
  16842. var reversed = _map(arr, function (x) {
  16843. return x;
  16844. }).reverse();
  16845. async.reduce(reversed, memo, iterator, callback);
  16846. };
  16847. // foldr alias
  16848. async.foldr = async.reduceRight;
  16849. var _filter = function (eachfn, arr, iterator, callback) {
  16850. var results = [];
  16851. arr = _map(arr, function (x, i) {
  16852. return {index: i, value: x};
  16853. });
  16854. eachfn(arr, function (x, callback) {
  16855. iterator(x.value, function (v) {
  16856. if (v) {
  16857. results.push(x);
  16858. }
  16859. callback();
  16860. });
  16861. }, function (err) {
  16862. callback(_map(results.sort(function (a, b) {
  16863. return a.index - b.index;
  16864. }), function (x) {
  16865. return x.value;
  16866. }));
  16867. });
  16868. };
  16869. async.filter = doParallel(_filter);
  16870. async.filterSeries = doSeries(_filter);
  16871. // select alias
  16872. async.select = async.filter;
  16873. async.selectSeries = async.filterSeries;
  16874. var _reject = function (eachfn, arr, iterator, callback) {
  16875. var results = [];
  16876. arr = _map(arr, function (x, i) {
  16877. return {index: i, value: x};
  16878. });
  16879. eachfn(arr, function (x, callback) {
  16880. iterator(x.value, function (v) {
  16881. if (!v) {
  16882. results.push(x);
  16883. }
  16884. callback();
  16885. });
  16886. }, function (err) {
  16887. callback(_map(results.sort(function (a, b) {
  16888. return a.index - b.index;
  16889. }), function (x) {
  16890. return x.value;
  16891. }));
  16892. });
  16893. };
  16894. async.reject = doParallel(_reject);
  16895. async.rejectSeries = doSeries(_reject);
  16896. var _detect = function (eachfn, arr, iterator, main_callback) {
  16897. eachfn(arr, function (x, callback) {
  16898. iterator(x, function (result) {
  16899. if (result) {
  16900. main_callback(x);
  16901. main_callback = function () {};
  16902. }
  16903. else {
  16904. callback();
  16905. }
  16906. });
  16907. }, function (err) {
  16908. main_callback();
  16909. });
  16910. };
  16911. async.detect = doParallel(_detect);
  16912. async.detectSeries = doSeries(_detect);
  16913. async.some = function (arr, iterator, main_callback) {
  16914. async.each(arr, function (x, callback) {
  16915. iterator(x, function (v) {
  16916. if (v) {
  16917. main_callback(true);
  16918. main_callback = function () {};
  16919. }
  16920. callback();
  16921. });
  16922. }, function (err) {
  16923. main_callback(false);
  16924. });
  16925. };
  16926. // any alias
  16927. async.any = async.some;
  16928. async.every = function (arr, iterator, main_callback) {
  16929. async.each(arr, function (x, callback) {
  16930. iterator(x, function (v) {
  16931. if (!v) {
  16932. main_callback(false);
  16933. main_callback = function () {};
  16934. }
  16935. callback();
  16936. });
  16937. }, function (err) {
  16938. main_callback(true);
  16939. });
  16940. };
  16941. // all alias
  16942. async.all = async.every;
  16943. async.sortBy = function (arr, iterator, callback) {
  16944. async.map(arr, function (x, callback) {
  16945. iterator(x, function (err, criteria) {
  16946. if (err) {
  16947. callback(err);
  16948. }
  16949. else {
  16950. callback(null, {value: x, criteria: criteria});
  16951. }
  16952. });
  16953. }, function (err, results) {
  16954. if (err) {
  16955. return callback(err);
  16956. }
  16957. else {
  16958. var fn = function (left, right) {
  16959. var a = left.criteria, b = right.criteria;
  16960. return a < b ? -1 : a > b ? 1 : 0;
  16961. };
  16962. callback(null, _map(results.sort(fn), function (x) {
  16963. return x.value;
  16964. }));
  16965. }
  16966. });
  16967. };
  16968. async.auto = function (tasks, callback) {
  16969. callback = callback || function () {};
  16970. var keys = _keys(tasks);
  16971. var remainingTasks = keys.length
  16972. if (!remainingTasks) {
  16973. return callback();
  16974. }
  16975. var results = {};
  16976. var listeners = [];
  16977. var addListener = function (fn) {
  16978. listeners.unshift(fn);
  16979. };
  16980. var removeListener = function (fn) {
  16981. for (var i = 0; i < listeners.length; i += 1) {
  16982. if (listeners[i] === fn) {
  16983. listeners.splice(i, 1);
  16984. return;
  16985. }
  16986. }
  16987. };
  16988. var taskComplete = function () {
  16989. remainingTasks--
  16990. _each(listeners.slice(0), function (fn) {
  16991. fn();
  16992. });
  16993. };
  16994. addListener(function () {
  16995. if (!remainingTasks) {
  16996. var theCallback = callback;
  16997. // prevent final callback from calling itself if it errors
  16998. callback = function () {};
  16999. theCallback(null, results);
  17000. }
  17001. });
  17002. _each(keys, function (k) {
  17003. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17004. var taskCallback = function (err) {
  17005. var args = Array.prototype.slice.call(arguments, 1);
  17006. if (args.length <= 1) {
  17007. args = args[0];
  17008. }
  17009. if (err) {
  17010. var safeResults = {};
  17011. _each(_keys(results), function(rkey) {
  17012. safeResults[rkey] = results[rkey];
  17013. });
  17014. safeResults[k] = args;
  17015. callback(err, safeResults);
  17016. // stop subsequent errors hitting callback multiple times
  17017. callback = function () {};
  17018. }
  17019. else {
  17020. results[k] = args;
  17021. async.setImmediate(taskComplete);
  17022. }
  17023. };
  17024. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17025. var ready = function () {
  17026. return _reduce(requires, function (a, x) {
  17027. return (a && results.hasOwnProperty(x));
  17028. }, true) && !results.hasOwnProperty(k);
  17029. };
  17030. if (ready()) {
  17031. task[task.length - 1](taskCallback, results);
  17032. }
  17033. else {
  17034. var listener = function () {
  17035. if (ready()) {
  17036. removeListener(listener);
  17037. task[task.length - 1](taskCallback, results);
  17038. }
  17039. };
  17040. addListener(listener);
  17041. }
  17042. });
  17043. };
  17044. async.retry = function(times, task, callback) {
  17045. var DEFAULT_TIMES = 5;
  17046. var attempts = [];
  17047. // Use defaults if times not passed
  17048. if (typeof times === 'function') {
  17049. callback = task;
  17050. task = times;
  17051. times = DEFAULT_TIMES;
  17052. }
  17053. // Make sure times is a number
  17054. times = parseInt(times, 10) || DEFAULT_TIMES;
  17055. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17056. var retryAttempt = function(task, finalAttempt) {
  17057. return function(seriesCallback) {
  17058. task(function(err, result){
  17059. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17060. }, wrappedResults);
  17061. };
  17062. };
  17063. while (times) {
  17064. attempts.push(retryAttempt(task, !(times-=1)));
  17065. }
  17066. async.series(attempts, function(done, data){
  17067. data = data[data.length - 1];
  17068. (wrappedCallback || callback)(data.err, data.result);
  17069. });
  17070. }
  17071. // If a callback is passed, run this as a controll flow
  17072. return callback ? wrappedTask() : wrappedTask
  17073. };
  17074. async.waterfall = function (tasks, callback) {
  17075. callback = callback || function () {};
  17076. if (!_isArray(tasks)) {
  17077. var err = new Error('First argument to waterfall must be an array of functions');
  17078. return callback(err);
  17079. }
  17080. if (!tasks.length) {
  17081. return callback();
  17082. }
  17083. var wrapIterator = function (iterator) {
  17084. return function (err) {
  17085. if (err) {
  17086. callback.apply(null, arguments);
  17087. callback = function () {};
  17088. }
  17089. else {
  17090. var args = Array.prototype.slice.call(arguments, 1);
  17091. var next = iterator.next();
  17092. if (next) {
  17093. args.push(wrapIterator(next));
  17094. }
  17095. else {
  17096. args.push(callback);
  17097. }
  17098. async.setImmediate(function () {
  17099. iterator.apply(null, args);
  17100. });
  17101. }
  17102. };
  17103. };
  17104. wrapIterator(async.iterator(tasks))();
  17105. };
  17106. var _parallel = function(eachfn, tasks, callback) {
  17107. callback = callback || function () {};
  17108. if (_isArray(tasks)) {
  17109. eachfn.map(tasks, function (fn, callback) {
  17110. if (fn) {
  17111. fn(function (err) {
  17112. var args = Array.prototype.slice.call(arguments, 1);
  17113. if (args.length <= 1) {
  17114. args = args[0];
  17115. }
  17116. callback.call(null, err, args);
  17117. });
  17118. }
  17119. }, callback);
  17120. }
  17121. else {
  17122. var results = {};
  17123. eachfn.each(_keys(tasks), function (k, callback) {
  17124. tasks[k](function (err) {
  17125. var args = Array.prototype.slice.call(arguments, 1);
  17126. if (args.length <= 1) {
  17127. args = args[0];
  17128. }
  17129. results[k] = args;
  17130. callback(err);
  17131. });
  17132. }, function (err) {
  17133. callback(err, results);
  17134. });
  17135. }
  17136. };
  17137. async.parallel = function (tasks, callback) {
  17138. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17139. };
  17140. async.parallelLimit = function(tasks, limit, callback) {
  17141. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17142. };
  17143. async.series = function (tasks, callback) {
  17144. callback = callback || function () {};
  17145. if (_isArray(tasks)) {
  17146. async.mapSeries(tasks, function (fn, callback) {
  17147. if (fn) {
  17148. fn(function (err) {
  17149. var args = Array.prototype.slice.call(arguments, 1);
  17150. if (args.length <= 1) {
  17151. args = args[0];
  17152. }
  17153. callback.call(null, err, args);
  17154. });
  17155. }
  17156. }, callback);
  17157. }
  17158. else {
  17159. var results = {};
  17160. async.eachSeries(_keys(tasks), function (k, callback) {
  17161. tasks[k](function (err) {
  17162. var args = Array.prototype.slice.call(arguments, 1);
  17163. if (args.length <= 1) {
  17164. args = args[0];
  17165. }
  17166. results[k] = args;
  17167. callback(err);
  17168. });
  17169. }, function (err) {
  17170. callback(err, results);
  17171. });
  17172. }
  17173. };
  17174. async.iterator = function (tasks) {
  17175. var makeCallback = function (index) {
  17176. var fn = function () {
  17177. if (tasks.length) {
  17178. tasks[index].apply(null, arguments);
  17179. }
  17180. return fn.next();
  17181. };
  17182. fn.next = function () {
  17183. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17184. };
  17185. return fn;
  17186. };
  17187. return makeCallback(0);
  17188. };
  17189. async.apply = function (fn) {
  17190. var args = Array.prototype.slice.call(arguments, 1);
  17191. return function () {
  17192. return fn.apply(
  17193. null, args.concat(Array.prototype.slice.call(arguments))
  17194. );
  17195. };
  17196. };
  17197. var _concat = function (eachfn, arr, fn, callback) {
  17198. var r = [];
  17199. eachfn(arr, function (x, cb) {
  17200. fn(x, function (err, y) {
  17201. r = r.concat(y || []);
  17202. cb(err);
  17203. });
  17204. }, function (err) {
  17205. callback(err, r);
  17206. });
  17207. };
  17208. async.concat = doParallel(_concat);
  17209. async.concatSeries = doSeries(_concat);
  17210. async.whilst = function (test, iterator, callback) {
  17211. if (test()) {
  17212. iterator(function (err) {
  17213. if (err) {
  17214. return callback(err);
  17215. }
  17216. async.whilst(test, iterator, callback);
  17217. });
  17218. }
  17219. else {
  17220. callback();
  17221. }
  17222. };
  17223. async.doWhilst = function (iterator, test, callback) {
  17224. iterator(function (err) {
  17225. if (err) {
  17226. return callback(err);
  17227. }
  17228. var args = Array.prototype.slice.call(arguments, 1);
  17229. if (test.apply(null, args)) {
  17230. async.doWhilst(iterator, test, callback);
  17231. }
  17232. else {
  17233. callback();
  17234. }
  17235. });
  17236. };
  17237. async.until = function (test, iterator, callback) {
  17238. if (!test()) {
  17239. iterator(function (err) {
  17240. if (err) {
  17241. return callback(err);
  17242. }
  17243. async.until(test, iterator, callback);
  17244. });
  17245. }
  17246. else {
  17247. callback();
  17248. }
  17249. };
  17250. async.doUntil = function (iterator, test, callback) {
  17251. iterator(function (err) {
  17252. if (err) {
  17253. return callback(err);
  17254. }
  17255. var args = Array.prototype.slice.call(arguments, 1);
  17256. if (!test.apply(null, args)) {
  17257. async.doUntil(iterator, test, callback);
  17258. }
  17259. else {
  17260. callback();
  17261. }
  17262. });
  17263. };
  17264. async.queue = function (worker, concurrency) {
  17265. if (concurrency === undefined) {
  17266. concurrency = 1;
  17267. }
  17268. function _insert(q, data, pos, callback) {
  17269. if (!q.started){
  17270. q.started = true;
  17271. }
  17272. if (!_isArray(data)) {
  17273. data = [data];
  17274. }
  17275. if(data.length == 0) {
  17276. // call drain immediately if there are no tasks
  17277. return async.setImmediate(function() {
  17278. if (q.drain) {
  17279. q.drain();
  17280. }
  17281. });
  17282. }
  17283. _each(data, function(task) {
  17284. var item = {
  17285. data: task,
  17286. callback: typeof callback === 'function' ? callback : null
  17287. };
  17288. if (pos) {
  17289. q.tasks.unshift(item);
  17290. } else {
  17291. q.tasks.push(item);
  17292. }
  17293. if (q.saturated && q.tasks.length === q.concurrency) {
  17294. q.saturated();
  17295. }
  17296. async.setImmediate(q.process);
  17297. });
  17298. }
  17299. var workers = 0;
  17300. var q = {
  17301. tasks: [],
  17302. concurrency: concurrency,
  17303. saturated: null,
  17304. empty: null,
  17305. drain: null,
  17306. started: false,
  17307. paused: false,
  17308. push: function (data, callback) {
  17309. _insert(q, data, false, callback);
  17310. },
  17311. kill: function () {
  17312. q.drain = null;
  17313. q.tasks = [];
  17314. },
  17315. unshift: function (data, callback) {
  17316. _insert(q, data, true, callback);
  17317. },
  17318. process: function () {
  17319. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17320. var task = q.tasks.shift();
  17321. if (q.empty && q.tasks.length === 0) {
  17322. q.empty();
  17323. }
  17324. workers += 1;
  17325. var next = function () {
  17326. workers -= 1;
  17327. if (task.callback) {
  17328. task.callback.apply(task, arguments);
  17329. }
  17330. if (q.drain && q.tasks.length + workers === 0) {
  17331. q.drain();
  17332. }
  17333. q.process();
  17334. };
  17335. var cb = only_once(next);
  17336. worker(task.data, cb);
  17337. }
  17338. },
  17339. length: function () {
  17340. return q.tasks.length;
  17341. },
  17342. running: function () {
  17343. return workers;
  17344. },
  17345. idle: function() {
  17346. return q.tasks.length + workers === 0;
  17347. },
  17348. pause: function () {
  17349. if (q.paused === true) { return; }
  17350. q.paused = true;
  17351. q.process();
  17352. },
  17353. resume: function () {
  17354. if (q.paused === false) { return; }
  17355. q.paused = false;
  17356. q.process();
  17357. }
  17358. };
  17359. return q;
  17360. };
  17361. async.priorityQueue = function (worker, concurrency) {
  17362. function _compareTasks(a, b){
  17363. return a.priority - b.priority;
  17364. };
  17365. function _binarySearch(sequence, item, compare) {
  17366. var beg = -1,
  17367. end = sequence.length - 1;
  17368. while (beg < end) {
  17369. var mid = beg + ((end - beg + 1) >>> 1);
  17370. if (compare(item, sequence[mid]) >= 0) {
  17371. beg = mid;
  17372. } else {
  17373. end = mid - 1;
  17374. }
  17375. }
  17376. return beg;
  17377. }
  17378. function _insert(q, data, priority, callback) {
  17379. if (!q.started){
  17380. q.started = true;
  17381. }
  17382. if (!_isArray(data)) {
  17383. data = [data];
  17384. }
  17385. if(data.length == 0) {
  17386. // call drain immediately if there are no tasks
  17387. return async.setImmediate(function() {
  17388. if (q.drain) {
  17389. q.drain();
  17390. }
  17391. });
  17392. }
  17393. _each(data, function(task) {
  17394. var item = {
  17395. data: task,
  17396. priority: priority,
  17397. callback: typeof callback === 'function' ? callback : null
  17398. };
  17399. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17400. if (q.saturated && q.tasks.length === q.concurrency) {
  17401. q.saturated();
  17402. }
  17403. async.setImmediate(q.process);
  17404. });
  17405. }
  17406. // Start with a normal queue
  17407. var q = async.queue(worker, concurrency);
  17408. // Override push to accept second parameter representing priority
  17409. q.push = function (data, priority, callback) {
  17410. _insert(q, data, priority, callback);
  17411. };
  17412. // Remove unshift function
  17413. delete q.unshift;
  17414. return q;
  17415. };
  17416. async.cargo = function (worker, payload) {
  17417. var working = false,
  17418. tasks = [];
  17419. var cargo = {
  17420. tasks: tasks,
  17421. payload: payload,
  17422. saturated: null,
  17423. empty: null,
  17424. drain: null,
  17425. drained: true,
  17426. push: function (data, callback) {
  17427. if (!_isArray(data)) {
  17428. data = [data];
  17429. }
  17430. _each(data, function(task) {
  17431. tasks.push({
  17432. data: task,
  17433. callback: typeof callback === 'function' ? callback : null
  17434. });
  17435. cargo.drained = false;
  17436. if (cargo.saturated && tasks.length === payload) {
  17437. cargo.saturated();
  17438. }
  17439. });
  17440. async.setImmediate(cargo.process);
  17441. },
  17442. process: function process() {
  17443. if (working) return;
  17444. if (tasks.length === 0) {
  17445. if(cargo.drain && !cargo.drained) cargo.drain();
  17446. cargo.drained = true;
  17447. return;
  17448. }
  17449. var ts = typeof payload === 'number'
  17450. ? tasks.splice(0, payload)
  17451. : tasks.splice(0, tasks.length);
  17452. var ds = _map(ts, function (task) {
  17453. return task.data;
  17454. });
  17455. if(cargo.empty) cargo.empty();
  17456. working = true;
  17457. worker(ds, function () {
  17458. working = false;
  17459. var args = arguments;
  17460. _each(ts, function (data) {
  17461. if (data.callback) {
  17462. data.callback.apply(null, args);
  17463. }
  17464. });
  17465. process();
  17466. });
  17467. },
  17468. length: function () {
  17469. return tasks.length;
  17470. },
  17471. running: function () {
  17472. return working;
  17473. }
  17474. };
  17475. return cargo;
  17476. };
  17477. var _console_fn = function (name) {
  17478. return function (fn) {
  17479. var args = Array.prototype.slice.call(arguments, 1);
  17480. fn.apply(null, args.concat([function (err) {
  17481. var args = Array.prototype.slice.call(arguments, 1);
  17482. if (typeof console !== 'undefined') {
  17483. if (err) {
  17484. if (console.error) {
  17485. console.error(err);
  17486. }
  17487. }
  17488. else if (console[name]) {
  17489. _each(args, function (x) {
  17490. console[name](x);
  17491. });
  17492. }
  17493. }
  17494. }]));
  17495. };
  17496. };
  17497. async.log = _console_fn('log');
  17498. async.dir = _console_fn('dir');
  17499. /*async.info = _console_fn('info');
  17500. async.warn = _console_fn('warn');
  17501. async.error = _console_fn('error');*/
  17502. async.memoize = function (fn, hasher) {
  17503. var memo = {};
  17504. var queues = {};
  17505. hasher = hasher || function (x) {
  17506. return x;
  17507. };
  17508. var memoized = function () {
  17509. var args = Array.prototype.slice.call(arguments);
  17510. var callback = args.pop();
  17511. var key = hasher.apply(null, args);
  17512. if (key in memo) {
  17513. async.nextTick(function () {
  17514. callback.apply(null, memo[key]);
  17515. });
  17516. }
  17517. else if (key in queues) {
  17518. queues[key].push(callback);
  17519. }
  17520. else {
  17521. queues[key] = [callback];
  17522. fn.apply(null, args.concat([function () {
  17523. memo[key] = arguments;
  17524. var q = queues[key];
  17525. delete queues[key];
  17526. for (var i = 0, l = q.length; i < l; i++) {
  17527. q[i].apply(null, arguments);
  17528. }
  17529. }]));
  17530. }
  17531. };
  17532. memoized.memo = memo;
  17533. memoized.unmemoized = fn;
  17534. return memoized;
  17535. };
  17536. async.unmemoize = function (fn) {
  17537. return function () {
  17538. return (fn.unmemoized || fn).apply(null, arguments);
  17539. };
  17540. };
  17541. async.times = function (count, iterator, callback) {
  17542. var counter = [];
  17543. for (var i = 0; i < count; i++) {
  17544. counter.push(i);
  17545. }
  17546. return async.map(counter, iterator, callback);
  17547. };
  17548. async.timesSeries = function (count, iterator, callback) {
  17549. var counter = [];
  17550. for (var i = 0; i < count; i++) {
  17551. counter.push(i);
  17552. }
  17553. return async.mapSeries(counter, iterator, callback);
  17554. };
  17555. async.seq = function (/* functions... */) {
  17556. var fns = arguments;
  17557. return function () {
  17558. var that = this;
  17559. var args = Array.prototype.slice.call(arguments);
  17560. var callback = args.pop();
  17561. async.reduce(fns, args, function (newargs, fn, cb) {
  17562. fn.apply(that, newargs.concat([function () {
  17563. var err = arguments[0];
  17564. var nextargs = Array.prototype.slice.call(arguments, 1);
  17565. cb(err, nextargs);
  17566. }]))
  17567. },
  17568. function (err, results) {
  17569. callback.apply(that, [err].concat(results));
  17570. });
  17571. };
  17572. };
  17573. async.compose = function (/* functions... */) {
  17574. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  17575. };
  17576. var _applyEach = function (eachfn, fns /*args...*/) {
  17577. var go = function () {
  17578. var that = this;
  17579. var args = Array.prototype.slice.call(arguments);
  17580. var callback = args.pop();
  17581. return eachfn(fns, function (fn, cb) {
  17582. fn.apply(that, args.concat([cb]));
  17583. },
  17584. callback);
  17585. };
  17586. if (arguments.length > 2) {
  17587. var args = Array.prototype.slice.call(arguments, 2);
  17588. return go.apply(this, args);
  17589. }
  17590. else {
  17591. return go;
  17592. }
  17593. };
  17594. async.applyEach = doParallel(_applyEach);
  17595. async.applyEachSeries = doSeries(_applyEach);
  17596. async.forever = function (fn, callback) {
  17597. function next(err) {
  17598. if (err) {
  17599. if (callback) {
  17600. return callback(err);
  17601. }
  17602. throw err;
  17603. }
  17604. fn(next);
  17605. }
  17606. next();
  17607. };
  17608. // Node.js
  17609. if (typeof module !== 'undefined' && module.exports) {
  17610. module.exports = async;
  17611. }
  17612. // AMD / RequireJS
  17613. else if (typeof define !== 'undefined' && define.amd) {
  17614. define([], function () {
  17615. return async;
  17616. });
  17617. }
  17618. // included directly via <script> tag
  17619. else {
  17620. root.async = async;
  17621. }
  17622. }());
  17623. }).call(this,require('_process'))
  17624. },{"_process":2}],70:[function(require,module,exports){
  17625. // i18next, v1.7.7
  17626. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  17627. // Distributed under MIT license
  17628. // http://i18next.com
  17629. (function() {
  17630. // add indexOf to non ECMA-262 standard compliant browsers
  17631. if (!Array.prototype.indexOf) {
  17632. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  17633. "use strict";
  17634. if (this == null) {
  17635. throw new TypeError();
  17636. }
  17637. var t = Object(this);
  17638. var len = t.length >>> 0;
  17639. if (len === 0) {
  17640. return -1;
  17641. }
  17642. var n = 0;
  17643. if (arguments.length > 0) {
  17644. n = Number(arguments[1]);
  17645. if (n != n) { // shortcut for verifying if it's NaN
  17646. n = 0;
  17647. } else if (n != 0 && n != Infinity && n != -Infinity) {
  17648. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17649. }
  17650. }
  17651. if (n >= len) {
  17652. return -1;
  17653. }
  17654. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  17655. for (; k < len; k++) {
  17656. if (k in t && t[k] === searchElement) {
  17657. return k;
  17658. }
  17659. }
  17660. return -1;
  17661. }
  17662. }
  17663. // add lastIndexOf to non ECMA-262 standard compliant browsers
  17664. if (!Array.prototype.lastIndexOf) {
  17665. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  17666. "use strict";
  17667. if (this == null) {
  17668. throw new TypeError();
  17669. }
  17670. var t = Object(this);
  17671. var len = t.length >>> 0;
  17672. if (len === 0) {
  17673. return -1;
  17674. }
  17675. var n = len;
  17676. if (arguments.length > 1) {
  17677. n = Number(arguments[1]);
  17678. if (n != n) {
  17679. n = 0;
  17680. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  17681. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  17682. }
  17683. }
  17684. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  17685. for (; k >= 0; k--) {
  17686. if (k in t && t[k] === searchElement) {
  17687. return k;
  17688. }
  17689. }
  17690. return -1;
  17691. };
  17692. }
  17693. // Add string trim for IE8.
  17694. if (typeof String.prototype.trim !== 'function') {
  17695. String.prototype.trim = function() {
  17696. return this.replace(/^\s+|\s+$/g, '');
  17697. }
  17698. }
  17699. var root = this
  17700. , $ = root.jQuery || root.Zepto
  17701. , i18n = {}
  17702. , resStore = {}
  17703. , currentLng
  17704. , replacementCounter = 0
  17705. , languages = []
  17706. , initialized = false
  17707. , sync = {};
  17708. // Export the i18next object for **CommonJS**.
  17709. // If we're not in CommonJS, add `i18n` to the
  17710. // global object or to jquery.
  17711. if (typeof module !== 'undefined' && module.exports) {
  17712. if (!$) {
  17713. try {
  17714. $ = require('jquery');
  17715. } catch(e) {
  17716. // just ignore
  17717. }
  17718. }
  17719. if ($) {
  17720. $.i18n = $.i18n || i18n;
  17721. }
  17722. module.exports = i18n;
  17723. } else {
  17724. if ($) {
  17725. $.i18n = $.i18n || i18n;
  17726. }
  17727. root.i18n = root.i18n || i18n;
  17728. }
  17729. sync = {
  17730. load: function(lngs, options, cb) {
  17731. if (options.useLocalStorage) {
  17732. sync._loadLocal(lngs, options, function(err, store) {
  17733. var missingLngs = [];
  17734. for (var i = 0, len = lngs.length; i < len; i++) {
  17735. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17736. }
  17737. if (missingLngs.length > 0) {
  17738. sync._fetch(missingLngs, options, function(err, fetched) {
  17739. f.extend(store, fetched);
  17740. sync._storeLocal(fetched);
  17741. cb(null, store);
  17742. });
  17743. } else {
  17744. cb(null, store);
  17745. }
  17746. });
  17747. } else {
  17748. sync._fetch(lngs, options, function(err, store){
  17749. cb(null, store);
  17750. });
  17751. }
  17752. },
  17753. _loadLocal: function(lngs, options, cb) {
  17754. var store = {}
  17755. , nowMS = new Date().getTime();
  17756. if(window.localStorage) {
  17757. var todo = lngs.length;
  17758. f.each(lngs, function(key, lng) {
  17759. var local = window.localStorage.getItem('res_' + lng);
  17760. if (local) {
  17761. local = JSON.parse(local);
  17762. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17763. store[lng] = local;
  17764. }
  17765. }
  17766. todo--; // wait for all done befor callback
  17767. if (todo === 0) cb(null, store);
  17768. });
  17769. }
  17770. },
  17771. _storeLocal: function(store) {
  17772. if(window.localStorage) {
  17773. for (var m in store) {
  17774. store[m].i18nStamp = new Date().getTime();
  17775. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17776. }
  17777. }
  17778. return;
  17779. },
  17780. _fetch: function(lngs, options, cb) {
  17781. var ns = options.ns
  17782. , store = {};
  17783. if (!options.dynamicLoad) {
  17784. var todo = ns.namespaces.length * lngs.length
  17785. , errors;
  17786. // load each file individual
  17787. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17788. f.each(lngs, function(lngIndex, lngValue) {
  17789. // Call this once our translation has returned.
  17790. var loadComplete = function(err, data) {
  17791. if (err) {
  17792. errors = errors || [];
  17793. errors.push(err);
  17794. }
  17795. store[lngValue] = store[lngValue] || {};
  17796. store[lngValue][nsValue] = data;
  17797. todo--; // wait for all done befor callback
  17798. if (todo === 0) cb(errors, store);
  17799. };
  17800. if(typeof options.customLoad == 'function'){
  17801. // Use the specified custom callback.
  17802. options.customLoad(lngValue, nsValue, options, loadComplete);
  17803. } else {
  17804. //~ // Use our inbuilt sync.
  17805. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17806. }
  17807. });
  17808. });
  17809. } else {
  17810. // Call this once our translation has returned.
  17811. var loadComplete = function(err, data) {
  17812. cb(null, data);
  17813. };
  17814. if(typeof options.customLoad == 'function'){
  17815. // Use the specified custom callback.
  17816. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17817. } else {
  17818. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17819. // load all needed stuff once
  17820. f.ajax({
  17821. url: url,
  17822. success: function(data, status, xhr) {
  17823. f.log('loaded: ' + url);
  17824. loadComplete(null, data);
  17825. },
  17826. error : function(xhr, status, error) {
  17827. f.log('failed loading: ' + url);
  17828. loadComplete('failed loading resource.json error: ' + error);
  17829. },
  17830. dataType: "json",
  17831. async : options.getAsync
  17832. });
  17833. }
  17834. }
  17835. },
  17836. _fetchOne: function(lng, ns, options, done) {
  17837. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17838. f.ajax({
  17839. url: url,
  17840. success: function(data, status, xhr) {
  17841. f.log('loaded: ' + url);
  17842. done(null, data);
  17843. },
  17844. error : function(xhr, status, error) {
  17845. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17846. // file loaded but invalid json, stop waste time !
  17847. f.error('There is a typo in: ' + url);
  17848. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17849. f.log('Does not exist: ' + url);
  17850. } else {
  17851. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17852. f.log(theStatus + ' when loading ' + url);
  17853. }
  17854. done(error, {});
  17855. },
  17856. dataType: "json",
  17857. async : options.getAsync
  17858. });
  17859. },
  17860. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17861. var payload = {};
  17862. payload[key] = defaultValue;
  17863. var urls = [];
  17864. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17865. for (var i = 0; i < o.fallbackLng.length; i++) {
  17866. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17867. }
  17868. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17869. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17870. } else if (o.sendMissingTo === 'all') {
  17871. for (var i = 0, l = lngs.length; i < l; i++) {
  17872. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17873. }
  17874. }
  17875. for (var y = 0, len = urls.length; y < len; y++) {
  17876. var item = urls[y];
  17877. f.ajax({
  17878. url: item.url,
  17879. type: o.sendType,
  17880. data: payload,
  17881. success: function(data, status, xhr) {
  17882. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17883. // add key to resStore
  17884. var keys = key.split('.');
  17885. var x = 0;
  17886. var value = resStore[item.lng][ns];
  17887. while (keys[x]) {
  17888. if (x === keys.length - 1) {
  17889. value = value[keys[x]] = defaultValue;
  17890. } else {
  17891. value = value[keys[x]] = value[keys[x]] || {};
  17892. }
  17893. x++;
  17894. }
  17895. },
  17896. error : function(xhr, status, error) {
  17897. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17898. },
  17899. dataType: "json",
  17900. async : o.postAsync
  17901. });
  17902. }
  17903. },
  17904. reload: reload
  17905. };
  17906. // defaults
  17907. var o = {
  17908. lng: undefined,
  17909. load: 'all',
  17910. preload: [],
  17911. lowerCaseLng: false,
  17912. returnObjectTrees: false,
  17913. fallbackLng: ['dev'],
  17914. fallbackNS: [],
  17915. detectLngQS: 'setLng',
  17916. detectLngFromLocalStorage: false,
  17917. ns: 'translation',
  17918. fallbackOnNull: true,
  17919. fallbackOnEmpty: false,
  17920. fallbackToDefaultNS: false,
  17921. nsseparator: ':',
  17922. keyseparator: '.',
  17923. selectorAttr: 'data-i18n',
  17924. debug: false,
  17925. resGetPath: 'locales/__lng__/__ns__.json',
  17926. resPostPath: 'locales/add/__lng__/__ns__',
  17927. getAsync: true,
  17928. postAsync: true,
  17929. resStore: undefined,
  17930. useLocalStorage: false,
  17931. localStorageExpirationTime: 7*24*60*60*1000,
  17932. dynamicLoad: false,
  17933. sendMissing: false,
  17934. sendMissingTo: 'fallback', // current | all
  17935. sendType: 'POST',
  17936. interpolationPrefix: '__',
  17937. interpolationSuffix: '__',
  17938. defaultVariables: false,
  17939. reusePrefix: '$t(',
  17940. reuseSuffix: ')',
  17941. pluralSuffix: '_plural',
  17942. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17943. contextNotFound: ['context_not_found', Math.random()].join(''),
  17944. escapeInterpolation: false,
  17945. indefiniteSuffix: '_indefinite',
  17946. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17947. setJqueryExt: true,
  17948. defaultValueFromContent: true,
  17949. useDataAttrOptions: false,
  17950. cookieExpirationTime: undefined,
  17951. useCookie: true,
  17952. cookieName: 'i18next',
  17953. cookieDomain: undefined,
  17954. objectTreeKeyHandler: undefined,
  17955. postProcess: undefined,
  17956. parseMissingKey: undefined,
  17957. missingKeyHandler: sync.postMissing,
  17958. shortcutFunction: 'sprintf' // or: defaultValue
  17959. };
  17960. function _extend(target, source) {
  17961. if (!source || typeof source === 'function') {
  17962. return target;
  17963. }
  17964. for (var attr in source) { target[attr] = source[attr]; }
  17965. return target;
  17966. }
  17967. function _deepExtend(target, source) {
  17968. for (var prop in source)
  17969. if (prop in target)
  17970. _deepExtend(target[prop], source[prop]);
  17971. else
  17972. target[prop] = source[prop];
  17973. return target;
  17974. }
  17975. function _each(object, callback, args) {
  17976. var name, i = 0,
  17977. length = object.length,
  17978. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17979. if (args) {
  17980. if (isObj) {
  17981. for (name in object) {
  17982. if (callback.apply(object[name], args) === false) {
  17983. break;
  17984. }
  17985. }
  17986. } else {
  17987. for ( ; i < length; ) {
  17988. if (callback.apply(object[i++], args) === false) {
  17989. break;
  17990. }
  17991. }
  17992. }
  17993. // A special, fast, case for the most common use of each
  17994. } else {
  17995. if (isObj) {
  17996. for (name in object) {
  17997. if (callback.call(object[name], name, object[name]) === false) {
  17998. break;
  17999. }
  18000. }
  18001. } else {
  18002. for ( ; i < length; ) {
  18003. if (callback.call(object[i], i, object[i++]) === false) {
  18004. break;
  18005. }
  18006. }
  18007. }
  18008. }
  18009. return object;
  18010. }
  18011. var _entityMap = {
  18012. "&": "&amp;",
  18013. "<": "&lt;",
  18014. ">": "&gt;",
  18015. '"': '&quot;',
  18016. "'": '&#39;',
  18017. "/": '&#x2F;'
  18018. };
  18019. function _escape(data) {
  18020. if (typeof data === 'string') {
  18021. return data.replace(/[&<>"'\/]/g, function (s) {
  18022. return _entityMap[s];
  18023. });
  18024. }else{
  18025. return data;
  18026. }
  18027. }
  18028. function _ajax(options) {
  18029. // v0.5.0 of https://github.com/goloroden/http.js
  18030. var getXhr = function (callback) {
  18031. // Use the native XHR object if the browser supports it.
  18032. if (window.XMLHttpRequest) {
  18033. return callback(null, new XMLHttpRequest());
  18034. } else if (window.ActiveXObject) {
  18035. // In Internet Explorer check for ActiveX versions of the XHR object.
  18036. try {
  18037. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18038. } catch (e) {
  18039. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18040. }
  18041. }
  18042. // If no XHR support was found, throw an error.
  18043. return callback(new Error());
  18044. };
  18045. var encodeUsingUrlEncoding = function (data) {
  18046. if(typeof data === 'string') {
  18047. return data;
  18048. }
  18049. var result = [];
  18050. for(var dataItem in data) {
  18051. if(data.hasOwnProperty(dataItem)) {
  18052. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18053. }
  18054. }
  18055. return result.join('&');
  18056. };
  18057. var utf8 = function (text) {
  18058. text = text.replace(/\r\n/g, '\n');
  18059. var result = '';
  18060. for(var i = 0; i < text.length; i++) {
  18061. var c = text.charCodeAt(i);
  18062. if(c < 128) {
  18063. result += String.fromCharCode(c);
  18064. } else if((c > 127) && (c < 2048)) {
  18065. result += String.fromCharCode((c >> 6) | 192);
  18066. result += String.fromCharCode((c & 63) | 128);
  18067. } else {
  18068. result += String.fromCharCode((c >> 12) | 224);
  18069. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18070. result += String.fromCharCode((c & 63) | 128);
  18071. }
  18072. }
  18073. return result;
  18074. };
  18075. var base64 = function (text) {
  18076. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18077. text = utf8(text);
  18078. var result = '',
  18079. chr1, chr2, chr3,
  18080. enc1, enc2, enc3, enc4,
  18081. i = 0;
  18082. do {
  18083. chr1 = text.charCodeAt(i++);
  18084. chr2 = text.charCodeAt(i++);
  18085. chr3 = text.charCodeAt(i++);
  18086. enc1 = chr1 >> 2;
  18087. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18088. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18089. enc4 = chr3 & 63;
  18090. if(isNaN(chr2)) {
  18091. enc3 = enc4 = 64;
  18092. } else if(isNaN(chr3)) {
  18093. enc4 = 64;
  18094. }
  18095. result +=
  18096. keyStr.charAt(enc1) +
  18097. keyStr.charAt(enc2) +
  18098. keyStr.charAt(enc3) +
  18099. keyStr.charAt(enc4);
  18100. chr1 = chr2 = chr3 = '';
  18101. enc1 = enc2 = enc3 = enc4 = '';
  18102. } while(i < text.length);
  18103. return result;
  18104. };
  18105. var mergeHeaders = function () {
  18106. // Use the first header object as base.
  18107. var result = arguments[0];
  18108. // Iterate through the remaining header objects and add them.
  18109. for(var i = 1; i < arguments.length; i++) {
  18110. var currentHeaders = arguments[i];
  18111. for(var header in currentHeaders) {
  18112. if(currentHeaders.hasOwnProperty(header)) {
  18113. result[header] = currentHeaders[header];
  18114. }
  18115. }
  18116. }
  18117. // Return the merged headers.
  18118. return result;
  18119. };
  18120. var ajax = function (method, url, options, callback) {
  18121. // Adjust parameters.
  18122. if(typeof options === 'function') {
  18123. callback = options;
  18124. options = {};
  18125. }
  18126. // Set default parameter values.
  18127. options.cache = options.cache || false;
  18128. options.data = options.data || {};
  18129. options.headers = options.headers || {};
  18130. options.jsonp = options.jsonp || false;
  18131. options.async = options.async === undefined ? true : options.async;
  18132. // Merge the various header objects.
  18133. var headers = mergeHeaders({
  18134. 'accept': '*/*',
  18135. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18136. }, ajax.headers, options.headers);
  18137. // Encode the data according to the content-type.
  18138. var payload;
  18139. if (headers['content-type'] === 'application/json') {
  18140. payload = JSON.stringify(options.data);
  18141. } else {
  18142. payload = encodeUsingUrlEncoding(options.data);
  18143. }
  18144. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18145. // if neccessary.
  18146. if(method === 'GET') {
  18147. // Setup the query string.
  18148. var queryString = [];
  18149. if(payload) {
  18150. queryString.push(payload);
  18151. payload = null;
  18152. }
  18153. // Handle caching.
  18154. if(!options.cache) {
  18155. queryString.push('_=' + (new Date()).getTime());
  18156. }
  18157. // If neccessary prepare the query string for a JSONP call.
  18158. if(options.jsonp) {
  18159. queryString.push('callback=' + options.jsonp);
  18160. queryString.push('jsonp=' + options.jsonp);
  18161. }
  18162. // Merge the query string and attach it to the url.
  18163. queryString = queryString.join('&');
  18164. if (queryString.length > 1) {
  18165. if (url.indexOf('?') > -1) {
  18166. url += '&' + queryString;
  18167. } else {
  18168. url += '?' + queryString;
  18169. }
  18170. }
  18171. // Make a JSONP call if neccessary.
  18172. if(options.jsonp) {
  18173. var head = document.getElementsByTagName('head')[0];
  18174. var script = document.createElement('script');
  18175. script.type = 'text/javascript';
  18176. script.src = url;
  18177. head.appendChild(script);
  18178. return;
  18179. }
  18180. }
  18181. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18182. getXhr(function (err, xhr) {
  18183. if(err) return callback(err);
  18184. // Open the request.
  18185. xhr.open(method, url, options.async);
  18186. // Set the request headers.
  18187. for(var header in headers) {
  18188. if(headers.hasOwnProperty(header)) {
  18189. xhr.setRequestHeader(header, headers[header]);
  18190. }
  18191. }
  18192. // Handle the request events.
  18193. xhr.onreadystatechange = function () {
  18194. if(xhr.readyState === 4) {
  18195. var data = xhr.responseText || '';
  18196. // If no callback is given, return.
  18197. if(!callback) {
  18198. return;
  18199. }
  18200. // Return an object that provides access to the data as text and JSON.
  18201. callback(xhr.status, {
  18202. text: function () {
  18203. return data;
  18204. },
  18205. json: function () {
  18206. try {
  18207. return JSON.parse(data)
  18208. } catch (e) {
  18209. f.error('Can not parse JSON. URL: ' + url);
  18210. return {};
  18211. }
  18212. }
  18213. });
  18214. }
  18215. };
  18216. // Actually send the XHR request.
  18217. xhr.send(payload);
  18218. });
  18219. };
  18220. // Define the external interface.
  18221. var http = {
  18222. authBasic: function (username, password) {
  18223. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18224. },
  18225. connect: function (url, options, callback) {
  18226. return ajax('CONNECT', url, options, callback);
  18227. },
  18228. del: function (url, options, callback) {
  18229. return ajax('DELETE', url, options, callback);
  18230. },
  18231. get: function (url, options, callback) {
  18232. return ajax('GET', url, options, callback);
  18233. },
  18234. head: function (url, options, callback) {
  18235. return ajax('HEAD', url, options, callback);
  18236. },
  18237. headers: function (headers) {
  18238. ajax.headers = headers || {};
  18239. },
  18240. isAllowed: function (url, verb, callback) {
  18241. this.options(url, function (status, data) {
  18242. callback(data.text().indexOf(verb) !== -1);
  18243. });
  18244. },
  18245. options: function (url, options, callback) {
  18246. return ajax('OPTIONS', url, options, callback);
  18247. },
  18248. patch: function (url, options, callback) {
  18249. return ajax('PATCH', url, options, callback);
  18250. },
  18251. post: function (url, options, callback) {
  18252. return ajax('POST', url, options, callback);
  18253. },
  18254. put: function (url, options, callback) {
  18255. return ajax('PUT', url, options, callback);
  18256. },
  18257. trace: function (url, options, callback) {
  18258. return ajax('TRACE', url, options, callback);
  18259. }
  18260. };
  18261. var methode = options.type ? options.type.toLowerCase() : 'get';
  18262. http[methode](options.url, options, function (status, data) {
  18263. // file: protocol always gives status code 0, so check for data
  18264. if (status === 200 || (status === 0 && data.text())) {
  18265. options.success(data.json(), status, null);
  18266. } else {
  18267. options.error(data.text(), status, null);
  18268. }
  18269. });
  18270. }
  18271. var _cookie = {
  18272. create: function(name,value,minutes,domain) {
  18273. var expires;
  18274. if (minutes) {
  18275. var date = new Date();
  18276. date.setTime(date.getTime()+(minutes*60*1000));
  18277. expires = "; expires="+date.toGMTString();
  18278. }
  18279. else expires = "";
  18280. domain = (domain)? "domain="+domain+";" : "";
  18281. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18282. },
  18283. read: function(name) {
  18284. var nameEQ = name + "=";
  18285. var ca = document.cookie.split(';');
  18286. for(var i=0;i < ca.length;i++) {
  18287. var c = ca[i];
  18288. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18289. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18290. }
  18291. return null;
  18292. },
  18293. remove: function(name) {
  18294. this.create(name,"",-1);
  18295. }
  18296. };
  18297. var cookie_noop = {
  18298. create: function(name,value,minutes,domain) {},
  18299. read: function(name) { return null; },
  18300. remove: function(name) {}
  18301. };
  18302. // move dependent functions to a container so that
  18303. // they can be overriden easier in no jquery environment (node.js)
  18304. var f = {
  18305. extend: $ ? $.extend : _extend,
  18306. deepExtend: _deepExtend,
  18307. each: $ ? $.each : _each,
  18308. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18309. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18310. detectLanguage: detectLanguage,
  18311. escape: _escape,
  18312. log: function(str) {
  18313. if (o.debug && typeof console !== "undefined") console.log(str);
  18314. },
  18315. error: function(str) {
  18316. if (typeof console !== "undefined") console.error(str);
  18317. },
  18318. getCountyIndexOfLng: function(lng) {
  18319. var lng_index = 0;
  18320. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18321. return lng_index;
  18322. },
  18323. toLanguages: function(lng) {
  18324. var log = this.log;
  18325. function applyCase(l) {
  18326. var ret = l;
  18327. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18328. var parts = l.split('-');
  18329. ret = o.lowerCaseLng ?
  18330. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18331. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18332. } else {
  18333. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18334. }
  18335. return ret;
  18336. }
  18337. var languages = [];
  18338. var whitelist = o.lngWhitelist || false;
  18339. var addLanguage = function(language){
  18340. //reject langs not whitelisted
  18341. if(!whitelist || whitelist.indexOf(language) > -1){
  18342. languages.push(language);
  18343. }else{
  18344. log('rejecting non-whitelisted language: ' + language);
  18345. }
  18346. };
  18347. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18348. var parts = lng.split('-');
  18349. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18350. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18351. } else {
  18352. addLanguage(applyCase(lng));
  18353. }
  18354. for (var i = 0; i < o.fallbackLng.length; i++) {
  18355. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18356. }
  18357. return languages;
  18358. },
  18359. regexEscape: function(str) {
  18360. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18361. },
  18362. regexReplacementEscape: function(strOrFn) {
  18363. if (typeof strOrFn === 'string') {
  18364. return strOrFn.replace(/\$/g, "$$$$");
  18365. } else {
  18366. return strOrFn;
  18367. }
  18368. },
  18369. localStorage: {
  18370. setItem: function(key, value) {
  18371. if (window.localStorage) {
  18372. try {
  18373. window.localStorage.setItem(key, value);
  18374. } catch (e) {
  18375. f.log('failed to set value for key "' + key + '" to localStorage.');
  18376. }
  18377. }
  18378. }
  18379. }
  18380. };
  18381. function init(options, cb) {
  18382. if (typeof options === 'function') {
  18383. cb = options;
  18384. options = {};
  18385. }
  18386. options = options || {};
  18387. // override defaults with passed in options
  18388. f.extend(o, options);
  18389. delete o.fixLng; /* passed in each time */
  18390. // override functions: .log(), .detectLanguage(), etc
  18391. if (o.functions) {
  18392. delete o.functions;
  18393. f.extend(f, options.functions);
  18394. }
  18395. // create namespace object if namespace is passed in as string
  18396. if (typeof o.ns == 'string') {
  18397. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18398. }
  18399. // fallback namespaces
  18400. if (typeof o.fallbackNS == 'string') {
  18401. o.fallbackNS = [o.fallbackNS];
  18402. }
  18403. // fallback languages
  18404. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18405. o.fallbackLng = [o.fallbackLng];
  18406. }
  18407. // escape prefix/suffix
  18408. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18409. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18410. if (!o.lng) o.lng = f.detectLanguage();
  18411. languages = f.toLanguages(o.lng);
  18412. currentLng = languages[0];
  18413. f.log('currentLng set to: ' + currentLng);
  18414. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18415. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  18416. }
  18417. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  18418. f.localStorage.setItem('i18next_lng', currentLng);
  18419. }
  18420. var lngTranslate = translate;
  18421. if (options.fixLng) {
  18422. lngTranslate = function(key, options) {
  18423. options = options || {};
  18424. options.lng = options.lng || lngTranslate.lng;
  18425. return translate(key, options);
  18426. };
  18427. lngTranslate.lng = currentLng;
  18428. }
  18429. pluralExtensions.setCurrentLng(currentLng);
  18430. // add JQuery extensions
  18431. if ($ && o.setJqueryExt) addJqueryFunct();
  18432. // jQuery deferred
  18433. var deferred;
  18434. if ($ && $.Deferred) {
  18435. deferred = $.Deferred();
  18436. }
  18437. // return immidiatly if res are passed in
  18438. if (o.resStore) {
  18439. resStore = o.resStore;
  18440. initialized = true;
  18441. if (cb) cb(lngTranslate);
  18442. if (deferred) deferred.resolve(lngTranslate);
  18443. if (deferred) return deferred.promise();
  18444. return;
  18445. }
  18446. // languages to load
  18447. var lngsToLoad = f.toLanguages(o.lng);
  18448. if (typeof o.preload === 'string') o.preload = [o.preload];
  18449. for (var i = 0, l = o.preload.length; i < l; i++) {
  18450. var pres = f.toLanguages(o.preload[i]);
  18451. for (var y = 0, len = pres.length; y < len; y++) {
  18452. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18453. lngsToLoad.push(pres[y]);
  18454. }
  18455. }
  18456. }
  18457. // else load them
  18458. i18n.sync.load(lngsToLoad, o, function(err, store) {
  18459. resStore = store;
  18460. initialized = true;
  18461. if (cb) cb(lngTranslate);
  18462. if (deferred) deferred.resolve(lngTranslate);
  18463. });
  18464. if (deferred) return deferred.promise();
  18465. }
  18466. function preload(lngs, cb) {
  18467. if (typeof lngs === 'string') lngs = [lngs];
  18468. for (var i = 0, l = lngs.length; i < l; i++) {
  18469. if (o.preload.indexOf(lngs[i]) < 0) {
  18470. o.preload.push(lngs[i]);
  18471. }
  18472. }
  18473. return init(cb);
  18474. }
  18475. function addResourceBundle(lng, ns, resources, deep) {
  18476. if (typeof ns !== 'string') {
  18477. resources = ns;
  18478. ns = o.ns.defaultNs;
  18479. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18480. o.ns.namespaces.push(ns);
  18481. }
  18482. resStore[lng] = resStore[lng] || {};
  18483. resStore[lng][ns] = resStore[lng][ns] || {};
  18484. if (deep) {
  18485. f.deepExtend(resStore[lng][ns], resources);
  18486. } else {
  18487. f.extend(resStore[lng][ns], resources);
  18488. }
  18489. }
  18490. function hasResourceBundle(lng, ns) {
  18491. if (typeof ns !== 'string') {
  18492. ns = o.ns.defaultNs;
  18493. }
  18494. resStore[lng] = resStore[lng] || {};
  18495. var res = resStore[lng][ns] || {};
  18496. var hasValues = false;
  18497. for(var prop in res) {
  18498. if (res.hasOwnProperty(prop)) {
  18499. hasValues = true;
  18500. }
  18501. }
  18502. return hasValues;
  18503. }
  18504. function removeResourceBundle(lng, ns) {
  18505. if (typeof ns !== 'string') {
  18506. ns = o.ns.defaultNs;
  18507. }
  18508. resStore[lng] = resStore[lng] || {};
  18509. resStore[lng][ns] = {};
  18510. }
  18511. function addResource(lng, ns, key, value) {
  18512. if (typeof ns !== 'string') {
  18513. resource = ns;
  18514. ns = o.ns.defaultNs;
  18515. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18516. o.ns.namespaces.push(ns);
  18517. }
  18518. resStore[lng] = resStore[lng] || {};
  18519. resStore[lng][ns] = resStore[lng][ns] || {};
  18520. var keys = key.split(o.keyseparator);
  18521. var x = 0;
  18522. var node = resStore[lng][ns];
  18523. var origRef = node;
  18524. while (keys[x]) {
  18525. if (x == keys.length - 1)
  18526. node[keys[x]] = value;
  18527. else {
  18528. if (node[keys[x]] == null)
  18529. node[keys[x]] = {};
  18530. node = node[keys[x]];
  18531. }
  18532. x++;
  18533. }
  18534. }
  18535. function addResources(lng, ns, resources) {
  18536. if (typeof ns !== 'string') {
  18537. resource = ns;
  18538. ns = o.ns.defaultNs;
  18539. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  18540. o.ns.namespaces.push(ns);
  18541. }
  18542. for (var m in resources) {
  18543. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  18544. }
  18545. }
  18546. function setDefaultNamespace(ns) {
  18547. o.ns.defaultNs = ns;
  18548. }
  18549. function loadNamespace(namespace, cb) {
  18550. loadNamespaces([namespace], cb);
  18551. }
  18552. function loadNamespaces(namespaces, cb) {
  18553. var opts = {
  18554. dynamicLoad: o.dynamicLoad,
  18555. resGetPath: o.resGetPath,
  18556. getAsync: o.getAsync,
  18557. customLoad: o.customLoad,
  18558. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  18559. };
  18560. // languages to load
  18561. var lngsToLoad = f.toLanguages(o.lng);
  18562. if (typeof o.preload === 'string') o.preload = [o.preload];
  18563. for (var i = 0, l = o.preload.length; i < l; i++) {
  18564. var pres = f.toLanguages(o.preload[i]);
  18565. for (var y = 0, len = pres.length; y < len; y++) {
  18566. if (lngsToLoad.indexOf(pres[y]) < 0) {
  18567. lngsToLoad.push(pres[y]);
  18568. }
  18569. }
  18570. }
  18571. // check if we have to load
  18572. var lngNeedLoad = [];
  18573. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  18574. var needLoad = false;
  18575. var resSet = resStore[lngsToLoad[a]];
  18576. if (resSet) {
  18577. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  18578. if (!resSet[namespaces[b]]) needLoad = true;
  18579. }
  18580. } else {
  18581. needLoad = true;
  18582. }
  18583. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  18584. }
  18585. if (lngNeedLoad.length) {
  18586. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  18587. var todo = namespaces.length * lngNeedLoad.length;
  18588. // load each file individual
  18589. f.each(namespaces, function(nsIndex, nsValue) {
  18590. // append namespace to namespace array
  18591. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  18592. o.ns.namespaces.push(nsValue);
  18593. }
  18594. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  18595. resStore[lngValue] = resStore[lngValue] || {};
  18596. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  18597. todo--; // wait for all done befor callback
  18598. if (todo === 0 && cb) {
  18599. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  18600. cb();
  18601. }
  18602. });
  18603. });
  18604. });
  18605. } else {
  18606. if (cb) cb();
  18607. }
  18608. }
  18609. function setLng(lng, options, cb) {
  18610. if (typeof options === 'function') {
  18611. cb = options;
  18612. options = {};
  18613. } else if (!options) {
  18614. options = {};
  18615. }
  18616. options.lng = lng;
  18617. return init(options, cb);
  18618. }
  18619. function lng() {
  18620. return currentLng;
  18621. }
  18622. function reload(cb) {
  18623. resStore = {};
  18624. setLng(currentLng, cb);
  18625. }
  18626. function addJqueryFunct() {
  18627. // $.t shortcut
  18628. $.t = $.t || translate;
  18629. function parse(ele, key, options) {
  18630. if (key.length === 0) return;
  18631. var attr = 'text';
  18632. if (key.indexOf('[') === 0) {
  18633. var parts = key.split(']');
  18634. key = parts[1];
  18635. attr = parts[0].substr(1, parts[0].length-1);
  18636. }
  18637. if (key.indexOf(';') === key.length-1) {
  18638. key = key.substr(0, key.length-2);
  18639. }
  18640. var optionsToUse;
  18641. if (attr === 'html') {
  18642. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18643. ele.html($.t(key, optionsToUse));
  18644. } else if (attr === 'text') {
  18645. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  18646. ele.text($.t(key, optionsToUse));
  18647. } else if (attr === 'prepend') {
  18648. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18649. ele.prepend($.t(key, optionsToUse));
  18650. } else if (attr === 'append') {
  18651. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  18652. ele.append($.t(key, optionsToUse));
  18653. } else if (attr.indexOf("data-") === 0) {
  18654. var dataAttr = attr.substr(("data-").length);
  18655. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  18656. var translated = $.t(key, optionsToUse);
  18657. //we change into the data cache
  18658. ele.data(dataAttr, translated);
  18659. //we change into the dom
  18660. ele.attr(attr, translated);
  18661. } else {
  18662. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  18663. ele.attr(attr, $.t(key, optionsToUse));
  18664. }
  18665. }
  18666. function localize(ele, options) {
  18667. var key = ele.attr(o.selectorAttr);
  18668. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  18669. if (!key) return;
  18670. var target = ele
  18671. , targetSelector = ele.data("i18n-target");
  18672. if (targetSelector) {
  18673. target = ele.find(targetSelector) || ele;
  18674. }
  18675. if (!options && o.useDataAttrOptions === true) {
  18676. options = ele.data("i18n-options");
  18677. }
  18678. options = options || {};
  18679. if (key.indexOf(';') >= 0) {
  18680. var keys = key.split(';');
  18681. $.each(keys, function(m, k) {
  18682. if (k !== '') parse(target, k, options);
  18683. });
  18684. } else {
  18685. parse(target, key, options);
  18686. }
  18687. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  18688. }
  18689. // fn
  18690. $.fn.i18n = function (options) {
  18691. return this.each(function() {
  18692. // localize element itself
  18693. localize($(this), options);
  18694. // localize childs
  18695. var elements = $(this).find('[' + o.selectorAttr + ']');
  18696. elements.each(function() {
  18697. localize($(this), options);
  18698. });
  18699. });
  18700. };
  18701. }
  18702. function applyReplacement(str, replacementHash, nestedKey, options) {
  18703. if (!str) return str;
  18704. options = options || replacementHash; // first call uses replacement hash combined with options
  18705. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18706. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18707. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18708. , unEscapingSuffix = 'HTML'+suffix;
  18709. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18710. f.each(hash, function(key, value) {
  18711. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18712. if (typeof value === 'object' && value !== null) {
  18713. str = applyReplacement(str, value, nextKey, options);
  18714. } else {
  18715. if (options.escapeInterpolation || o.escapeInterpolation) {
  18716. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18717. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18718. } else {
  18719. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18720. }
  18721. // str = options.escapeInterpolation;
  18722. }
  18723. });
  18724. return str;
  18725. }
  18726. // append it to functions
  18727. f.applyReplacement = applyReplacement;
  18728. function applyReuse(translated, options) {
  18729. var comma = ',';
  18730. var options_open = '{';
  18731. var options_close = '}';
  18732. var opts = f.extend({}, options);
  18733. delete opts.postProcess;
  18734. while (translated.indexOf(o.reusePrefix) != -1) {
  18735. replacementCounter++;
  18736. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18737. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18738. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18739. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18740. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18741. if (index_of_end_of_closing <= index_of_opening) {
  18742. f.error('there is an missing closing in following translation value', translated);
  18743. return '';
  18744. }
  18745. if (token_without_symbols.indexOf(comma) != -1) {
  18746. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18747. 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) {
  18748. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18749. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18750. try {
  18751. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18752. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18753. } catch (e) {
  18754. }
  18755. }
  18756. }
  18757. var translated_token = _translate(token_without_symbols, opts);
  18758. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18759. }
  18760. return translated;
  18761. }
  18762. function hasContext(options) {
  18763. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18764. }
  18765. function needsPlural(options, lng) {
  18766. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18767. }
  18768. function needsIndefiniteArticle(options) {
  18769. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18770. }
  18771. function exists(key, options) {
  18772. options = options || {};
  18773. var notFound = _getDefaultValue(key, options)
  18774. , found = _find(key, options);
  18775. return found !== undefined || found === notFound;
  18776. }
  18777. function translate(key, options) {
  18778. options = options || {};
  18779. if (!initialized) {
  18780. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18781. return options.defaultValue || '';
  18782. };
  18783. replacementCounter = 0;
  18784. return _translate.apply(null, arguments);
  18785. }
  18786. function _getDefaultValue(key, options) {
  18787. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18788. }
  18789. function _injectSprintfProcessor() {
  18790. var values = [];
  18791. // mh: build array from second argument onwards
  18792. for (var i = 1; i < arguments.length; i++) {
  18793. values.push(arguments[i]);
  18794. }
  18795. return {
  18796. postProcess: 'sprintf',
  18797. sprintf: values
  18798. };
  18799. }
  18800. function _translate(potentialKeys, options) {
  18801. if (options && typeof options !== 'object') {
  18802. if (o.shortcutFunction === 'sprintf') {
  18803. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18804. options = _injectSprintfProcessor.apply(null, arguments);
  18805. } else if (o.shortcutFunction === 'defaultValue') {
  18806. options = {
  18807. defaultValue: options
  18808. }
  18809. }
  18810. } else {
  18811. options = options || {};
  18812. }
  18813. if (typeof o.defaultVariables === 'object') {
  18814. options = f.extend({}, o.defaultVariables, options);
  18815. }
  18816. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18817. if (typeof potentialKeys === 'string') {
  18818. potentialKeys = [potentialKeys];
  18819. }
  18820. var key = potentialKeys[0];
  18821. if (potentialKeys.length > 1) {
  18822. for (var i = 0; i < potentialKeys.length; i++) {
  18823. key = potentialKeys[i];
  18824. if (exists(key, options)) {
  18825. break;
  18826. }
  18827. }
  18828. }
  18829. var notFound = _getDefaultValue(key, options)
  18830. , found = _find(key, options)
  18831. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18832. , ns = options.ns || o.ns.defaultNs
  18833. , parts;
  18834. // split ns and key
  18835. if (key.indexOf(o.nsseparator) > -1) {
  18836. parts = key.split(o.nsseparator);
  18837. ns = parts[0];
  18838. key = parts[1];
  18839. }
  18840. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18841. if (options.lng) {
  18842. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18843. } else {
  18844. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18845. }
  18846. }
  18847. var postProcessor = options.postProcess || o.postProcess;
  18848. if (found !== undefined && postProcessor) {
  18849. if (postProcessors[postProcessor]) {
  18850. found = postProcessors[postProcessor](found, key, options);
  18851. }
  18852. }
  18853. // process notFound if function exists
  18854. var splitNotFound = notFound;
  18855. if (notFound.indexOf(o.nsseparator) > -1) {
  18856. parts = notFound.split(o.nsseparator);
  18857. splitNotFound = parts[1];
  18858. }
  18859. if (splitNotFound === key && o.parseMissingKey) {
  18860. notFound = o.parseMissingKey(notFound);
  18861. }
  18862. if (found === undefined) {
  18863. notFound = applyReplacement(notFound, options);
  18864. notFound = applyReuse(notFound, options);
  18865. if (postProcessor && postProcessors[postProcessor]) {
  18866. var val = _getDefaultValue(key, options);
  18867. found = postProcessors[postProcessor](val, key, options);
  18868. }
  18869. }
  18870. return (found !== undefined) ? found : notFound;
  18871. }
  18872. function _find(key, options) {
  18873. options = options || {};
  18874. var optionWithoutCount, translated
  18875. , notFound = _getDefaultValue(key, options)
  18876. , lngs = languages;
  18877. if (!resStore) { return notFound; } // no resStore to translate from
  18878. // CI mode
  18879. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18880. // passed in lng
  18881. if (options.lngs) lngs = options.lngs;
  18882. if (options.lng) {
  18883. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18884. if (!resStore[lngs[0]]) {
  18885. var oldAsync = o.getAsync;
  18886. o.getAsync = false;
  18887. i18n.sync.load(lngs, o, function(err, store) {
  18888. f.extend(resStore, store);
  18889. o.getAsync = oldAsync;
  18890. });
  18891. }
  18892. }
  18893. var ns = options.ns || o.ns.defaultNs;
  18894. if (key.indexOf(o.nsseparator) > -1) {
  18895. var parts = key.split(o.nsseparator);
  18896. ns = parts[0];
  18897. key = parts[1];
  18898. }
  18899. if (hasContext(options)) {
  18900. optionWithoutCount = f.extend({}, options);
  18901. delete optionWithoutCount.context;
  18902. optionWithoutCount.defaultValue = o.contextNotFound;
  18903. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18904. translated = translate(contextKey, optionWithoutCount);
  18905. if (translated != o.contextNotFound) {
  18906. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18907. } // else continue translation with original/nonContext key
  18908. }
  18909. if (needsPlural(options, lngs[0])) {
  18910. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18911. delete optionWithoutCount.count;
  18912. delete optionWithoutCount.lng;
  18913. optionWithoutCount.defaultValue = o.pluralNotFound;
  18914. var pluralKey;
  18915. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18916. pluralKey = ns + o.nsseparator + key;
  18917. } else {
  18918. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18919. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18920. if (pluralExtension >= 0) {
  18921. pluralKey = pluralKey + '_' + pluralExtension;
  18922. } else if (pluralExtension === 1) {
  18923. pluralKey = ns + o.nsseparator + key; // singular
  18924. }
  18925. }
  18926. translated = translate(pluralKey, optionWithoutCount);
  18927. if (translated != o.pluralNotFound) {
  18928. return applyReplacement(translated, {
  18929. count: options.count,
  18930. interpolationPrefix: options.interpolationPrefix,
  18931. interpolationSuffix: options.interpolationSuffix
  18932. }); // apply replacement for count only
  18933. } else if (lngs.length > 1) {
  18934. // remove failed lng
  18935. var clone = lngs.slice();
  18936. clone.shift();
  18937. options = f.extend(options, { lngs: clone });
  18938. delete options.lng;
  18939. // retry with fallbacks
  18940. translated = translate(ns + o.nsseparator + key, options);
  18941. if (translated != o.pluralNotFound) return translated;
  18942. } else {
  18943. return translated;
  18944. }
  18945. }
  18946. if (needsIndefiniteArticle(options)) {
  18947. var optionsWithoutIndef = f.extend({}, options);
  18948. delete optionsWithoutIndef.indefinite_article;
  18949. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18950. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18951. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18952. translated = translate(indefiniteKey, optionsWithoutIndef);
  18953. if (translated != o.indefiniteNotFound) {
  18954. return translated;
  18955. }
  18956. }
  18957. var found;
  18958. var keys = key.split(o.keyseparator);
  18959. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18960. if (found !== undefined) break;
  18961. var l = lngs[i];
  18962. var x = 0;
  18963. var value = resStore[l] && resStore[l][ns];
  18964. while (keys[x]) {
  18965. value = value && value[keys[x]];
  18966. x++;
  18967. }
  18968. if (value !== undefined) {
  18969. var valueType = Object.prototype.toString.apply(value);
  18970. if (typeof value === 'string') {
  18971. value = applyReplacement(value, options);
  18972. value = applyReuse(value, options);
  18973. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18974. value = value.join('\n');
  18975. value = applyReplacement(value, options);
  18976. value = applyReuse(value, options);
  18977. } else if (value === null && o.fallbackOnNull === true) {
  18978. value = undefined;
  18979. } else if (value !== null) {
  18980. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18981. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18982. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18983. } else {
  18984. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18985. 'returned an object instead of string.';
  18986. f.log(value);
  18987. }
  18988. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18989. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18990. f.each(value, function(m) {
  18991. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18992. });
  18993. value = copy;
  18994. }
  18995. }
  18996. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18997. value = undefined;
  18998. found = value;
  18999. }
  19000. }
  19001. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19002. // set flag for fallback lookup - avoid recursion
  19003. options.isFallbackLookup = true;
  19004. if (o.fallbackNS.length) {
  19005. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19006. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19007. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19008. /* compare value without namespace */
  19009. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19010. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19011. if (foundValue !== notFoundValue) break;
  19012. }
  19013. }
  19014. } else {
  19015. found = _find(key, options); // fallback to default NS
  19016. }
  19017. options.isFallbackLookup = false;
  19018. }
  19019. return found;
  19020. }
  19021. function detectLanguage() {
  19022. var detectedLng;
  19023. var whitelist = o.lngWhitelist || [];
  19024. var userLngChoices = [];
  19025. // get from qs
  19026. var qsParm = [];
  19027. if (typeof window !== 'undefined') {
  19028. (function() {
  19029. var query = window.location.search.substring(1);
  19030. var params = query.split('&');
  19031. for (var i=0; i<params.length; i++) {
  19032. var pos = params[i].indexOf('=');
  19033. if (pos > 0) {
  19034. var key = params[i].substring(0,pos);
  19035. if (key == o.detectLngQS) {
  19036. userLngChoices.push(params[i].substring(pos+1));
  19037. }
  19038. }
  19039. }
  19040. })();
  19041. }
  19042. // get from cookie
  19043. if (o.useCookie && typeof document !== 'undefined') {
  19044. var c = f.cookie.read(o.cookieName);
  19045. if (c) userLngChoices.push(c);
  19046. }
  19047. // get from localStorage
  19048. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19049. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19050. }
  19051. // get from navigator
  19052. if (typeof navigator !== 'undefined') {
  19053. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19054. for (var i=0;i<navigator.languages.length;i++) {
  19055. userLngChoices.push(navigator.languages[i]);
  19056. }
  19057. }
  19058. if (navigator.userLanguage) {
  19059. userLngChoices.push(navigator.userLanguage);
  19060. }
  19061. if (navigator.language) {
  19062. userLngChoices.push(navigator.language);
  19063. }
  19064. }
  19065. (function() {
  19066. for (var i=0;i<userLngChoices.length;i++) {
  19067. var lng = userLngChoices[i];
  19068. if (lng.indexOf('-') > -1) {
  19069. var parts = lng.split('-');
  19070. lng = o.lowerCaseLng ?
  19071. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19072. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19073. }
  19074. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19075. detectedLng = lng;
  19076. break;
  19077. }
  19078. }
  19079. })();
  19080. //fallback
  19081. if (!detectedLng){
  19082. detectedLng = o.fallbackLng[0];
  19083. }
  19084. return detectedLng;
  19085. }
  19086. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19087. /* [code, name, numbers, pluralsType] */
  19088. var _rules = [
  19089. ["ach", "Acholi", [1,2], 1],
  19090. ["af", "Afrikaans",[1,2], 2],
  19091. ["ak", "Akan", [1,2], 1],
  19092. ["am", "Amharic", [1,2], 1],
  19093. ["an", "Aragonese",[1,2], 2],
  19094. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19095. ["arn", "Mapudungun",[1,2], 1],
  19096. ["ast", "Asturian", [1,2], 2],
  19097. ["ay", "Aymará", [1], 3],
  19098. ["az", "Azerbaijani",[1,2],2],
  19099. ["be", "Belarusian",[1,2,5],4],
  19100. ["bg", "Bulgarian",[1,2], 2],
  19101. ["bn", "Bengali", [1,2], 2],
  19102. ["bo", "Tibetan", [1], 3],
  19103. ["br", "Breton", [1,2], 1],
  19104. ["bs", "Bosnian", [1,2,5],4],
  19105. ["ca", "Catalan", [1,2], 2],
  19106. ["cgg", "Chiga", [1], 3],
  19107. ["cs", "Czech", [1,2,5],6],
  19108. ["csb", "Kashubian",[1,2,5],7],
  19109. ["cy", "Welsh", [1,2,3,8],8],
  19110. ["da", "Danish", [1,2], 2],
  19111. ["de", "German", [1,2], 2],
  19112. ["dev", "Development Fallback", [1,2], 2],
  19113. ["dz", "Dzongkha", [1], 3],
  19114. ["el", "Greek", [1,2], 2],
  19115. ["en", "English", [1,2], 2],
  19116. ["eo", "Esperanto",[1,2], 2],
  19117. ["es", "Spanish", [1,2], 2],
  19118. ["es_ar","Argentinean Spanish", [1,2], 2],
  19119. ["et", "Estonian", [1,2], 2],
  19120. ["eu", "Basque", [1,2], 2],
  19121. ["fa", "Persian", [1], 3],
  19122. ["fi", "Finnish", [1,2], 2],
  19123. ["fil", "Filipino", [1,2], 1],
  19124. ["fo", "Faroese", [1,2], 2],
  19125. ["fr", "French", [1,2], 9],
  19126. ["fur", "Friulian", [1,2], 2],
  19127. ["fy", "Frisian", [1,2], 2],
  19128. ["ga", "Irish", [1,2,3,7,11],10],
  19129. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19130. ["gl", "Galician", [1,2], 2],
  19131. ["gu", "Gujarati", [1,2], 2],
  19132. ["gun", "Gun", [1,2], 1],
  19133. ["ha", "Hausa", [1,2], 2],
  19134. ["he", "Hebrew", [1,2], 2],
  19135. ["hi", "Hindi", [1,2], 2],
  19136. ["hr", "Croatian", [1,2,5],4],
  19137. ["hu", "Hungarian",[1,2], 2],
  19138. ["hy", "Armenian", [1,2], 2],
  19139. ["ia", "Interlingua",[1,2],2],
  19140. ["id", "Indonesian",[1], 3],
  19141. ["is", "Icelandic",[1,2], 12],
  19142. ["it", "Italian", [1,2], 2],
  19143. ["ja", "Japanese", [1], 3],
  19144. ["jbo", "Lojban", [1], 3],
  19145. ["jv", "Javanese", [0,1], 13],
  19146. ["ka", "Georgian", [1], 3],
  19147. ["kk", "Kazakh", [1], 3],
  19148. ["km", "Khmer", [1], 3],
  19149. ["kn", "Kannada", [1,2], 2],
  19150. ["ko", "Korean", [1], 3],
  19151. ["ku", "Kurdish", [1,2], 2],
  19152. ["kw", "Cornish", [1,2,3,4],14],
  19153. ["ky", "Kyrgyz", [1], 3],
  19154. ["lb", "Letzeburgesch",[1,2],2],
  19155. ["ln", "Lingala", [1,2], 1],
  19156. ["lo", "Lao", [1], 3],
  19157. ["lt", "Lithuanian",[1,2,10],15],
  19158. ["lv", "Latvian", [1,2,0],16],
  19159. ["mai", "Maithili", [1,2], 2],
  19160. ["mfe", "Mauritian Creole",[1,2],1],
  19161. ["mg", "Malagasy", [1,2], 1],
  19162. ["mi", "Maori", [1,2], 1],
  19163. ["mk", "Macedonian",[1,2],17],
  19164. ["ml", "Malayalam",[1,2], 2],
  19165. ["mn", "Mongolian",[1,2], 2],
  19166. ["mnk", "Mandinka", [0,1,2],18],
  19167. ["mr", "Marathi", [1,2], 2],
  19168. ["ms", "Malay", [1], 3],
  19169. ["mt", "Maltese", [1,2,11,20],19],
  19170. ["nah", "Nahuatl", [1,2], 2],
  19171. ["nap", "Neapolitan",[1,2], 2],
  19172. ["nb", "Norwegian Bokmal",[1,2],2],
  19173. ["ne", "Nepali", [1,2], 2],
  19174. ["nl", "Dutch", [1,2], 2],
  19175. ["nn", "Norwegian Nynorsk",[1,2],2],
  19176. ["no", "Norwegian",[1,2], 2],
  19177. ["nso", "Northern Sotho",[1,2],2],
  19178. ["oc", "Occitan", [1,2], 1],
  19179. ["or", "Oriya", [2,1], 2],
  19180. ["pa", "Punjabi", [1,2], 2],
  19181. ["pap", "Papiamento",[1,2], 2],
  19182. ["pl", "Polish", [1,2,5],7],
  19183. ["pms", "Piemontese",[1,2], 2],
  19184. ["ps", "Pashto", [1,2], 2],
  19185. ["pt", "Portuguese",[1,2], 2],
  19186. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19187. ["rm", "Romansh", [1,2], 2],
  19188. ["ro", "Romanian", [1,2,20],20],
  19189. ["ru", "Russian", [1,2,5],4],
  19190. ["sah", "Yakut", [1], 3],
  19191. ["sco", "Scots", [1,2], 2],
  19192. ["se", "Northern Sami",[1,2], 2],
  19193. ["si", "Sinhala", [1,2], 2],
  19194. ["sk", "Slovak", [1,2,5],6],
  19195. ["sl", "Slovenian",[5,1,2,3],21],
  19196. ["so", "Somali", [1,2], 2],
  19197. ["son", "Songhay", [1,2], 2],
  19198. ["sq", "Albanian", [1,2], 2],
  19199. ["sr", "Serbian", [1,2,5],4],
  19200. ["su", "Sundanese",[1], 3],
  19201. ["sv", "Swedish", [1,2], 2],
  19202. ["sw", "Swahili", [1,2], 2],
  19203. ["ta", "Tamil", [1,2], 2],
  19204. ["te", "Telugu", [1,2], 2],
  19205. ["tg", "Tajik", [1,2], 1],
  19206. ["th", "Thai", [1], 3],
  19207. ["ti", "Tigrinya", [1,2], 1],
  19208. ["tk", "Turkmen", [1,2], 2],
  19209. ["tr", "Turkish", [1,2], 1],
  19210. ["tt", "Tatar", [1], 3],
  19211. ["ug", "Uyghur", [1], 3],
  19212. ["uk", "Ukrainian",[1,2,5],4],
  19213. ["ur", "Urdu", [1,2], 2],
  19214. ["uz", "Uzbek", [1,2], 1],
  19215. ["vi", "Vietnamese",[1], 3],
  19216. ["wa", "Walloon", [1,2], 1],
  19217. ["wo", "Wolof", [1], 3],
  19218. ["yo", "Yoruba", [1,2], 2],
  19219. ["zh", "Chinese", [1], 3]
  19220. ];
  19221. var _rulesPluralsTypes = {
  19222. 1: function(n) {return Number(n > 1);},
  19223. 2: function(n) {return Number(n != 1);},
  19224. 3: function(n) {return 0;},
  19225. 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);},
  19226. 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);},
  19227. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19228. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19229. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19230. 9: function(n) {return Number(n >= 2);},
  19231. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19232. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19233. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19234. 13: function(n) {return Number(n !== 0);},
  19235. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19236. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19237. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19238. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19239. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19240. 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);},
  19241. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19242. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19243. };
  19244. var pluralExtensions = {
  19245. rules: (function () {
  19246. var l, rules = {};
  19247. for (l=_rules.length; l-- ;) {
  19248. rules[_rules[l][0]] = {
  19249. name: _rules[l][1],
  19250. numbers: _rules[l][2],
  19251. plurals: _rulesPluralsTypes[_rules[l][3]]
  19252. }
  19253. }
  19254. return rules;
  19255. }()),
  19256. // you can add your own pluralExtensions
  19257. addRule: function(lng, obj) {
  19258. pluralExtensions.rules[lng] = obj;
  19259. },
  19260. setCurrentLng: function(lng) {
  19261. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19262. var parts = lng.split('-');
  19263. pluralExtensions.currentRule = {
  19264. lng: lng,
  19265. rule: pluralExtensions.rules[parts[0]]
  19266. };
  19267. }
  19268. },
  19269. needsPlural: function(lng, count) {
  19270. var parts = lng.split('-');
  19271. var ext;
  19272. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19273. ext = pluralExtensions.currentRule.rule;
  19274. } else {
  19275. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19276. }
  19277. if (ext && ext.numbers.length <= 1) {
  19278. return false;
  19279. } else {
  19280. return this.get(lng, count) !== 1;
  19281. }
  19282. },
  19283. get: function(lng, count) {
  19284. var parts = lng.split('-');
  19285. function getResult(l, c) {
  19286. var ext;
  19287. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19288. ext = pluralExtensions.currentRule.rule;
  19289. } else {
  19290. ext = pluralExtensions.rules[l];
  19291. }
  19292. if (ext) {
  19293. var i;
  19294. if (ext.noAbs) {
  19295. i = ext.plurals(c);
  19296. } else {
  19297. i = ext.plurals(Math.abs(c));
  19298. }
  19299. var number = ext.numbers[i];
  19300. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19301. if (number === 2) {
  19302. number = -1; // regular plural
  19303. } else if (number === 1) {
  19304. number = 1; // singular
  19305. }
  19306. }//console.log(count + '-' + number);
  19307. return number;
  19308. } else {
  19309. return c === 1 ? '1' : '-1';
  19310. }
  19311. }
  19312. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19313. }
  19314. };
  19315. var postProcessors = {};
  19316. var addPostProcessor = function(name, fc) {
  19317. postProcessors[name] = fc;
  19318. };
  19319. // sprintf support
  19320. var sprintf = (function() {
  19321. function get_type(variable) {
  19322. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19323. }
  19324. function str_repeat(input, multiplier) {
  19325. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19326. return output.join('');
  19327. }
  19328. var str_format = function() {
  19329. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19330. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19331. }
  19332. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19333. };
  19334. str_format.format = function(parse_tree, argv) {
  19335. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19336. for (i = 0; i < tree_length; i++) {
  19337. node_type = get_type(parse_tree[i]);
  19338. if (node_type === 'string') {
  19339. output.push(parse_tree[i]);
  19340. }
  19341. else if (node_type === 'array') {
  19342. match = parse_tree[i]; // convenience purposes only
  19343. if (match[2]) { // keyword argument
  19344. arg = argv[cursor];
  19345. for (k = 0; k < match[2].length; k++) {
  19346. if (!arg.hasOwnProperty(match[2][k])) {
  19347. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19348. }
  19349. arg = arg[match[2][k]];
  19350. }
  19351. }
  19352. else if (match[1]) { // positional argument (explicit)
  19353. arg = argv[match[1]];
  19354. }
  19355. else { // positional argument (implicit)
  19356. arg = argv[cursor++];
  19357. }
  19358. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19359. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19360. }
  19361. switch (match[8]) {
  19362. case 'b': arg = arg.toString(2); break;
  19363. case 'c': arg = String.fromCharCode(arg); break;
  19364. case 'd': arg = parseInt(arg, 10); break;
  19365. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19366. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19367. case 'o': arg = arg.toString(8); break;
  19368. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19369. case 'u': arg = Math.abs(arg); break;
  19370. case 'x': arg = arg.toString(16); break;
  19371. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19372. }
  19373. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19374. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19375. pad_length = match[6] - String(arg).length;
  19376. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19377. output.push(match[5] ? arg + pad : pad + arg);
  19378. }
  19379. }
  19380. return output.join('');
  19381. };
  19382. str_format.cache = {};
  19383. str_format.parse = function(fmt) {
  19384. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19385. while (_fmt) {
  19386. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19387. parse_tree.push(match[0]);
  19388. }
  19389. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19390. parse_tree.push('%');
  19391. }
  19392. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19393. if (match[2]) {
  19394. arg_names |= 1;
  19395. var field_list = [], replacement_field = match[2], field_match = [];
  19396. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19397. field_list.push(field_match[1]);
  19398. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19399. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19400. field_list.push(field_match[1]);
  19401. }
  19402. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19403. field_list.push(field_match[1]);
  19404. }
  19405. else {
  19406. throw('[sprintf] huh?');
  19407. }
  19408. }
  19409. }
  19410. else {
  19411. throw('[sprintf] huh?');
  19412. }
  19413. match[2] = field_list;
  19414. }
  19415. else {
  19416. arg_names |= 2;
  19417. }
  19418. if (arg_names === 3) {
  19419. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  19420. }
  19421. parse_tree.push(match);
  19422. }
  19423. else {
  19424. throw('[sprintf] huh?');
  19425. }
  19426. _fmt = _fmt.substring(match[0].length);
  19427. }
  19428. return parse_tree;
  19429. };
  19430. return str_format;
  19431. })();
  19432. var vsprintf = function(fmt, argv) {
  19433. argv.unshift(fmt);
  19434. return sprintf.apply(null, argv);
  19435. };
  19436. addPostProcessor("sprintf", function(val, key, opts) {
  19437. if (!opts.sprintf) return val;
  19438. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  19439. return vsprintf(val, opts.sprintf);
  19440. } else if (typeof opts.sprintf === 'object') {
  19441. return sprintf(val, opts.sprintf);
  19442. }
  19443. return val;
  19444. });
  19445. // public api interface
  19446. i18n.init = init;
  19447. i18n.setLng = setLng;
  19448. i18n.preload = preload;
  19449. i18n.addResourceBundle = addResourceBundle;
  19450. i18n.hasResourceBundle = hasResourceBundle;
  19451. i18n.addResource = addResource;
  19452. i18n.addResources = addResources;
  19453. i18n.removeResourceBundle = removeResourceBundle;
  19454. i18n.loadNamespace = loadNamespace;
  19455. i18n.loadNamespaces = loadNamespaces;
  19456. i18n.setDefaultNamespace = setDefaultNamespace;
  19457. i18n.t = translate;
  19458. i18n.translate = translate;
  19459. i18n.exists = exists;
  19460. i18n.detectLanguage = f.detectLanguage;
  19461. i18n.pluralExtensions = pluralExtensions;
  19462. i18n.sync = sync;
  19463. i18n.functions = f;
  19464. i18n.lng = lng;
  19465. i18n.addPostProcessor = addPostProcessor;
  19466. i18n.options = o;
  19467. })();
  19468. },{"jquery":"jquery"}],71:[function(require,module,exports){
  19469. // Top level file is just a mixin of submodules & constants
  19470. 'use strict';
  19471. var assign = require('./lib/utils/common').assign;
  19472. var deflate = require('./lib/deflate');
  19473. var inflate = require('./lib/inflate');
  19474. var constants = require('./lib/zlib/constants');
  19475. var pako = {};
  19476. assign(pako, deflate, inflate, constants);
  19477. module.exports = pako;
  19478. },{"./lib/deflate":72,"./lib/inflate":73,"./lib/utils/common":74,"./lib/zlib/constants":77}],72:[function(require,module,exports){
  19479. 'use strict';
  19480. var zlib_deflate = require('./zlib/deflate.js');
  19481. var utils = require('./utils/common');
  19482. var strings = require('./utils/strings');
  19483. var msg = require('./zlib/messages');
  19484. var zstream = require('./zlib/zstream');
  19485. var toString = Object.prototype.toString;
  19486. /* Public constants ==========================================================*/
  19487. /* ===========================================================================*/
  19488. var Z_NO_FLUSH = 0;
  19489. var Z_FINISH = 4;
  19490. var Z_OK = 0;
  19491. var Z_STREAM_END = 1;
  19492. var Z_SYNC_FLUSH = 2;
  19493. var Z_DEFAULT_COMPRESSION = -1;
  19494. var Z_DEFAULT_STRATEGY = 0;
  19495. var Z_DEFLATED = 8;
  19496. /* ===========================================================================*/
  19497. /**
  19498. * class Deflate
  19499. *
  19500. * Generic JS-style wrapper for zlib calls. If you don't need
  19501. * streaming behaviour - use more simple functions: [[deflate]],
  19502. * [[deflateRaw]] and [[gzip]].
  19503. **/
  19504. /* internal
  19505. * Deflate.chunks -> Array
  19506. *
  19507. * Chunks of output data, if [[Deflate#onData]] not overriden.
  19508. **/
  19509. /**
  19510. * Deflate.result -> Uint8Array|Array
  19511. *
  19512. * Compressed result, generated by default [[Deflate#onData]]
  19513. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  19514. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  19515. * push a chunk with explicit flush (call [[Deflate#push]] with
  19516. * `Z_SYNC_FLUSH` param).
  19517. **/
  19518. /**
  19519. * Deflate.err -> Number
  19520. *
  19521. * Error code after deflate finished. 0 (Z_OK) on success.
  19522. * You will not need it in real life, because deflate errors
  19523. * are possible only on wrong options or bad `onData` / `onEnd`
  19524. * custom handlers.
  19525. **/
  19526. /**
  19527. * Deflate.msg -> String
  19528. *
  19529. * Error message, if [[Deflate.err]] != 0
  19530. **/
  19531. /**
  19532. * new Deflate(options)
  19533. * - options (Object): zlib deflate options.
  19534. *
  19535. * Creates new deflator instance with specified params. Throws exception
  19536. * on bad params. Supported options:
  19537. *
  19538. * - `level`
  19539. * - `windowBits`
  19540. * - `memLevel`
  19541. * - `strategy`
  19542. *
  19543. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19544. * for more information on these.
  19545. *
  19546. * Additional options, for internal needs:
  19547. *
  19548. * - `chunkSize` - size of generated data chunks (16K by default)
  19549. * - `raw` (Boolean) - do raw deflate
  19550. * - `gzip` (Boolean) - create gzip wrapper
  19551. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19552. * (each char code [0..255])
  19553. * - `header` (Object) - custom header for gzip
  19554. * - `text` (Boolean) - true if compressed data believed to be text
  19555. * - `time` (Number) - modification time, unix timestamp
  19556. * - `os` (Number) - operation system code
  19557. * - `extra` (Array) - array of bytes with extra data (max 65536)
  19558. * - `name` (String) - file name (binary string)
  19559. * - `comment` (String) - comment (binary string)
  19560. * - `hcrc` (Boolean) - true if header crc should be added
  19561. *
  19562. * ##### Example:
  19563. *
  19564. * ```javascript
  19565. * var pako = require('pako')
  19566. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19567. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19568. *
  19569. * var deflate = new pako.Deflate({ level: 3});
  19570. *
  19571. * deflate.push(chunk1, false);
  19572. * deflate.push(chunk2, true); // true -> last chunk
  19573. *
  19574. * if (deflate.err) { throw new Error(deflate.err); }
  19575. *
  19576. * console.log(deflate.result);
  19577. * ```
  19578. **/
  19579. var Deflate = function(options) {
  19580. this.options = utils.assign({
  19581. level: Z_DEFAULT_COMPRESSION,
  19582. method: Z_DEFLATED,
  19583. chunkSize: 16384,
  19584. windowBits: 15,
  19585. memLevel: 8,
  19586. strategy: Z_DEFAULT_STRATEGY,
  19587. to: ''
  19588. }, options || {});
  19589. var opt = this.options;
  19590. if (opt.raw && (opt.windowBits > 0)) {
  19591. opt.windowBits = -opt.windowBits;
  19592. }
  19593. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  19594. opt.windowBits += 16;
  19595. }
  19596. this.err = 0; // error code, if happens (0 = Z_OK)
  19597. this.msg = ''; // error message
  19598. this.ended = false; // used to avoid multiple onEnd() calls
  19599. this.chunks = []; // chunks of compressed data
  19600. this.strm = new zstream();
  19601. this.strm.avail_out = 0;
  19602. var status = zlib_deflate.deflateInit2(
  19603. this.strm,
  19604. opt.level,
  19605. opt.method,
  19606. opt.windowBits,
  19607. opt.memLevel,
  19608. opt.strategy
  19609. );
  19610. if (status !== Z_OK) {
  19611. throw new Error(msg[status]);
  19612. }
  19613. if (opt.header) {
  19614. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  19615. }
  19616. };
  19617. /**
  19618. * Deflate#push(data[, mode]) -> Boolean
  19619. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  19620. * converted to utf8 byte sequence.
  19621. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19622. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19623. *
  19624. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  19625. * new compressed chunks. Returns `true` on success. The last data block must have
  19626. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19627. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19628. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  19629. *
  19630. * On fail call [[Deflate#onEnd]] with error code and return false.
  19631. *
  19632. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19633. * array format is detected automatically). Also, don't skip last param and always
  19634. * use the same type in your code (boolean or number). That will improve JS speed.
  19635. *
  19636. * For regular `Array`-s make sure all elements are [0..255].
  19637. *
  19638. * ##### Example
  19639. *
  19640. * ```javascript
  19641. * push(chunk, false); // push one of data chunks
  19642. * ...
  19643. * push(chunk, true); // push last chunk
  19644. * ```
  19645. **/
  19646. Deflate.prototype.push = function(data, mode) {
  19647. var strm = this.strm;
  19648. var chunkSize = this.options.chunkSize;
  19649. var status, _mode;
  19650. if (this.ended) { return false; }
  19651. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  19652. // Convert data if needed
  19653. if (typeof data === 'string') {
  19654. // If we need to compress text, change encoding to utf8.
  19655. strm.input = strings.string2buf(data);
  19656. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19657. strm.input = new Uint8Array(data);
  19658. } else {
  19659. strm.input = data;
  19660. }
  19661. strm.next_in = 0;
  19662. strm.avail_in = strm.input.length;
  19663. do {
  19664. if (strm.avail_out === 0) {
  19665. strm.output = new utils.Buf8(chunkSize);
  19666. strm.next_out = 0;
  19667. strm.avail_out = chunkSize;
  19668. }
  19669. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  19670. if (status !== Z_STREAM_END && status !== Z_OK) {
  19671. this.onEnd(status);
  19672. this.ended = true;
  19673. return false;
  19674. }
  19675. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  19676. if (this.options.to === 'string') {
  19677. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  19678. } else {
  19679. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19680. }
  19681. }
  19682. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  19683. // Finalize on the last chunk.
  19684. if (_mode === Z_FINISH) {
  19685. status = zlib_deflate.deflateEnd(this.strm);
  19686. this.onEnd(status);
  19687. this.ended = true;
  19688. return status === Z_OK;
  19689. }
  19690. // callback interim results if Z_SYNC_FLUSH.
  19691. if (_mode === Z_SYNC_FLUSH) {
  19692. this.onEnd(Z_OK);
  19693. strm.avail_out = 0;
  19694. return true;
  19695. }
  19696. return true;
  19697. };
  19698. /**
  19699. * Deflate#onData(chunk) -> Void
  19700. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19701. * on js engine support. When string output requested, each chunk
  19702. * will be string.
  19703. *
  19704. * By default, stores data blocks in `chunks[]` property and glue
  19705. * those in `onEnd`. Override this handler, if you need another behaviour.
  19706. **/
  19707. Deflate.prototype.onData = function(chunk) {
  19708. this.chunks.push(chunk);
  19709. };
  19710. /**
  19711. * Deflate#onEnd(status) -> Void
  19712. * - status (Number): deflate status. 0 (Z_OK) on success,
  19713. * other if not.
  19714. *
  19715. * Called once after you tell deflate that the input stream is
  19716. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  19717. * or if an error happened. By default - join collected chunks,
  19718. * free memory and fill `results` / `err` properties.
  19719. **/
  19720. Deflate.prototype.onEnd = function(status) {
  19721. // On success - join
  19722. if (status === Z_OK) {
  19723. if (this.options.to === 'string') {
  19724. this.result = this.chunks.join('');
  19725. } else {
  19726. this.result = utils.flattenChunks(this.chunks);
  19727. }
  19728. }
  19729. this.chunks = [];
  19730. this.err = status;
  19731. this.msg = this.strm.msg;
  19732. };
  19733. /**
  19734. * deflate(data[, options]) -> Uint8Array|Array|String
  19735. * - data (Uint8Array|Array|String): input data to compress.
  19736. * - options (Object): zlib deflate options.
  19737. *
  19738. * Compress `data` with deflate alrorythm and `options`.
  19739. *
  19740. * Supported options are:
  19741. *
  19742. * - level
  19743. * - windowBits
  19744. * - memLevel
  19745. * - strategy
  19746. *
  19747. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19748. * for more information on these.
  19749. *
  19750. * Sugar (options):
  19751. *
  19752. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19753. * negative windowBits implicitly.
  19754. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19755. * (each char code [0..255])
  19756. *
  19757. * ##### Example:
  19758. *
  19759. * ```javascript
  19760. * var pako = require('pako')
  19761. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19762. *
  19763. * console.log(pako.deflate(data));
  19764. * ```
  19765. **/
  19766. function deflate(input, options) {
  19767. var deflator = new Deflate(options);
  19768. deflator.push(input, true);
  19769. // That will never happens, if you don't cheat with options :)
  19770. if (deflator.err) { throw deflator.msg; }
  19771. return deflator.result;
  19772. }
  19773. /**
  19774. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19775. * - data (Uint8Array|Array|String): input data to compress.
  19776. * - options (Object): zlib deflate options.
  19777. *
  19778. * The same as [[deflate]], but creates raw data, without wrapper
  19779. * (header and adler32 crc).
  19780. **/
  19781. function deflateRaw(input, options) {
  19782. options = options || {};
  19783. options.raw = true;
  19784. return deflate(input, options);
  19785. }
  19786. /**
  19787. * gzip(data[, options]) -> Uint8Array|Array|String
  19788. * - data (Uint8Array|Array|String): input data to compress.
  19789. * - options (Object): zlib deflate options.
  19790. *
  19791. * The same as [[deflate]], but create gzip wrapper instead of
  19792. * deflate one.
  19793. **/
  19794. function gzip(input, options) {
  19795. options = options || {};
  19796. options.gzip = true;
  19797. return deflate(input, options);
  19798. }
  19799. exports.Deflate = Deflate;
  19800. exports.deflate = deflate;
  19801. exports.deflateRaw = deflateRaw;
  19802. exports.gzip = gzip;
  19803. },{"./utils/common":74,"./utils/strings":75,"./zlib/deflate.js":79,"./zlib/messages":84,"./zlib/zstream":86}],73:[function(require,module,exports){
  19804. 'use strict';
  19805. var zlib_inflate = require('./zlib/inflate.js');
  19806. var utils = require('./utils/common');
  19807. var strings = require('./utils/strings');
  19808. var c = require('./zlib/constants');
  19809. var msg = require('./zlib/messages');
  19810. var zstream = require('./zlib/zstream');
  19811. var gzheader = require('./zlib/gzheader');
  19812. var toString = Object.prototype.toString;
  19813. /**
  19814. * class Inflate
  19815. *
  19816. * Generic JS-style wrapper for zlib calls. If you don't need
  19817. * streaming behaviour - use more simple functions: [[inflate]]
  19818. * and [[inflateRaw]].
  19819. **/
  19820. /* internal
  19821. * inflate.chunks -> Array
  19822. *
  19823. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19824. **/
  19825. /**
  19826. * Inflate.result -> Uint8Array|Array|String
  19827. *
  19828. * Uncompressed result, generated by default [[Inflate#onData]]
  19829. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19830. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  19831. * push a chunk with explicit flush (call [[Inflate#push]] with
  19832. * `Z_SYNC_FLUSH` param).
  19833. **/
  19834. /**
  19835. * Inflate.err -> Number
  19836. *
  19837. * Error code after inflate finished. 0 (Z_OK) on success.
  19838. * Should be checked if broken data possible.
  19839. **/
  19840. /**
  19841. * Inflate.msg -> String
  19842. *
  19843. * Error message, if [[Inflate.err]] != 0
  19844. **/
  19845. /**
  19846. * new Inflate(options)
  19847. * - options (Object): zlib inflate options.
  19848. *
  19849. * Creates new inflator instance with specified params. Throws exception
  19850. * on bad params. Supported options:
  19851. *
  19852. * - `windowBits`
  19853. *
  19854. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19855. * for more information on these.
  19856. *
  19857. * Additional options, for internal needs:
  19858. *
  19859. * - `chunkSize` - size of generated data chunks (16K by default)
  19860. * - `raw` (Boolean) - do raw inflate
  19861. * - `to` (String) - if equal to 'string', then result will be converted
  19862. * from utf8 to utf16 (javascript) string. When string output requested,
  19863. * chunk length can differ from `chunkSize`, depending on content.
  19864. *
  19865. * By default, when no options set, autodetect deflate/gzip data format via
  19866. * wrapper header.
  19867. *
  19868. * ##### Example:
  19869. *
  19870. * ```javascript
  19871. * var pako = require('pako')
  19872. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19873. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19874. *
  19875. * var inflate = new pako.Inflate({ level: 3});
  19876. *
  19877. * inflate.push(chunk1, false);
  19878. * inflate.push(chunk2, true); // true -> last chunk
  19879. *
  19880. * if (inflate.err) { throw new Error(inflate.err); }
  19881. *
  19882. * console.log(inflate.result);
  19883. * ```
  19884. **/
  19885. var Inflate = function(options) {
  19886. this.options = utils.assign({
  19887. chunkSize: 16384,
  19888. windowBits: 0,
  19889. to: ''
  19890. }, options || {});
  19891. var opt = this.options;
  19892. // Force window size for `raw` data, if not set directly,
  19893. // because we have no header for autodetect.
  19894. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19895. opt.windowBits = -opt.windowBits;
  19896. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19897. }
  19898. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19899. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19900. !(options && options.windowBits)) {
  19901. opt.windowBits += 32;
  19902. }
  19903. // Gzip header has no info about windows size, we can do autodetect only
  19904. // for deflate. So, if window size not set, force it to max when gzip possible
  19905. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19906. // bit 3 (16) -> gzipped data
  19907. // bit 4 (32) -> autodetect gzip/deflate
  19908. if ((opt.windowBits & 15) === 0) {
  19909. opt.windowBits |= 15;
  19910. }
  19911. }
  19912. this.err = 0; // error code, if happens (0 = Z_OK)
  19913. this.msg = ''; // error message
  19914. this.ended = false; // used to avoid multiple onEnd() calls
  19915. this.chunks = []; // chunks of compressed data
  19916. this.strm = new zstream();
  19917. this.strm.avail_out = 0;
  19918. var status = zlib_inflate.inflateInit2(
  19919. this.strm,
  19920. opt.windowBits
  19921. );
  19922. if (status !== c.Z_OK) {
  19923. throw new Error(msg[status]);
  19924. }
  19925. this.header = new gzheader();
  19926. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19927. };
  19928. /**
  19929. * Inflate#push(data[, mode]) -> Boolean
  19930. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19931. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19932. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19933. *
  19934. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19935. * new output chunks. Returns `true` on success. The last data block must have
  19936. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  19937. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  19938. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  19939. *
  19940. * On fail call [[Inflate#onEnd]] with error code and return false.
  19941. *
  19942. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19943. * format is detected automatically). Also, don't skip last param and always
  19944. * use the same type in your code (boolean or number). That will improve JS speed.
  19945. *
  19946. * For regular `Array`-s make sure all elements are [0..255].
  19947. *
  19948. * ##### Example
  19949. *
  19950. * ```javascript
  19951. * push(chunk, false); // push one of data chunks
  19952. * ...
  19953. * push(chunk, true); // push last chunk
  19954. * ```
  19955. **/
  19956. Inflate.prototype.push = function(data, mode) {
  19957. var strm = this.strm;
  19958. var chunkSize = this.options.chunkSize;
  19959. var status, _mode;
  19960. var next_out_utf8, tail, utf8str;
  19961. if (this.ended) { return false; }
  19962. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19963. // Convert data if needed
  19964. if (typeof data === 'string') {
  19965. // Only binary strings can be decompressed on practice
  19966. strm.input = strings.binstring2buf(data);
  19967. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19968. strm.input = new Uint8Array(data);
  19969. } else {
  19970. strm.input = data;
  19971. }
  19972. strm.next_in = 0;
  19973. strm.avail_in = strm.input.length;
  19974. do {
  19975. if (strm.avail_out === 0) {
  19976. strm.output = new utils.Buf8(chunkSize);
  19977. strm.next_out = 0;
  19978. strm.avail_out = chunkSize;
  19979. }
  19980. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19981. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19982. this.onEnd(status);
  19983. this.ended = true;
  19984. return false;
  19985. }
  19986. if (strm.next_out) {
  19987. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  19988. if (this.options.to === 'string') {
  19989. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19990. tail = strm.next_out - next_out_utf8;
  19991. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19992. // move tail
  19993. strm.next_out = tail;
  19994. strm.avail_out = chunkSize - tail;
  19995. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19996. this.onData(utf8str);
  19997. } else {
  19998. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19999. }
  20000. }
  20001. }
  20002. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20003. if (status === c.Z_STREAM_END) {
  20004. _mode = c.Z_FINISH;
  20005. }
  20006. // Finalize on the last chunk.
  20007. if (_mode === c.Z_FINISH) {
  20008. status = zlib_inflate.inflateEnd(this.strm);
  20009. this.onEnd(status);
  20010. this.ended = true;
  20011. return status === c.Z_OK;
  20012. }
  20013. // callback interim results if Z_SYNC_FLUSH.
  20014. if (_mode === c.Z_SYNC_FLUSH) {
  20015. this.onEnd(c.Z_OK);
  20016. strm.avail_out = 0;
  20017. return true;
  20018. }
  20019. return true;
  20020. };
  20021. /**
  20022. * Inflate#onData(chunk) -> Void
  20023. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20024. * on js engine support. When string output requested, each chunk
  20025. * will be string.
  20026. *
  20027. * By default, stores data blocks in `chunks[]` property and glue
  20028. * those in `onEnd`. Override this handler, if you need another behaviour.
  20029. **/
  20030. Inflate.prototype.onData = function(chunk) {
  20031. this.chunks.push(chunk);
  20032. };
  20033. /**
  20034. * Inflate#onEnd(status) -> Void
  20035. * - status (Number): inflate status. 0 (Z_OK) on success,
  20036. * other if not.
  20037. *
  20038. * Called either after you tell inflate that the input stream is
  20039. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20040. * or if an error happened. By default - join collected chunks,
  20041. * free memory and fill `results` / `err` properties.
  20042. **/
  20043. Inflate.prototype.onEnd = function(status) {
  20044. // On success - join
  20045. if (status === c.Z_OK) {
  20046. if (this.options.to === 'string') {
  20047. // Glue & convert here, until we teach pako to send
  20048. // utf8 alligned strings to onData
  20049. this.result = this.chunks.join('');
  20050. } else {
  20051. this.result = utils.flattenChunks(this.chunks);
  20052. }
  20053. }
  20054. this.chunks = [];
  20055. this.err = status;
  20056. this.msg = this.strm.msg;
  20057. };
  20058. /**
  20059. * inflate(data[, options]) -> Uint8Array|Array|String
  20060. * - data (Uint8Array|Array|String): input data to decompress.
  20061. * - options (Object): zlib inflate options.
  20062. *
  20063. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20064. * format via wrapper header by default. That's why we don't provide
  20065. * separate `ungzip` method.
  20066. *
  20067. * Supported options are:
  20068. *
  20069. * - windowBits
  20070. *
  20071. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20072. * for more information.
  20073. *
  20074. * Sugar (options):
  20075. *
  20076. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20077. * negative windowBits implicitly.
  20078. * - `to` (String) - if equal to 'string', then result will be converted
  20079. * from utf8 to utf16 (javascript) string. When string output requested,
  20080. * chunk length can differ from `chunkSize`, depending on content.
  20081. *
  20082. *
  20083. * ##### Example:
  20084. *
  20085. * ```javascript
  20086. * var pako = require('pako')
  20087. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20088. * , output;
  20089. *
  20090. * try {
  20091. * output = pako.inflate(input);
  20092. * } catch (err)
  20093. * console.log(err);
  20094. * }
  20095. * ```
  20096. **/
  20097. function inflate(input, options) {
  20098. var inflator = new Inflate(options);
  20099. inflator.push(input, true);
  20100. // That will never happens, if you don't cheat with options :)
  20101. if (inflator.err) { throw inflator.msg; }
  20102. return inflator.result;
  20103. }
  20104. /**
  20105. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20106. * - data (Uint8Array|Array|String): input data to decompress.
  20107. * - options (Object): zlib inflate options.
  20108. *
  20109. * The same as [[inflate]], but creates raw data, without wrapper
  20110. * (header and adler32 crc).
  20111. **/
  20112. function inflateRaw(input, options) {
  20113. options = options || {};
  20114. options.raw = true;
  20115. return inflate(input, options);
  20116. }
  20117. /**
  20118. * ungzip(data[, options]) -> Uint8Array|Array|String
  20119. * - data (Uint8Array|Array|String): input data to decompress.
  20120. * - options (Object): zlib inflate options.
  20121. *
  20122. * Just shortcut to [[inflate]], because it autodetects format
  20123. * by header.content. Done for convenience.
  20124. **/
  20125. exports.Inflate = Inflate;
  20126. exports.inflate = inflate;
  20127. exports.inflateRaw = inflateRaw;
  20128. exports.ungzip = inflate;
  20129. },{"./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){
  20130. 'use strict';
  20131. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20132. (typeof Uint16Array !== 'undefined') &&
  20133. (typeof Int32Array !== 'undefined');
  20134. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20135. var sources = Array.prototype.slice.call(arguments, 1);
  20136. while (sources.length) {
  20137. var source = sources.shift();
  20138. if (!source) { continue; }
  20139. if (typeof source !== 'object') {
  20140. throw new TypeError(source + 'must be non-object');
  20141. }
  20142. for (var p in source) {
  20143. if (source.hasOwnProperty(p)) {
  20144. obj[p] = source[p];
  20145. }
  20146. }
  20147. }
  20148. return obj;
  20149. };
  20150. // reduce buffer size, avoiding mem copy
  20151. exports.shrinkBuf = function (buf, size) {
  20152. if (buf.length === size) { return buf; }
  20153. if (buf.subarray) { return buf.subarray(0, size); }
  20154. buf.length = size;
  20155. return buf;
  20156. };
  20157. var fnTyped = {
  20158. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20159. if (src.subarray && dest.subarray) {
  20160. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20161. return;
  20162. }
  20163. // Fallback to ordinary array
  20164. for (var i=0; i<len; i++) {
  20165. dest[dest_offs + i] = src[src_offs + i];
  20166. }
  20167. },
  20168. // Join array of chunks to single array.
  20169. flattenChunks: function(chunks) {
  20170. var i, l, len, pos, chunk, result;
  20171. // calculate data length
  20172. len = 0;
  20173. for (i=0, l=chunks.length; i<l; i++) {
  20174. len += chunks[i].length;
  20175. }
  20176. // join chunks
  20177. result = new Uint8Array(len);
  20178. pos = 0;
  20179. for (i=0, l=chunks.length; i<l; i++) {
  20180. chunk = chunks[i];
  20181. result.set(chunk, pos);
  20182. pos += chunk.length;
  20183. }
  20184. return result;
  20185. }
  20186. };
  20187. var fnUntyped = {
  20188. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20189. for (var i=0; i<len; i++) {
  20190. dest[dest_offs + i] = src[src_offs + i];
  20191. }
  20192. },
  20193. // Join array of chunks to single array.
  20194. flattenChunks: function(chunks) {
  20195. return [].concat.apply([], chunks);
  20196. }
  20197. };
  20198. // Enable/Disable typed arrays use, for testing
  20199. //
  20200. exports.setTyped = function (on) {
  20201. if (on) {
  20202. exports.Buf8 = Uint8Array;
  20203. exports.Buf16 = Uint16Array;
  20204. exports.Buf32 = Int32Array;
  20205. exports.assign(exports, fnTyped);
  20206. } else {
  20207. exports.Buf8 = Array;
  20208. exports.Buf16 = Array;
  20209. exports.Buf32 = Array;
  20210. exports.assign(exports, fnUntyped);
  20211. }
  20212. };
  20213. exports.setTyped(TYPED_OK);
  20214. },{}],75:[function(require,module,exports){
  20215. // String encode/decode helpers
  20216. 'use strict';
  20217. var utils = require('./common');
  20218. // Quick check if we can use fast array to bin string conversion
  20219. //
  20220. // - apply(Array) can fail on Android 2.2
  20221. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20222. //
  20223. var STR_APPLY_OK = true;
  20224. var STR_APPLY_UIA_OK = true;
  20225. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20226. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20227. // Table with utf8 lengths (calculated by first byte of sequence)
  20228. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20229. // because max possible codepoint is 0x10ffff
  20230. var _utf8len = new utils.Buf8(256);
  20231. for (var q=0; q<256; q++) {
  20232. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20233. }
  20234. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20235. // convert string to array (typed, when possible)
  20236. exports.string2buf = function (str) {
  20237. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20238. // count binary size
  20239. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20240. c = str.charCodeAt(m_pos);
  20241. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20242. c2 = str.charCodeAt(m_pos+1);
  20243. if ((c2 & 0xfc00) === 0xdc00) {
  20244. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20245. m_pos++;
  20246. }
  20247. }
  20248. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20249. }
  20250. // allocate buffer
  20251. buf = new utils.Buf8(buf_len);
  20252. // convert
  20253. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20254. c = str.charCodeAt(m_pos);
  20255. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20256. c2 = str.charCodeAt(m_pos+1);
  20257. if ((c2 & 0xfc00) === 0xdc00) {
  20258. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20259. m_pos++;
  20260. }
  20261. }
  20262. if (c < 0x80) {
  20263. /* one byte */
  20264. buf[i++] = c;
  20265. } else if (c < 0x800) {
  20266. /* two bytes */
  20267. buf[i++] = 0xC0 | (c >>> 6);
  20268. buf[i++] = 0x80 | (c & 0x3f);
  20269. } else if (c < 0x10000) {
  20270. /* three bytes */
  20271. buf[i++] = 0xE0 | (c >>> 12);
  20272. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20273. buf[i++] = 0x80 | (c & 0x3f);
  20274. } else {
  20275. /* four bytes */
  20276. buf[i++] = 0xf0 | (c >>> 18);
  20277. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20278. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20279. buf[i++] = 0x80 | (c & 0x3f);
  20280. }
  20281. }
  20282. return buf;
  20283. };
  20284. // Helper (used in 2 places)
  20285. function buf2binstring(buf, len) {
  20286. // use fallback for big arrays to avoid stack overflow
  20287. if (len < 65537) {
  20288. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20289. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20290. }
  20291. }
  20292. var result = '';
  20293. for (var i=0; i < len; i++) {
  20294. result += String.fromCharCode(buf[i]);
  20295. }
  20296. return result;
  20297. }
  20298. // Convert byte array to binary string
  20299. exports.buf2binstring = function(buf) {
  20300. return buf2binstring(buf, buf.length);
  20301. };
  20302. // Convert binary string (typed, when possible)
  20303. exports.binstring2buf = function(str) {
  20304. var buf = new utils.Buf8(str.length);
  20305. for (var i=0, len=buf.length; i < len; i++) {
  20306. buf[i] = str.charCodeAt(i);
  20307. }
  20308. return buf;
  20309. };
  20310. // convert array to string
  20311. exports.buf2string = function (buf, max) {
  20312. var i, out, c, c_len;
  20313. var len = max || buf.length;
  20314. // Reserve max possible length (2 words per char)
  20315. // NB: by unknown reasons, Array is significantly faster for
  20316. // String.fromCharCode.apply than Uint16Array.
  20317. var utf16buf = new Array(len*2);
  20318. for (out=0, i=0; i<len;) {
  20319. c = buf[i++];
  20320. // quick process ascii
  20321. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20322. c_len = _utf8len[c];
  20323. // skip 5 & 6 byte codes
  20324. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20325. // apply mask on first byte
  20326. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20327. // join the rest
  20328. while (c_len > 1 && i < len) {
  20329. c = (c << 6) | (buf[i++] & 0x3f);
  20330. c_len--;
  20331. }
  20332. // terminated by end of string?
  20333. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20334. if (c < 0x10000) {
  20335. utf16buf[out++] = c;
  20336. } else {
  20337. c -= 0x10000;
  20338. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20339. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20340. }
  20341. }
  20342. return buf2binstring(utf16buf, out);
  20343. };
  20344. // Calculate max possible position in utf8 buffer,
  20345. // that will not break sequence. If that's not possible
  20346. // - (very small limits) return max size as is.
  20347. //
  20348. // buf[] - utf8 bytes array
  20349. // max - length limit (mandatory);
  20350. exports.utf8border = function(buf, max) {
  20351. var pos;
  20352. max = max || buf.length;
  20353. if (max > buf.length) { max = buf.length; }
  20354. // go back from last position, until start of sequence found
  20355. pos = max-1;
  20356. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20357. // Fuckup - very small and broken sequence,
  20358. // return max, because we should return something anyway.
  20359. if (pos < 0) { return max; }
  20360. // If we came to start of buffer - that means vuffer is too small,
  20361. // return max too.
  20362. if (pos === 0) { return max; }
  20363. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20364. };
  20365. },{"./common":74}],76:[function(require,module,exports){
  20366. 'use strict';
  20367. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20368. // It doesn't worth to make additional optimizationa as in original.
  20369. // Small size is preferable.
  20370. function adler32(adler, buf, len, pos) {
  20371. var s1 = (adler & 0xffff) |0,
  20372. s2 = ((adler >>> 16) & 0xffff) |0,
  20373. n = 0;
  20374. while (len !== 0) {
  20375. // Set limit ~ twice less than 5552, to keep
  20376. // s2 in 31-bits, because we force signed ints.
  20377. // in other case %= will fail.
  20378. n = len > 2000 ? 2000 : len;
  20379. len -= n;
  20380. do {
  20381. s1 = (s1 + buf[pos++]) |0;
  20382. s2 = (s2 + s1) |0;
  20383. } while (--n);
  20384. s1 %= 65521;
  20385. s2 %= 65521;
  20386. }
  20387. return (s1 | (s2 << 16)) |0;
  20388. }
  20389. module.exports = adler32;
  20390. },{}],77:[function(require,module,exports){
  20391. module.exports = {
  20392. /* Allowed flush values; see deflate() and inflate() below for details */
  20393. Z_NO_FLUSH: 0,
  20394. Z_PARTIAL_FLUSH: 1,
  20395. Z_SYNC_FLUSH: 2,
  20396. Z_FULL_FLUSH: 3,
  20397. Z_FINISH: 4,
  20398. Z_BLOCK: 5,
  20399. Z_TREES: 6,
  20400. /* Return codes for the compression/decompression functions. Negative values
  20401. * are errors, positive values are used for special but normal events.
  20402. */
  20403. Z_OK: 0,
  20404. Z_STREAM_END: 1,
  20405. Z_NEED_DICT: 2,
  20406. Z_ERRNO: -1,
  20407. Z_STREAM_ERROR: -2,
  20408. Z_DATA_ERROR: -3,
  20409. //Z_MEM_ERROR: -4,
  20410. Z_BUF_ERROR: -5,
  20411. //Z_VERSION_ERROR: -6,
  20412. /* compression levels */
  20413. Z_NO_COMPRESSION: 0,
  20414. Z_BEST_SPEED: 1,
  20415. Z_BEST_COMPRESSION: 9,
  20416. Z_DEFAULT_COMPRESSION: -1,
  20417. Z_FILTERED: 1,
  20418. Z_HUFFMAN_ONLY: 2,
  20419. Z_RLE: 3,
  20420. Z_FIXED: 4,
  20421. Z_DEFAULT_STRATEGY: 0,
  20422. /* Possible values of the data_type field (though see inflate()) */
  20423. Z_BINARY: 0,
  20424. Z_TEXT: 1,
  20425. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  20426. Z_UNKNOWN: 2,
  20427. /* The deflate compression method */
  20428. Z_DEFLATED: 8
  20429. //Z_NULL: null // Use -1 or null inline, depending on var type
  20430. };
  20431. },{}],78:[function(require,module,exports){
  20432. 'use strict';
  20433. // Note: we can't get significant speed boost here.
  20434. // So write code to minimize size - no pregenerated tables
  20435. // and array tools dependencies.
  20436. // Use ordinary array, since untyped makes no boost here
  20437. function makeTable() {
  20438. var c, table = [];
  20439. for (var n =0; n < 256; n++) {
  20440. c = n;
  20441. for (var k =0; k < 8; k++) {
  20442. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  20443. }
  20444. table[n] = c;
  20445. }
  20446. return table;
  20447. }
  20448. // Create table on load. Just 255 signed longs. Not a problem.
  20449. var crcTable = makeTable();
  20450. function crc32(crc, buf, len, pos) {
  20451. var t = crcTable,
  20452. end = pos + len;
  20453. crc = crc ^ (-1);
  20454. for (var i = pos; i < end; i++) {
  20455. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  20456. }
  20457. return (crc ^ (-1)); // >>> 0;
  20458. }
  20459. module.exports = crc32;
  20460. },{}],79:[function(require,module,exports){
  20461. 'use strict';
  20462. var utils = require('../utils/common');
  20463. var trees = require('./trees');
  20464. var adler32 = require('./adler32');
  20465. var crc32 = require('./crc32');
  20466. var msg = require('./messages');
  20467. /* Public constants ==========================================================*/
  20468. /* ===========================================================================*/
  20469. /* Allowed flush values; see deflate() and inflate() below for details */
  20470. var Z_NO_FLUSH = 0;
  20471. var Z_PARTIAL_FLUSH = 1;
  20472. //var Z_SYNC_FLUSH = 2;
  20473. var Z_FULL_FLUSH = 3;
  20474. var Z_FINISH = 4;
  20475. var Z_BLOCK = 5;
  20476. //var Z_TREES = 6;
  20477. /* Return codes for the compression/decompression functions. Negative values
  20478. * are errors, positive values are used for special but normal events.
  20479. */
  20480. var Z_OK = 0;
  20481. var Z_STREAM_END = 1;
  20482. //var Z_NEED_DICT = 2;
  20483. //var Z_ERRNO = -1;
  20484. var Z_STREAM_ERROR = -2;
  20485. var Z_DATA_ERROR = -3;
  20486. //var Z_MEM_ERROR = -4;
  20487. var Z_BUF_ERROR = -5;
  20488. //var Z_VERSION_ERROR = -6;
  20489. /* compression levels */
  20490. //var Z_NO_COMPRESSION = 0;
  20491. //var Z_BEST_SPEED = 1;
  20492. //var Z_BEST_COMPRESSION = 9;
  20493. var Z_DEFAULT_COMPRESSION = -1;
  20494. var Z_FILTERED = 1;
  20495. var Z_HUFFMAN_ONLY = 2;
  20496. var Z_RLE = 3;
  20497. var Z_FIXED = 4;
  20498. var Z_DEFAULT_STRATEGY = 0;
  20499. /* Possible values of the data_type field (though see inflate()) */
  20500. //var Z_BINARY = 0;
  20501. //var Z_TEXT = 1;
  20502. //var Z_ASCII = 1; // = Z_TEXT
  20503. var Z_UNKNOWN = 2;
  20504. /* The deflate compression method */
  20505. var Z_DEFLATED = 8;
  20506. /*============================================================================*/
  20507. var MAX_MEM_LEVEL = 9;
  20508. /* Maximum value for memLevel in deflateInit2 */
  20509. var MAX_WBITS = 15;
  20510. /* 32K LZ77 window */
  20511. var DEF_MEM_LEVEL = 8;
  20512. var LENGTH_CODES = 29;
  20513. /* number of length codes, not counting the special END_BLOCK code */
  20514. var LITERALS = 256;
  20515. /* number of literal bytes 0..255 */
  20516. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  20517. /* number of Literal or Length codes, including the END_BLOCK code */
  20518. var D_CODES = 30;
  20519. /* number of distance codes */
  20520. var BL_CODES = 19;
  20521. /* number of codes used to transfer the bit lengths */
  20522. var HEAP_SIZE = 2*L_CODES + 1;
  20523. /* maximum heap size */
  20524. var MAX_BITS = 15;
  20525. /* All codes must not exceed MAX_BITS bits */
  20526. var MIN_MATCH = 3;
  20527. var MAX_MATCH = 258;
  20528. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  20529. var PRESET_DICT = 0x20;
  20530. var INIT_STATE = 42;
  20531. var EXTRA_STATE = 69;
  20532. var NAME_STATE = 73;
  20533. var COMMENT_STATE = 91;
  20534. var HCRC_STATE = 103;
  20535. var BUSY_STATE = 113;
  20536. var FINISH_STATE = 666;
  20537. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  20538. var BS_BLOCK_DONE = 2; /* block flush performed */
  20539. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  20540. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  20541. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  20542. function err(strm, errorCode) {
  20543. strm.msg = msg[errorCode];
  20544. return errorCode;
  20545. }
  20546. function rank(f) {
  20547. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  20548. }
  20549. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  20550. /* =========================================================================
  20551. * Flush as much pending output as possible. All deflate() output goes
  20552. * through this function so some applications may wish to modify it
  20553. * to avoid allocating a large strm->output buffer and copying into it.
  20554. * (See also read_buf()).
  20555. */
  20556. function flush_pending(strm) {
  20557. var s = strm.state;
  20558. //_tr_flush_bits(s);
  20559. var len = s.pending;
  20560. if (len > strm.avail_out) {
  20561. len = strm.avail_out;
  20562. }
  20563. if (len === 0) { return; }
  20564. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  20565. strm.next_out += len;
  20566. s.pending_out += len;
  20567. strm.total_out += len;
  20568. strm.avail_out -= len;
  20569. s.pending -= len;
  20570. if (s.pending === 0) {
  20571. s.pending_out = 0;
  20572. }
  20573. }
  20574. function flush_block_only (s, last) {
  20575. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  20576. s.block_start = s.strstart;
  20577. flush_pending(s.strm);
  20578. }
  20579. function put_byte(s, b) {
  20580. s.pending_buf[s.pending++] = b;
  20581. }
  20582. /* =========================================================================
  20583. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  20584. * IN assertion: the stream state is correct and there is enough room in
  20585. * pending_buf.
  20586. */
  20587. function putShortMSB(s, b) {
  20588. // put_byte(s, (Byte)(b >> 8));
  20589. // put_byte(s, (Byte)(b & 0xff));
  20590. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  20591. s.pending_buf[s.pending++] = b & 0xff;
  20592. }
  20593. /* ===========================================================================
  20594. * Read a new buffer from the current input stream, update the adler32
  20595. * and total number of bytes read. All deflate() input goes through
  20596. * this function so some applications may wish to modify it to avoid
  20597. * allocating a large strm->input buffer and copying from it.
  20598. * (See also flush_pending()).
  20599. */
  20600. function read_buf(strm, buf, start, size) {
  20601. var len = strm.avail_in;
  20602. if (len > size) { len = size; }
  20603. if (len === 0) { return 0; }
  20604. strm.avail_in -= len;
  20605. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  20606. if (strm.state.wrap === 1) {
  20607. strm.adler = adler32(strm.adler, buf, len, start);
  20608. }
  20609. else if (strm.state.wrap === 2) {
  20610. strm.adler = crc32(strm.adler, buf, len, start);
  20611. }
  20612. strm.next_in += len;
  20613. strm.total_in += len;
  20614. return len;
  20615. }
  20616. /* ===========================================================================
  20617. * Set match_start to the longest match starting at the given string and
  20618. * return its length. Matches shorter or equal to prev_length are discarded,
  20619. * in which case the result is equal to prev_length and match_start is
  20620. * garbage.
  20621. * IN assertions: cur_match is the head of the hash chain for the current
  20622. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  20623. * OUT assertion: the match length is not greater than s->lookahead.
  20624. */
  20625. function longest_match(s, cur_match) {
  20626. var chain_length = s.max_chain_length; /* max hash chain length */
  20627. var scan = s.strstart; /* current string */
  20628. var match; /* matched string */
  20629. var len; /* length of current match */
  20630. var best_len = s.prev_length; /* best match length so far */
  20631. var nice_match = s.nice_match; /* stop if match long enough */
  20632. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  20633. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  20634. var _win = s.window; // shortcut
  20635. var wmask = s.w_mask;
  20636. var prev = s.prev;
  20637. /* Stop when cur_match becomes <= limit. To simplify the code,
  20638. * we prevent matches with the string of window index 0.
  20639. */
  20640. var strend = s.strstart + MAX_MATCH;
  20641. var scan_end1 = _win[scan + best_len - 1];
  20642. var scan_end = _win[scan + best_len];
  20643. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  20644. * It is easy to get rid of this optimization if necessary.
  20645. */
  20646. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  20647. /* Do not waste too much time if we already have a good match: */
  20648. if (s.prev_length >= s.good_match) {
  20649. chain_length >>= 2;
  20650. }
  20651. /* Do not look for matches beyond the end of the input. This is necessary
  20652. * to make deflate deterministic.
  20653. */
  20654. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  20655. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  20656. do {
  20657. // Assert(cur_match < s->strstart, "no future");
  20658. match = cur_match;
  20659. /* Skip to next match if the match length cannot increase
  20660. * or if the match length is less than 2. Note that the checks below
  20661. * for insufficient lookahead only occur occasionally for performance
  20662. * reasons. Therefore uninitialized memory will be accessed, and
  20663. * conditional jumps will be made that depend on those values.
  20664. * However the length of the match is limited to the lookahead, so
  20665. * the output of deflate is not affected by the uninitialized values.
  20666. */
  20667. if (_win[match + best_len] !== scan_end ||
  20668. _win[match + best_len - 1] !== scan_end1 ||
  20669. _win[match] !== _win[scan] ||
  20670. _win[++match] !== _win[scan + 1]) {
  20671. continue;
  20672. }
  20673. /* The check at best_len-1 can be removed because it will be made
  20674. * again later. (This heuristic is not always a win.)
  20675. * It is not necessary to compare scan[2] and match[2] since they
  20676. * are always equal when the other bytes match, given that
  20677. * the hash keys are equal and that HASH_BITS >= 8.
  20678. */
  20679. scan += 2;
  20680. match++;
  20681. // Assert(*scan == *match, "match[2]?");
  20682. /* We check for insufficient lookahead only every 8th comparison;
  20683. * the 256th check will be made at strstart+258.
  20684. */
  20685. do {
  20686. /*jshint noempty:false*/
  20687. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20688. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20689. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20690. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  20691. scan < strend);
  20692. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  20693. len = MAX_MATCH - (strend - scan);
  20694. scan = strend - MAX_MATCH;
  20695. if (len > best_len) {
  20696. s.match_start = cur_match;
  20697. best_len = len;
  20698. if (len >= nice_match) {
  20699. break;
  20700. }
  20701. scan_end1 = _win[scan + best_len - 1];
  20702. scan_end = _win[scan + best_len];
  20703. }
  20704. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  20705. if (best_len <= s.lookahead) {
  20706. return best_len;
  20707. }
  20708. return s.lookahead;
  20709. }
  20710. /* ===========================================================================
  20711. * Fill the window when the lookahead becomes insufficient.
  20712. * Updates strstart and lookahead.
  20713. *
  20714. * IN assertion: lookahead < MIN_LOOKAHEAD
  20715. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20716. * At least one byte has been read, or avail_in == 0; reads are
  20717. * performed for at least two bytes (required for the zip translate_eol
  20718. * option -- not supported here).
  20719. */
  20720. function fill_window(s) {
  20721. var _w_size = s.w_size;
  20722. var p, n, m, more, str;
  20723. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20724. do {
  20725. more = s.window_size - s.lookahead - s.strstart;
  20726. // JS ints have 32 bit, block below not needed
  20727. /* Deal with !@#$% 64K limit: */
  20728. //if (sizeof(int) <= 2) {
  20729. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20730. // more = wsize;
  20731. //
  20732. // } else if (more == (unsigned)(-1)) {
  20733. // /* Very unlikely, but possible on 16 bit machine if
  20734. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20735. // */
  20736. // more--;
  20737. // }
  20738. //}
  20739. /* If the window is almost full and there is insufficient lookahead,
  20740. * move the upper half to the lower one to make room in the upper half.
  20741. */
  20742. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20743. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20744. s.match_start -= _w_size;
  20745. s.strstart -= _w_size;
  20746. /* we now have strstart >= MAX_DIST */
  20747. s.block_start -= _w_size;
  20748. /* Slide the hash table (could be avoided with 32 bit values
  20749. at the expense of memory usage). We slide even when level == 0
  20750. to keep the hash table consistent if we switch back to level > 0
  20751. later. (Using level 0 permanently is not an optimal usage of
  20752. zlib, so we don't care about this pathological case.)
  20753. */
  20754. n = s.hash_size;
  20755. p = n;
  20756. do {
  20757. m = s.head[--p];
  20758. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20759. } while (--n);
  20760. n = _w_size;
  20761. p = n;
  20762. do {
  20763. m = s.prev[--p];
  20764. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20765. /* If n is not on any hash chain, prev[n] is garbage but
  20766. * its value will never be used.
  20767. */
  20768. } while (--n);
  20769. more += _w_size;
  20770. }
  20771. if (s.strm.avail_in === 0) {
  20772. break;
  20773. }
  20774. /* If there was no sliding:
  20775. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20776. * more == window_size - lookahead - strstart
  20777. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20778. * => more >= window_size - 2*WSIZE + 2
  20779. * In the BIG_MEM or MMAP case (not yet supported),
  20780. * window_size == input_size + MIN_LOOKAHEAD &&
  20781. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20782. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20783. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20784. */
  20785. //Assert(more >= 2, "more < 2");
  20786. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20787. s.lookahead += n;
  20788. /* Initialize the hash value now that we have some input: */
  20789. if (s.lookahead + s.insert >= MIN_MATCH) {
  20790. str = s.strstart - s.insert;
  20791. s.ins_h = s.window[str];
  20792. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20793. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20794. //#if MIN_MATCH != 3
  20795. // Call update_hash() MIN_MATCH-3 more times
  20796. //#endif
  20797. while (s.insert) {
  20798. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20799. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20800. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20801. s.head[s.ins_h] = str;
  20802. str++;
  20803. s.insert--;
  20804. if (s.lookahead + s.insert < MIN_MATCH) {
  20805. break;
  20806. }
  20807. }
  20808. }
  20809. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20810. * but this is not important since only literal bytes will be emitted.
  20811. */
  20812. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20813. /* If the WIN_INIT bytes after the end of the current data have never been
  20814. * written, then zero those bytes in order to avoid memory check reports of
  20815. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20816. * the longest match routines. Update the high water mark for the next
  20817. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20818. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20819. */
  20820. // if (s.high_water < s.window_size) {
  20821. // var curr = s.strstart + s.lookahead;
  20822. // var init = 0;
  20823. //
  20824. // if (s.high_water < curr) {
  20825. // /* Previous high water mark below current data -- zero WIN_INIT
  20826. // * bytes or up to end of window, whichever is less.
  20827. // */
  20828. // init = s.window_size - curr;
  20829. // if (init > WIN_INIT)
  20830. // init = WIN_INIT;
  20831. // zmemzero(s->window + curr, (unsigned)init);
  20832. // s->high_water = curr + init;
  20833. // }
  20834. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20835. // /* High water mark at or above current data, but below current data
  20836. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20837. // * to end of window, whichever is less.
  20838. // */
  20839. // init = (ulg)curr + WIN_INIT - s->high_water;
  20840. // if (init > s->window_size - s->high_water)
  20841. // init = s->window_size - s->high_water;
  20842. // zmemzero(s->window + s->high_water, (unsigned)init);
  20843. // s->high_water += init;
  20844. // }
  20845. // }
  20846. //
  20847. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20848. // "not enough room for search");
  20849. }
  20850. /* ===========================================================================
  20851. * Copy without compression as much as possible from the input stream, return
  20852. * the current block state.
  20853. * This function does not insert new strings in the dictionary since
  20854. * uncompressible data is probably not useful. This function is used
  20855. * only for the level=0 compression option.
  20856. * NOTE: this function should be optimized to avoid extra copying from
  20857. * window to pending_buf.
  20858. */
  20859. function deflate_stored(s, flush) {
  20860. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20861. * to pending_buf_size, and each stored block has a 5 byte header:
  20862. */
  20863. var max_block_size = 0xffff;
  20864. if (max_block_size > s.pending_buf_size - 5) {
  20865. max_block_size = s.pending_buf_size - 5;
  20866. }
  20867. /* Copy as much as possible from input to output: */
  20868. for (;;) {
  20869. /* Fill the window as much as possible: */
  20870. if (s.lookahead <= 1) {
  20871. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20872. // s->block_start >= (long)s->w_size, "slide too late");
  20873. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20874. // s.block_start >= s.w_size)) {
  20875. // throw new Error("slide too late");
  20876. // }
  20877. fill_window(s);
  20878. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20879. return BS_NEED_MORE;
  20880. }
  20881. if (s.lookahead === 0) {
  20882. break;
  20883. }
  20884. /* flush the current block */
  20885. }
  20886. //Assert(s->block_start >= 0L, "block gone");
  20887. // if (s.block_start < 0) throw new Error("block gone");
  20888. s.strstart += s.lookahead;
  20889. s.lookahead = 0;
  20890. /* Emit a stored block if pending_buf will be full: */
  20891. var max_start = s.block_start + max_block_size;
  20892. if (s.strstart === 0 || s.strstart >= max_start) {
  20893. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20894. s.lookahead = s.strstart - max_start;
  20895. s.strstart = max_start;
  20896. /*** FLUSH_BLOCK(s, 0); ***/
  20897. flush_block_only(s, false);
  20898. if (s.strm.avail_out === 0) {
  20899. return BS_NEED_MORE;
  20900. }
  20901. /***/
  20902. }
  20903. /* Flush if we may have to slide, otherwise block_start may become
  20904. * negative and the data will be gone:
  20905. */
  20906. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20907. /*** FLUSH_BLOCK(s, 0); ***/
  20908. flush_block_only(s, false);
  20909. if (s.strm.avail_out === 0) {
  20910. return BS_NEED_MORE;
  20911. }
  20912. /***/
  20913. }
  20914. }
  20915. s.insert = 0;
  20916. if (flush === Z_FINISH) {
  20917. /*** FLUSH_BLOCK(s, 1); ***/
  20918. flush_block_only(s, true);
  20919. if (s.strm.avail_out === 0) {
  20920. return BS_FINISH_STARTED;
  20921. }
  20922. /***/
  20923. return BS_FINISH_DONE;
  20924. }
  20925. if (s.strstart > s.block_start) {
  20926. /*** FLUSH_BLOCK(s, 0); ***/
  20927. flush_block_only(s, false);
  20928. if (s.strm.avail_out === 0) {
  20929. return BS_NEED_MORE;
  20930. }
  20931. /***/
  20932. }
  20933. return BS_NEED_MORE;
  20934. }
  20935. /* ===========================================================================
  20936. * Compress as much as possible from the input stream, return the current
  20937. * block state.
  20938. * This function does not perform lazy evaluation of matches and inserts
  20939. * new strings in the dictionary only for unmatched strings or for short
  20940. * matches. It is used only for the fast compression options.
  20941. */
  20942. function deflate_fast(s, flush) {
  20943. var hash_head; /* head of the hash chain */
  20944. var bflush; /* set if current block must be flushed */
  20945. for (;;) {
  20946. /* Make sure that we always have enough lookahead, except
  20947. * at the end of the input file. We need MAX_MATCH bytes
  20948. * for the next match, plus MIN_MATCH bytes to insert the
  20949. * string following the next match.
  20950. */
  20951. if (s.lookahead < MIN_LOOKAHEAD) {
  20952. fill_window(s);
  20953. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20954. return BS_NEED_MORE;
  20955. }
  20956. if (s.lookahead === 0) {
  20957. break; /* flush the current block */
  20958. }
  20959. }
  20960. /* Insert the string window[strstart .. strstart+2] in the
  20961. * dictionary, and set hash_head to the head of the hash chain:
  20962. */
  20963. hash_head = 0/*NIL*/;
  20964. if (s.lookahead >= MIN_MATCH) {
  20965. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20966. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20967. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20968. s.head[s.ins_h] = s.strstart;
  20969. /***/
  20970. }
  20971. /* Find the longest match, discarding those <= prev_length.
  20972. * At this point we have always match_length < MIN_MATCH
  20973. */
  20974. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20975. /* To simplify the code, we prevent matches with the string
  20976. * of window index 0 (in particular we have to avoid a match
  20977. * of the string with itself at the start of the input file).
  20978. */
  20979. s.match_length = longest_match(s, hash_head);
  20980. /* longest_match() sets match_start */
  20981. }
  20982. if (s.match_length >= MIN_MATCH) {
  20983. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20984. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20985. s.match_length - MIN_MATCH, bflush); ***/
  20986. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20987. s.lookahead -= s.match_length;
  20988. /* Insert new strings in the hash table only if the match length
  20989. * is not too large. This saves time but degrades compression.
  20990. */
  20991. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20992. s.match_length--; /* string at strstart already in table */
  20993. do {
  20994. s.strstart++;
  20995. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20996. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20997. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20998. s.head[s.ins_h] = s.strstart;
  20999. /***/
  21000. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21001. * always MIN_MATCH bytes ahead.
  21002. */
  21003. } while (--s.match_length !== 0);
  21004. s.strstart++;
  21005. } else
  21006. {
  21007. s.strstart += s.match_length;
  21008. s.match_length = 0;
  21009. s.ins_h = s.window[s.strstart];
  21010. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21011. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21012. //#if MIN_MATCH != 3
  21013. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21014. //#endif
  21015. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21016. * matter since it will be recomputed at next deflate call.
  21017. */
  21018. }
  21019. } else {
  21020. /* No match, output a literal byte */
  21021. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21022. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21023. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21024. s.lookahead--;
  21025. s.strstart++;
  21026. }
  21027. if (bflush) {
  21028. /*** FLUSH_BLOCK(s, 0); ***/
  21029. flush_block_only(s, false);
  21030. if (s.strm.avail_out === 0) {
  21031. return BS_NEED_MORE;
  21032. }
  21033. /***/
  21034. }
  21035. }
  21036. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21037. if (flush === Z_FINISH) {
  21038. /*** FLUSH_BLOCK(s, 1); ***/
  21039. flush_block_only(s, true);
  21040. if (s.strm.avail_out === 0) {
  21041. return BS_FINISH_STARTED;
  21042. }
  21043. /***/
  21044. return BS_FINISH_DONE;
  21045. }
  21046. if (s.last_lit) {
  21047. /*** FLUSH_BLOCK(s, 0); ***/
  21048. flush_block_only(s, false);
  21049. if (s.strm.avail_out === 0) {
  21050. return BS_NEED_MORE;
  21051. }
  21052. /***/
  21053. }
  21054. return BS_BLOCK_DONE;
  21055. }
  21056. /* ===========================================================================
  21057. * Same as above, but achieves better compression. We use a lazy
  21058. * evaluation for matches: a match is finally adopted only if there is
  21059. * no better match at the next window position.
  21060. */
  21061. function deflate_slow(s, flush) {
  21062. var hash_head; /* head of hash chain */
  21063. var bflush; /* set if current block must be flushed */
  21064. var max_insert;
  21065. /* Process the input block. */
  21066. for (;;) {
  21067. /* Make sure that we always have enough lookahead, except
  21068. * at the end of the input file. We need MAX_MATCH bytes
  21069. * for the next match, plus MIN_MATCH bytes to insert the
  21070. * string following the next match.
  21071. */
  21072. if (s.lookahead < MIN_LOOKAHEAD) {
  21073. fill_window(s);
  21074. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21075. return BS_NEED_MORE;
  21076. }
  21077. if (s.lookahead === 0) { break; } /* flush the current block */
  21078. }
  21079. /* Insert the string window[strstart .. strstart+2] in the
  21080. * dictionary, and set hash_head to the head of the hash chain:
  21081. */
  21082. hash_head = 0/*NIL*/;
  21083. if (s.lookahead >= MIN_MATCH) {
  21084. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21085. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21086. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21087. s.head[s.ins_h] = s.strstart;
  21088. /***/
  21089. }
  21090. /* Find the longest match, discarding those <= prev_length.
  21091. */
  21092. s.prev_length = s.match_length;
  21093. s.prev_match = s.match_start;
  21094. s.match_length = MIN_MATCH-1;
  21095. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21096. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21097. /* To simplify the code, we prevent matches with the string
  21098. * of window index 0 (in particular we have to avoid a match
  21099. * of the string with itself at the start of the input file).
  21100. */
  21101. s.match_length = longest_match(s, hash_head);
  21102. /* longest_match() sets match_start */
  21103. if (s.match_length <= 5 &&
  21104. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21105. /* If prev_match is also MIN_MATCH, match_start is garbage
  21106. * but we will ignore the current match anyway.
  21107. */
  21108. s.match_length = MIN_MATCH-1;
  21109. }
  21110. }
  21111. /* If there was a match at the previous step and the current
  21112. * match is not better, output the previous match:
  21113. */
  21114. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21115. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21116. /* Do not insert strings in hash table beyond this. */
  21117. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21118. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21119. s.prev_length - MIN_MATCH, bflush);***/
  21120. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21121. /* Insert in hash table all strings up to the end of the match.
  21122. * strstart-1 and strstart are already inserted. If there is not
  21123. * enough lookahead, the last two strings are not inserted in
  21124. * the hash table.
  21125. */
  21126. s.lookahead -= s.prev_length-1;
  21127. s.prev_length -= 2;
  21128. do {
  21129. if (++s.strstart <= max_insert) {
  21130. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21131. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21132. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21133. s.head[s.ins_h] = s.strstart;
  21134. /***/
  21135. }
  21136. } while (--s.prev_length !== 0);
  21137. s.match_available = 0;
  21138. s.match_length = MIN_MATCH-1;
  21139. s.strstart++;
  21140. if (bflush) {
  21141. /*** FLUSH_BLOCK(s, 0); ***/
  21142. flush_block_only(s, false);
  21143. if (s.strm.avail_out === 0) {
  21144. return BS_NEED_MORE;
  21145. }
  21146. /***/
  21147. }
  21148. } else if (s.match_available) {
  21149. /* If there was no match at the previous position, output a
  21150. * single literal. If there was a match but the current match
  21151. * is longer, truncate the previous match to a single literal.
  21152. */
  21153. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21154. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21155. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21156. if (bflush) {
  21157. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21158. flush_block_only(s, false);
  21159. /***/
  21160. }
  21161. s.strstart++;
  21162. s.lookahead--;
  21163. if (s.strm.avail_out === 0) {
  21164. return BS_NEED_MORE;
  21165. }
  21166. } else {
  21167. /* There is no previous match to compare with, wait for
  21168. * the next step to decide.
  21169. */
  21170. s.match_available = 1;
  21171. s.strstart++;
  21172. s.lookahead--;
  21173. }
  21174. }
  21175. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21176. if (s.match_available) {
  21177. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21178. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21179. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21180. s.match_available = 0;
  21181. }
  21182. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21183. if (flush === Z_FINISH) {
  21184. /*** FLUSH_BLOCK(s, 1); ***/
  21185. flush_block_only(s, true);
  21186. if (s.strm.avail_out === 0) {
  21187. return BS_FINISH_STARTED;
  21188. }
  21189. /***/
  21190. return BS_FINISH_DONE;
  21191. }
  21192. if (s.last_lit) {
  21193. /*** FLUSH_BLOCK(s, 0); ***/
  21194. flush_block_only(s, false);
  21195. if (s.strm.avail_out === 0) {
  21196. return BS_NEED_MORE;
  21197. }
  21198. /***/
  21199. }
  21200. return BS_BLOCK_DONE;
  21201. }
  21202. /* ===========================================================================
  21203. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21204. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21205. * deflate switches away from Z_RLE.)
  21206. */
  21207. function deflate_rle(s, flush) {
  21208. var bflush; /* set if current block must be flushed */
  21209. var prev; /* byte at distance one to match */
  21210. var scan, strend; /* scan goes up to strend for length of run */
  21211. var _win = s.window;
  21212. for (;;) {
  21213. /* Make sure that we always have enough lookahead, except
  21214. * at the end of the input file. We need MAX_MATCH bytes
  21215. * for the longest run, plus one for the unrolled loop.
  21216. */
  21217. if (s.lookahead <= MAX_MATCH) {
  21218. fill_window(s);
  21219. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21220. return BS_NEED_MORE;
  21221. }
  21222. if (s.lookahead === 0) { break; } /* flush the current block */
  21223. }
  21224. /* See how many times the previous byte repeats */
  21225. s.match_length = 0;
  21226. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21227. scan = s.strstart - 1;
  21228. prev = _win[scan];
  21229. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21230. strend = s.strstart + MAX_MATCH;
  21231. do {
  21232. /*jshint noempty:false*/
  21233. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21234. prev === _win[++scan] && prev === _win[++scan] &&
  21235. prev === _win[++scan] && prev === _win[++scan] &&
  21236. prev === _win[++scan] && prev === _win[++scan] &&
  21237. scan < strend);
  21238. s.match_length = MAX_MATCH - (strend - scan);
  21239. if (s.match_length > s.lookahead) {
  21240. s.match_length = s.lookahead;
  21241. }
  21242. }
  21243. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21244. }
  21245. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21246. if (s.match_length >= MIN_MATCH) {
  21247. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21248. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21249. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21250. s.lookahead -= s.match_length;
  21251. s.strstart += s.match_length;
  21252. s.match_length = 0;
  21253. } else {
  21254. /* No match, output a literal byte */
  21255. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21256. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21257. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21258. s.lookahead--;
  21259. s.strstart++;
  21260. }
  21261. if (bflush) {
  21262. /*** FLUSH_BLOCK(s, 0); ***/
  21263. flush_block_only(s, false);
  21264. if (s.strm.avail_out === 0) {
  21265. return BS_NEED_MORE;
  21266. }
  21267. /***/
  21268. }
  21269. }
  21270. s.insert = 0;
  21271. if (flush === Z_FINISH) {
  21272. /*** FLUSH_BLOCK(s, 1); ***/
  21273. flush_block_only(s, true);
  21274. if (s.strm.avail_out === 0) {
  21275. return BS_FINISH_STARTED;
  21276. }
  21277. /***/
  21278. return BS_FINISH_DONE;
  21279. }
  21280. if (s.last_lit) {
  21281. /*** FLUSH_BLOCK(s, 0); ***/
  21282. flush_block_only(s, false);
  21283. if (s.strm.avail_out === 0) {
  21284. return BS_NEED_MORE;
  21285. }
  21286. /***/
  21287. }
  21288. return BS_BLOCK_DONE;
  21289. }
  21290. /* ===========================================================================
  21291. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21292. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21293. */
  21294. function deflate_huff(s, flush) {
  21295. var bflush; /* set if current block must be flushed */
  21296. for (;;) {
  21297. /* Make sure that we have a literal to write. */
  21298. if (s.lookahead === 0) {
  21299. fill_window(s);
  21300. if (s.lookahead === 0) {
  21301. if (flush === Z_NO_FLUSH) {
  21302. return BS_NEED_MORE;
  21303. }
  21304. break; /* flush the current block */
  21305. }
  21306. }
  21307. /* Output a literal byte */
  21308. s.match_length = 0;
  21309. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21310. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21311. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21312. s.lookahead--;
  21313. s.strstart++;
  21314. if (bflush) {
  21315. /*** FLUSH_BLOCK(s, 0); ***/
  21316. flush_block_only(s, false);
  21317. if (s.strm.avail_out === 0) {
  21318. return BS_NEED_MORE;
  21319. }
  21320. /***/
  21321. }
  21322. }
  21323. s.insert = 0;
  21324. if (flush === Z_FINISH) {
  21325. /*** FLUSH_BLOCK(s, 1); ***/
  21326. flush_block_only(s, true);
  21327. if (s.strm.avail_out === 0) {
  21328. return BS_FINISH_STARTED;
  21329. }
  21330. /***/
  21331. return BS_FINISH_DONE;
  21332. }
  21333. if (s.last_lit) {
  21334. /*** FLUSH_BLOCK(s, 0); ***/
  21335. flush_block_only(s, false);
  21336. if (s.strm.avail_out === 0) {
  21337. return BS_NEED_MORE;
  21338. }
  21339. /***/
  21340. }
  21341. return BS_BLOCK_DONE;
  21342. }
  21343. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21344. * the desired pack level (0..9). The values given below have been tuned to
  21345. * exclude worst case performance for pathological files. Better values may be
  21346. * found for specific files.
  21347. */
  21348. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21349. this.good_length = good_length;
  21350. this.max_lazy = max_lazy;
  21351. this.nice_length = nice_length;
  21352. this.max_chain = max_chain;
  21353. this.func = func;
  21354. };
  21355. var configuration_table;
  21356. configuration_table = [
  21357. /* good lazy nice chain */
  21358. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21359. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21360. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21361. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21362. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21363. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21364. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21365. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21366. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21367. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21368. ];
  21369. /* ===========================================================================
  21370. * Initialize the "longest match" routines for a new zlib stream
  21371. */
  21372. function lm_init(s) {
  21373. s.window_size = 2 * s.w_size;
  21374. /*** CLEAR_HASH(s); ***/
  21375. zero(s.head); // Fill with NIL (= 0);
  21376. /* Set the default configuration parameters:
  21377. */
  21378. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21379. s.good_match = configuration_table[s.level].good_length;
  21380. s.nice_match = configuration_table[s.level].nice_length;
  21381. s.max_chain_length = configuration_table[s.level].max_chain;
  21382. s.strstart = 0;
  21383. s.block_start = 0;
  21384. s.lookahead = 0;
  21385. s.insert = 0;
  21386. s.match_length = s.prev_length = MIN_MATCH - 1;
  21387. s.match_available = 0;
  21388. s.ins_h = 0;
  21389. }
  21390. function DeflateState() {
  21391. this.strm = null; /* pointer back to this zlib stream */
  21392. this.status = 0; /* as the name implies */
  21393. this.pending_buf = null; /* output still pending */
  21394. this.pending_buf_size = 0; /* size of pending_buf */
  21395. this.pending_out = 0; /* next pending byte to output to the stream */
  21396. this.pending = 0; /* nb of bytes in the pending buffer */
  21397. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21398. this.gzhead = null; /* gzip header information to write */
  21399. this.gzindex = 0; /* where in extra, name, or comment */
  21400. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21401. this.last_flush = -1; /* value of flush param for previous deflate call */
  21402. this.w_size = 0; /* LZ77 window size (32K by default) */
  21403. this.w_bits = 0; /* log2(w_size) (8..16) */
  21404. this.w_mask = 0; /* w_size - 1 */
  21405. this.window = null;
  21406. /* Sliding window. Input bytes are read into the second half of the window,
  21407. * and move to the first half later to keep a dictionary of at least wSize
  21408. * bytes. With this organization, matches are limited to a distance of
  21409. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21410. * performed with a length multiple of the block size.
  21411. */
  21412. this.window_size = 0;
  21413. /* Actual size of window: 2*wSize, except when the user input buffer
  21414. * is directly used as sliding window.
  21415. */
  21416. this.prev = null;
  21417. /* Link to older string with same hash index. To limit the size of this
  21418. * array to 64K, this link is maintained only for the last 32K strings.
  21419. * An index in this array is thus a window index modulo 32K.
  21420. */
  21421. this.head = null; /* Heads of the hash chains or NIL. */
  21422. this.ins_h = 0; /* hash index of string to be inserted */
  21423. this.hash_size = 0; /* number of elements in hash table */
  21424. this.hash_bits = 0; /* log2(hash_size) */
  21425. this.hash_mask = 0; /* hash_size-1 */
  21426. this.hash_shift = 0;
  21427. /* Number of bits by which ins_h must be shifted at each input
  21428. * step. It must be such that after MIN_MATCH steps, the oldest
  21429. * byte no longer takes part in the hash key, that is:
  21430. * hash_shift * MIN_MATCH >= hash_bits
  21431. */
  21432. this.block_start = 0;
  21433. /* Window position at the beginning of the current output block. Gets
  21434. * negative when the window is moved backwards.
  21435. */
  21436. this.match_length = 0; /* length of best match */
  21437. this.prev_match = 0; /* previous match */
  21438. this.match_available = 0; /* set if previous match exists */
  21439. this.strstart = 0; /* start of string to insert */
  21440. this.match_start = 0; /* start of matching string */
  21441. this.lookahead = 0; /* number of valid bytes ahead in window */
  21442. this.prev_length = 0;
  21443. /* Length of the best match at previous step. Matches not greater than this
  21444. * are discarded. This is used in the lazy match evaluation.
  21445. */
  21446. this.max_chain_length = 0;
  21447. /* To speed up deflation, hash chains are never searched beyond this
  21448. * length. A higher limit improves compression ratio but degrades the
  21449. * speed.
  21450. */
  21451. this.max_lazy_match = 0;
  21452. /* Attempt to find a better match only when the current match is strictly
  21453. * smaller than this value. This mechanism is used only for compression
  21454. * levels >= 4.
  21455. */
  21456. // That's alias to max_lazy_match, don't use directly
  21457. //this.max_insert_length = 0;
  21458. /* Insert new strings in the hash table only if the match length is not
  21459. * greater than this length. This saves time but degrades compression.
  21460. * max_insert_length is used only for compression levels <= 3.
  21461. */
  21462. this.level = 0; /* compression level (1..9) */
  21463. this.strategy = 0; /* favor or force Huffman coding*/
  21464. this.good_match = 0;
  21465. /* Use a faster search when the previous match is longer than this */
  21466. this.nice_match = 0; /* Stop searching when current match exceeds this */
  21467. /* used by trees.c: */
  21468. /* Didn't use ct_data typedef below to suppress compiler warning */
  21469. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  21470. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  21471. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  21472. // Use flat array of DOUBLE size, with interleaved fata,
  21473. // because JS does not support effective
  21474. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  21475. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  21476. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  21477. zero(this.dyn_ltree);
  21478. zero(this.dyn_dtree);
  21479. zero(this.bl_tree);
  21480. this.l_desc = null; /* desc. for literal tree */
  21481. this.d_desc = null; /* desc. for distance tree */
  21482. this.bl_desc = null; /* desc. for bit length tree */
  21483. //ush bl_count[MAX_BITS+1];
  21484. this.bl_count = new utils.Buf16(MAX_BITS+1);
  21485. /* number of codes at each bit length for an optimal tree */
  21486. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  21487. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  21488. zero(this.heap);
  21489. this.heap_len = 0; /* number of elements in the heap */
  21490. this.heap_max = 0; /* element of largest frequency */
  21491. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  21492. * The same heap array is used to build all trees.
  21493. */
  21494. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  21495. zero(this.depth);
  21496. /* Depth of each subtree used as tie breaker for trees of equal frequency
  21497. */
  21498. this.l_buf = 0; /* buffer index for literals or lengths */
  21499. this.lit_bufsize = 0;
  21500. /* Size of match buffer for literals/lengths. There are 4 reasons for
  21501. * limiting lit_bufsize to 64K:
  21502. * - frequencies can be kept in 16 bit counters
  21503. * - if compression is not successful for the first block, all input
  21504. * data is still in the window so we can still emit a stored block even
  21505. * when input comes from standard input. (This can also be done for
  21506. * all blocks if lit_bufsize is not greater than 32K.)
  21507. * - if compression is not successful for a file smaller than 64K, we can
  21508. * even emit a stored file instead of a stored block (saving 5 bytes).
  21509. * This is applicable only for zip (not gzip or zlib).
  21510. * - creating new Huffman trees less frequently may not provide fast
  21511. * adaptation to changes in the input data statistics. (Take for
  21512. * example a binary file with poorly compressible code followed by
  21513. * a highly compressible string table.) Smaller buffer sizes give
  21514. * fast adaptation but have of course the overhead of transmitting
  21515. * trees more frequently.
  21516. * - I can't count above 4
  21517. */
  21518. this.last_lit = 0; /* running index in l_buf */
  21519. this.d_buf = 0;
  21520. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  21521. * the same number of elements. To use different lengths, an extra flag
  21522. * array would be necessary.
  21523. */
  21524. this.opt_len = 0; /* bit length of current block with optimal trees */
  21525. this.static_len = 0; /* bit length of current block with static trees */
  21526. this.matches = 0; /* number of string matches in current block */
  21527. this.insert = 0; /* bytes at end of window left to insert */
  21528. this.bi_buf = 0;
  21529. /* Output buffer. bits are inserted starting at the bottom (least
  21530. * significant bits).
  21531. */
  21532. this.bi_valid = 0;
  21533. /* Number of valid bits in bi_buf. All bits above the last valid bit
  21534. * are always zero.
  21535. */
  21536. // Used for window memory init. We safely ignore it for JS. That makes
  21537. // sense only for pointers and memory check tools.
  21538. //this.high_water = 0;
  21539. /* High water mark offset in window for initialized bytes -- bytes above
  21540. * this are set to zero in order to avoid memory check warnings when
  21541. * longest match routines access bytes past the input. This is then
  21542. * updated to the new high water mark.
  21543. */
  21544. }
  21545. function deflateResetKeep(strm) {
  21546. var s;
  21547. if (!strm || !strm.state) {
  21548. return err(strm, Z_STREAM_ERROR);
  21549. }
  21550. strm.total_in = strm.total_out = 0;
  21551. strm.data_type = Z_UNKNOWN;
  21552. s = strm.state;
  21553. s.pending = 0;
  21554. s.pending_out = 0;
  21555. if (s.wrap < 0) {
  21556. s.wrap = -s.wrap;
  21557. /* was made negative by deflate(..., Z_FINISH); */
  21558. }
  21559. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  21560. strm.adler = (s.wrap === 2) ?
  21561. 0 // crc32(0, Z_NULL, 0)
  21562. :
  21563. 1; // adler32(0, Z_NULL, 0)
  21564. s.last_flush = Z_NO_FLUSH;
  21565. trees._tr_init(s);
  21566. return Z_OK;
  21567. }
  21568. function deflateReset(strm) {
  21569. var ret = deflateResetKeep(strm);
  21570. if (ret === Z_OK) {
  21571. lm_init(strm.state);
  21572. }
  21573. return ret;
  21574. }
  21575. function deflateSetHeader(strm, head) {
  21576. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21577. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  21578. strm.state.gzhead = head;
  21579. return Z_OK;
  21580. }
  21581. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  21582. if (!strm) { // === Z_NULL
  21583. return Z_STREAM_ERROR;
  21584. }
  21585. var wrap = 1;
  21586. if (level === Z_DEFAULT_COMPRESSION) {
  21587. level = 6;
  21588. }
  21589. if (windowBits < 0) { /* suppress zlib wrapper */
  21590. wrap = 0;
  21591. windowBits = -windowBits;
  21592. }
  21593. else if (windowBits > 15) {
  21594. wrap = 2; /* write gzip wrapper instead */
  21595. windowBits -= 16;
  21596. }
  21597. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  21598. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  21599. strategy < 0 || strategy > Z_FIXED) {
  21600. return err(strm, Z_STREAM_ERROR);
  21601. }
  21602. if (windowBits === 8) {
  21603. windowBits = 9;
  21604. }
  21605. /* until 256-byte window bug fixed */
  21606. var s = new DeflateState();
  21607. strm.state = s;
  21608. s.strm = strm;
  21609. s.wrap = wrap;
  21610. s.gzhead = null;
  21611. s.w_bits = windowBits;
  21612. s.w_size = 1 << s.w_bits;
  21613. s.w_mask = s.w_size - 1;
  21614. s.hash_bits = memLevel + 7;
  21615. s.hash_size = 1 << s.hash_bits;
  21616. s.hash_mask = s.hash_size - 1;
  21617. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  21618. s.window = new utils.Buf8(s.w_size * 2);
  21619. s.head = new utils.Buf16(s.hash_size);
  21620. s.prev = new utils.Buf16(s.w_size);
  21621. // Don't need mem init magic for JS.
  21622. //s.high_water = 0; /* nothing written to s->window yet */
  21623. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  21624. s.pending_buf_size = s.lit_bufsize * 4;
  21625. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  21626. s.d_buf = s.lit_bufsize >> 1;
  21627. s.l_buf = (1 + 2) * s.lit_bufsize;
  21628. s.level = level;
  21629. s.strategy = strategy;
  21630. s.method = method;
  21631. return deflateReset(strm);
  21632. }
  21633. function deflateInit(strm, level) {
  21634. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  21635. }
  21636. function deflate(strm, flush) {
  21637. var old_flush, s;
  21638. var beg, val; // for gzip header write only
  21639. if (!strm || !strm.state ||
  21640. flush > Z_BLOCK || flush < 0) {
  21641. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  21642. }
  21643. s = strm.state;
  21644. if (!strm.output ||
  21645. (!strm.input && strm.avail_in !== 0) ||
  21646. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  21647. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  21648. }
  21649. s.strm = strm; /* just in case */
  21650. old_flush = s.last_flush;
  21651. s.last_flush = flush;
  21652. /* Write the header */
  21653. if (s.status === INIT_STATE) {
  21654. if (s.wrap === 2) { // GZIP header
  21655. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21656. put_byte(s, 31);
  21657. put_byte(s, 139);
  21658. put_byte(s, 8);
  21659. if (!s.gzhead) { // s->gzhead == Z_NULL
  21660. put_byte(s, 0);
  21661. put_byte(s, 0);
  21662. put_byte(s, 0);
  21663. put_byte(s, 0);
  21664. put_byte(s, 0);
  21665. put_byte(s, s.level === 9 ? 2 :
  21666. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21667. 4 : 0));
  21668. put_byte(s, OS_CODE);
  21669. s.status = BUSY_STATE;
  21670. }
  21671. else {
  21672. put_byte(s, (s.gzhead.text ? 1 : 0) +
  21673. (s.gzhead.hcrc ? 2 : 0) +
  21674. (!s.gzhead.extra ? 0 : 4) +
  21675. (!s.gzhead.name ? 0 : 8) +
  21676. (!s.gzhead.comment ? 0 : 16)
  21677. );
  21678. put_byte(s, s.gzhead.time & 0xff);
  21679. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  21680. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  21681. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  21682. put_byte(s, s.level === 9 ? 2 :
  21683. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  21684. 4 : 0));
  21685. put_byte(s, s.gzhead.os & 0xff);
  21686. if (s.gzhead.extra && s.gzhead.extra.length) {
  21687. put_byte(s, s.gzhead.extra.length & 0xff);
  21688. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  21689. }
  21690. if (s.gzhead.hcrc) {
  21691. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  21692. }
  21693. s.gzindex = 0;
  21694. s.status = EXTRA_STATE;
  21695. }
  21696. }
  21697. else // DEFLATE header
  21698. {
  21699. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  21700. var level_flags = -1;
  21701. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  21702. level_flags = 0;
  21703. } else if (s.level < 6) {
  21704. level_flags = 1;
  21705. } else if (s.level === 6) {
  21706. level_flags = 2;
  21707. } else {
  21708. level_flags = 3;
  21709. }
  21710. header |= (level_flags << 6);
  21711. if (s.strstart !== 0) { header |= PRESET_DICT; }
  21712. header += 31 - (header % 31);
  21713. s.status = BUSY_STATE;
  21714. putShortMSB(s, header);
  21715. /* Save the adler32 of the preset dictionary: */
  21716. if (s.strstart !== 0) {
  21717. putShortMSB(s, strm.adler >>> 16);
  21718. putShortMSB(s, strm.adler & 0xffff);
  21719. }
  21720. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21721. }
  21722. }
  21723. //#ifdef GZIP
  21724. if (s.status === EXTRA_STATE) {
  21725. if (s.gzhead.extra/* != Z_NULL*/) {
  21726. beg = s.pending; /* start of bytes to update crc */
  21727. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21728. if (s.pending === s.pending_buf_size) {
  21729. if (s.gzhead.hcrc && s.pending > beg) {
  21730. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21731. }
  21732. flush_pending(strm);
  21733. beg = s.pending;
  21734. if (s.pending === s.pending_buf_size) {
  21735. break;
  21736. }
  21737. }
  21738. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21739. s.gzindex++;
  21740. }
  21741. if (s.gzhead.hcrc && s.pending > beg) {
  21742. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21743. }
  21744. if (s.gzindex === s.gzhead.extra.length) {
  21745. s.gzindex = 0;
  21746. s.status = NAME_STATE;
  21747. }
  21748. }
  21749. else {
  21750. s.status = NAME_STATE;
  21751. }
  21752. }
  21753. if (s.status === NAME_STATE) {
  21754. if (s.gzhead.name/* != Z_NULL*/) {
  21755. beg = s.pending; /* start of bytes to update crc */
  21756. //int val;
  21757. do {
  21758. if (s.pending === s.pending_buf_size) {
  21759. if (s.gzhead.hcrc && s.pending > beg) {
  21760. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21761. }
  21762. flush_pending(strm);
  21763. beg = s.pending;
  21764. if (s.pending === s.pending_buf_size) {
  21765. val = 1;
  21766. break;
  21767. }
  21768. }
  21769. // JS specific: little magic to add zero terminator to end of string
  21770. if (s.gzindex < s.gzhead.name.length) {
  21771. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21772. } else {
  21773. val = 0;
  21774. }
  21775. put_byte(s, val);
  21776. } while (val !== 0);
  21777. if (s.gzhead.hcrc && s.pending > beg) {
  21778. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21779. }
  21780. if (val === 0) {
  21781. s.gzindex = 0;
  21782. s.status = COMMENT_STATE;
  21783. }
  21784. }
  21785. else {
  21786. s.status = COMMENT_STATE;
  21787. }
  21788. }
  21789. if (s.status === COMMENT_STATE) {
  21790. if (s.gzhead.comment/* != Z_NULL*/) {
  21791. beg = s.pending; /* start of bytes to update crc */
  21792. //int val;
  21793. do {
  21794. if (s.pending === s.pending_buf_size) {
  21795. if (s.gzhead.hcrc && s.pending > beg) {
  21796. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21797. }
  21798. flush_pending(strm);
  21799. beg = s.pending;
  21800. if (s.pending === s.pending_buf_size) {
  21801. val = 1;
  21802. break;
  21803. }
  21804. }
  21805. // JS specific: little magic to add zero terminator to end of string
  21806. if (s.gzindex < s.gzhead.comment.length) {
  21807. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21808. } else {
  21809. val = 0;
  21810. }
  21811. put_byte(s, val);
  21812. } while (val !== 0);
  21813. if (s.gzhead.hcrc && s.pending > beg) {
  21814. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21815. }
  21816. if (val === 0) {
  21817. s.status = HCRC_STATE;
  21818. }
  21819. }
  21820. else {
  21821. s.status = HCRC_STATE;
  21822. }
  21823. }
  21824. if (s.status === HCRC_STATE) {
  21825. if (s.gzhead.hcrc) {
  21826. if (s.pending + 2 > s.pending_buf_size) {
  21827. flush_pending(strm);
  21828. }
  21829. if (s.pending + 2 <= s.pending_buf_size) {
  21830. put_byte(s, strm.adler & 0xff);
  21831. put_byte(s, (strm.adler >> 8) & 0xff);
  21832. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21833. s.status = BUSY_STATE;
  21834. }
  21835. }
  21836. else {
  21837. s.status = BUSY_STATE;
  21838. }
  21839. }
  21840. //#endif
  21841. /* Flush as much pending output as possible */
  21842. if (s.pending !== 0) {
  21843. flush_pending(strm);
  21844. if (strm.avail_out === 0) {
  21845. /* Since avail_out is 0, deflate will be called again with
  21846. * more output space, but possibly with both pending and
  21847. * avail_in equal to zero. There won't be anything to do,
  21848. * but this is not an error situation so make sure we
  21849. * return OK instead of BUF_ERROR at next call of deflate:
  21850. */
  21851. s.last_flush = -1;
  21852. return Z_OK;
  21853. }
  21854. /* Make sure there is something to do and avoid duplicate consecutive
  21855. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21856. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21857. */
  21858. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21859. flush !== Z_FINISH) {
  21860. return err(strm, Z_BUF_ERROR);
  21861. }
  21862. /* User must not provide more input after the first FINISH: */
  21863. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21864. return err(strm, Z_BUF_ERROR);
  21865. }
  21866. /* Start a new block or continue the current one.
  21867. */
  21868. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21869. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21870. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21871. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21872. configuration_table[s.level].func(s, flush));
  21873. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21874. s.status = FINISH_STATE;
  21875. }
  21876. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21877. if (strm.avail_out === 0) {
  21878. s.last_flush = -1;
  21879. /* avoid BUF_ERROR next call, see above */
  21880. }
  21881. return Z_OK;
  21882. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21883. * of deflate should use the same flush parameter to make sure
  21884. * that the flush is complete. So we don't have to output an
  21885. * empty block here, this will be done at next call. This also
  21886. * ensures that for a very small output buffer, we emit at most
  21887. * one empty block.
  21888. */
  21889. }
  21890. if (bstate === BS_BLOCK_DONE) {
  21891. if (flush === Z_PARTIAL_FLUSH) {
  21892. trees._tr_align(s);
  21893. }
  21894. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21895. trees._tr_stored_block(s, 0, 0, false);
  21896. /* For a full flush, this empty block will be recognized
  21897. * as a special marker by inflate_sync().
  21898. */
  21899. if (flush === Z_FULL_FLUSH) {
  21900. /*** CLEAR_HASH(s); ***/ /* forget history */
  21901. zero(s.head); // Fill with NIL (= 0);
  21902. if (s.lookahead === 0) {
  21903. s.strstart = 0;
  21904. s.block_start = 0;
  21905. s.insert = 0;
  21906. }
  21907. }
  21908. }
  21909. flush_pending(strm);
  21910. if (strm.avail_out === 0) {
  21911. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21912. return Z_OK;
  21913. }
  21914. }
  21915. }
  21916. //Assert(strm->avail_out > 0, "bug2");
  21917. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21918. if (flush !== Z_FINISH) { return Z_OK; }
  21919. if (s.wrap <= 0) { return Z_STREAM_END; }
  21920. /* Write the trailer */
  21921. if (s.wrap === 2) {
  21922. put_byte(s, strm.adler & 0xff);
  21923. put_byte(s, (strm.adler >> 8) & 0xff);
  21924. put_byte(s, (strm.adler >> 16) & 0xff);
  21925. put_byte(s, (strm.adler >> 24) & 0xff);
  21926. put_byte(s, strm.total_in & 0xff);
  21927. put_byte(s, (strm.total_in >> 8) & 0xff);
  21928. put_byte(s, (strm.total_in >> 16) & 0xff);
  21929. put_byte(s, (strm.total_in >> 24) & 0xff);
  21930. }
  21931. else
  21932. {
  21933. putShortMSB(s, strm.adler >>> 16);
  21934. putShortMSB(s, strm.adler & 0xffff);
  21935. }
  21936. flush_pending(strm);
  21937. /* If avail_out is zero, the application will call deflate again
  21938. * to flush the rest.
  21939. */
  21940. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21941. /* write the trailer only once! */
  21942. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21943. }
  21944. function deflateEnd(strm) {
  21945. var status;
  21946. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21947. return Z_STREAM_ERROR;
  21948. }
  21949. status = strm.state.status;
  21950. if (status !== INIT_STATE &&
  21951. status !== EXTRA_STATE &&
  21952. status !== NAME_STATE &&
  21953. status !== COMMENT_STATE &&
  21954. status !== HCRC_STATE &&
  21955. status !== BUSY_STATE &&
  21956. status !== FINISH_STATE
  21957. ) {
  21958. return err(strm, Z_STREAM_ERROR);
  21959. }
  21960. strm.state = null;
  21961. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21962. }
  21963. /* =========================================================================
  21964. * Copy the source state to the destination state
  21965. */
  21966. //function deflateCopy(dest, source) {
  21967. //
  21968. //}
  21969. exports.deflateInit = deflateInit;
  21970. exports.deflateInit2 = deflateInit2;
  21971. exports.deflateReset = deflateReset;
  21972. exports.deflateResetKeep = deflateResetKeep;
  21973. exports.deflateSetHeader = deflateSetHeader;
  21974. exports.deflate = deflate;
  21975. exports.deflateEnd = deflateEnd;
  21976. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21977. /* Not implemented
  21978. exports.deflateBound = deflateBound;
  21979. exports.deflateCopy = deflateCopy;
  21980. exports.deflateSetDictionary = deflateSetDictionary;
  21981. exports.deflateParams = deflateParams;
  21982. exports.deflatePending = deflatePending;
  21983. exports.deflatePrime = deflatePrime;
  21984. exports.deflateTune = deflateTune;
  21985. */
  21986. },{"../utils/common":74,"./adler32":76,"./crc32":78,"./messages":84,"./trees":85}],80:[function(require,module,exports){
  21987. 'use strict';
  21988. function GZheader() {
  21989. /* true if compressed data believed to be text */
  21990. this.text = 0;
  21991. /* modification time */
  21992. this.time = 0;
  21993. /* extra flags (not used when writing a gzip file) */
  21994. this.xflags = 0;
  21995. /* operating system */
  21996. this.os = 0;
  21997. /* pointer to extra field or Z_NULL if none */
  21998. this.extra = null;
  21999. /* extra field length (valid if extra != Z_NULL) */
  22000. this.extra_len = 0; // Actually, we don't need it in JS,
  22001. // but leave for few code modifications
  22002. //
  22003. // Setup limits is not necessary because in js we should not preallocate memory
  22004. // for inflate use constant limit in 65536 bytes
  22005. //
  22006. /* space at extra (only when reading header) */
  22007. // this.extra_max = 0;
  22008. /* pointer to zero-terminated file name or Z_NULL */
  22009. this.name = '';
  22010. /* space at name (only when reading header) */
  22011. // this.name_max = 0;
  22012. /* pointer to zero-terminated comment or Z_NULL */
  22013. this.comment = '';
  22014. /* space at comment (only when reading header) */
  22015. // this.comm_max = 0;
  22016. /* true if there was or will be a header crc */
  22017. this.hcrc = 0;
  22018. /* true when done reading gzip header (not used when writing a gzip file) */
  22019. this.done = false;
  22020. }
  22021. module.exports = GZheader;
  22022. },{}],81:[function(require,module,exports){
  22023. 'use strict';
  22024. // See state defs from inflate.js
  22025. var BAD = 30; /* got a data error -- remain here until reset */
  22026. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22027. /*
  22028. Decode literal, length, and distance codes and write out the resulting
  22029. literal and match bytes until either not enough input or output is
  22030. available, an end-of-block is encountered, or a data error is encountered.
  22031. When large enough input and output buffers are supplied to inflate(), for
  22032. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22033. inflate execution time is spent in this routine.
  22034. Entry assumptions:
  22035. state.mode === LEN
  22036. strm.avail_in >= 6
  22037. strm.avail_out >= 258
  22038. start >= strm.avail_out
  22039. state.bits < 8
  22040. On return, state.mode is one of:
  22041. LEN -- ran out of enough output space or enough available input
  22042. TYPE -- reached end of block code, inflate() to interpret next block
  22043. BAD -- error in block data
  22044. Notes:
  22045. - The maximum input bits used by a length/distance pair is 15 bits for the
  22046. length code, 5 bits for the length extra, 15 bits for the distance code,
  22047. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22048. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22049. checking for available input while decoding.
  22050. - The maximum bytes that a single length/distance pair can output is 258
  22051. bytes, which is the maximum length that can be coded. inflate_fast()
  22052. requires strm.avail_out >= 258 for each loop to avoid checking for
  22053. output space.
  22054. */
  22055. module.exports = function inflate_fast(strm, start) {
  22056. var state;
  22057. var _in; /* local strm.input */
  22058. var last; /* have enough input while in < last */
  22059. var _out; /* local strm.output */
  22060. var beg; /* inflate()'s initial strm.output */
  22061. var end; /* while out < end, enough space available */
  22062. //#ifdef INFLATE_STRICT
  22063. var dmax; /* maximum distance from zlib header */
  22064. //#endif
  22065. var wsize; /* window size or zero if not using window */
  22066. var whave; /* valid bytes in the window */
  22067. var wnext; /* window write index */
  22068. var window; /* allocated sliding window, if wsize != 0 */
  22069. var hold; /* local strm.hold */
  22070. var bits; /* local strm.bits */
  22071. var lcode; /* local strm.lencode */
  22072. var dcode; /* local strm.distcode */
  22073. var lmask; /* mask for first level of length codes */
  22074. var dmask; /* mask for first level of distance codes */
  22075. var here; /* retrieved table entry */
  22076. var op; /* code bits, operation, extra bits, or */
  22077. /* window position, window bytes to copy */
  22078. var len; /* match length, unused bytes */
  22079. var dist; /* match distance */
  22080. var from; /* where to copy match from */
  22081. var from_source;
  22082. var input, output; // JS specific, because we have no pointers
  22083. /* copy state to local variables */
  22084. state = strm.state;
  22085. //here = state.here;
  22086. _in = strm.next_in;
  22087. input = strm.input;
  22088. last = _in + (strm.avail_in - 5);
  22089. _out = strm.next_out;
  22090. output = strm.output;
  22091. beg = _out - (start - strm.avail_out);
  22092. end = _out + (strm.avail_out - 257);
  22093. //#ifdef INFLATE_STRICT
  22094. dmax = state.dmax;
  22095. //#endif
  22096. wsize = state.wsize;
  22097. whave = state.whave;
  22098. wnext = state.wnext;
  22099. window = state.window;
  22100. hold = state.hold;
  22101. bits = state.bits;
  22102. lcode = state.lencode;
  22103. dcode = state.distcode;
  22104. lmask = (1 << state.lenbits) - 1;
  22105. dmask = (1 << state.distbits) - 1;
  22106. /* decode literals and length/distances until end-of-block or not enough
  22107. input data or output space */
  22108. top:
  22109. do {
  22110. if (bits < 15) {
  22111. hold += input[_in++] << bits;
  22112. bits += 8;
  22113. hold += input[_in++] << bits;
  22114. bits += 8;
  22115. }
  22116. here = lcode[hold & lmask];
  22117. dolen:
  22118. for (;;) { // Goto emulation
  22119. op = here >>> 24/*here.bits*/;
  22120. hold >>>= op;
  22121. bits -= op;
  22122. op = (here >>> 16) & 0xff/*here.op*/;
  22123. if (op === 0) { /* literal */
  22124. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22125. // "inflate: literal '%c'\n" :
  22126. // "inflate: literal 0x%02x\n", here.val));
  22127. output[_out++] = here & 0xffff/*here.val*/;
  22128. }
  22129. else if (op & 16) { /* length base */
  22130. len = here & 0xffff/*here.val*/;
  22131. op &= 15; /* number of extra bits */
  22132. if (op) {
  22133. if (bits < op) {
  22134. hold += input[_in++] << bits;
  22135. bits += 8;
  22136. }
  22137. len += hold & ((1 << op) - 1);
  22138. hold >>>= op;
  22139. bits -= op;
  22140. }
  22141. //Tracevv((stderr, "inflate: length %u\n", len));
  22142. if (bits < 15) {
  22143. hold += input[_in++] << bits;
  22144. bits += 8;
  22145. hold += input[_in++] << bits;
  22146. bits += 8;
  22147. }
  22148. here = dcode[hold & dmask];
  22149. dodist:
  22150. for (;;) { // goto emulation
  22151. op = here >>> 24/*here.bits*/;
  22152. hold >>>= op;
  22153. bits -= op;
  22154. op = (here >>> 16) & 0xff/*here.op*/;
  22155. if (op & 16) { /* distance base */
  22156. dist = here & 0xffff/*here.val*/;
  22157. op &= 15; /* number of extra bits */
  22158. if (bits < op) {
  22159. hold += input[_in++] << bits;
  22160. bits += 8;
  22161. if (bits < op) {
  22162. hold += input[_in++] << bits;
  22163. bits += 8;
  22164. }
  22165. }
  22166. dist += hold & ((1 << op) - 1);
  22167. //#ifdef INFLATE_STRICT
  22168. if (dist > dmax) {
  22169. strm.msg = 'invalid distance too far back';
  22170. state.mode = BAD;
  22171. break top;
  22172. }
  22173. //#endif
  22174. hold >>>= op;
  22175. bits -= op;
  22176. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22177. op = _out - beg; /* max distance in output */
  22178. if (dist > op) { /* see if copy from window */
  22179. op = dist - op; /* distance back in window */
  22180. if (op > whave) {
  22181. if (state.sane) {
  22182. strm.msg = 'invalid distance too far back';
  22183. state.mode = BAD;
  22184. break top;
  22185. }
  22186. // (!) This block is disabled in zlib defailts,
  22187. // don't enable it for binary compatibility
  22188. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22189. // if (len <= op - whave) {
  22190. // do {
  22191. // output[_out++] = 0;
  22192. // } while (--len);
  22193. // continue top;
  22194. // }
  22195. // len -= op - whave;
  22196. // do {
  22197. // output[_out++] = 0;
  22198. // } while (--op > whave);
  22199. // if (op === 0) {
  22200. // from = _out - dist;
  22201. // do {
  22202. // output[_out++] = output[from++];
  22203. // } while (--len);
  22204. // continue top;
  22205. // }
  22206. //#endif
  22207. }
  22208. from = 0; // window index
  22209. from_source = window;
  22210. if (wnext === 0) { /* very common case */
  22211. from += wsize - op;
  22212. if (op < len) { /* some from window */
  22213. len -= op;
  22214. do {
  22215. output[_out++] = window[from++];
  22216. } while (--op);
  22217. from = _out - dist; /* rest from output */
  22218. from_source = output;
  22219. }
  22220. }
  22221. else if (wnext < op) { /* wrap around window */
  22222. from += wsize + wnext - op;
  22223. op -= wnext;
  22224. if (op < len) { /* some from end of window */
  22225. len -= op;
  22226. do {
  22227. output[_out++] = window[from++];
  22228. } while (--op);
  22229. from = 0;
  22230. if (wnext < len) { /* some from start of window */
  22231. op = wnext;
  22232. len -= op;
  22233. do {
  22234. output[_out++] = window[from++];
  22235. } while (--op);
  22236. from = _out - dist; /* rest from output */
  22237. from_source = output;
  22238. }
  22239. }
  22240. }
  22241. else { /* contiguous in window */
  22242. from += wnext - op;
  22243. if (op < len) { /* some from window */
  22244. len -= op;
  22245. do {
  22246. output[_out++] = window[from++];
  22247. } while (--op);
  22248. from = _out - dist; /* rest from output */
  22249. from_source = output;
  22250. }
  22251. }
  22252. while (len > 2) {
  22253. output[_out++] = from_source[from++];
  22254. output[_out++] = from_source[from++];
  22255. output[_out++] = from_source[from++];
  22256. len -= 3;
  22257. }
  22258. if (len) {
  22259. output[_out++] = from_source[from++];
  22260. if (len > 1) {
  22261. output[_out++] = from_source[from++];
  22262. }
  22263. }
  22264. }
  22265. else {
  22266. from = _out - dist; /* copy direct from output */
  22267. do { /* minimum length is three */
  22268. output[_out++] = output[from++];
  22269. output[_out++] = output[from++];
  22270. output[_out++] = output[from++];
  22271. len -= 3;
  22272. } while (len > 2);
  22273. if (len) {
  22274. output[_out++] = output[from++];
  22275. if (len > 1) {
  22276. output[_out++] = output[from++];
  22277. }
  22278. }
  22279. }
  22280. }
  22281. else if ((op & 64) === 0) { /* 2nd level distance code */
  22282. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22283. continue dodist;
  22284. }
  22285. else {
  22286. strm.msg = 'invalid distance code';
  22287. state.mode = BAD;
  22288. break top;
  22289. }
  22290. break; // need to emulate goto via "continue"
  22291. }
  22292. }
  22293. else if ((op & 64) === 0) { /* 2nd level length code */
  22294. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22295. continue dolen;
  22296. }
  22297. else if (op & 32) { /* end-of-block */
  22298. //Tracevv((stderr, "inflate: end of block\n"));
  22299. state.mode = TYPE;
  22300. break top;
  22301. }
  22302. else {
  22303. strm.msg = 'invalid literal/length code';
  22304. state.mode = BAD;
  22305. break top;
  22306. }
  22307. break; // need to emulate goto via "continue"
  22308. }
  22309. } while (_in < last && _out < end);
  22310. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22311. len = bits >> 3;
  22312. _in -= len;
  22313. bits -= len << 3;
  22314. hold &= (1 << bits) - 1;
  22315. /* update state and return */
  22316. strm.next_in = _in;
  22317. strm.next_out = _out;
  22318. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22319. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22320. state.hold = hold;
  22321. state.bits = bits;
  22322. return;
  22323. };
  22324. },{}],82:[function(require,module,exports){
  22325. 'use strict';
  22326. var utils = require('../utils/common');
  22327. var adler32 = require('./adler32');
  22328. var crc32 = require('./crc32');
  22329. var inflate_fast = require('./inffast');
  22330. var inflate_table = require('./inftrees');
  22331. var CODES = 0;
  22332. var LENS = 1;
  22333. var DISTS = 2;
  22334. /* Public constants ==========================================================*/
  22335. /* ===========================================================================*/
  22336. /* Allowed flush values; see deflate() and inflate() below for details */
  22337. //var Z_NO_FLUSH = 0;
  22338. //var Z_PARTIAL_FLUSH = 1;
  22339. //var Z_SYNC_FLUSH = 2;
  22340. //var Z_FULL_FLUSH = 3;
  22341. var Z_FINISH = 4;
  22342. var Z_BLOCK = 5;
  22343. var Z_TREES = 6;
  22344. /* Return codes for the compression/decompression functions. Negative values
  22345. * are errors, positive values are used for special but normal events.
  22346. */
  22347. var Z_OK = 0;
  22348. var Z_STREAM_END = 1;
  22349. var Z_NEED_DICT = 2;
  22350. //var Z_ERRNO = -1;
  22351. var Z_STREAM_ERROR = -2;
  22352. var Z_DATA_ERROR = -3;
  22353. var Z_MEM_ERROR = -4;
  22354. var Z_BUF_ERROR = -5;
  22355. //var Z_VERSION_ERROR = -6;
  22356. /* The deflate compression method */
  22357. var Z_DEFLATED = 8;
  22358. /* STATES ====================================================================*/
  22359. /* ===========================================================================*/
  22360. var HEAD = 1; /* i: waiting for magic header */
  22361. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22362. var TIME = 3; /* i: waiting for modification time (gzip) */
  22363. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22364. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22365. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22366. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22367. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22368. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22369. var DICTID = 10; /* i: waiting for dictionary check value */
  22370. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22371. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22372. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22373. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22374. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22375. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22376. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22377. var LENLENS = 18; /* i: waiting for code length code lengths */
  22378. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22379. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22380. var LEN = 21; /* i: waiting for length/lit/eob code */
  22381. var LENEXT = 22; /* i: waiting for length extra bits */
  22382. var DIST = 23; /* i: waiting for distance code */
  22383. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22384. var MATCH = 25; /* o: waiting for output space to copy string */
  22385. var LIT = 26; /* o: waiting for output space to write literal */
  22386. var CHECK = 27; /* i: waiting for 32-bit check value */
  22387. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22388. var DONE = 29; /* finished check, done -- remain here until reset */
  22389. var BAD = 30; /* got a data error -- remain here until reset */
  22390. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22391. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22392. /* ===========================================================================*/
  22393. var ENOUGH_LENS = 852;
  22394. var ENOUGH_DISTS = 592;
  22395. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22396. var MAX_WBITS = 15;
  22397. /* 32K LZ77 window */
  22398. var DEF_WBITS = MAX_WBITS;
  22399. function ZSWAP32(q) {
  22400. return (((q >>> 24) & 0xff) +
  22401. ((q >>> 8) & 0xff00) +
  22402. ((q & 0xff00) << 8) +
  22403. ((q & 0xff) << 24));
  22404. }
  22405. function InflateState() {
  22406. this.mode = 0; /* current inflate mode */
  22407. this.last = false; /* true if processing last block */
  22408. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22409. this.havedict = false; /* true if dictionary provided */
  22410. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22411. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22412. this.check = 0; /* protected copy of check value */
  22413. this.total = 0; /* protected copy of output count */
  22414. // TODO: may be {}
  22415. this.head = null; /* where to save gzip header information */
  22416. /* sliding window */
  22417. this.wbits = 0; /* log base 2 of requested window size */
  22418. this.wsize = 0; /* window size or zero if not using window */
  22419. this.whave = 0; /* valid bytes in the window */
  22420. this.wnext = 0; /* window write index */
  22421. this.window = null; /* allocated sliding window, if needed */
  22422. /* bit accumulator */
  22423. this.hold = 0; /* input bit accumulator */
  22424. this.bits = 0; /* number of bits in "in" */
  22425. /* for string and stored block copying */
  22426. this.length = 0; /* literal or length of data to copy */
  22427. this.offset = 0; /* distance back to copy string from */
  22428. /* for table and code decoding */
  22429. this.extra = 0; /* extra bits needed */
  22430. /* fixed and dynamic code tables */
  22431. this.lencode = null; /* starting table for length/literal codes */
  22432. this.distcode = null; /* starting table for distance codes */
  22433. this.lenbits = 0; /* index bits for lencode */
  22434. this.distbits = 0; /* index bits for distcode */
  22435. /* dynamic table building */
  22436. this.ncode = 0; /* number of code length code lengths */
  22437. this.nlen = 0; /* number of length code lengths */
  22438. this.ndist = 0; /* number of distance code lengths */
  22439. this.have = 0; /* number of code lengths in lens[] */
  22440. this.next = null; /* next available space in codes[] */
  22441. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  22442. this.work = new utils.Buf16(288); /* work area for code table building */
  22443. /*
  22444. because we don't have pointers in js, we use lencode and distcode directly
  22445. as buffers so we don't need codes
  22446. */
  22447. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  22448. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  22449. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  22450. this.sane = 0; /* if false, allow invalid distance too far */
  22451. this.back = 0; /* bits back of last unprocessed length/lit */
  22452. this.was = 0; /* initial length of match */
  22453. }
  22454. function inflateResetKeep(strm) {
  22455. var state;
  22456. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22457. state = strm.state;
  22458. strm.total_in = strm.total_out = state.total = 0;
  22459. strm.msg = ''; /*Z_NULL*/
  22460. if (state.wrap) { /* to support ill-conceived Java test suite */
  22461. strm.adler = state.wrap & 1;
  22462. }
  22463. state.mode = HEAD;
  22464. state.last = 0;
  22465. state.havedict = 0;
  22466. state.dmax = 32768;
  22467. state.head = null/*Z_NULL*/;
  22468. state.hold = 0;
  22469. state.bits = 0;
  22470. //state.lencode = state.distcode = state.next = state.codes;
  22471. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  22472. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  22473. state.sane = 1;
  22474. state.back = -1;
  22475. //Tracev((stderr, "inflate: reset\n"));
  22476. return Z_OK;
  22477. }
  22478. function inflateReset(strm) {
  22479. var state;
  22480. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22481. state = strm.state;
  22482. state.wsize = 0;
  22483. state.whave = 0;
  22484. state.wnext = 0;
  22485. return inflateResetKeep(strm);
  22486. }
  22487. function inflateReset2(strm, windowBits) {
  22488. var wrap;
  22489. var state;
  22490. /* get the state */
  22491. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22492. state = strm.state;
  22493. /* extract wrap request from windowBits parameter */
  22494. if (windowBits < 0) {
  22495. wrap = 0;
  22496. windowBits = -windowBits;
  22497. }
  22498. else {
  22499. wrap = (windowBits >> 4) + 1;
  22500. if (windowBits < 48) {
  22501. windowBits &= 15;
  22502. }
  22503. }
  22504. /* set number of window bits, free window if different */
  22505. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  22506. return Z_STREAM_ERROR;
  22507. }
  22508. if (state.window !== null && state.wbits !== windowBits) {
  22509. state.window = null;
  22510. }
  22511. /* update state and reset the rest of it */
  22512. state.wrap = wrap;
  22513. state.wbits = windowBits;
  22514. return inflateReset(strm);
  22515. }
  22516. function inflateInit2(strm, windowBits) {
  22517. var ret;
  22518. var state;
  22519. if (!strm) { return Z_STREAM_ERROR; }
  22520. //strm.msg = Z_NULL; /* in case we return an error */
  22521. state = new InflateState();
  22522. //if (state === Z_NULL) return Z_MEM_ERROR;
  22523. //Tracev((stderr, "inflate: allocated\n"));
  22524. strm.state = state;
  22525. state.window = null/*Z_NULL*/;
  22526. ret = inflateReset2(strm, windowBits);
  22527. if (ret !== Z_OK) {
  22528. strm.state = null/*Z_NULL*/;
  22529. }
  22530. return ret;
  22531. }
  22532. function inflateInit(strm) {
  22533. return inflateInit2(strm, DEF_WBITS);
  22534. }
  22535. /*
  22536. Return state with length and distance decoding tables and index sizes set to
  22537. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  22538. If BUILDFIXED is defined, then instead this routine builds the tables the
  22539. first time it's called, and returns those tables the first time and
  22540. thereafter. This reduces the size of the code by about 2K bytes, in
  22541. exchange for a little execution time. However, BUILDFIXED should not be
  22542. used for threaded applications, since the rewriting of the tables and virgin
  22543. may not be thread-safe.
  22544. */
  22545. var virgin = true;
  22546. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  22547. function fixedtables(state) {
  22548. /* build fixed huffman tables if first call (may not be thread safe) */
  22549. if (virgin) {
  22550. var sym;
  22551. lenfix = new utils.Buf32(512);
  22552. distfix = new utils.Buf32(32);
  22553. /* literal/length table */
  22554. sym = 0;
  22555. while (sym < 144) { state.lens[sym++] = 8; }
  22556. while (sym < 256) { state.lens[sym++] = 9; }
  22557. while (sym < 280) { state.lens[sym++] = 7; }
  22558. while (sym < 288) { state.lens[sym++] = 8; }
  22559. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  22560. /* distance table */
  22561. sym = 0;
  22562. while (sym < 32) { state.lens[sym++] = 5; }
  22563. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  22564. /* do this just once */
  22565. virgin = false;
  22566. }
  22567. state.lencode = lenfix;
  22568. state.lenbits = 9;
  22569. state.distcode = distfix;
  22570. state.distbits = 5;
  22571. }
  22572. /*
  22573. Update the window with the last wsize (normally 32K) bytes written before
  22574. returning. If window does not exist yet, create it. This is only called
  22575. when a window is already in use, or when output has been written during this
  22576. inflate call, but the end of the deflate stream has not been reached yet.
  22577. It is also called to create a window for dictionary data when a dictionary
  22578. is loaded.
  22579. Providing output buffers larger than 32K to inflate() should provide a speed
  22580. advantage, since only the last 32K of output is copied to the sliding window
  22581. upon return from inflate(), and since all distances after the first 32K of
  22582. output will fall in the output data, making match copies simpler and faster.
  22583. The advantage may be dependent on the size of the processor's data caches.
  22584. */
  22585. function updatewindow(strm, src, end, copy) {
  22586. var dist;
  22587. var state = strm.state;
  22588. /* if it hasn't been done already, allocate space for the window */
  22589. if (state.window === null) {
  22590. state.wsize = 1 << state.wbits;
  22591. state.wnext = 0;
  22592. state.whave = 0;
  22593. state.window = new utils.Buf8(state.wsize);
  22594. }
  22595. /* copy state->wsize or less output bytes into the circular window */
  22596. if (copy >= state.wsize) {
  22597. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  22598. state.wnext = 0;
  22599. state.whave = state.wsize;
  22600. }
  22601. else {
  22602. dist = state.wsize - state.wnext;
  22603. if (dist > copy) {
  22604. dist = copy;
  22605. }
  22606. //zmemcpy(state->window + state->wnext, end - copy, dist);
  22607. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  22608. copy -= dist;
  22609. if (copy) {
  22610. //zmemcpy(state->window, end - copy, copy);
  22611. utils.arraySet(state.window,src, end - copy, copy, 0);
  22612. state.wnext = copy;
  22613. state.whave = state.wsize;
  22614. }
  22615. else {
  22616. state.wnext += dist;
  22617. if (state.wnext === state.wsize) { state.wnext = 0; }
  22618. if (state.whave < state.wsize) { state.whave += dist; }
  22619. }
  22620. }
  22621. return 0;
  22622. }
  22623. function inflate(strm, flush) {
  22624. var state;
  22625. var input, output; // input/output buffers
  22626. var next; /* next input INDEX */
  22627. var put; /* next output INDEX */
  22628. var have, left; /* available input and output */
  22629. var hold; /* bit buffer */
  22630. var bits; /* bits in bit buffer */
  22631. var _in, _out; /* save starting available input and output */
  22632. var copy; /* number of stored or match bytes to copy */
  22633. var from; /* where to copy match bytes from */
  22634. var from_source;
  22635. var here = 0; /* current decoding table entry */
  22636. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  22637. //var last; /* parent table entry */
  22638. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  22639. var len; /* length to copy for repeats, bits to drop */
  22640. var ret; /* return code */
  22641. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  22642. var opts;
  22643. var n; // temporary var for NEED_BITS
  22644. var order = /* permutation of code lengths */
  22645. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  22646. if (!strm || !strm.state || !strm.output ||
  22647. (!strm.input && strm.avail_in !== 0)) {
  22648. return Z_STREAM_ERROR;
  22649. }
  22650. state = strm.state;
  22651. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  22652. //--- LOAD() ---
  22653. put = strm.next_out;
  22654. output = strm.output;
  22655. left = strm.avail_out;
  22656. next = strm.next_in;
  22657. input = strm.input;
  22658. have = strm.avail_in;
  22659. hold = state.hold;
  22660. bits = state.bits;
  22661. //---
  22662. _in = have;
  22663. _out = left;
  22664. ret = Z_OK;
  22665. inf_leave: // goto emulation
  22666. for (;;) {
  22667. switch (state.mode) {
  22668. case HEAD:
  22669. if (state.wrap === 0) {
  22670. state.mode = TYPEDO;
  22671. break;
  22672. }
  22673. //=== NEEDBITS(16);
  22674. while (bits < 16) {
  22675. if (have === 0) { break inf_leave; }
  22676. have--;
  22677. hold += input[next++] << bits;
  22678. bits += 8;
  22679. }
  22680. //===//
  22681. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  22682. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  22683. //=== CRC2(state.check, hold);
  22684. hbuf[0] = hold & 0xff;
  22685. hbuf[1] = (hold >>> 8) & 0xff;
  22686. state.check = crc32(state.check, hbuf, 2, 0);
  22687. //===//
  22688. //=== INITBITS();
  22689. hold = 0;
  22690. bits = 0;
  22691. //===//
  22692. state.mode = FLAGS;
  22693. break;
  22694. }
  22695. state.flags = 0; /* expect zlib header */
  22696. if (state.head) {
  22697. state.head.done = false;
  22698. }
  22699. if (!(state.wrap & 1) || /* check if zlib header allowed */
  22700. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  22701. strm.msg = 'incorrect header check';
  22702. state.mode = BAD;
  22703. break;
  22704. }
  22705. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  22706. strm.msg = 'unknown compression method';
  22707. state.mode = BAD;
  22708. break;
  22709. }
  22710. //--- DROPBITS(4) ---//
  22711. hold >>>= 4;
  22712. bits -= 4;
  22713. //---//
  22714. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22715. if (state.wbits === 0) {
  22716. state.wbits = len;
  22717. }
  22718. else if (len > state.wbits) {
  22719. strm.msg = 'invalid window size';
  22720. state.mode = BAD;
  22721. break;
  22722. }
  22723. state.dmax = 1 << len;
  22724. //Tracev((stderr, "inflate: zlib header ok\n"));
  22725. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22726. state.mode = hold & 0x200 ? DICTID : TYPE;
  22727. //=== INITBITS();
  22728. hold = 0;
  22729. bits = 0;
  22730. //===//
  22731. break;
  22732. case FLAGS:
  22733. //=== NEEDBITS(16); */
  22734. while (bits < 16) {
  22735. if (have === 0) { break inf_leave; }
  22736. have--;
  22737. hold += input[next++] << bits;
  22738. bits += 8;
  22739. }
  22740. //===//
  22741. state.flags = hold;
  22742. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22743. strm.msg = 'unknown compression method';
  22744. state.mode = BAD;
  22745. break;
  22746. }
  22747. if (state.flags & 0xe000) {
  22748. strm.msg = 'unknown header flags set';
  22749. state.mode = BAD;
  22750. break;
  22751. }
  22752. if (state.head) {
  22753. state.head.text = ((hold >> 8) & 1);
  22754. }
  22755. if (state.flags & 0x0200) {
  22756. //=== CRC2(state.check, hold);
  22757. hbuf[0] = hold & 0xff;
  22758. hbuf[1] = (hold >>> 8) & 0xff;
  22759. state.check = crc32(state.check, hbuf, 2, 0);
  22760. //===//
  22761. }
  22762. //=== INITBITS();
  22763. hold = 0;
  22764. bits = 0;
  22765. //===//
  22766. state.mode = TIME;
  22767. /* falls through */
  22768. case TIME:
  22769. //=== NEEDBITS(32); */
  22770. while (bits < 32) {
  22771. if (have === 0) { break inf_leave; }
  22772. have--;
  22773. hold += input[next++] << bits;
  22774. bits += 8;
  22775. }
  22776. //===//
  22777. if (state.head) {
  22778. state.head.time = hold;
  22779. }
  22780. if (state.flags & 0x0200) {
  22781. //=== CRC4(state.check, hold)
  22782. hbuf[0] = hold & 0xff;
  22783. hbuf[1] = (hold >>> 8) & 0xff;
  22784. hbuf[2] = (hold >>> 16) & 0xff;
  22785. hbuf[3] = (hold >>> 24) & 0xff;
  22786. state.check = crc32(state.check, hbuf, 4, 0);
  22787. //===
  22788. }
  22789. //=== INITBITS();
  22790. hold = 0;
  22791. bits = 0;
  22792. //===//
  22793. state.mode = OS;
  22794. /* falls through */
  22795. case OS:
  22796. //=== NEEDBITS(16); */
  22797. while (bits < 16) {
  22798. if (have === 0) { break inf_leave; }
  22799. have--;
  22800. hold += input[next++] << bits;
  22801. bits += 8;
  22802. }
  22803. //===//
  22804. if (state.head) {
  22805. state.head.xflags = (hold & 0xff);
  22806. state.head.os = (hold >> 8);
  22807. }
  22808. if (state.flags & 0x0200) {
  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. }
  22815. //=== INITBITS();
  22816. hold = 0;
  22817. bits = 0;
  22818. //===//
  22819. state.mode = EXLEN;
  22820. /* falls through */
  22821. case EXLEN:
  22822. if (state.flags & 0x0400) {
  22823. //=== NEEDBITS(16); */
  22824. while (bits < 16) {
  22825. if (have === 0) { break inf_leave; }
  22826. have--;
  22827. hold += input[next++] << bits;
  22828. bits += 8;
  22829. }
  22830. //===//
  22831. state.length = hold;
  22832. if (state.head) {
  22833. state.head.extra_len = hold;
  22834. }
  22835. if (state.flags & 0x0200) {
  22836. //=== CRC2(state.check, hold);
  22837. hbuf[0] = hold & 0xff;
  22838. hbuf[1] = (hold >>> 8) & 0xff;
  22839. state.check = crc32(state.check, hbuf, 2, 0);
  22840. //===//
  22841. }
  22842. //=== INITBITS();
  22843. hold = 0;
  22844. bits = 0;
  22845. //===//
  22846. }
  22847. else if (state.head) {
  22848. state.head.extra = null/*Z_NULL*/;
  22849. }
  22850. state.mode = EXTRA;
  22851. /* falls through */
  22852. case EXTRA:
  22853. if (state.flags & 0x0400) {
  22854. copy = state.length;
  22855. if (copy > have) { copy = have; }
  22856. if (copy) {
  22857. if (state.head) {
  22858. len = state.head.extra_len - state.length;
  22859. if (!state.head.extra) {
  22860. // Use untyped array for more conveniend processing later
  22861. state.head.extra = new Array(state.head.extra_len);
  22862. }
  22863. utils.arraySet(
  22864. state.head.extra,
  22865. input,
  22866. next,
  22867. // extra field is limited to 65536 bytes
  22868. // - no need for additional size check
  22869. copy,
  22870. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22871. len
  22872. );
  22873. //zmemcpy(state.head.extra + len, next,
  22874. // len + copy > state.head.extra_max ?
  22875. // state.head.extra_max - len : copy);
  22876. }
  22877. if (state.flags & 0x0200) {
  22878. state.check = crc32(state.check, input, copy, next);
  22879. }
  22880. have -= copy;
  22881. next += copy;
  22882. state.length -= copy;
  22883. }
  22884. if (state.length) { break inf_leave; }
  22885. }
  22886. state.length = 0;
  22887. state.mode = NAME;
  22888. /* falls through */
  22889. case NAME:
  22890. if (state.flags & 0x0800) {
  22891. if (have === 0) { break inf_leave; }
  22892. copy = 0;
  22893. do {
  22894. // TODO: 2 or 1 bytes?
  22895. len = input[next + copy++];
  22896. /* use constant limit because in js we should not preallocate memory */
  22897. if (state.head && len &&
  22898. (state.length < 65536 /*state.head.name_max*/)) {
  22899. state.head.name += String.fromCharCode(len);
  22900. }
  22901. } while (len && copy < have);
  22902. if (state.flags & 0x0200) {
  22903. state.check = crc32(state.check, input, copy, next);
  22904. }
  22905. have -= copy;
  22906. next += copy;
  22907. if (len) { break inf_leave; }
  22908. }
  22909. else if (state.head) {
  22910. state.head.name = null;
  22911. }
  22912. state.length = 0;
  22913. state.mode = COMMENT;
  22914. /* falls through */
  22915. case COMMENT:
  22916. if (state.flags & 0x1000) {
  22917. if (have === 0) { break inf_leave; }
  22918. copy = 0;
  22919. do {
  22920. len = input[next + copy++];
  22921. /* use constant limit because in js we should not preallocate memory */
  22922. if (state.head && len &&
  22923. (state.length < 65536 /*state.head.comm_max*/)) {
  22924. state.head.comment += String.fromCharCode(len);
  22925. }
  22926. } while (len && copy < have);
  22927. if (state.flags & 0x0200) {
  22928. state.check = crc32(state.check, input, copy, next);
  22929. }
  22930. have -= copy;
  22931. next += copy;
  22932. if (len) { break inf_leave; }
  22933. }
  22934. else if (state.head) {
  22935. state.head.comment = null;
  22936. }
  22937. state.mode = HCRC;
  22938. /* falls through */
  22939. case HCRC:
  22940. if (state.flags & 0x0200) {
  22941. //=== NEEDBITS(16); */
  22942. while (bits < 16) {
  22943. if (have === 0) { break inf_leave; }
  22944. have--;
  22945. hold += input[next++] << bits;
  22946. bits += 8;
  22947. }
  22948. //===//
  22949. if (hold !== (state.check & 0xffff)) {
  22950. strm.msg = 'header crc mismatch';
  22951. state.mode = BAD;
  22952. break;
  22953. }
  22954. //=== INITBITS();
  22955. hold = 0;
  22956. bits = 0;
  22957. //===//
  22958. }
  22959. if (state.head) {
  22960. state.head.hcrc = ((state.flags >> 9) & 1);
  22961. state.head.done = true;
  22962. }
  22963. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22964. state.mode = TYPE;
  22965. break;
  22966. case DICTID:
  22967. //=== NEEDBITS(32); */
  22968. while (bits < 32) {
  22969. if (have === 0) { break inf_leave; }
  22970. have--;
  22971. hold += input[next++] << bits;
  22972. bits += 8;
  22973. }
  22974. //===//
  22975. strm.adler = state.check = ZSWAP32(hold);
  22976. //=== INITBITS();
  22977. hold = 0;
  22978. bits = 0;
  22979. //===//
  22980. state.mode = DICT;
  22981. /* falls through */
  22982. case DICT:
  22983. if (state.havedict === 0) {
  22984. //--- RESTORE() ---
  22985. strm.next_out = put;
  22986. strm.avail_out = left;
  22987. strm.next_in = next;
  22988. strm.avail_in = have;
  22989. state.hold = hold;
  22990. state.bits = bits;
  22991. //---
  22992. return Z_NEED_DICT;
  22993. }
  22994. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22995. state.mode = TYPE;
  22996. /* falls through */
  22997. case TYPE:
  22998. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22999. /* falls through */
  23000. case TYPEDO:
  23001. if (state.last) {
  23002. //--- BYTEBITS() ---//
  23003. hold >>>= bits & 7;
  23004. bits -= bits & 7;
  23005. //---//
  23006. state.mode = CHECK;
  23007. break;
  23008. }
  23009. //=== NEEDBITS(3); */
  23010. while (bits < 3) {
  23011. if (have === 0) { break inf_leave; }
  23012. have--;
  23013. hold += input[next++] << bits;
  23014. bits += 8;
  23015. }
  23016. //===//
  23017. state.last = (hold & 0x01)/*BITS(1)*/;
  23018. //--- DROPBITS(1) ---//
  23019. hold >>>= 1;
  23020. bits -= 1;
  23021. //---//
  23022. switch ((hold & 0x03)/*BITS(2)*/) {
  23023. case 0: /* stored block */
  23024. //Tracev((stderr, "inflate: stored block%s\n",
  23025. // state.last ? " (last)" : ""));
  23026. state.mode = STORED;
  23027. break;
  23028. case 1: /* fixed block */
  23029. fixedtables(state);
  23030. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23031. // state.last ? " (last)" : ""));
  23032. state.mode = LEN_; /* decode codes */
  23033. if (flush === Z_TREES) {
  23034. //--- DROPBITS(2) ---//
  23035. hold >>>= 2;
  23036. bits -= 2;
  23037. //---//
  23038. break inf_leave;
  23039. }
  23040. break;
  23041. case 2: /* dynamic block */
  23042. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23043. // state.last ? " (last)" : ""));
  23044. state.mode = TABLE;
  23045. break;
  23046. case 3:
  23047. strm.msg = 'invalid block type';
  23048. state.mode = BAD;
  23049. }
  23050. //--- DROPBITS(2) ---//
  23051. hold >>>= 2;
  23052. bits -= 2;
  23053. //---//
  23054. break;
  23055. case STORED:
  23056. //--- BYTEBITS() ---// /* go to byte boundary */
  23057. hold >>>= bits & 7;
  23058. bits -= bits & 7;
  23059. //---//
  23060. //=== NEEDBITS(32); */
  23061. while (bits < 32) {
  23062. if (have === 0) { break inf_leave; }
  23063. have--;
  23064. hold += input[next++] << bits;
  23065. bits += 8;
  23066. }
  23067. //===//
  23068. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23069. strm.msg = 'invalid stored block lengths';
  23070. state.mode = BAD;
  23071. break;
  23072. }
  23073. state.length = hold & 0xffff;
  23074. //Tracev((stderr, "inflate: stored length %u\n",
  23075. // state.length));
  23076. //=== INITBITS();
  23077. hold = 0;
  23078. bits = 0;
  23079. //===//
  23080. state.mode = COPY_;
  23081. if (flush === Z_TREES) { break inf_leave; }
  23082. /* falls through */
  23083. case COPY_:
  23084. state.mode = COPY;
  23085. /* falls through */
  23086. case COPY:
  23087. copy = state.length;
  23088. if (copy) {
  23089. if (copy > have) { copy = have; }
  23090. if (copy > left) { copy = left; }
  23091. if (copy === 0) { break inf_leave; }
  23092. //--- zmemcpy(put, next, copy); ---
  23093. utils.arraySet(output, input, next, copy, put);
  23094. //---//
  23095. have -= copy;
  23096. next += copy;
  23097. left -= copy;
  23098. put += copy;
  23099. state.length -= copy;
  23100. break;
  23101. }
  23102. //Tracev((stderr, "inflate: stored end\n"));
  23103. state.mode = TYPE;
  23104. break;
  23105. case TABLE:
  23106. //=== NEEDBITS(14); */
  23107. while (bits < 14) {
  23108. if (have === 0) { break inf_leave; }
  23109. have--;
  23110. hold += input[next++] << bits;
  23111. bits += 8;
  23112. }
  23113. //===//
  23114. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23115. //--- DROPBITS(5) ---//
  23116. hold >>>= 5;
  23117. bits -= 5;
  23118. //---//
  23119. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23120. //--- DROPBITS(5) ---//
  23121. hold >>>= 5;
  23122. bits -= 5;
  23123. //---//
  23124. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23125. //--- DROPBITS(4) ---//
  23126. hold >>>= 4;
  23127. bits -= 4;
  23128. //---//
  23129. //#ifndef PKZIP_BUG_WORKAROUND
  23130. if (state.nlen > 286 || state.ndist > 30) {
  23131. strm.msg = 'too many length or distance symbols';
  23132. state.mode = BAD;
  23133. break;
  23134. }
  23135. //#endif
  23136. //Tracev((stderr, "inflate: table sizes ok\n"));
  23137. state.have = 0;
  23138. state.mode = LENLENS;
  23139. /* falls through */
  23140. case LENLENS:
  23141. while (state.have < state.ncode) {
  23142. //=== NEEDBITS(3);
  23143. while (bits < 3) {
  23144. if (have === 0) { break inf_leave; }
  23145. have--;
  23146. hold += input[next++] << bits;
  23147. bits += 8;
  23148. }
  23149. //===//
  23150. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23151. //--- DROPBITS(3) ---//
  23152. hold >>>= 3;
  23153. bits -= 3;
  23154. //---//
  23155. }
  23156. while (state.have < 19) {
  23157. state.lens[order[state.have++]] = 0;
  23158. }
  23159. // We have separate tables & no pointers. 2 commented lines below not needed.
  23160. //state.next = state.codes;
  23161. //state.lencode = state.next;
  23162. // Switch to use dynamic table
  23163. state.lencode = state.lendyn;
  23164. state.lenbits = 7;
  23165. opts = {bits: state.lenbits};
  23166. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23167. state.lenbits = opts.bits;
  23168. if (ret) {
  23169. strm.msg = 'invalid code lengths set';
  23170. state.mode = BAD;
  23171. break;
  23172. }
  23173. //Tracev((stderr, "inflate: code lengths ok\n"));
  23174. state.have = 0;
  23175. state.mode = CODELENS;
  23176. /* falls through */
  23177. case CODELENS:
  23178. while (state.have < state.nlen + state.ndist) {
  23179. for (;;) {
  23180. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23181. here_bits = here >>> 24;
  23182. here_op = (here >>> 16) & 0xff;
  23183. here_val = here & 0xffff;
  23184. if ((here_bits) <= bits) { break; }
  23185. //--- PULLBYTE() ---//
  23186. if (have === 0) { break inf_leave; }
  23187. have--;
  23188. hold += input[next++] << bits;
  23189. bits += 8;
  23190. //---//
  23191. }
  23192. if (here_val < 16) {
  23193. //--- DROPBITS(here.bits) ---//
  23194. hold >>>= here_bits;
  23195. bits -= here_bits;
  23196. //---//
  23197. state.lens[state.have++] = here_val;
  23198. }
  23199. else {
  23200. if (here_val === 16) {
  23201. //=== NEEDBITS(here.bits + 2);
  23202. n = here_bits + 2;
  23203. while (bits < n) {
  23204. if (have === 0) { break inf_leave; }
  23205. have--;
  23206. hold += input[next++] << bits;
  23207. bits += 8;
  23208. }
  23209. //===//
  23210. //--- DROPBITS(here.bits) ---//
  23211. hold >>>= here_bits;
  23212. bits -= here_bits;
  23213. //---//
  23214. if (state.have === 0) {
  23215. strm.msg = 'invalid bit length repeat';
  23216. state.mode = BAD;
  23217. break;
  23218. }
  23219. len = state.lens[state.have - 1];
  23220. copy = 3 + (hold & 0x03);//BITS(2);
  23221. //--- DROPBITS(2) ---//
  23222. hold >>>= 2;
  23223. bits -= 2;
  23224. //---//
  23225. }
  23226. else if (here_val === 17) {
  23227. //=== NEEDBITS(here.bits + 3);
  23228. n = here_bits + 3;
  23229. while (bits < n) {
  23230. if (have === 0) { break inf_leave; }
  23231. have--;
  23232. hold += input[next++] << bits;
  23233. bits += 8;
  23234. }
  23235. //===//
  23236. //--- DROPBITS(here.bits) ---//
  23237. hold >>>= here_bits;
  23238. bits -= here_bits;
  23239. //---//
  23240. len = 0;
  23241. copy = 3 + (hold & 0x07);//BITS(3);
  23242. //--- DROPBITS(3) ---//
  23243. hold >>>= 3;
  23244. bits -= 3;
  23245. //---//
  23246. }
  23247. else {
  23248. //=== NEEDBITS(here.bits + 7);
  23249. n = here_bits + 7;
  23250. while (bits < n) {
  23251. if (have === 0) { break inf_leave; }
  23252. have--;
  23253. hold += input[next++] << bits;
  23254. bits += 8;
  23255. }
  23256. //===//
  23257. //--- DROPBITS(here.bits) ---//
  23258. hold >>>= here_bits;
  23259. bits -= here_bits;
  23260. //---//
  23261. len = 0;
  23262. copy = 11 + (hold & 0x7f);//BITS(7);
  23263. //--- DROPBITS(7) ---//
  23264. hold >>>= 7;
  23265. bits -= 7;
  23266. //---//
  23267. }
  23268. if (state.have + copy > state.nlen + state.ndist) {
  23269. strm.msg = 'invalid bit length repeat';
  23270. state.mode = BAD;
  23271. break;
  23272. }
  23273. while (copy--) {
  23274. state.lens[state.have++] = len;
  23275. }
  23276. }
  23277. }
  23278. /* handle error breaks in while */
  23279. if (state.mode === BAD) { break; }
  23280. /* check for end-of-block code (better have one) */
  23281. if (state.lens[256] === 0) {
  23282. strm.msg = 'invalid code -- missing end-of-block';
  23283. state.mode = BAD;
  23284. break;
  23285. }
  23286. /* build code tables -- note: do not change the lenbits or distbits
  23287. values here (9 and 6) without reading the comments in inftrees.h
  23288. concerning the ENOUGH constants, which depend on those values */
  23289. state.lenbits = 9;
  23290. opts = {bits: state.lenbits};
  23291. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23292. // We have separate tables & no pointers. 2 commented lines below not needed.
  23293. // state.next_index = opts.table_index;
  23294. state.lenbits = opts.bits;
  23295. // state.lencode = state.next;
  23296. if (ret) {
  23297. strm.msg = 'invalid literal/lengths set';
  23298. state.mode = BAD;
  23299. break;
  23300. }
  23301. state.distbits = 6;
  23302. //state.distcode.copy(state.codes);
  23303. // Switch to use dynamic table
  23304. state.distcode = state.distdyn;
  23305. opts = {bits: state.distbits};
  23306. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23307. // We have separate tables & no pointers. 2 commented lines below not needed.
  23308. // state.next_index = opts.table_index;
  23309. state.distbits = opts.bits;
  23310. // state.distcode = state.next;
  23311. if (ret) {
  23312. strm.msg = 'invalid distances set';
  23313. state.mode = BAD;
  23314. break;
  23315. }
  23316. //Tracev((stderr, 'inflate: codes ok\n'));
  23317. state.mode = LEN_;
  23318. if (flush === Z_TREES) { break inf_leave; }
  23319. /* falls through */
  23320. case LEN_:
  23321. state.mode = LEN;
  23322. /* falls through */
  23323. case LEN:
  23324. if (have >= 6 && left >= 258) {
  23325. //--- RESTORE() ---
  23326. strm.next_out = put;
  23327. strm.avail_out = left;
  23328. strm.next_in = next;
  23329. strm.avail_in = have;
  23330. state.hold = hold;
  23331. state.bits = bits;
  23332. //---
  23333. inflate_fast(strm, _out);
  23334. //--- LOAD() ---
  23335. put = strm.next_out;
  23336. output = strm.output;
  23337. left = strm.avail_out;
  23338. next = strm.next_in;
  23339. input = strm.input;
  23340. have = strm.avail_in;
  23341. hold = state.hold;
  23342. bits = state.bits;
  23343. //---
  23344. if (state.mode === TYPE) {
  23345. state.back = -1;
  23346. }
  23347. break;
  23348. }
  23349. state.back = 0;
  23350. for (;;) {
  23351. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23352. here_bits = here >>> 24;
  23353. here_op = (here >>> 16) & 0xff;
  23354. here_val = here & 0xffff;
  23355. if (here_bits <= bits) { break; }
  23356. //--- PULLBYTE() ---//
  23357. if (have === 0) { break inf_leave; }
  23358. have--;
  23359. hold += input[next++] << bits;
  23360. bits += 8;
  23361. //---//
  23362. }
  23363. if (here_op && (here_op & 0xf0) === 0) {
  23364. last_bits = here_bits;
  23365. last_op = here_op;
  23366. last_val = here_val;
  23367. for (;;) {
  23368. here = state.lencode[last_val +
  23369. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23370. here_bits = here >>> 24;
  23371. here_op = (here >>> 16) & 0xff;
  23372. here_val = here & 0xffff;
  23373. if ((last_bits + here_bits) <= bits) { break; }
  23374. //--- PULLBYTE() ---//
  23375. if (have === 0) { break inf_leave; }
  23376. have--;
  23377. hold += input[next++] << bits;
  23378. bits += 8;
  23379. //---//
  23380. }
  23381. //--- DROPBITS(last.bits) ---//
  23382. hold >>>= last_bits;
  23383. bits -= last_bits;
  23384. //---//
  23385. state.back += last_bits;
  23386. }
  23387. //--- DROPBITS(here.bits) ---//
  23388. hold >>>= here_bits;
  23389. bits -= here_bits;
  23390. //---//
  23391. state.back += here_bits;
  23392. state.length = here_val;
  23393. if (here_op === 0) {
  23394. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23395. // "inflate: literal '%c'\n" :
  23396. // "inflate: literal 0x%02x\n", here.val));
  23397. state.mode = LIT;
  23398. break;
  23399. }
  23400. if (here_op & 32) {
  23401. //Tracevv((stderr, "inflate: end of block\n"));
  23402. state.back = -1;
  23403. state.mode = TYPE;
  23404. break;
  23405. }
  23406. if (here_op & 64) {
  23407. strm.msg = 'invalid literal/length code';
  23408. state.mode = BAD;
  23409. break;
  23410. }
  23411. state.extra = here_op & 15;
  23412. state.mode = LENEXT;
  23413. /* falls through */
  23414. case LENEXT:
  23415. if (state.extra) {
  23416. //=== NEEDBITS(state.extra);
  23417. n = state.extra;
  23418. while (bits < n) {
  23419. if (have === 0) { break inf_leave; }
  23420. have--;
  23421. hold += input[next++] << bits;
  23422. bits += 8;
  23423. }
  23424. //===//
  23425. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23426. //--- DROPBITS(state.extra) ---//
  23427. hold >>>= state.extra;
  23428. bits -= state.extra;
  23429. //---//
  23430. state.back += state.extra;
  23431. }
  23432. //Tracevv((stderr, "inflate: length %u\n", state.length));
  23433. state.was = state.length;
  23434. state.mode = DIST;
  23435. /* falls through */
  23436. case DIST:
  23437. for (;;) {
  23438. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  23439. here_bits = here >>> 24;
  23440. here_op = (here >>> 16) & 0xff;
  23441. here_val = here & 0xffff;
  23442. if ((here_bits) <= bits) { break; }
  23443. //--- PULLBYTE() ---//
  23444. if (have === 0) { break inf_leave; }
  23445. have--;
  23446. hold += input[next++] << bits;
  23447. bits += 8;
  23448. //---//
  23449. }
  23450. if ((here_op & 0xf0) === 0) {
  23451. last_bits = here_bits;
  23452. last_op = here_op;
  23453. last_val = here_val;
  23454. for (;;) {
  23455. here = state.distcode[last_val +
  23456. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23457. here_bits = here >>> 24;
  23458. here_op = (here >>> 16) & 0xff;
  23459. here_val = here & 0xffff;
  23460. if ((last_bits + here_bits) <= bits) { break; }
  23461. //--- PULLBYTE() ---//
  23462. if (have === 0) { break inf_leave; }
  23463. have--;
  23464. hold += input[next++] << bits;
  23465. bits += 8;
  23466. //---//
  23467. }
  23468. //--- DROPBITS(last.bits) ---//
  23469. hold >>>= last_bits;
  23470. bits -= last_bits;
  23471. //---//
  23472. state.back += last_bits;
  23473. }
  23474. //--- DROPBITS(here.bits) ---//
  23475. hold >>>= here_bits;
  23476. bits -= here_bits;
  23477. //---//
  23478. state.back += here_bits;
  23479. if (here_op & 64) {
  23480. strm.msg = 'invalid distance code';
  23481. state.mode = BAD;
  23482. break;
  23483. }
  23484. state.offset = here_val;
  23485. state.extra = (here_op) & 15;
  23486. state.mode = DISTEXT;
  23487. /* falls through */
  23488. case DISTEXT:
  23489. if (state.extra) {
  23490. //=== NEEDBITS(state.extra);
  23491. n = state.extra;
  23492. while (bits < n) {
  23493. if (have === 0) { break inf_leave; }
  23494. have--;
  23495. hold += input[next++] << bits;
  23496. bits += 8;
  23497. }
  23498. //===//
  23499. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  23500. //--- DROPBITS(state.extra) ---//
  23501. hold >>>= state.extra;
  23502. bits -= state.extra;
  23503. //---//
  23504. state.back += state.extra;
  23505. }
  23506. //#ifdef INFLATE_STRICT
  23507. if (state.offset > state.dmax) {
  23508. strm.msg = 'invalid distance too far back';
  23509. state.mode = BAD;
  23510. break;
  23511. }
  23512. //#endif
  23513. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  23514. state.mode = MATCH;
  23515. /* falls through */
  23516. case MATCH:
  23517. if (left === 0) { break inf_leave; }
  23518. copy = _out - left;
  23519. if (state.offset > copy) { /* copy from window */
  23520. copy = state.offset - copy;
  23521. if (copy > state.whave) {
  23522. if (state.sane) {
  23523. strm.msg = 'invalid distance too far back';
  23524. state.mode = BAD;
  23525. break;
  23526. }
  23527. // (!) This block is disabled in zlib defailts,
  23528. // don't enable it for binary compatibility
  23529. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  23530. // Trace((stderr, "inflate.c too far\n"));
  23531. // copy -= state.whave;
  23532. // if (copy > state.length) { copy = state.length; }
  23533. // if (copy > left) { copy = left; }
  23534. // left -= copy;
  23535. // state.length -= copy;
  23536. // do {
  23537. // output[put++] = 0;
  23538. // } while (--copy);
  23539. // if (state.length === 0) { state.mode = LEN; }
  23540. // break;
  23541. //#endif
  23542. }
  23543. if (copy > state.wnext) {
  23544. copy -= state.wnext;
  23545. from = state.wsize - copy;
  23546. }
  23547. else {
  23548. from = state.wnext - copy;
  23549. }
  23550. if (copy > state.length) { copy = state.length; }
  23551. from_source = state.window;
  23552. }
  23553. else { /* copy from output */
  23554. from_source = output;
  23555. from = put - state.offset;
  23556. copy = state.length;
  23557. }
  23558. if (copy > left) { copy = left; }
  23559. left -= copy;
  23560. state.length -= copy;
  23561. do {
  23562. output[put++] = from_source[from++];
  23563. } while (--copy);
  23564. if (state.length === 0) { state.mode = LEN; }
  23565. break;
  23566. case LIT:
  23567. if (left === 0) { break inf_leave; }
  23568. output[put++] = state.length;
  23569. left--;
  23570. state.mode = LEN;
  23571. break;
  23572. case CHECK:
  23573. if (state.wrap) {
  23574. //=== NEEDBITS(32);
  23575. while (bits < 32) {
  23576. if (have === 0) { break inf_leave; }
  23577. have--;
  23578. // Use '|' insdead of '+' to make sure that result is signed
  23579. hold |= input[next++] << bits;
  23580. bits += 8;
  23581. }
  23582. //===//
  23583. _out -= left;
  23584. strm.total_out += _out;
  23585. state.total += _out;
  23586. if (_out) {
  23587. strm.adler = state.check =
  23588. /*UPDATE(state.check, put - _out, _out);*/
  23589. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  23590. }
  23591. _out = left;
  23592. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  23593. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  23594. strm.msg = 'incorrect data check';
  23595. state.mode = BAD;
  23596. break;
  23597. }
  23598. //=== INITBITS();
  23599. hold = 0;
  23600. bits = 0;
  23601. //===//
  23602. //Tracev((stderr, "inflate: check matches trailer\n"));
  23603. }
  23604. state.mode = LENGTH;
  23605. /* falls through */
  23606. case LENGTH:
  23607. if (state.wrap && state.flags) {
  23608. //=== NEEDBITS(32);
  23609. while (bits < 32) {
  23610. if (have === 0) { break inf_leave; }
  23611. have--;
  23612. hold += input[next++] << bits;
  23613. bits += 8;
  23614. }
  23615. //===//
  23616. if (hold !== (state.total & 0xffffffff)) {
  23617. strm.msg = 'incorrect length check';
  23618. state.mode = BAD;
  23619. break;
  23620. }
  23621. //=== INITBITS();
  23622. hold = 0;
  23623. bits = 0;
  23624. //===//
  23625. //Tracev((stderr, "inflate: length matches trailer\n"));
  23626. }
  23627. state.mode = DONE;
  23628. /* falls through */
  23629. case DONE:
  23630. ret = Z_STREAM_END;
  23631. break inf_leave;
  23632. case BAD:
  23633. ret = Z_DATA_ERROR;
  23634. break inf_leave;
  23635. case MEM:
  23636. return Z_MEM_ERROR;
  23637. case SYNC:
  23638. /* falls through */
  23639. default:
  23640. return Z_STREAM_ERROR;
  23641. }
  23642. }
  23643. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  23644. /*
  23645. Return from inflate(), updating the total counts and the check value.
  23646. If there was no progress during the inflate() call, return a buffer
  23647. error. Call updatewindow() to create and/or update the window state.
  23648. Note: a memory error from inflate() is non-recoverable.
  23649. */
  23650. //--- RESTORE() ---
  23651. strm.next_out = put;
  23652. strm.avail_out = left;
  23653. strm.next_in = next;
  23654. strm.avail_in = have;
  23655. state.hold = hold;
  23656. state.bits = bits;
  23657. //---
  23658. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  23659. (state.mode < CHECK || flush !== Z_FINISH))) {
  23660. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  23661. state.mode = MEM;
  23662. return Z_MEM_ERROR;
  23663. }
  23664. }
  23665. _in -= strm.avail_in;
  23666. _out -= strm.avail_out;
  23667. strm.total_in += _in;
  23668. strm.total_out += _out;
  23669. state.total += _out;
  23670. if (state.wrap && _out) {
  23671. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  23672. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  23673. }
  23674. strm.data_type = state.bits + (state.last ? 64 : 0) +
  23675. (state.mode === TYPE ? 128 : 0) +
  23676. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  23677. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  23678. ret = Z_BUF_ERROR;
  23679. }
  23680. return ret;
  23681. }
  23682. function inflateEnd(strm) {
  23683. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  23684. return Z_STREAM_ERROR;
  23685. }
  23686. var state = strm.state;
  23687. if (state.window) {
  23688. state.window = null;
  23689. }
  23690. strm.state = null;
  23691. return Z_OK;
  23692. }
  23693. function inflateGetHeader(strm, head) {
  23694. var state;
  23695. /* check state */
  23696. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23697. state = strm.state;
  23698. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  23699. /* save header structure */
  23700. state.head = head;
  23701. head.done = false;
  23702. return Z_OK;
  23703. }
  23704. exports.inflateReset = inflateReset;
  23705. exports.inflateReset2 = inflateReset2;
  23706. exports.inflateResetKeep = inflateResetKeep;
  23707. exports.inflateInit = inflateInit;
  23708. exports.inflateInit2 = inflateInit2;
  23709. exports.inflate = inflate;
  23710. exports.inflateEnd = inflateEnd;
  23711. exports.inflateGetHeader = inflateGetHeader;
  23712. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  23713. /* Not implemented
  23714. exports.inflateCopy = inflateCopy;
  23715. exports.inflateGetDictionary = inflateGetDictionary;
  23716. exports.inflateMark = inflateMark;
  23717. exports.inflatePrime = inflatePrime;
  23718. exports.inflateSetDictionary = inflateSetDictionary;
  23719. exports.inflateSync = inflateSync;
  23720. exports.inflateSyncPoint = inflateSyncPoint;
  23721. exports.inflateUndermine = inflateUndermine;
  23722. */
  23723. },{"../utils/common":74,"./adler32":76,"./crc32":78,"./inffast":81,"./inftrees":83}],83:[function(require,module,exports){
  23724. 'use strict';
  23725. var utils = require('../utils/common');
  23726. var MAXBITS = 15;
  23727. var ENOUGH_LENS = 852;
  23728. var ENOUGH_DISTS = 592;
  23729. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23730. var CODES = 0;
  23731. var LENS = 1;
  23732. var DISTS = 2;
  23733. var lbase = [ /* Length codes 257..285 base */
  23734. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23735. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23736. ];
  23737. var lext = [ /* Length codes 257..285 extra */
  23738. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23739. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23740. ];
  23741. var dbase = [ /* Distance codes 0..29 base */
  23742. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23743. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23744. 8193, 12289, 16385, 24577, 0, 0
  23745. ];
  23746. var dext = [ /* Distance codes 0..29 extra */
  23747. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23748. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23749. 28, 28, 29, 29, 64, 64
  23750. ];
  23751. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23752. {
  23753. var bits = opts.bits;
  23754. //here = opts.here; /* table entry for duplication */
  23755. var len = 0; /* a code's length in bits */
  23756. var sym = 0; /* index of code symbols */
  23757. var min = 0, max = 0; /* minimum and maximum code lengths */
  23758. var root = 0; /* number of index bits for root table */
  23759. var curr = 0; /* number of index bits for current table */
  23760. var drop = 0; /* code bits to drop for sub-table */
  23761. var left = 0; /* number of prefix codes available */
  23762. var used = 0; /* code entries in table used */
  23763. var huff = 0; /* Huffman code */
  23764. var incr; /* for incrementing code, index */
  23765. var fill; /* index for replicating entries */
  23766. var low; /* low bits for current root entry */
  23767. var mask; /* mask for low root bits */
  23768. var next; /* next available space in table */
  23769. var base = null; /* base value table to use */
  23770. var base_index = 0;
  23771. // var shoextra; /* extra bits table to use */
  23772. var end; /* use base and extra for symbol > end */
  23773. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23774. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23775. var extra = null;
  23776. var extra_index = 0;
  23777. var here_bits, here_op, here_val;
  23778. /*
  23779. Process a set of code lengths to create a canonical Huffman code. The
  23780. code lengths are lens[0..codes-1]. Each length corresponds to the
  23781. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23782. symbols by length from short to long, and retaining the symbol order
  23783. for codes with equal lengths. Then the code starts with all zero bits
  23784. for the first code of the shortest length, and the codes are integer
  23785. increments for the same length, and zeros are appended as the length
  23786. increases. For the deflate format, these bits are stored backwards
  23787. from their more natural integer increment ordering, and so when the
  23788. decoding tables are built in the large loop below, the integer codes
  23789. are incremented backwards.
  23790. This routine assumes, but does not check, that all of the entries in
  23791. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23792. 1..MAXBITS is interpreted as that code length. zero means that that
  23793. symbol does not occur in this code.
  23794. The codes are sorted by computing a count of codes for each length,
  23795. creating from that a table of starting indices for each length in the
  23796. sorted table, and then entering the symbols in order in the sorted
  23797. table. The sorted table is work[], with that space being provided by
  23798. the caller.
  23799. The length counts are used for other purposes as well, i.e. finding
  23800. the minimum and maximum length codes, determining if there are any
  23801. codes at all, checking for a valid set of lengths, and looking ahead
  23802. at length counts to determine sub-table sizes when building the
  23803. decoding tables.
  23804. */
  23805. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23806. for (len = 0; len <= MAXBITS; len++) {
  23807. count[len] = 0;
  23808. }
  23809. for (sym = 0; sym < codes; sym++) {
  23810. count[lens[lens_index + sym]]++;
  23811. }
  23812. /* bound code lengths, force root to be within code lengths */
  23813. root = bits;
  23814. for (max = MAXBITS; max >= 1; max--) {
  23815. if (count[max] !== 0) { break; }
  23816. }
  23817. if (root > max) {
  23818. root = max;
  23819. }
  23820. if (max === 0) { /* no symbols to code at all */
  23821. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23822. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23823. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23824. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23825. //table.op[opts.table_index] = 64;
  23826. //table.bits[opts.table_index] = 1;
  23827. //table.val[opts.table_index++] = 0;
  23828. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23829. opts.bits = 1;
  23830. return 0; /* no symbols, but wait for decoding to report error */
  23831. }
  23832. for (min = 1; min < max; min++) {
  23833. if (count[min] !== 0) { break; }
  23834. }
  23835. if (root < min) {
  23836. root = min;
  23837. }
  23838. /* check for an over-subscribed or incomplete set of lengths */
  23839. left = 1;
  23840. for (len = 1; len <= MAXBITS; len++) {
  23841. left <<= 1;
  23842. left -= count[len];
  23843. if (left < 0) {
  23844. return -1;
  23845. } /* over-subscribed */
  23846. }
  23847. if (left > 0 && (type === CODES || max !== 1)) {
  23848. return -1; /* incomplete set */
  23849. }
  23850. /* generate offsets into symbol table for each length for sorting */
  23851. offs[1] = 0;
  23852. for (len = 1; len < MAXBITS; len++) {
  23853. offs[len + 1] = offs[len] + count[len];
  23854. }
  23855. /* sort symbols by length, by symbol order within each length */
  23856. for (sym = 0; sym < codes; sym++) {
  23857. if (lens[lens_index + sym] !== 0) {
  23858. work[offs[lens[lens_index + sym]]++] = sym;
  23859. }
  23860. }
  23861. /*
  23862. Create and fill in decoding tables. In this loop, the table being
  23863. filled is at next and has curr index bits. The code being used is huff
  23864. with length len. That code is converted to an index by dropping drop
  23865. bits off of the bottom. For codes where len is less than drop + curr,
  23866. those top drop + curr - len bits are incremented through all values to
  23867. fill the table with replicated entries.
  23868. root is the number of index bits for the root table. When len exceeds
  23869. root, sub-tables are created pointed to by the root entry with an index
  23870. of the low root bits of huff. This is saved in low to check for when a
  23871. new sub-table should be started. drop is zero when the root table is
  23872. being filled, and drop is root when sub-tables are being filled.
  23873. When a new sub-table is needed, it is necessary to look ahead in the
  23874. code lengths to determine what size sub-table is needed. The length
  23875. counts are used for this, and so count[] is decremented as codes are
  23876. entered in the tables.
  23877. used keeps track of how many table entries have been allocated from the
  23878. provided *table space. It is checked for LENS and DIST tables against
  23879. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23880. the initial root table size constants. See the comments in inftrees.h
  23881. for more information.
  23882. sym increments through all symbols, and the loop terminates when
  23883. all codes of length max, i.e. all codes, have been processed. This
  23884. routine permits incomplete codes, so another loop after this one fills
  23885. in the rest of the decoding tables with invalid code markers.
  23886. */
  23887. /* set up for code type */
  23888. // poor man optimization - use if-else instead of switch,
  23889. // to avoid deopts in old v8
  23890. if (type === CODES) {
  23891. base = extra = work; /* dummy value--not used */
  23892. end = 19;
  23893. } else if (type === LENS) {
  23894. base = lbase;
  23895. base_index -= 257;
  23896. extra = lext;
  23897. extra_index -= 257;
  23898. end = 256;
  23899. } else { /* DISTS */
  23900. base = dbase;
  23901. extra = dext;
  23902. end = -1;
  23903. }
  23904. /* initialize opts for loop */
  23905. huff = 0; /* starting code */
  23906. sym = 0; /* starting code symbol */
  23907. len = min; /* starting code length */
  23908. next = table_index; /* current table to fill in */
  23909. curr = root; /* current table index bits */
  23910. drop = 0; /* current bits to drop from code for index */
  23911. low = -1; /* trigger new sub-table when len > root */
  23912. used = 1 << root; /* use root table entries */
  23913. mask = used - 1; /* mask for comparing low */
  23914. /* check available table space */
  23915. if ((type === LENS && used > ENOUGH_LENS) ||
  23916. (type === DISTS && used > ENOUGH_DISTS)) {
  23917. return 1;
  23918. }
  23919. var i=0;
  23920. /* process all codes and make table entries */
  23921. for (;;) {
  23922. i++;
  23923. /* create table entry */
  23924. here_bits = len - drop;
  23925. if (work[sym] < end) {
  23926. here_op = 0;
  23927. here_val = work[sym];
  23928. }
  23929. else if (work[sym] > end) {
  23930. here_op = extra[extra_index + work[sym]];
  23931. here_val = base[base_index + work[sym]];
  23932. }
  23933. else {
  23934. here_op = 32 + 64; /* end of block */
  23935. here_val = 0;
  23936. }
  23937. /* replicate for those indices with low len bits equal to huff */
  23938. incr = 1 << (len - drop);
  23939. fill = 1 << curr;
  23940. min = fill; /* save offset to next table */
  23941. do {
  23942. fill -= incr;
  23943. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23944. } while (fill !== 0);
  23945. /* backwards increment the len-bit code huff */
  23946. incr = 1 << (len - 1);
  23947. while (huff & incr) {
  23948. incr >>= 1;
  23949. }
  23950. if (incr !== 0) {
  23951. huff &= incr - 1;
  23952. huff += incr;
  23953. } else {
  23954. huff = 0;
  23955. }
  23956. /* go to next symbol, update count, len */
  23957. sym++;
  23958. if (--count[len] === 0) {
  23959. if (len === max) { break; }
  23960. len = lens[lens_index + work[sym]];
  23961. }
  23962. /* create new sub-table if needed */
  23963. if (len > root && (huff & mask) !== low) {
  23964. /* if first time, transition to sub-tables */
  23965. if (drop === 0) {
  23966. drop = root;
  23967. }
  23968. /* increment past last table */
  23969. next += min; /* here min is 1 << curr */
  23970. /* determine length of next table */
  23971. curr = len - drop;
  23972. left = 1 << curr;
  23973. while (curr + drop < max) {
  23974. left -= count[curr + drop];
  23975. if (left <= 0) { break; }
  23976. curr++;
  23977. left <<= 1;
  23978. }
  23979. /* check for enough space */
  23980. used += 1 << curr;
  23981. if ((type === LENS && used > ENOUGH_LENS) ||
  23982. (type === DISTS && used > ENOUGH_DISTS)) {
  23983. return 1;
  23984. }
  23985. /* point entry in root table to sub-table */
  23986. low = huff & mask;
  23987. /*table.op[low] = curr;
  23988. table.bits[low] = root;
  23989. table.val[low] = next - opts.table_index;*/
  23990. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23991. }
  23992. }
  23993. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23994. at most one remaining entry, since if the code is incomplete, the
  23995. maximum code length that was allowed to get this far is one bit) */
  23996. if (huff !== 0) {
  23997. //table.op[next + huff] = 64; /* invalid code marker */
  23998. //table.bits[next + huff] = len - drop;
  23999. //table.val[next + huff] = 0;
  24000. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24001. }
  24002. /* set return parameters */
  24003. //opts.table_index += used;
  24004. opts.bits = root;
  24005. return 0;
  24006. };
  24007. },{"../utils/common":74}],84:[function(require,module,exports){
  24008. 'use strict';
  24009. module.exports = {
  24010. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24011. '1': 'stream end', /* Z_STREAM_END 1 */
  24012. '0': '', /* Z_OK 0 */
  24013. '-1': 'file error', /* Z_ERRNO (-1) */
  24014. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24015. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24016. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24017. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24018. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24019. };
  24020. },{}],85:[function(require,module,exports){
  24021. 'use strict';
  24022. var utils = require('../utils/common');
  24023. /* Public constants ==========================================================*/
  24024. /* ===========================================================================*/
  24025. //var Z_FILTERED = 1;
  24026. //var Z_HUFFMAN_ONLY = 2;
  24027. //var Z_RLE = 3;
  24028. var Z_FIXED = 4;
  24029. //var Z_DEFAULT_STRATEGY = 0;
  24030. /* Possible values of the data_type field (though see inflate()) */
  24031. var Z_BINARY = 0;
  24032. var Z_TEXT = 1;
  24033. //var Z_ASCII = 1; // = Z_TEXT
  24034. var Z_UNKNOWN = 2;
  24035. /*============================================================================*/
  24036. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24037. // From zutil.h
  24038. var STORED_BLOCK = 0;
  24039. var STATIC_TREES = 1;
  24040. var DYN_TREES = 2;
  24041. /* The three kinds of block type */
  24042. var MIN_MATCH = 3;
  24043. var MAX_MATCH = 258;
  24044. /* The minimum and maximum match lengths */
  24045. // From deflate.h
  24046. /* ===========================================================================
  24047. * Internal compression state.
  24048. */
  24049. var LENGTH_CODES = 29;
  24050. /* number of length codes, not counting the special END_BLOCK code */
  24051. var LITERALS = 256;
  24052. /* number of literal bytes 0..255 */
  24053. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24054. /* number of Literal or Length codes, including the END_BLOCK code */
  24055. var D_CODES = 30;
  24056. /* number of distance codes */
  24057. var BL_CODES = 19;
  24058. /* number of codes used to transfer the bit lengths */
  24059. var HEAP_SIZE = 2*L_CODES + 1;
  24060. /* maximum heap size */
  24061. var MAX_BITS = 15;
  24062. /* All codes must not exceed MAX_BITS bits */
  24063. var Buf_size = 16;
  24064. /* size of bit buffer in bi_buf */
  24065. /* ===========================================================================
  24066. * Constants
  24067. */
  24068. var MAX_BL_BITS = 7;
  24069. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24070. var END_BLOCK = 256;
  24071. /* end of block literal code */
  24072. var REP_3_6 = 16;
  24073. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24074. var REPZ_3_10 = 17;
  24075. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24076. var REPZ_11_138 = 18;
  24077. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24078. var extra_lbits = /* extra bits for each length code */
  24079. [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];
  24080. var extra_dbits = /* extra bits for each distance code */
  24081. [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];
  24082. var extra_blbits = /* extra bits for each bit length code */
  24083. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24084. var bl_order =
  24085. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24086. /* The lengths of the bit length codes are sent in order of decreasing
  24087. * probability, to avoid transmitting the lengths for unused bit length codes.
  24088. */
  24089. /* ===========================================================================
  24090. * Local data. These are initialized only once.
  24091. */
  24092. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24093. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24094. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24095. var static_ltree = new Array((L_CODES+2) * 2);
  24096. zero(static_ltree);
  24097. /* The static literal tree. Since the bit lengths are imposed, there is no
  24098. * need for the L_CODES extra codes used during heap construction. However
  24099. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24100. * below).
  24101. */
  24102. var static_dtree = new Array(D_CODES * 2);
  24103. zero(static_dtree);
  24104. /* The static distance tree. (Actually a trivial tree since all codes use
  24105. * 5 bits.)
  24106. */
  24107. var _dist_code = new Array(DIST_CODE_LEN);
  24108. zero(_dist_code);
  24109. /* Distance codes. The first 256 values correspond to the distances
  24110. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24111. * the 15 bit distances.
  24112. */
  24113. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24114. zero(_length_code);
  24115. /* length code for each normalized match length (0 == MIN_MATCH) */
  24116. var base_length = new Array(LENGTH_CODES);
  24117. zero(base_length);
  24118. /* First normalized length for each code (0 = MIN_MATCH) */
  24119. var base_dist = new Array(D_CODES);
  24120. zero(base_dist);
  24121. /* First normalized distance for each code (0 = distance of 1) */
  24122. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24123. this.static_tree = static_tree; /* static tree or NULL */
  24124. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24125. this.extra_base = extra_base; /* base index for extra_bits */
  24126. this.elems = elems; /* max number of elements in the tree */
  24127. this.max_length = max_length; /* max bit length for the codes */
  24128. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24129. this.has_stree = static_tree && static_tree.length;
  24130. };
  24131. var static_l_desc;
  24132. var static_d_desc;
  24133. var static_bl_desc;
  24134. var TreeDesc = function(dyn_tree, stat_desc) {
  24135. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24136. this.max_code = 0; /* largest code with non zero frequency */
  24137. this.stat_desc = stat_desc; /* the corresponding static tree */
  24138. };
  24139. function d_code(dist) {
  24140. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24141. }
  24142. /* ===========================================================================
  24143. * Output a short LSB first on the stream.
  24144. * IN assertion: there is enough room in pendingBuf.
  24145. */
  24146. function put_short (s, w) {
  24147. // put_byte(s, (uch)((w) & 0xff));
  24148. // put_byte(s, (uch)((ush)(w) >> 8));
  24149. s.pending_buf[s.pending++] = (w) & 0xff;
  24150. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24151. }
  24152. /* ===========================================================================
  24153. * Send a value on a given number of bits.
  24154. * IN assertion: length <= 16 and value fits in length bits.
  24155. */
  24156. function send_bits(s, value, length) {
  24157. if (s.bi_valid > (Buf_size - length)) {
  24158. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24159. put_short(s, s.bi_buf);
  24160. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24161. s.bi_valid += length - Buf_size;
  24162. } else {
  24163. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24164. s.bi_valid += length;
  24165. }
  24166. }
  24167. function send_code(s, c, tree) {
  24168. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24169. }
  24170. /* ===========================================================================
  24171. * Reverse the first len bits of a code, using straightforward code (a faster
  24172. * method would use a table)
  24173. * IN assertion: 1 <= len <= 15
  24174. */
  24175. function bi_reverse(code, len) {
  24176. var res = 0;
  24177. do {
  24178. res |= code & 1;
  24179. code >>>= 1;
  24180. res <<= 1;
  24181. } while (--len > 0);
  24182. return res >>> 1;
  24183. }
  24184. /* ===========================================================================
  24185. * Flush the bit buffer, keeping at most 7 bits in it.
  24186. */
  24187. function bi_flush(s) {
  24188. if (s.bi_valid === 16) {
  24189. put_short(s, s.bi_buf);
  24190. s.bi_buf = 0;
  24191. s.bi_valid = 0;
  24192. } else if (s.bi_valid >= 8) {
  24193. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24194. s.bi_buf >>= 8;
  24195. s.bi_valid -= 8;
  24196. }
  24197. }
  24198. /* ===========================================================================
  24199. * Compute the optimal bit lengths for a tree and update the total bit length
  24200. * for the current block.
  24201. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24202. * above are the tree nodes sorted by increasing frequency.
  24203. * OUT assertions: the field len is set to the optimal bit length, the
  24204. * array bl_count contains the frequencies for each bit length.
  24205. * The length opt_len is updated; static_len is also updated if stree is
  24206. * not null.
  24207. */
  24208. function gen_bitlen(s, desc)
  24209. // deflate_state *s;
  24210. // tree_desc *desc; /* the tree descriptor */
  24211. {
  24212. var tree = desc.dyn_tree;
  24213. var max_code = desc.max_code;
  24214. var stree = desc.stat_desc.static_tree;
  24215. var has_stree = desc.stat_desc.has_stree;
  24216. var extra = desc.stat_desc.extra_bits;
  24217. var base = desc.stat_desc.extra_base;
  24218. var max_length = desc.stat_desc.max_length;
  24219. var h; /* heap index */
  24220. var n, m; /* iterate over the tree elements */
  24221. var bits; /* bit length */
  24222. var xbits; /* extra bits */
  24223. var f; /* frequency */
  24224. var overflow = 0; /* number of elements with bit length too large */
  24225. for (bits = 0; bits <= MAX_BITS; bits++) {
  24226. s.bl_count[bits] = 0;
  24227. }
  24228. /* In a first pass, compute the optimal bit lengths (which may
  24229. * overflow in the case of the bit length tree).
  24230. */
  24231. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24232. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24233. n = s.heap[h];
  24234. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24235. if (bits > max_length) {
  24236. bits = max_length;
  24237. overflow++;
  24238. }
  24239. tree[n*2 + 1]/*.Len*/ = bits;
  24240. /* We overwrite tree[n].Dad which is no longer needed */
  24241. if (n > max_code) { continue; } /* not a leaf node */
  24242. s.bl_count[bits]++;
  24243. xbits = 0;
  24244. if (n >= base) {
  24245. xbits = extra[n-base];
  24246. }
  24247. f = tree[n * 2]/*.Freq*/;
  24248. s.opt_len += f * (bits + xbits);
  24249. if (has_stree) {
  24250. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24251. }
  24252. }
  24253. if (overflow === 0) { return; }
  24254. // Trace((stderr,"\nbit length overflow\n"));
  24255. /* This happens for example on obj2 and pic of the Calgary corpus */
  24256. /* Find the first bit length which could increase: */
  24257. do {
  24258. bits = max_length-1;
  24259. while (s.bl_count[bits] === 0) { bits--; }
  24260. s.bl_count[bits]--; /* move one leaf down the tree */
  24261. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24262. s.bl_count[max_length]--;
  24263. /* The brother of the overflow item also moves one step up,
  24264. * but this does not affect bl_count[max_length]
  24265. */
  24266. overflow -= 2;
  24267. } while (overflow > 0);
  24268. /* Now recompute all bit lengths, scanning in increasing frequency.
  24269. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24270. * lengths instead of fixing only the wrong ones. This idea is taken
  24271. * from 'ar' written by Haruhiko Okumura.)
  24272. */
  24273. for (bits = max_length; bits !== 0; bits--) {
  24274. n = s.bl_count[bits];
  24275. while (n !== 0) {
  24276. m = s.heap[--h];
  24277. if (m > max_code) { continue; }
  24278. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24279. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24280. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24281. tree[m*2 + 1]/*.Len*/ = bits;
  24282. }
  24283. n--;
  24284. }
  24285. }
  24286. }
  24287. /* ===========================================================================
  24288. * Generate the codes for a given tree and bit counts (which need not be
  24289. * optimal).
  24290. * IN assertion: the array bl_count contains the bit length statistics for
  24291. * the given tree and the field len is set for all tree elements.
  24292. * OUT assertion: the field code is set for all tree elements of non
  24293. * zero code length.
  24294. */
  24295. function gen_codes(tree, max_code, bl_count)
  24296. // ct_data *tree; /* the tree to decorate */
  24297. // int max_code; /* largest code with non zero frequency */
  24298. // ushf *bl_count; /* number of codes at each bit length */
  24299. {
  24300. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24301. var code = 0; /* running code value */
  24302. var bits; /* bit index */
  24303. var n; /* code index */
  24304. /* The distribution counts are first used to generate the code values
  24305. * without bit reversal.
  24306. */
  24307. for (bits = 1; bits <= MAX_BITS; bits++) {
  24308. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24309. }
  24310. /* Check that the bit counts in bl_count are consistent. The last code
  24311. * must be all ones.
  24312. */
  24313. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24314. // "inconsistent bit counts");
  24315. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24316. for (n = 0; n <= max_code; n++) {
  24317. var len = tree[n*2 + 1]/*.Len*/;
  24318. if (len === 0) { continue; }
  24319. /* Now reverse the bits */
  24320. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24321. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24322. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24323. }
  24324. }
  24325. /* ===========================================================================
  24326. * Initialize the various 'constant' tables.
  24327. */
  24328. function tr_static_init() {
  24329. var n; /* iterates over tree elements */
  24330. var bits; /* bit counter */
  24331. var length; /* length value */
  24332. var code; /* code value */
  24333. var dist; /* distance index */
  24334. var bl_count = new Array(MAX_BITS+1);
  24335. /* number of codes at each bit length for an optimal tree */
  24336. // do check in _tr_init()
  24337. //if (static_init_done) return;
  24338. /* For some embedded targets, global variables are not initialized: */
  24339. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24340. static_l_desc.static_tree = static_ltree;
  24341. static_l_desc.extra_bits = extra_lbits;
  24342. static_d_desc.static_tree = static_dtree;
  24343. static_d_desc.extra_bits = extra_dbits;
  24344. static_bl_desc.extra_bits = extra_blbits;
  24345. #endif*/
  24346. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24347. length = 0;
  24348. for (code = 0; code < LENGTH_CODES-1; code++) {
  24349. base_length[code] = length;
  24350. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24351. _length_code[length++] = code;
  24352. }
  24353. }
  24354. //Assert (length == 256, "tr_static_init: length != 256");
  24355. /* Note that the length 255 (match length 258) can be represented
  24356. * in two different ways: code 284 + 5 bits or code 285, so we
  24357. * overwrite length_code[255] to use the best encoding:
  24358. */
  24359. _length_code[length-1] = code;
  24360. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24361. dist = 0;
  24362. for (code = 0 ; code < 16; code++) {
  24363. base_dist[code] = dist;
  24364. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24365. _dist_code[dist++] = code;
  24366. }
  24367. }
  24368. //Assert (dist == 256, "tr_static_init: dist != 256");
  24369. dist >>= 7; /* from now on, all distances are divided by 128 */
  24370. for (; code < D_CODES; code++) {
  24371. base_dist[code] = dist << 7;
  24372. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24373. _dist_code[256 + dist++] = code;
  24374. }
  24375. }
  24376. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24377. /* Construct the codes of the static literal tree */
  24378. for (bits = 0; bits <= MAX_BITS; bits++) {
  24379. bl_count[bits] = 0;
  24380. }
  24381. n = 0;
  24382. while (n <= 143) {
  24383. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24384. n++;
  24385. bl_count[8]++;
  24386. }
  24387. while (n <= 255) {
  24388. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24389. n++;
  24390. bl_count[9]++;
  24391. }
  24392. while (n <= 279) {
  24393. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24394. n++;
  24395. bl_count[7]++;
  24396. }
  24397. while (n <= 287) {
  24398. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24399. n++;
  24400. bl_count[8]++;
  24401. }
  24402. /* Codes 286 and 287 do not exist, but we must include them in the
  24403. * tree construction to get a canonical Huffman tree (longest code
  24404. * all ones)
  24405. */
  24406. gen_codes(static_ltree, L_CODES+1, bl_count);
  24407. /* The static distance tree is trivial: */
  24408. for (n = 0; n < D_CODES; n++) {
  24409. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24410. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24411. }
  24412. // Now data ready and we can init static trees
  24413. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24414. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24415. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  24416. //static_init_done = true;
  24417. }
  24418. /* ===========================================================================
  24419. * Initialize a new block.
  24420. */
  24421. function init_block(s) {
  24422. var n; /* iterates over tree elements */
  24423. /* Initialize the trees. */
  24424. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  24425. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  24426. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  24427. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  24428. s.opt_len = s.static_len = 0;
  24429. s.last_lit = s.matches = 0;
  24430. }
  24431. /* ===========================================================================
  24432. * Flush the bit buffer and align the output on a byte boundary
  24433. */
  24434. function bi_windup(s)
  24435. {
  24436. if (s.bi_valid > 8) {
  24437. put_short(s, s.bi_buf);
  24438. } else if (s.bi_valid > 0) {
  24439. //put_byte(s, (Byte)s->bi_buf);
  24440. s.pending_buf[s.pending++] = s.bi_buf;
  24441. }
  24442. s.bi_buf = 0;
  24443. s.bi_valid = 0;
  24444. }
  24445. /* ===========================================================================
  24446. * Copy a stored block, storing first the length and its
  24447. * one's complement if requested.
  24448. */
  24449. function copy_block(s, buf, len, header)
  24450. //DeflateState *s;
  24451. //charf *buf; /* the input data */
  24452. //unsigned len; /* its length */
  24453. //int header; /* true if block header must be written */
  24454. {
  24455. bi_windup(s); /* align on byte boundary */
  24456. if (header) {
  24457. put_short(s, len);
  24458. put_short(s, ~len);
  24459. }
  24460. // while (len--) {
  24461. // put_byte(s, *buf++);
  24462. // }
  24463. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  24464. s.pending += len;
  24465. }
  24466. /* ===========================================================================
  24467. * Compares to subtrees, using the tree depth as tie breaker when
  24468. * the subtrees have equal frequency. This minimizes the worst case length.
  24469. */
  24470. function smaller(tree, n, m, depth) {
  24471. var _n2 = n*2;
  24472. var _m2 = m*2;
  24473. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  24474. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  24475. }
  24476. /* ===========================================================================
  24477. * Restore the heap property by moving down the tree starting at node k,
  24478. * exchanging a node with the smallest of its two sons if necessary, stopping
  24479. * when the heap property is re-established (each father smaller than its
  24480. * two sons).
  24481. */
  24482. function pqdownheap(s, tree, k)
  24483. // deflate_state *s;
  24484. // ct_data *tree; /* the tree to restore */
  24485. // int k; /* node to move down */
  24486. {
  24487. var v = s.heap[k];
  24488. var j = k << 1; /* left son of k */
  24489. while (j <= s.heap_len) {
  24490. /* Set j to the smallest of the two sons: */
  24491. if (j < s.heap_len &&
  24492. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  24493. j++;
  24494. }
  24495. /* Exit if v is smaller than both sons */
  24496. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  24497. /* Exchange v with the smallest son */
  24498. s.heap[k] = s.heap[j];
  24499. k = j;
  24500. /* And continue down the tree, setting j to the left son of k */
  24501. j <<= 1;
  24502. }
  24503. s.heap[k] = v;
  24504. }
  24505. // inlined manually
  24506. // var SMALLEST = 1;
  24507. /* ===========================================================================
  24508. * Send the block data compressed using the given Huffman trees
  24509. */
  24510. function compress_block(s, ltree, dtree)
  24511. // deflate_state *s;
  24512. // const ct_data *ltree; /* literal tree */
  24513. // const ct_data *dtree; /* distance tree */
  24514. {
  24515. var dist; /* distance of matched string */
  24516. var lc; /* match length or unmatched char (if dist == 0) */
  24517. var lx = 0; /* running index in l_buf */
  24518. var code; /* the code to send */
  24519. var extra; /* number of extra bits to send */
  24520. if (s.last_lit !== 0) {
  24521. do {
  24522. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  24523. lc = s.pending_buf[s.l_buf + lx];
  24524. lx++;
  24525. if (dist === 0) {
  24526. send_code(s, lc, ltree); /* send a literal byte */
  24527. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  24528. } else {
  24529. /* Here, lc is the match length - MIN_MATCH */
  24530. code = _length_code[lc];
  24531. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  24532. extra = extra_lbits[code];
  24533. if (extra !== 0) {
  24534. lc -= base_length[code];
  24535. send_bits(s, lc, extra); /* send the extra length bits */
  24536. }
  24537. dist--; /* dist is now the match distance - 1 */
  24538. code = d_code(dist);
  24539. //Assert (code < D_CODES, "bad d_code");
  24540. send_code(s, code, dtree); /* send the distance code */
  24541. extra = extra_dbits[code];
  24542. if (extra !== 0) {
  24543. dist -= base_dist[code];
  24544. send_bits(s, dist, extra); /* send the extra distance bits */
  24545. }
  24546. } /* literal or match pair ? */
  24547. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  24548. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  24549. // "pendingBuf overflow");
  24550. } while (lx < s.last_lit);
  24551. }
  24552. send_code(s, END_BLOCK, ltree);
  24553. }
  24554. /* ===========================================================================
  24555. * Construct one Huffman tree and assigns the code bit strings and lengths.
  24556. * Update the total bit length for the current block.
  24557. * IN assertion: the field freq is set for all tree elements.
  24558. * OUT assertions: the fields len and code are set to the optimal bit length
  24559. * and corresponding code. The length opt_len is updated; static_len is
  24560. * also updated if stree is not null. The field max_code is set.
  24561. */
  24562. function build_tree(s, desc)
  24563. // deflate_state *s;
  24564. // tree_desc *desc; /* the tree descriptor */
  24565. {
  24566. var tree = desc.dyn_tree;
  24567. var stree = desc.stat_desc.static_tree;
  24568. var has_stree = desc.stat_desc.has_stree;
  24569. var elems = desc.stat_desc.elems;
  24570. var n, m; /* iterate over heap elements */
  24571. var max_code = -1; /* largest code with non zero frequency */
  24572. var node; /* new node being created */
  24573. /* Construct the initial heap, with least frequent element in
  24574. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  24575. * heap[0] is not used.
  24576. */
  24577. s.heap_len = 0;
  24578. s.heap_max = HEAP_SIZE;
  24579. for (n = 0; n < elems; n++) {
  24580. if (tree[n * 2]/*.Freq*/ !== 0) {
  24581. s.heap[++s.heap_len] = max_code = n;
  24582. s.depth[n] = 0;
  24583. } else {
  24584. tree[n*2 + 1]/*.Len*/ = 0;
  24585. }
  24586. }
  24587. /* The pkzip format requires that at least one distance code exists,
  24588. * and that at least one bit should be sent even if there is only one
  24589. * possible code. So to avoid special checks later on we force at least
  24590. * two codes of non zero frequency.
  24591. */
  24592. while (s.heap_len < 2) {
  24593. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  24594. tree[node * 2]/*.Freq*/ = 1;
  24595. s.depth[node] = 0;
  24596. s.opt_len--;
  24597. if (has_stree) {
  24598. s.static_len -= stree[node*2 + 1]/*.Len*/;
  24599. }
  24600. /* node is 0 or 1 so it does not have extra bits */
  24601. }
  24602. desc.max_code = max_code;
  24603. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  24604. * establish sub-heaps of increasing lengths:
  24605. */
  24606. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  24607. /* Construct the Huffman tree by repeatedly combining the least two
  24608. * frequent nodes.
  24609. */
  24610. node = elems; /* next internal node of the tree */
  24611. do {
  24612. //pqremove(s, tree, n); /* n = node of least frequency */
  24613. /*** pqremove ***/
  24614. n = s.heap[1/*SMALLEST*/];
  24615. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  24616. pqdownheap(s, tree, 1/*SMALLEST*/);
  24617. /***/
  24618. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  24619. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  24620. s.heap[--s.heap_max] = m;
  24621. /* Create a new node father of n and m */
  24622. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  24623. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  24624. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  24625. /* and insert the new node in the heap */
  24626. s.heap[1/*SMALLEST*/] = node++;
  24627. pqdownheap(s, tree, 1/*SMALLEST*/);
  24628. } while (s.heap_len >= 2);
  24629. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  24630. /* At this point, the fields freq and dad are set. We can now
  24631. * generate the bit lengths.
  24632. */
  24633. gen_bitlen(s, desc);
  24634. /* The field len is now set, we can generate the bit codes */
  24635. gen_codes(tree, max_code, s.bl_count);
  24636. }
  24637. /* ===========================================================================
  24638. * Scan a literal or distance tree to determine the frequencies of the codes
  24639. * in the bit length tree.
  24640. */
  24641. function scan_tree(s, tree, max_code)
  24642. // deflate_state *s;
  24643. // ct_data *tree; /* the tree to be scanned */
  24644. // int max_code; /* and its largest code of non zero frequency */
  24645. {
  24646. var n; /* iterates over all tree elements */
  24647. var prevlen = -1; /* last emitted length */
  24648. var curlen; /* length of current code */
  24649. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24650. var count = 0; /* repeat count of the current code */
  24651. var max_count = 7; /* max repeat count */
  24652. var min_count = 4; /* min repeat count */
  24653. if (nextlen === 0) {
  24654. max_count = 138;
  24655. min_count = 3;
  24656. }
  24657. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  24658. for (n = 0; n <= max_code; n++) {
  24659. curlen = nextlen;
  24660. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24661. if (++count < max_count && curlen === nextlen) {
  24662. continue;
  24663. } else if (count < min_count) {
  24664. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  24665. } else if (curlen !== 0) {
  24666. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  24667. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  24668. } else if (count <= 10) {
  24669. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  24670. } else {
  24671. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  24672. }
  24673. count = 0;
  24674. prevlen = curlen;
  24675. if (nextlen === 0) {
  24676. max_count = 138;
  24677. min_count = 3;
  24678. } else if (curlen === nextlen) {
  24679. max_count = 6;
  24680. min_count = 3;
  24681. } else {
  24682. max_count = 7;
  24683. min_count = 4;
  24684. }
  24685. }
  24686. }
  24687. /* ===========================================================================
  24688. * Send a literal or distance tree in compressed form, using the codes in
  24689. * bl_tree.
  24690. */
  24691. function send_tree(s, tree, max_code)
  24692. // deflate_state *s;
  24693. // ct_data *tree; /* the tree to be scanned */
  24694. // int max_code; /* and its largest code of non zero frequency */
  24695. {
  24696. var n; /* iterates over all tree elements */
  24697. var prevlen = -1; /* last emitted length */
  24698. var curlen; /* length of current code */
  24699. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  24700. var count = 0; /* repeat count of the current code */
  24701. var max_count = 7; /* max repeat count */
  24702. var min_count = 4; /* min repeat count */
  24703. /* tree[max_code+1].Len = -1; */ /* guard already set */
  24704. if (nextlen === 0) {
  24705. max_count = 138;
  24706. min_count = 3;
  24707. }
  24708. for (n = 0; n <= max_code; n++) {
  24709. curlen = nextlen;
  24710. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  24711. if (++count < max_count && curlen === nextlen) {
  24712. continue;
  24713. } else if (count < min_count) {
  24714. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24715. } else if (curlen !== 0) {
  24716. if (curlen !== prevlen) {
  24717. send_code(s, curlen, s.bl_tree);
  24718. count--;
  24719. }
  24720. //Assert(count >= 3 && count <= 6, " 3_6?");
  24721. send_code(s, REP_3_6, s.bl_tree);
  24722. send_bits(s, count-3, 2);
  24723. } else if (count <= 10) {
  24724. send_code(s, REPZ_3_10, s.bl_tree);
  24725. send_bits(s, count-3, 3);
  24726. } else {
  24727. send_code(s, REPZ_11_138, s.bl_tree);
  24728. send_bits(s, count-11, 7);
  24729. }
  24730. count = 0;
  24731. prevlen = curlen;
  24732. if (nextlen === 0) {
  24733. max_count = 138;
  24734. min_count = 3;
  24735. } else if (curlen === nextlen) {
  24736. max_count = 6;
  24737. min_count = 3;
  24738. } else {
  24739. max_count = 7;
  24740. min_count = 4;
  24741. }
  24742. }
  24743. }
  24744. /* ===========================================================================
  24745. * Construct the Huffman tree for the bit lengths and return the index in
  24746. * bl_order of the last bit length code to send.
  24747. */
  24748. function build_bl_tree(s) {
  24749. var max_blindex; /* index of last bit length code of non zero freq */
  24750. /* Determine the bit length frequencies for literal and distance trees */
  24751. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24752. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24753. /* Build the bit length tree: */
  24754. build_tree(s, s.bl_desc);
  24755. /* opt_len now includes the length of the tree representations, except
  24756. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24757. */
  24758. /* Determine the number of bit length codes to send. The pkzip format
  24759. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24760. * 3 but the actual value used is 4.)
  24761. */
  24762. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24763. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24764. break;
  24765. }
  24766. }
  24767. /* Update opt_len to include the bit length tree and counts */
  24768. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24769. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24770. // s->opt_len, s->static_len));
  24771. return max_blindex;
  24772. }
  24773. /* ===========================================================================
  24774. * Send the header for a block using dynamic Huffman trees: the counts, the
  24775. * lengths of the bit length codes, the literal tree and the distance tree.
  24776. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24777. */
  24778. function send_all_trees(s, lcodes, dcodes, blcodes)
  24779. // deflate_state *s;
  24780. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24781. {
  24782. var rank; /* index in bl_order */
  24783. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24784. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24785. // "too many codes");
  24786. //Tracev((stderr, "\nbl counts: "));
  24787. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24788. send_bits(s, dcodes-1, 5);
  24789. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24790. for (rank = 0; rank < blcodes; rank++) {
  24791. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24792. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24793. }
  24794. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24795. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24796. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24797. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24798. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24799. }
  24800. /* ===========================================================================
  24801. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24802. * - TEXT if the two conditions below are satisfied:
  24803. * a) There are no non-portable control characters belonging to the
  24804. * "black list" (0..6, 14..25, 28..31).
  24805. * b) There is at least one printable character belonging to the
  24806. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24807. * - BINARY otherwise.
  24808. * - The following partially-portable control characters form a
  24809. * "gray list" that is ignored in this detection algorithm:
  24810. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24811. * IN assertion: the fields Freq of dyn_ltree are set.
  24812. */
  24813. function detect_data_type(s) {
  24814. /* black_mask is the bit mask of black-listed bytes
  24815. * set bits 0..6, 14..25, and 28..31
  24816. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24817. */
  24818. var black_mask = 0xf3ffc07f;
  24819. var n;
  24820. /* Check for non-textual ("black-listed") bytes. */
  24821. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24822. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24823. return Z_BINARY;
  24824. }
  24825. }
  24826. /* Check for textual ("white-listed") bytes. */
  24827. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24828. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24829. return Z_TEXT;
  24830. }
  24831. for (n = 32; n < LITERALS; n++) {
  24832. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24833. return Z_TEXT;
  24834. }
  24835. }
  24836. /* There are no "black-listed" or "white-listed" bytes:
  24837. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24838. */
  24839. return Z_BINARY;
  24840. }
  24841. var static_init_done = false;
  24842. /* ===========================================================================
  24843. * Initialize the tree data structures for a new zlib stream.
  24844. */
  24845. function _tr_init(s)
  24846. {
  24847. if (!static_init_done) {
  24848. tr_static_init();
  24849. static_init_done = true;
  24850. }
  24851. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24852. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24853. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24854. s.bi_buf = 0;
  24855. s.bi_valid = 0;
  24856. /* Initialize the first block of the first file: */
  24857. init_block(s);
  24858. }
  24859. /* ===========================================================================
  24860. * Send a stored block
  24861. */
  24862. function _tr_stored_block(s, buf, stored_len, last)
  24863. //DeflateState *s;
  24864. //charf *buf; /* input block */
  24865. //ulg stored_len; /* length of input block */
  24866. //int last; /* one if this is the last block for a file */
  24867. {
  24868. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24869. copy_block(s, buf, stored_len, true); /* with header */
  24870. }
  24871. /* ===========================================================================
  24872. * Send one empty static block to give enough lookahead for inflate.
  24873. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24874. */
  24875. function _tr_align(s) {
  24876. send_bits(s, STATIC_TREES<<1, 3);
  24877. send_code(s, END_BLOCK, static_ltree);
  24878. bi_flush(s);
  24879. }
  24880. /* ===========================================================================
  24881. * Determine the best encoding for the current block: dynamic trees, static
  24882. * trees or store, and output the encoded block to the zip file.
  24883. */
  24884. function _tr_flush_block(s, buf, stored_len, last)
  24885. //DeflateState *s;
  24886. //charf *buf; /* input block, or NULL if too old */
  24887. //ulg stored_len; /* length of input block */
  24888. //int last; /* one if this is the last block for a file */
  24889. {
  24890. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24891. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24892. /* Build the Huffman trees unless a stored block is forced */
  24893. if (s.level > 0) {
  24894. /* Check if the file is binary or text */
  24895. if (s.strm.data_type === Z_UNKNOWN) {
  24896. s.strm.data_type = detect_data_type(s);
  24897. }
  24898. /* Construct the literal and distance trees */
  24899. build_tree(s, s.l_desc);
  24900. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24901. // s->static_len));
  24902. build_tree(s, s.d_desc);
  24903. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24904. // s->static_len));
  24905. /* At this point, opt_len and static_len are the total bit lengths of
  24906. * the compressed block data, excluding the tree representations.
  24907. */
  24908. /* Build the bit length tree for the above two trees, and get the index
  24909. * in bl_order of the last bit length code to send.
  24910. */
  24911. max_blindex = build_bl_tree(s);
  24912. /* Determine the best encoding. Compute the block lengths in bytes. */
  24913. opt_lenb = (s.opt_len+3+7) >>> 3;
  24914. static_lenb = (s.static_len+3+7) >>> 3;
  24915. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24916. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24917. // s->last_lit));
  24918. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24919. } else {
  24920. // Assert(buf != (char*)0, "lost buf");
  24921. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24922. }
  24923. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24924. /* 4: two words for the lengths */
  24925. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24926. * Otherwise we can't have processed more than WSIZE input bytes since
  24927. * the last block flush, because compression would have been
  24928. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24929. * transform a block into a stored block.
  24930. */
  24931. _tr_stored_block(s, buf, stored_len, last);
  24932. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24933. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24934. compress_block(s, static_ltree, static_dtree);
  24935. } else {
  24936. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24937. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24938. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24939. }
  24940. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24941. /* The above check is made mod 2^32, for files larger than 512 MB
  24942. * and uLong implemented on 32 bits.
  24943. */
  24944. init_block(s);
  24945. if (last) {
  24946. bi_windup(s);
  24947. }
  24948. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24949. // s->compressed_len-7*last));
  24950. }
  24951. /* ===========================================================================
  24952. * Save the match info and tally the frequency counts. Return true if
  24953. * the current block must be flushed.
  24954. */
  24955. function _tr_tally(s, dist, lc)
  24956. // deflate_state *s;
  24957. // unsigned dist; /* distance of matched string */
  24958. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24959. {
  24960. //var out_length, in_length, dcode;
  24961. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24962. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24963. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24964. s.last_lit++;
  24965. if (dist === 0) {
  24966. /* lc is the unmatched char */
  24967. s.dyn_ltree[lc*2]/*.Freq*/++;
  24968. } else {
  24969. s.matches++;
  24970. /* Here, lc is the match length - MIN_MATCH */
  24971. dist--; /* dist = match distance - 1 */
  24972. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24973. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24974. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24975. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24976. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24977. }
  24978. // (!) This block is disabled in zlib defailts,
  24979. // don't enable it for binary compatibility
  24980. //#ifdef TRUNCATE_BLOCK
  24981. // /* Try to guess if it is profitable to stop the current block here */
  24982. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24983. // /* Compute an upper bound for the compressed length */
  24984. // out_length = s.last_lit*8;
  24985. // in_length = s.strstart - s.block_start;
  24986. //
  24987. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24988. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24989. // }
  24990. // out_length >>>= 3;
  24991. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24992. // // s->last_lit, in_length, out_length,
  24993. // // 100L - out_length*100L/in_length));
  24994. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24995. // return true;
  24996. // }
  24997. // }
  24998. //#endif
  24999. return (s.last_lit === s.lit_bufsize-1);
  25000. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25001. * on 16 bit machines and because stored blocks are restricted to
  25002. * 64K-1 bytes.
  25003. */
  25004. }
  25005. exports._tr_init = _tr_init;
  25006. exports._tr_stored_block = _tr_stored_block;
  25007. exports._tr_flush_block = _tr_flush_block;
  25008. exports._tr_tally = _tr_tally;
  25009. exports._tr_align = _tr_align;
  25010. },{"../utils/common":74}],86:[function(require,module,exports){
  25011. 'use strict';
  25012. function ZStream() {
  25013. /* next input byte */
  25014. this.input = null; // JS specific, because we have no pointers
  25015. this.next_in = 0;
  25016. /* number of bytes available at input */
  25017. this.avail_in = 0;
  25018. /* total number of input bytes read so far */
  25019. this.total_in = 0;
  25020. /* next output byte should be put there */
  25021. this.output = null; // JS specific, because we have no pointers
  25022. this.next_out = 0;
  25023. /* remaining free space at output */
  25024. this.avail_out = 0;
  25025. /* total number of bytes output so far */
  25026. this.total_out = 0;
  25027. /* last error message, NULL if no error */
  25028. this.msg = ''/*Z_NULL*/;
  25029. /* not visible by applications */
  25030. this.state = null;
  25031. /* best guess about the data type: binary or text */
  25032. this.data_type = 2/*Z_UNKNOWN*/;
  25033. /* adler32 value of the uncompressed data */
  25034. this.adler = 0;
  25035. }
  25036. module.exports = ZStream;
  25037. },{}],87:[function(require,module,exports){
  25038. module.exports = require('./lib/retry');
  25039. },{"./lib/retry":88}],88:[function(require,module,exports){
  25040. var RetryOperation = require('./retry_operation');
  25041. exports.operation = function(options) {
  25042. var timeouts = exports.timeouts(options);
  25043. return new RetryOperation(timeouts);
  25044. };
  25045. exports.timeouts = function(options) {
  25046. if (options instanceof Array) {
  25047. return [].concat(options);
  25048. }
  25049. var opts = {
  25050. retries: 10,
  25051. factor: 2,
  25052. minTimeout: 1 * 1000,
  25053. maxTimeout: Infinity,
  25054. randomize: false
  25055. };
  25056. for (var key in options) {
  25057. opts[key] = options[key];
  25058. }
  25059. if (opts.minTimeout > opts.maxTimeout) {
  25060. throw new Error('minTimeout is greater than maxTimeout');
  25061. }
  25062. var timeouts = [];
  25063. for (var i = 0; i < opts.retries; i++) {
  25064. timeouts.push(this._createTimeout(i, opts));
  25065. }
  25066. // sort the array numerically ascending
  25067. timeouts.sort(function(a,b) {
  25068. return a - b;
  25069. });
  25070. return timeouts;
  25071. };
  25072. exports._createTimeout = function(attempt, opts) {
  25073. var random = (opts.randomize)
  25074. ? (Math.random() + 1)
  25075. : 1;
  25076. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25077. timeout = Math.min(timeout, opts.maxTimeout);
  25078. return timeout;
  25079. };
  25080. },{"./retry_operation":89}],89:[function(require,module,exports){
  25081. function RetryOperation(timeouts) {
  25082. this._timeouts = timeouts;
  25083. this._fn = null;
  25084. this._errors = [];
  25085. this._attempts = 1;
  25086. this._operationTimeout = null;
  25087. this._operationTimeoutCb = null;
  25088. this._timeout = null;
  25089. }
  25090. module.exports = RetryOperation;
  25091. RetryOperation.prototype.retry = function(err) {
  25092. if (this._timeout) {
  25093. clearTimeout(this._timeout);
  25094. }
  25095. if (!err) {
  25096. return false;
  25097. }
  25098. this._errors.push(err);
  25099. var timeout = this._timeouts.shift();
  25100. if (timeout === undefined) {
  25101. return false;
  25102. }
  25103. this._attempts++;
  25104. var self = this;
  25105. setTimeout(function() {
  25106. self._fn(self._attempts);
  25107. if (self._operationTimeoutCb) {
  25108. self._timeout = setTimeout(function() {
  25109. self._operationTimeoutCb(self._attempts);
  25110. }, self._operationTimeout);
  25111. }
  25112. }, timeout);
  25113. return true;
  25114. };
  25115. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25116. this._fn = fn;
  25117. if (timeoutOps) {
  25118. if (timeoutOps.timeout) {
  25119. this._operationTimeout = timeoutOps.timeout;
  25120. }
  25121. if (timeoutOps.cb) {
  25122. this._operationTimeoutCb = timeoutOps.cb;
  25123. }
  25124. }
  25125. this._fn(this._attempts);
  25126. var self = this;
  25127. if (this._operationTimeoutCb) {
  25128. this._timeout = setTimeout(function() {
  25129. self._operationTimeoutCb();
  25130. }, self._operationTimeout);
  25131. }
  25132. };
  25133. RetryOperation.prototype.try = function(fn) {
  25134. console.log('Using RetryOperation.try() is deprecated');
  25135. this.attempt(fn);
  25136. };
  25137. RetryOperation.prototype.start = function(fn) {
  25138. console.log('Using RetryOperation.start() is deprecated');
  25139. this.attempt(fn);
  25140. };
  25141. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25142. RetryOperation.prototype.errors = function() {
  25143. return this._errors;
  25144. };
  25145. RetryOperation.prototype.attempts = function() {
  25146. return this._attempts;
  25147. };
  25148. RetryOperation.prototype.mainError = function() {
  25149. if (this._errors.length === 0) {
  25150. return null;
  25151. }
  25152. var counts = {};
  25153. var mainError = null;
  25154. var mainErrorCount = 0;
  25155. for (var i = 0; i < this._errors.length; i++) {
  25156. var error = this._errors[i];
  25157. var message = error.message;
  25158. var count = (counts[message] || 0) + 1;
  25159. counts[message] = count;
  25160. if (count >= mainErrorCount) {
  25161. mainError = error;
  25162. mainErrorCount = count;
  25163. }
  25164. }
  25165. return mainError;
  25166. };
  25167. },{}],90:[function(require,module,exports){
  25168. module.exports = function arrayEquals(array) {
  25169. // if the other array is a falsy value, return
  25170. if (!array)
  25171. return false;
  25172. // compare lengths - can save a lot of time
  25173. if (this.length != array.length)
  25174. return false;
  25175. for (var i = 0, l = this.length; i < l; i++) {
  25176. // Check if we have nested arrays
  25177. if (this[i] instanceof Array && array[i] instanceof Array) {
  25178. // recurse into the nested arrays
  25179. if (!arrayEquals.apply(this[i], [array[i]]))
  25180. return false;
  25181. } else if (this[i] != array[i]) {
  25182. // Warning - two different object instances will never be equal:
  25183. // {x:20} != {x:20}
  25184. return false;
  25185. }
  25186. }
  25187. return true;
  25188. }
  25189. },{}],91:[function(require,module,exports){
  25190. exports.Interop = require('./interop');
  25191. },{"./interop":92}],92:[function(require,module,exports){
  25192. "use strict";
  25193. var transform = require('./transform');
  25194. var arrayEquals = require('./array-equals');
  25195. function Interop() {
  25196. /**
  25197. * This map holds the most recent Unified Plan offer/answer SDP that was
  25198. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25199. * the SDP string as values.
  25200. *
  25201. * @type {{}}
  25202. */
  25203. this.cache = {};
  25204. }
  25205. module.exports = Interop;
  25206. /**
  25207. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25208. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25209. * application.
  25210. *
  25211. * @param desc
  25212. * @returns {*}
  25213. */
  25214. Interop.prototype.toPlanB = function(desc) {
  25215. //#region Preliminary input validation.
  25216. if (typeof desc !== 'object' || desc === null ||
  25217. typeof desc.sdp !== 'string') {
  25218. console.warn('An empty description was passed as an argument.');
  25219. return desc;
  25220. }
  25221. // Objectify the SDP for easier manipulation.
  25222. var session = transform.parse(desc.sdp);
  25223. // If the SDP contains no media, there's nothing to transform.
  25224. if (typeof session.media === 'undefined' ||
  25225. !Array.isArray(session.media) || session.media.length === 0) {
  25226. console.warn('The description has no media.');
  25227. return desc;
  25228. }
  25229. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25230. // SDP has a video, an audio and a data "channel" at most.
  25231. if (session.media.length <= 3 && session.media.every(function(m) {
  25232. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25233. })) {
  25234. console.warn('This description does not look like Unified Plan.');
  25235. return desc;
  25236. }
  25237. //#endregion
  25238. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25239. // -> Unified Plan transformation.
  25240. this.cache[desc.type] = desc.sdp;
  25241. //#region Convert from Unified Plan to Plan B.
  25242. // We rebuild the session.media array.
  25243. var media = session.media;
  25244. session.media = [];
  25245. // Associative array that maps channel types to channel objects for fast
  25246. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25247. // obj.
  25248. var type2bl = {};
  25249. // Used to build the group:BUNDLE value after the channels construction
  25250. // loop.
  25251. var types = [];
  25252. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25253. media.forEach(function(unifiedLine) {
  25254. // rtcp-mux is required in the Plan B SDP.
  25255. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25256. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25257. unifiedLine.direction !== 'inactive') {
  25258. throw new Error('Cannot convert to Plan B because m-lines ' +
  25259. 'without the rtcp-mux attribute were found.');
  25260. }
  25261. if (unifiedLine.type === 'application') {
  25262. session.media.push(unifiedLine);
  25263. types.push(unifiedLine.mid);
  25264. return;
  25265. }
  25266. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25267. // as the channel basis.
  25268. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25269. type2bl[unifiedLine.type] = unifiedLine;
  25270. }
  25271. // Add sources to the channel and handle a=msid.
  25272. if (typeof unifiedLine.sources === 'object') {
  25273. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25274. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25275. type2bl[unifiedLine.type].sources = {};
  25276. // Assign the sources to the channel.
  25277. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25278. if (typeof unifiedLine.msid !== 'undefined') {
  25279. // In Plan B the msid is an SSRC attribute. Also, we don't
  25280. // care about the obsolete label and mslabel attributes.
  25281. //
  25282. // Note that it is not guaranteed that the unifiedLine will have
  25283. // an msid. recvonly channels in particular don't have one.
  25284. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25285. }
  25286. // NOTE ssrcs in ssrc groups will share msids, as
  25287. // draft-uberti-rtcweb-plan-00 mandates.
  25288. });
  25289. }
  25290. // Add ssrc groups to the channel.
  25291. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25292. Array.isArray(unifiedLine.ssrcGroups)) {
  25293. // Create the ssrcGroups array, if it's not defined.
  25294. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25295. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25296. type2bl[unifiedLine.type].ssrcGroups = [];
  25297. }
  25298. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25299. }
  25300. if (type2bl[unifiedLine.type] === unifiedLine) {
  25301. // Copy ICE related stuff from the principal media line.
  25302. unifiedLine.candidates = media[0].candidates;
  25303. unifiedLine.iceUfrag = media[0].iceUfrag;
  25304. unifiedLine.icePwd = media[0].icePwd;
  25305. unifiedLine.fingerprint = media[0].fingerprint;
  25306. // Plan B mids are in ['audio', 'video', 'data']
  25307. unifiedLine.mid = unifiedLine.type;
  25308. // Plan B doesn't support/need the bundle-only attribute.
  25309. delete unifiedLine.bundleOnly;
  25310. // In Plan B the msid is an SSRC attribute.
  25311. delete unifiedLine.msid;
  25312. // Used to build the group:BUNDLE value after this loop.
  25313. types.push(unifiedLine.type);
  25314. // Add the channel to the new media array.
  25315. session.media.push(unifiedLine);
  25316. }
  25317. });
  25318. // We regenerate the BUNDLE group with the new mids.
  25319. session.groups.some(function(group) {
  25320. if (group.type === 'BUNDLE') {
  25321. group.mids = types.join(' ');
  25322. return true;
  25323. }
  25324. });
  25325. // msid semantic
  25326. session.msidSemantic = {
  25327. semantic: 'WMS',
  25328. token: '*'
  25329. };
  25330. var resStr = transform.write(session);
  25331. return new RTCSessionDescription({
  25332. type: desc.type,
  25333. sdp: resStr
  25334. });
  25335. //#endregion
  25336. };
  25337. /**
  25338. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25339. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25340. * to FF.
  25341. *
  25342. * @param desc
  25343. * @returns {*}
  25344. */
  25345. Interop.prototype.toUnifiedPlan = function(desc) {
  25346. //#region Preliminary input validation.
  25347. if (typeof desc !== 'object' || desc === null ||
  25348. typeof desc.sdp !== 'string') {
  25349. console.warn('An empty description was passed as an argument.');
  25350. return desc;
  25351. }
  25352. var session = transform.parse(desc.sdp);
  25353. // If the SDP contains no media, there's nothing to transform.
  25354. if (typeof session.media === 'undefined' ||
  25355. !Array.isArray(session.media) || session.media.length === 0) {
  25356. console.warn('The description has no media.');
  25357. return desc;
  25358. }
  25359. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25360. // a video, an audio and a data "channel" at most.
  25361. if (session.media.length > 3 || !session.media.every(function(m) {
  25362. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25363. })) {
  25364. console.warn('This description does not look like Plan B.');
  25365. return desc;
  25366. }
  25367. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25368. var mids = [];
  25369. session.media.forEach(function(m) {
  25370. mids.push(m.mid);
  25371. });
  25372. var hasBundle = false;
  25373. if (typeof session.groups !== 'undefined' &&
  25374. Array.isArray(session.groups)) {
  25375. hasBundle = session.groups.every(function(g) {
  25376. return g.type !== 'BUNDLE' ||
  25377. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25378. });
  25379. }
  25380. if (!hasBundle) {
  25381. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25382. " are not bundled were found.");
  25383. }
  25384. //#endregion
  25385. //#region Convert from Plan B to Unified Plan.
  25386. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25387. // rebuild an equivalent Unified Plan offer/answer.
  25388. //
  25389. // For example, if this is a local answer (in Unified Plan style) that we
  25390. // convert to Plan B prior to handing it over to the application (the
  25391. // PeerConnection wrapper called us, for instance, after a successful
  25392. // createAnswer), we want to remember the m-line at which we've seen the
  25393. // (local) SSRC. That's because when the application wants to do call the
  25394. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25395. // Unified Plan), we need to know to which m-line to assign the (local)
  25396. // SSRC. We also need to know all the other m-lines that the original
  25397. // answer had and include them in the transformed answer as well.
  25398. //
  25399. // Another example is if this is a remote offer that we convert to Plan B
  25400. // prior to giving it to the application, we want to remember the mid at
  25401. // which we've seen the (remote) SSRC.
  25402. //
  25403. // In the iteration that follows, we use the cached Unified Plan (if it
  25404. // exists) to assign mids to ssrcs.
  25405. var cached;
  25406. if (typeof this.cache[desc.type] !== 'undefined') {
  25407. cached = transform.parse(this.cache[desc.type]);
  25408. }
  25409. // A helper map that sends mids to m-line objects. We use it later to
  25410. // rebuild the Unified Plan style session.media array.
  25411. var mid2ul = {};
  25412. session.media.forEach(function(bLine) {
  25413. if ((typeof bLine.rtcpMux !== 'string' ||
  25414. bLine.rtcpMux !== 'rtcp-mux') &&
  25415. bLine.direction !== 'inactive') {
  25416. throw new Error("Cannot convert to Unified Plan because m-lines " +
  25417. "without the rtcp-mux attribute were found.");
  25418. }
  25419. if (bLine.type === 'application') {
  25420. mid2ul[bLine.mid] = bLine;
  25421. return;
  25422. }
  25423. // With rtcp-mux and bundle all the channels should have the same ICE
  25424. // stuff.
  25425. var sources = bLine.sources;
  25426. var ssrcGroups = bLine.ssrcGroups;
  25427. var candidates = bLine.candidates;
  25428. var iceUfrag = bLine.iceUfrag;
  25429. var icePwd = bLine.icePwd;
  25430. var fingerprint = bLine.fingerprint;
  25431. var port = bLine.port;
  25432. // We'll use the "bLine" object as a prototype for each new "mLine"
  25433. // that we create, but first we need to clean it up a bit.
  25434. delete bLine.sources;
  25435. delete bLine.ssrcGroups;
  25436. delete bLine.candidates;
  25437. delete bLine.iceUfrag;
  25438. delete bLine.icePwd;
  25439. delete bLine.fingerprint;
  25440. delete bLine.port;
  25441. delete bLine.mid;
  25442. // inverted ssrc group map
  25443. var ssrc2group = {};
  25444. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  25445. ssrcGroups.forEach(function (ssrcGroup) {
  25446. // TODO(gp) find out how to receive simulcast with FF. For the
  25447. // time being, hide it.
  25448. if (ssrcGroup.semantics === 'SIM') {
  25449. return;
  25450. }
  25451. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25452. Array.isArray(ssrcGroup.ssrcs)) {
  25453. ssrcGroup.ssrcs.forEach(function (ssrc) {
  25454. if (typeof ssrc2group[ssrc] === 'undefined') {
  25455. ssrc2group[ssrc] = [];
  25456. }
  25457. ssrc2group[ssrc].push(ssrcGroup);
  25458. });
  25459. }
  25460. });
  25461. }
  25462. // ssrc to m-line index.
  25463. var ssrc2ml = {};
  25464. if (typeof sources === 'object') {
  25465. // Explode the Plan B channel sources with one m-line per source.
  25466. Object.keys(sources).forEach(function(ssrc) {
  25467. // The (unified) m-line for this SSRC. We either create it from
  25468. // scratch or, if it's a grouped SSRC, we re-use a related
  25469. // mline. In other words, if the source is grouped with another
  25470. // source, put the two together in the same m-line.
  25471. var unifiedLine;
  25472. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  25473. Array.isArray(ssrc2group[ssrc])) {
  25474. ssrc2group[ssrc].some(function (ssrcGroup) {
  25475. // ssrcGroup.ssrcs *is* an Array, no need to check
  25476. // again here.
  25477. return ssrcGroup.ssrcs.some(function (related) {
  25478. if (typeof ssrc2ml[related] === 'object') {
  25479. unifiedLine = ssrc2ml[related];
  25480. return true;
  25481. }
  25482. });
  25483. });
  25484. }
  25485. if (typeof unifiedLine === 'object') {
  25486. // the m-line already exists. Just add the source.
  25487. unifiedLine.sources[ssrc] = sources[ssrc];
  25488. delete sources[ssrc].msid;
  25489. } else {
  25490. // Use the "bLine" as a prototype for the "unifiedLine".
  25491. unifiedLine = Object.create(bLine);
  25492. ssrc2ml[ssrc] = unifiedLine;
  25493. if (typeof sources[ssrc].msid !== 'undefined') {
  25494. // Assign the msid of the source to the m-line. Note
  25495. // that it is not guaranteed that the source will have
  25496. // msid. In particular "recvonly" sources don't have an
  25497. // msid. Note that "recvonly" is a term only defined
  25498. // for m-lines.
  25499. unifiedLine.msid = sources[ssrc].msid;
  25500. delete sources[ssrc].msid;
  25501. }
  25502. // We assign one SSRC per media line.
  25503. unifiedLine.sources = {};
  25504. unifiedLine.sources[ssrc] = sources[ssrc];
  25505. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  25506. // Use the cached Unified Plan SDP (if it exists) to assign
  25507. // SSRCs to mids.
  25508. if (typeof cached !== 'undefined' &&
  25509. typeof cached.media !== 'undefined' &&
  25510. Array.isArray(cached.media)) {
  25511. cached.media.forEach(function (m) {
  25512. if (typeof m.sources === 'object') {
  25513. Object.keys(m.sources).forEach(function (s) {
  25514. if (s === ssrc) {
  25515. unifiedLine.mid = m.mid;
  25516. }
  25517. });
  25518. }
  25519. });
  25520. }
  25521. if (typeof unifiedLine.mid === 'undefined') {
  25522. // If this is an SSRC that we see for the first time
  25523. // assign it a new mid. This is typically the case when
  25524. // this method is called to transform a remote
  25525. // description for the first time or when there is a
  25526. // new SSRC in the remote description because a new
  25527. // peer has joined the conference. Local SSRCs should
  25528. // have already been added to the map in the toPlanB
  25529. // method.
  25530. //
  25531. // Because FF generates answers in Unified Plan style,
  25532. // we MUST already have a cached answer with all the
  25533. // local SSRCs mapped to some m-line/mid.
  25534. if (desc.type === 'answer') {
  25535. throw new Error("An unmapped SSRC was found.");
  25536. }
  25537. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  25538. }
  25539. // Include the candidates in the 1st media line.
  25540. unifiedLine.candidates = candidates;
  25541. unifiedLine.iceUfrag = iceUfrag;
  25542. unifiedLine.icePwd = icePwd;
  25543. unifiedLine.fingerprint = fingerprint;
  25544. unifiedLine.port = port;
  25545. mid2ul[unifiedLine.mid] = unifiedLine;
  25546. }
  25547. });
  25548. }
  25549. });
  25550. // Rebuild the media array in the right order and add the missing mLines
  25551. // (missing from the Plan B SDP).
  25552. session.media = [];
  25553. mids = []; // reuse
  25554. if (desc.type === 'answer') {
  25555. // The media lines in the answer must match the media lines in the
  25556. // offer. The order is important too. Here we assume that Firefox is the
  25557. // answerer, so we merely have to use the reconstructed (unified) answer
  25558. // to update the cached (unified) answer accordingly.
  25559. //
  25560. // In the general case, one would have to use the cached (unified) offer
  25561. // to find the m-lines that are missing from the reconstructed answer,
  25562. // potentially grabbing them from the cached (unified) answer. One has
  25563. // to be carefull with this approach because inactive m-lines do not
  25564. // always have an mid, making it tricky (impossible?) to find where
  25565. // exactly and which m-lines are missing from the reconstructed answer.
  25566. for (var i = 0; i < cached.media.length; i++) {
  25567. var unifiedLine = cached.media[i];
  25568. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  25569. // The mid isn't in the reconstructed (unified) answer.
  25570. // This is either a (unified) m-line containing a remote
  25571. // track only, or a (unified) m-line containing a remote
  25572. // track and a local track that has been removed.
  25573. // In either case, it MUST exist in the cached
  25574. // (unified) answer.
  25575. //
  25576. // In case this is a removed local track, clean-up
  25577. // the (unified) m-line and make sure it's 'recvonly' or
  25578. // 'inactive'.
  25579. delete unifiedLine.msid;
  25580. delete unifiedLine.sources;
  25581. delete unifiedLine.ssrcGroups;
  25582. if (!unifiedLine.direction
  25583. || unifiedLine.direction === 'sendrecv')
  25584. unifiedLine.direction = 'recvonly';
  25585. if (!unifiedLine.direction
  25586. || unifiedLine.direction === 'sendonly')
  25587. unifiedLine.direction = 'inactive';
  25588. } else {
  25589. // This is an (unified) m-line/channel that contains a local
  25590. // track (sendrecv or sendonly channel) or it's a unified
  25591. // recvonly m-line/channel. In either case, since we're
  25592. // going from PlanB -> Unified Plan this m-line MUST
  25593. // exist in the cached answer.
  25594. }
  25595. session.media.push(unifiedLine);
  25596. if (typeof unifiedLine.mid === 'string') {
  25597. // inactive lines don't/may not have an mid.
  25598. mids.push(unifiedLine.mid);
  25599. }
  25600. }
  25601. } else {
  25602. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  25603. // under any circumstances. If we are no longer interested in sending a
  25604. // track, we just remove the msid and ssrc attributes and set it to
  25605. // either a=recvonly (as the reofferer, we must use recvonly if the
  25606. // other side was previously sending on the m-section, but we can also
  25607. // leave the possibility open if it wasn't previously in use), or
  25608. // a=inacive.
  25609. if (typeof cached !== 'undefined' &&
  25610. typeof cached.media !== 'undefined' &&
  25611. Array.isArray(cached.media)) {
  25612. cached.media.forEach(function(unifiedLine) {
  25613. mids.push(unifiedLine.mid);
  25614. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  25615. session.media.push(mid2ul[unifiedLine.mid]);
  25616. } else {
  25617. delete unifiedLine.msid;
  25618. delete unifiedLine.sources;
  25619. delete unifiedLine.ssrcGroups;
  25620. if (!unifiedLine.direction
  25621. || unifiedLine.direction === 'sendrecv')
  25622. unifiedLine.direction = 'recvonly';
  25623. if (!unifiedLine.direction
  25624. || unifiedLine.direction === 'sendonly')
  25625. unifiedLine.direction = 'inactive';
  25626. session.media.push(unifiedLine);
  25627. }
  25628. });
  25629. }
  25630. // Add all the remaining (new) m-lines of the transformed SDP.
  25631. Object.keys(mid2ul).forEach(function(mid) {
  25632. if (mids.indexOf(mid) === -1) {
  25633. mids.push(mid);
  25634. if (typeof mid2ul[mid].direction === 'recvonly') {
  25635. // This is a remote recvonly channel. Add its SSRC to the
  25636. // appropriate sendrecv or sendonly channel.
  25637. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  25638. session.media.some(function (unifiedLine) {
  25639. if ((unifiedLine.direction === 'sendrecv' ||
  25640. unifiedLine.direction === 'sendonly') &&
  25641. unifiedLine.type === mid2ul[mid].type) {
  25642. // mid2ul[mid] shouldn't have any ssrc-groups
  25643. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  25644. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  25645. });
  25646. return true;
  25647. }
  25648. });
  25649. } else {
  25650. session.media.push(mid2ul[mid]);
  25651. }
  25652. }
  25653. });
  25654. }
  25655. // We regenerate the BUNDLE group (since we regenerated the mids)
  25656. session.groups.some(function(group) {
  25657. if (group.type === 'BUNDLE') {
  25658. group.mids = mids.join(' ');
  25659. return true;
  25660. }
  25661. });
  25662. // msid semantic
  25663. session.msidSemantic = {
  25664. semantic: 'WMS',
  25665. token: '*'
  25666. };
  25667. var resStr = transform.write(session);
  25668. // Cache the transformed SDP (Unified Plan) for later re-use in this
  25669. // function.
  25670. this.cache[desc.type] = resStr;
  25671. return new RTCSessionDescription({
  25672. type: desc.type,
  25673. sdp: resStr
  25674. });
  25675. //#endregion
  25676. };
  25677. },{"./array-equals":90,"./transform":93}],93:[function(require,module,exports){
  25678. var transform = require('sdp-transform');
  25679. exports.write = function(session, opts) {
  25680. if (typeof session !== 'undefined' &&
  25681. typeof session.media !== 'undefined' &&
  25682. Array.isArray(session.media)) {
  25683. session.media.forEach(function (mLine) {
  25684. // expand sources to ssrcs
  25685. if (typeof mLine.sources !== 'undefined' &&
  25686. Object.keys(mLine.sources).length !== 0) {
  25687. mLine.ssrcs = [];
  25688. Object.keys(mLine.sources).forEach(function (ssrc) {
  25689. var source = mLine.sources[ssrc];
  25690. Object.keys(source).forEach(function (attribute) {
  25691. mLine.ssrcs.push({
  25692. id: ssrc,
  25693. attribute: attribute,
  25694. value: source[attribute]
  25695. });
  25696. });
  25697. });
  25698. delete mLine.sources;
  25699. }
  25700. // join ssrcs in ssrc groups
  25701. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25702. Array.isArray(mLine.ssrcGroups)) {
  25703. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25704. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  25705. Array.isArray(ssrcGroup.ssrcs)) {
  25706. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  25707. }
  25708. });
  25709. }
  25710. });
  25711. }
  25712. // join group mids
  25713. if (typeof session !== 'undefined' &&
  25714. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25715. session.groups.forEach(function (g) {
  25716. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25717. g.mids = g.mids.join(' ');
  25718. }
  25719. });
  25720. }
  25721. return transform.write(session, opts);
  25722. };
  25723. exports.parse = function(sdp) {
  25724. var session = transform.parse(sdp);
  25725. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25726. Array.isArray(session.media)) {
  25727. session.media.forEach(function (mLine) {
  25728. // group sources attributes by ssrc
  25729. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25730. mLine.sources = {};
  25731. mLine.ssrcs.forEach(function (ssrc) {
  25732. if (!mLine.sources[ssrc.id])
  25733. mLine.sources[ssrc.id] = {};
  25734. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25735. });
  25736. delete mLine.ssrcs;
  25737. }
  25738. // split ssrcs in ssrc groups
  25739. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25740. Array.isArray(mLine.ssrcGroups)) {
  25741. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25742. if (typeof ssrcGroup.ssrcs === 'string') {
  25743. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25744. }
  25745. });
  25746. }
  25747. });
  25748. }
  25749. // split group mids
  25750. if (typeof session !== 'undefined' &&
  25751. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25752. session.groups.forEach(function (g) {
  25753. if (typeof g.mids === 'string') {
  25754. g.mids = g.mids.split(' ');
  25755. }
  25756. });
  25757. }
  25758. return session;
  25759. };
  25760. },{"sdp-transform":97}],94:[function(require,module,exports){
  25761. var transform = require('sdp-transform');
  25762. var transformUtils = require('./transform-utils');
  25763. var parseSsrcs = transformUtils.parseSsrcs;
  25764. var writeSsrcs = transformUtils.writeSsrcs;
  25765. //region Constants
  25766. var DEFAULT_NUM_OF_LAYERS = 3;
  25767. //endregion
  25768. //region Ctor
  25769. function Simulcast(options) {
  25770. this.options = options ? options : {};
  25771. if (!this.options.numOfLayers) {
  25772. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  25773. }
  25774. this.layers = [];
  25775. }
  25776. //endregion
  25777. //region Stateless private utility functions
  25778. /**
  25779. * Returns a random integer between min (included) and max (excluded)
  25780. * Using Math.round() gives a non-uniform distribution!
  25781. * @returns {number}
  25782. */
  25783. function generateSSRC() {
  25784. var min = 0, max = 0xffffffff;
  25785. return Math.floor(Math.random() * (max - min)) + min;
  25786. };
  25787. function processVideo(session, action) {
  25788. if (session == null || !Array.isArray(session.media)) {
  25789. return;
  25790. }
  25791. session.media.forEach(function (mLine) {
  25792. if (mLine.type === 'video') {
  25793. action(mLine);
  25794. }
  25795. });
  25796. }
  25797. function validateDescription(desc)
  25798. {
  25799. return desc && desc != null
  25800. && desc.type && desc.type != ''
  25801. && desc.sdp && desc.sdp != '';
  25802. }
  25803. function explodeRemoteSimulcast(mLine) {
  25804. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25805. return;
  25806. }
  25807. var sources = parseSsrcs(mLine);
  25808. var order = [];
  25809. // Find the SIM group and explode its sources.
  25810. var j = mLine.ssrcGroups.length;
  25811. while (j--) {
  25812. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  25813. continue;
  25814. }
  25815. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  25816. for (var i = 0; i < simulcastSsrcs.length; i++) {
  25817. var ssrc = simulcastSsrcs[i];
  25818. order.push(ssrc);
  25819. var parts = sources[ssrc].msid.split(' ');
  25820. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  25821. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  25822. // Remove all the groups that this SSRC participates in.
  25823. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25824. if (relatedGroup.semantics === 'SIM') {
  25825. return;
  25826. }
  25827. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25828. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25829. return;
  25830. }
  25831. // Nuke all the related SSRCs.
  25832. relatedSsrcs.forEach(function (relatedSSRC) {
  25833. sources[relatedSSRC].msid = sources[ssrc].msid;
  25834. sources[relatedSSRC].cname = sources[ssrc].cname;
  25835. if (relatedSSRC !== ssrc) {
  25836. order.push(relatedSSRC);
  25837. }
  25838. });
  25839. // Schedule the related group for nuking.
  25840. })
  25841. }
  25842. mLine.ssrcs = writeSsrcs(sources, order);
  25843. mLine.ssrcGroups.splice(j, 1);
  25844. };
  25845. }
  25846. function squeezeRemoteSimulcast(mLine) {
  25847. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  25848. return;
  25849. }
  25850. var sources = parseSsrcs(mLine);
  25851. // Find the SIM group and nuke it.
  25852. mLine.ssrcGroups.some(function (simulcastGroup) {
  25853. if (simulcastGroup.semantics !== 'SIM') {
  25854. return false;
  25855. }
  25856. // Schedule the SIM group for nuking.
  25857. simulcastGroup.nuke = true;
  25858. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  25859. // Nuke all the higher layer SSRCs.
  25860. for (var i = 1; i < simulcastSsrcs.length; i++) {
  25861. var ssrc = simulcastSsrcs[i];
  25862. delete sources[ssrc];
  25863. // Remove all the groups that this SSRC participates in.
  25864. mLine.ssrcGroups.forEach(function (relatedGroup) {
  25865. if (relatedGroup.semantics === 'SIM') {
  25866. return;
  25867. }
  25868. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  25869. if (relatedSsrcs.indexOf(ssrc) === -1) {
  25870. return;
  25871. }
  25872. // Nuke all the related SSRCs.
  25873. relatedSsrcs.forEach(function (relatedSSRC) {
  25874. delete sources[relatedSSRC];
  25875. });
  25876. // Schedule the related group for nuking.
  25877. relatedGroup.nuke = true;
  25878. })
  25879. }
  25880. return true;
  25881. });
  25882. mLine.ssrcs = writeSsrcs(sources);
  25883. // Nuke all the scheduled groups.
  25884. var i = mLine.ssrcGroups.length;
  25885. while (i--) {
  25886. if (mLine.ssrcGroups[i].nuke) {
  25887. mLine.ssrcGroups.splice(i, 1);
  25888. }
  25889. }
  25890. }
  25891. function removeGoogConference(mLine) {
  25892. if (!mLine || !Array.isArray(mLine.invalid)) {
  25893. return;
  25894. }
  25895. var i = mLine.invalid.length;
  25896. while (i--) {
  25897. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  25898. mLine.invalid.splice(i, 1);
  25899. }
  25900. }
  25901. }
  25902. function assertGoogConference(mLine) {
  25903. if (!mLine) {
  25904. return;
  25905. }
  25906. if (!Array.isArray(mLine.invalid)) {
  25907. mLine.invalid = [];
  25908. }
  25909. if (!mLine.invalid.some(
  25910. function (i) { return i.value === 'x-google-flag:conference' })) {
  25911. mLine.invalid.push({'value': 'x-google-flag:conference'});
  25912. }
  25913. }
  25914. //endregion
  25915. //region "Private" functions
  25916. /**
  25917. *
  25918. * @param mLine
  25919. * @private
  25920. */
  25921. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  25922. if (!mLine || mLine.type !== 'video') {
  25923. return;
  25924. }
  25925. var sources = parseSsrcs(mLine);
  25926. if (Object.keys(sources).length === 0) {
  25927. // no sources, disable simulcast.
  25928. if (this.layers.length !== 0) {
  25929. this.layers = [];
  25930. }
  25931. return;
  25932. }
  25933. // find the base layer (we'll reuse its msid and cname).
  25934. var baseLayerSSRC = Object.keys(sources)[0];
  25935. var baseLayer = sources[baseLayerSSRC];
  25936. // todo(gp) handle screen sharing.
  25937. // check if base CNAME has changed and reinitialise layers.
  25938. if (this.layers.length > 0
  25939. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  25940. this.layers = [];
  25941. }
  25942. // (re)initialise layers
  25943. if (this.layers.length < 1) {
  25944. // first push the base layer.
  25945. this.layers.push({
  25946. ssrc: baseLayerSSRC,
  25947. msid: baseLayer.msid,
  25948. cname: baseLayer.cname
  25949. });
  25950. var rtx = false; // RFC 4588
  25951. if (Array.isArray(mLine.rtp)) {
  25952. rtx = mLine.rtp.some(
  25953. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  25954. }
  25955. if (rtx) {
  25956. this.layers[0].rtx = generateSSRC();
  25957. }
  25958. // now push additional layers.
  25959. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  25960. var layer = { ssrc: generateSSRC() };
  25961. if (rtx) {
  25962. layer.rtx = generateSSRC();
  25963. }
  25964. this.layers.push(layer);
  25965. }
  25966. }
  25967. };
  25968. /**
  25969. *
  25970. * @param mLine
  25971. * @private
  25972. */
  25973. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  25974. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  25975. var sources = {};
  25976. var msid = this.layers[0].msid;
  25977. var cname = this.layers[0].cname;
  25978. var simulcastSsrcs = [];
  25979. var ssrcGroups = [];
  25980. for (var i = 0; i < this.layers.length; i++) {
  25981. var layer = this.layers[i];
  25982. sources[layer.ssrc] = { msid: msid, cname: cname };
  25983. simulcastSsrcs.push(layer.ssrc);
  25984. if (layer.rtx) {
  25985. sources[layer.rtx] = {
  25986. msid: msid,
  25987. cname: cname
  25988. }
  25989. ssrcGroups.push({
  25990. semantics: 'FID',
  25991. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  25992. });
  25993. }
  25994. }
  25995. ssrcGroups.push({
  25996. semantics: 'SIM',
  25997. ssrcs: simulcastSsrcs.join(' ')
  25998. });
  25999. mLine.ssrcGroups = ssrcGroups;
  26000. mLine.ssrcs = writeSsrcs(sources);
  26001. }
  26002. }
  26003. //endregion
  26004. //region "Public" functions
  26005. Simulcast.prototype.isSupported = function () {
  26006. return window.chrome;
  26007. // TODO this needs improvements. For example I doubt that Chrome in Android
  26008. // has simulcast support. Also, only recent versions of Chromium have native
  26009. // simulcast support.
  26010. }
  26011. /**
  26012. *
  26013. * @param desc
  26014. * @returns {RTCSessionDescription}
  26015. */
  26016. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26017. if (!validateDescription(desc)) {
  26018. return desc;
  26019. }
  26020. var session = transform.parse(desc.sdp);
  26021. var self = this;
  26022. processVideo(session, function (mLine) {
  26023. // Handle simulcast reception.
  26024. if (self.options.explodeRemoteSimulcast) {
  26025. explodeRemoteSimulcast(mLine);
  26026. } else {
  26027. squeezeRemoteSimulcast(mLine);
  26028. }
  26029. // If native simulcast is enabled, we must append the x-goog-conference
  26030. // attribute to the SDP.
  26031. if (self.layers.length < 1) {
  26032. removeGoogConference(mLine);
  26033. } else {
  26034. assertGoogConference(mLine);
  26035. }
  26036. });
  26037. return new RTCSessionDescription({
  26038. type: desc.type,
  26039. sdp: transform.write(session)
  26040. });
  26041. };
  26042. /**
  26043. *
  26044. * @param desc
  26045. * @returns {RTCSessionDescription}
  26046. */
  26047. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26048. if (!validateDescription(desc) || !this.isSupported()) {
  26049. return desc;
  26050. }
  26051. var session = transform.parse(desc.sdp);
  26052. var self = this;
  26053. processVideo(session, function (mLine) {
  26054. // Initialize native simulcast layers, if not already done.
  26055. self._maybeInitializeLayers(mLine);
  26056. // Update the SDP with the simulcast layers.
  26057. self._restoreSimulcastView(mLine);
  26058. });
  26059. return new RTCSessionDescription({
  26060. type: desc.type,
  26061. sdp: transform.write(session)
  26062. });
  26063. };
  26064. //endregion
  26065. module.exports = Simulcast;
  26066. },{"./transform-utils":95,"sdp-transform":97}],95:[function(require,module,exports){
  26067. exports.writeSsrcs = function(sources, order) {
  26068. var ssrcs = [];
  26069. // expand sources to ssrcs
  26070. if (typeof sources !== 'undefined' &&
  26071. Object.keys(sources).length !== 0) {
  26072. if (Array.isArray(order)) {
  26073. for (var i = 0; i < order.length; i++) {
  26074. var ssrc = order[i];
  26075. var source = sources[ssrc];
  26076. Object.keys(source).forEach(function (attribute) {
  26077. ssrcs.push({
  26078. id: ssrc,
  26079. attribute: attribute,
  26080. value: source[attribute]
  26081. });
  26082. });
  26083. }
  26084. } else {
  26085. Object.keys(sources).forEach(function (ssrc) {
  26086. var source = sources[ssrc];
  26087. Object.keys(source).forEach(function (attribute) {
  26088. ssrcs.push({
  26089. id: ssrc,
  26090. attribute: attribute,
  26091. value: source[attribute]
  26092. });
  26093. });
  26094. });
  26095. }
  26096. }
  26097. return ssrcs;
  26098. };
  26099. exports.parseSsrcs = function (mLine) {
  26100. var sources = {};
  26101. // group sources attributes by ssrc.
  26102. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26103. mLine.ssrcs.forEach(function (ssrc) {
  26104. if (!sources[ssrc.id])
  26105. sources[ssrc.id] = {};
  26106. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26107. });
  26108. }
  26109. return sources;
  26110. };
  26111. },{}],96:[function(require,module,exports){
  26112. var grammar = module.exports = {
  26113. v: [{
  26114. name: 'version',
  26115. reg: /^(\d*)$/
  26116. }],
  26117. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26118. // NB: sessionId will be a String in most cases because it is huge
  26119. name: 'origin',
  26120. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26121. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26122. format: "%s %s %d %s IP%d %s"
  26123. }],
  26124. // default parsing of these only (though some of these feel outdated)
  26125. s: [{ name: 'name' }],
  26126. i: [{ name: 'description' }],
  26127. u: [{ name: 'uri' }],
  26128. e: [{ name: 'email' }],
  26129. p: [{ name: 'phone' }],
  26130. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26131. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26132. //k: [{}], // outdated thing ignored
  26133. t: [{ //t=0 0
  26134. name: 'timing',
  26135. reg: /^(\d*) (\d*)/,
  26136. names: ['start', 'stop'],
  26137. format: "%d %d"
  26138. }],
  26139. c: [{ //c=IN IP4 10.47.197.26
  26140. name: 'connection',
  26141. reg: /^IN IP(\d) (\S*)/,
  26142. names: ['version', 'ip'],
  26143. format: "IN IP%d %s"
  26144. }],
  26145. b: [{ //b=AS:4000
  26146. push: 'bandwidth',
  26147. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26148. names: ['type', 'limit'],
  26149. format: "%s:%s"
  26150. }],
  26151. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26152. // NB: special - pushes to session
  26153. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26154. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26155. names: ['type', 'port', 'protocol', 'payloads'],
  26156. format: "%s %d %s %s"
  26157. }],
  26158. a: [
  26159. { //a=rtpmap:110 opus/48000/2
  26160. push: 'rtp',
  26161. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26162. names: ['payload', 'codec', 'rate', 'encoding'],
  26163. format: function (o) {
  26164. return (o.encoding) ?
  26165. "rtpmap:%d %s/%s/%s":
  26166. "rtpmap:%d %s/%s";
  26167. }
  26168. },
  26169. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26170. push: 'fmtp',
  26171. reg: /^fmtp:(\d*) (\S*)/,
  26172. names: ['payload', 'config'],
  26173. format: "fmtp:%d %s"
  26174. },
  26175. { //a=control:streamid=0
  26176. name: 'control',
  26177. reg: /^control:(.*)/,
  26178. format: "control:%s"
  26179. },
  26180. { //a=rtcp:65179 IN IP4 193.84.77.194
  26181. name: 'rtcp',
  26182. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26183. names: ['port', 'netType', 'ipVer', 'address'],
  26184. format: function (o) {
  26185. return (o.address != null) ?
  26186. "rtcp:%d %s IP%d %s":
  26187. "rtcp:%d";
  26188. }
  26189. },
  26190. { //a=rtcp-fb:98 trr-int 100
  26191. push: 'rtcpFbTrrInt',
  26192. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26193. names: ['payload', 'value'],
  26194. format: "rtcp-fb:%d trr-int %d"
  26195. },
  26196. { //a=rtcp-fb:98 nack rpsi
  26197. push: 'rtcpFb',
  26198. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26199. names: ['payload', 'type', 'subtype'],
  26200. format: function (o) {
  26201. return (o.subtype != null) ?
  26202. "rtcp-fb:%s %s %s":
  26203. "rtcp-fb:%s %s";
  26204. }
  26205. },
  26206. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26207. //a=extmap:1/recvonly URI-gps-string
  26208. push: 'ext',
  26209. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26210. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26211. format: function (o) {
  26212. return (o.config != null) ?
  26213. "extmap:%s %s %s":
  26214. "extmap:%s %s";
  26215. }
  26216. },
  26217. {
  26218. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26219. push: 'crypto',
  26220. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26221. names: ['id', 'suite', 'config', 'sessionConfig'],
  26222. format: function (o) {
  26223. return (o.sessionConfig != null) ?
  26224. "crypto:%d %s %s %s":
  26225. "crypto:%d %s %s";
  26226. }
  26227. },
  26228. { //a=setup:actpass
  26229. name: 'setup',
  26230. reg: /^setup:(\w*)/,
  26231. format: "setup:%s"
  26232. },
  26233. { //a=mid:1
  26234. name: 'mid',
  26235. reg: /^mid:([^\s]*)/,
  26236. format: "mid:%s"
  26237. },
  26238. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26239. name: 'msid',
  26240. reg: /^msid:(.*)/,
  26241. format: "msid:%s"
  26242. },
  26243. { //a=ptime:20
  26244. name: 'ptime',
  26245. reg: /^ptime:(\d*)/,
  26246. format: "ptime:%d"
  26247. },
  26248. { //a=maxptime:60
  26249. name: 'maxptime',
  26250. reg: /^maxptime:(\d*)/,
  26251. format: "maxptime:%d"
  26252. },
  26253. { //a=sendrecv
  26254. name: 'direction',
  26255. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26256. },
  26257. { //a=ice-lite
  26258. name: 'icelite',
  26259. reg: /^(ice-lite)/
  26260. },
  26261. { //a=ice-ufrag:F7gI
  26262. name: 'iceUfrag',
  26263. reg: /^ice-ufrag:(\S*)/,
  26264. format: "ice-ufrag:%s"
  26265. },
  26266. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26267. name: 'icePwd',
  26268. reg: /^ice-pwd:(\S*)/,
  26269. format: "ice-pwd:%s"
  26270. },
  26271. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26272. name: 'fingerprint',
  26273. reg: /^fingerprint:(\S*) (\S*)/,
  26274. names: ['type', 'hash'],
  26275. format: "fingerprint:%s %s"
  26276. },
  26277. {
  26278. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26279. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26280. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26281. push:'candidates',
  26282. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26283. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26284. format: function (o) {
  26285. var str = "candidate:%s %d %s %d %s %d typ %s";
  26286. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26287. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26288. if (o.generation != null) {
  26289. str += " generation %d";
  26290. }
  26291. return str;
  26292. }
  26293. },
  26294. { //a=end-of-candidates (keep after the candidates line for readability)
  26295. name: 'endOfCandidates',
  26296. reg: /^(end-of-candidates)/
  26297. },
  26298. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26299. name: 'remoteCandidates',
  26300. reg: /^remote-candidates:(.*)/,
  26301. format: "remote-candidates:%s"
  26302. },
  26303. { //a=ice-options:google-ice
  26304. name: 'iceOptions',
  26305. reg: /^ice-options:(\S*)/,
  26306. format: "ice-options:%s"
  26307. },
  26308. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26309. push: "ssrcs",
  26310. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26311. names: ['id', 'attribute', 'value'],
  26312. format: "ssrc:%d %s:%s"
  26313. },
  26314. { //a=ssrc-group:FEC 1 2
  26315. push: "ssrcGroups",
  26316. reg: /^ssrc-group:(\w*) (.*)/,
  26317. names: ['semantics', 'ssrcs'],
  26318. format: "ssrc-group:%s %s"
  26319. },
  26320. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26321. name: "msidSemantic",
  26322. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26323. names: ['semantic', 'token'],
  26324. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26325. },
  26326. { //a=group:BUNDLE audio video
  26327. push: 'groups',
  26328. reg: /^group:(\w*) (.*)/,
  26329. names: ['type', 'mids'],
  26330. format: "group:%s %s"
  26331. },
  26332. { //a=rtcp-mux
  26333. name: 'rtcpMux',
  26334. reg: /^(rtcp-mux)/
  26335. },
  26336. { //a=rtcp-rsize
  26337. name: 'rtcpRsize',
  26338. reg: /^(rtcp-rsize)/
  26339. },
  26340. { // any a= that we don't understand is kepts verbatim on media.invalid
  26341. push: 'invalid',
  26342. names: ["value"]
  26343. }
  26344. ]
  26345. };
  26346. // set sensible defaults to avoid polluting the grammar with boring details
  26347. Object.keys(grammar).forEach(function (key) {
  26348. var objs = grammar[key];
  26349. objs.forEach(function (obj) {
  26350. if (!obj.reg) {
  26351. obj.reg = /(.*)/;
  26352. }
  26353. if (!obj.format) {
  26354. obj.format = "%s";
  26355. }
  26356. });
  26357. });
  26358. },{}],97:[function(require,module,exports){
  26359. var parser = require('./parser');
  26360. var writer = require('./writer');
  26361. exports.write = writer;
  26362. exports.parse = parser.parse;
  26363. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26364. exports.parsePayloads = parser.parsePayloads;
  26365. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26366. },{"./parser":98,"./writer":99}],98:[function(require,module,exports){
  26367. var toIntIfInt = function (v) {
  26368. return String(Number(v)) === v ? Number(v) : v;
  26369. };
  26370. var attachProperties = function (match, location, names, rawName) {
  26371. if (rawName && !names) {
  26372. location[rawName] = toIntIfInt(match[1]);
  26373. }
  26374. else {
  26375. for (var i = 0; i < names.length; i += 1) {
  26376. if (match[i+1] != null) {
  26377. location[names[i]] = toIntIfInt(match[i+1]);
  26378. }
  26379. }
  26380. }
  26381. };
  26382. var parseReg = function (obj, location, content) {
  26383. var needsBlank = obj.name && obj.names;
  26384. if (obj.push && !location[obj.push]) {
  26385. location[obj.push] = [];
  26386. }
  26387. else if (needsBlank && !location[obj.name]) {
  26388. location[obj.name] = {};
  26389. }
  26390. var keyLocation = obj.push ?
  26391. {} : // blank object that will be pushed
  26392. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26393. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26394. if (obj.push) {
  26395. location[obj.push].push(keyLocation);
  26396. }
  26397. };
  26398. var grammar = require('./grammar');
  26399. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26400. exports.parse = function (sdp) {
  26401. var session = {}
  26402. , media = []
  26403. , location = session; // points at where properties go under (one of the above)
  26404. // parse lines we understand
  26405. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26406. var type = l[0];
  26407. var content = l.slice(2);
  26408. if (type === 'm') {
  26409. media.push({rtp: [], fmtp: []});
  26410. location = media[media.length-1]; // point at latest media line
  26411. }
  26412. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26413. var obj = grammar[type][j];
  26414. if (obj.reg.test(content)) {
  26415. return parseReg(obj, location, content);
  26416. }
  26417. }
  26418. });
  26419. session.media = media; // link it up
  26420. return session;
  26421. };
  26422. var fmtpReducer = function (acc, expr) {
  26423. var s = expr.split('=');
  26424. if (s.length === 2) {
  26425. acc[s[0]] = toIntIfInt(s[1]);
  26426. }
  26427. return acc;
  26428. };
  26429. exports.parseFmtpConfig = function (str) {
  26430. return str.split(';').reduce(fmtpReducer, {});
  26431. };
  26432. exports.parsePayloads = function (str) {
  26433. return str.split(' ').map(Number);
  26434. };
  26435. exports.parseRemoteCandidates = function (str) {
  26436. var candidates = [];
  26437. var parts = str.split(' ').map(toIntIfInt);
  26438. for (var i = 0; i < parts.length; i += 3) {
  26439. candidates.push({
  26440. component: parts[i],
  26441. ip: parts[i + 1],
  26442. port: parts[i + 2]
  26443. });
  26444. }
  26445. return candidates;
  26446. };
  26447. },{"./grammar":96}],99:[function(require,module,exports){
  26448. var grammar = require('./grammar');
  26449. // customized util.format - discards excess arguments and can void middle ones
  26450. var formatRegExp = /%[sdv%]/g;
  26451. var format = function (formatStr) {
  26452. var i = 1;
  26453. var args = arguments;
  26454. var len = args.length;
  26455. return formatStr.replace(formatRegExp, function (x) {
  26456. if (i >= len) {
  26457. return x; // missing argument
  26458. }
  26459. var arg = args[i];
  26460. i += 1;
  26461. switch (x) {
  26462. case '%%':
  26463. return '%';
  26464. case '%s':
  26465. return String(arg);
  26466. case '%d':
  26467. return Number(arg);
  26468. case '%v':
  26469. return '';
  26470. }
  26471. });
  26472. // NB: we discard excess arguments - they are typically undefined from makeLine
  26473. };
  26474. var makeLine = function (type, obj, location) {
  26475. var str = obj.format instanceof Function ?
  26476. (obj.format(obj.push ? location : location[obj.name])) :
  26477. obj.format;
  26478. var args = [type + '=' + str];
  26479. if (obj.names) {
  26480. for (var i = 0; i < obj.names.length; i += 1) {
  26481. var n = obj.names[i];
  26482. if (obj.name) {
  26483. args.push(location[obj.name][n]);
  26484. }
  26485. else { // for mLine and push attributes
  26486. args.push(location[obj.names[i]]);
  26487. }
  26488. }
  26489. }
  26490. else {
  26491. args.push(location[obj.name]);
  26492. }
  26493. return format.apply(null, args);
  26494. };
  26495. // RFC specified order
  26496. // TODO: extend this with all the rest
  26497. var defaultOuterOrder = [
  26498. 'v', 'o', 's', 'i',
  26499. 'u', 'e', 'p', 'c',
  26500. 'b', 't', 'r', 'z', 'a'
  26501. ];
  26502. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  26503. module.exports = function (session, opts) {
  26504. opts = opts || {};
  26505. // ensure certain properties exist
  26506. if (session.version == null) {
  26507. session.version = 0; // "v=0" must be there (only defined version atm)
  26508. }
  26509. if (session.name == null) {
  26510. session.name = " "; // "s= " must be there if no meaningful name set
  26511. }
  26512. session.media.forEach(function (mLine) {
  26513. if (mLine.payloads == null) {
  26514. mLine.payloads = "";
  26515. }
  26516. });
  26517. var outerOrder = opts.outerOrder || defaultOuterOrder;
  26518. var innerOrder = opts.innerOrder || defaultInnerOrder;
  26519. var sdp = [];
  26520. // loop through outerOrder for matching properties on session
  26521. outerOrder.forEach(function (type) {
  26522. grammar[type].forEach(function (obj) {
  26523. if (obj.name in session && session[obj.name] != null) {
  26524. sdp.push(makeLine(type, obj, session));
  26525. }
  26526. else if (obj.push in session && session[obj.push] != null) {
  26527. session[obj.push].forEach(function (el) {
  26528. sdp.push(makeLine(type, obj, el));
  26529. });
  26530. }
  26531. });
  26532. });
  26533. // then for each media line, follow the innerOrder
  26534. session.media.forEach(function (mLine) {
  26535. sdp.push(makeLine('m', grammar.m[0], mLine));
  26536. innerOrder.forEach(function (type) {
  26537. grammar[type].forEach(function (obj) {
  26538. if (obj.name in mLine && mLine[obj.name] != null) {
  26539. sdp.push(makeLine(type, obj, mLine));
  26540. }
  26541. else if (obj.push in mLine && mLine[obj.push] != null) {
  26542. mLine[obj.push].forEach(function (el) {
  26543. sdp.push(makeLine(type, obj, el));
  26544. });
  26545. }
  26546. });
  26547. });
  26548. });
  26549. return sdp.join('\r\n') + '\r\n';
  26550. };
  26551. },{"./grammar":96}],100:[function(require,module,exports){
  26552. var MediaStreamType = {
  26553. VIDEO_TYPE: "Video",
  26554. AUDIO_TYPE: "Audio"
  26555. };
  26556. module.exports = MediaStreamType;
  26557. },{}],101:[function(require,module,exports){
  26558. var RTCEvents = {
  26559. RTC_READY: "rtc.ready",
  26560. LASTN_CHANGED: "rtc.lastn_changed",
  26561. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  26562. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  26563. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  26564. AUDIO_MUTE: "rtc.audio_mute",
  26565. VIDEO_MUTE: "rtc.video_mute"
  26566. };
  26567. module.exports = RTCEvents;
  26568. },{}],102:[function(require,module,exports){
  26569. var Resolutions = {
  26570. "1080": {
  26571. width: 1920,
  26572. height: 1080,
  26573. order: 7
  26574. },
  26575. "fullhd": {
  26576. width: 1920,
  26577. height: 1080,
  26578. order: 7
  26579. },
  26580. "720": {
  26581. width: 1280,
  26582. height: 720,
  26583. order: 6
  26584. },
  26585. "hd": {
  26586. width: 1280,
  26587. height: 720,
  26588. order: 6
  26589. },
  26590. "960": {
  26591. width: 960,
  26592. height: 720,
  26593. order: 5
  26594. },
  26595. "640": {
  26596. width: 640,
  26597. height: 480,
  26598. order: 4
  26599. },
  26600. "vga": {
  26601. width: 640,
  26602. height: 480,
  26603. order: 4
  26604. },
  26605. "360": {
  26606. width: 640,
  26607. height: 360,
  26608. order: 3
  26609. },
  26610. "320": {
  26611. width: 320,
  26612. height: 240,
  26613. order: 2
  26614. },
  26615. "180": {
  26616. width: 320,
  26617. height: 180,
  26618. order: 1
  26619. }
  26620. };
  26621. module.exports = Resolutions;
  26622. },{}],103:[function(require,module,exports){
  26623. var StreamEventTypes = {
  26624. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  26625. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  26626. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  26627. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  26628. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  26629. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  26630. };
  26631. module.exports = StreamEventTypes;
  26632. },{}],104:[function(require,module,exports){
  26633. var UIEvents = {
  26634. NICKNAME_CHANGED: "UI.nickname_changed",
  26635. SELECTED_ENDPOINT: "UI.selected_endpoint",
  26636. PINNED_ENDPOINT: "UI.pinned_endpoint"
  26637. };
  26638. module.exports = UIEvents;
  26639. },{}],105:[function(require,module,exports){
  26640. var AuthenticationEvents = {
  26641. /**
  26642. * Event callback arguments:
  26643. * function(authenticationEnabled, userIdentity)
  26644. * authenticationEnabled - indicates whether authentication has been enabled
  26645. * in this session
  26646. * userIdentity - if user has been logged in then it contains user name. If
  26647. * contains 'null' or 'undefined' then user is not logged in.
  26648. */
  26649. IDENTITY_UPDATED: "authentication.identity_updated"
  26650. };
  26651. module.exports = AuthenticationEvents;
  26652. },{}],106:[function(require,module,exports){
  26653. var CQEvents = {
  26654. LOCALSTATS_UPDATED: "cq.localstats_updated",
  26655. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  26656. STOP: "cq.stop"
  26657. };
  26658. module.exports = CQEvents;
  26659. },{}],107:[function(require,module,exports){
  26660. var DesktopSharingEventTypes = {
  26661. INIT: "ds.init",
  26662. SWITCHING_DONE: "ds.switching_done",
  26663. NEW_STREAM_CREATED: "ds.new_stream_created"
  26664. };
  26665. module.exports = DesktopSharingEventTypes;
  26666. },{}],108:[function(require,module,exports){
  26667. var Events = {
  26668. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  26669. };
  26670. module.exports = Events;
  26671. },{}],109:[function(require,module,exports){
  26672. module.exports = {
  26673. getLanguages : function () {
  26674. var languages = [];
  26675. for(var lang in this)
  26676. {
  26677. if(typeof this[lang] === "string")
  26678. languages.push(this[lang]);
  26679. }
  26680. return languages;
  26681. },
  26682. EN: "en",
  26683. BG: "bg",
  26684. DE: "de",
  26685. TR: "tr",
  26686. FR: "fr"
  26687. }
  26688. },{}],110:[function(require,module,exports){
  26689. var XMPPEvents = {
  26690. CONNECTION_FAILED: "xmpp.connection.failed",
  26691. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  26692. CALL_INCOMING: "xmpp.callincoming.jingle",
  26693. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  26694. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  26695. KICKED: "xmpp.kicked",
  26696. BRIDGE_DOWN: "xmpp.bridge_down",
  26697. USER_ID_CHANGED: "xmpp.user_id_changed",
  26698. STREAMS_CHANGED: "xmpp.streams_changed",
  26699. // We joined the MUC
  26700. MUC_JOINED: "xmpp.muc_joined",
  26701. // A member joined the MUC
  26702. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  26703. // A member left the MUC
  26704. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  26705. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  26706. MUC_DESTROYED: "xmpp.muc_destroyed",
  26707. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  26708. REMOTE_STATS: "xmpp.remote_stats",
  26709. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  26710. PRESENCE_STATUS: "xmpp.presence_status",
  26711. RESERVATION_ERROR: "xmpp.room_reservation_error",
  26712. SUBJECT_CHANGED: "xmpp.subject_changed",
  26713. MESSAGE_RECEIVED: "xmpp.message_received",
  26714. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  26715. PASSWORD_REQUIRED: "xmpp.password_required",
  26716. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  26717. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  26718. ETHERPAD: "xmpp.etherpad",
  26719. DEVICE_AVAILABLE: "xmpp.device_available",
  26720. START_MUTED: "xmpp.start_muted",
  26721. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  26722. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  26723. AUDIO_MUTED: "xmpp.audio_muted",
  26724. VIDEO_MUTED: "xmpp.video_muted"
  26725. };
  26726. module.exports = XMPPEvents;
  26727. },{}]},{},[3])(3)
  26728. });